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, NextWorkspace, PreviousWorkspace, Sidebar, SidebarEvent, SidebarHandle,
36 SidebarRenderState, SidebarSide, 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(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
660 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
661 workspace_window
662 .update(cx, |multi_workspace, window, cx| {
663 let workspace = multi_workspace.workspace().clone();
664 workspace.update(cx, |workspace, cx| {
665 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
666 });
667 })
668 .ok();
669 } else {
670 let task = Workspace::new_local(
671 Vec::new(),
672 app_state.clone(),
673 None,
674 None,
675 None,
676 OpenMode::Activate,
677 cx,
678 );
679 cx.spawn(async move |cx| {
680 let OpenResult { window, .. } = task.await?;
681 window.update(cx, |multi_workspace, window, cx| {
682 window.activate_window();
683 let workspace = multi_workspace.workspace().clone();
684 workspace.update(cx, |workspace, cx| {
685 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
686 });
687 })?;
688 anyhow::Ok(())
689 })
690 .detach_and_log_err(cx);
691 }
692}
693
694pub fn prompt_for_open_path_and_open(
695 workspace: &mut Workspace,
696 app_state: Arc<AppState>,
697 options: PathPromptOptions,
698 create_new_window: bool,
699 window: &mut Window,
700 cx: &mut Context<Workspace>,
701) {
702 let paths = workspace.prompt_for_open_path(
703 options,
704 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
705 window,
706 cx,
707 );
708 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
709 cx.spawn_in(window, async move |this, cx| {
710 let Some(paths) = paths.await.log_err().flatten() else {
711 return;
712 };
713 if !create_new_window {
714 if let Some(handle) = multi_workspace_handle {
715 if let Some(task) = handle
716 .update(cx, |multi_workspace, window, cx| {
717 multi_workspace.open_project(paths, OpenMode::Activate, window, cx)
718 })
719 .log_err()
720 {
721 task.await.log_err();
722 }
723 return;
724 }
725 }
726 if let Some(task) = this
727 .update_in(cx, |this, window, cx| {
728 this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
729 })
730 .log_err()
731 {
732 task.await.log_err();
733 }
734 })
735 .detach();
736}
737
738pub fn init(app_state: Arc<AppState>, cx: &mut App) {
739 component::init();
740 theme_preview::init(cx);
741 toast_layer::init(cx);
742 history_manager::init(app_state.fs.clone(), cx);
743
744 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
745 .on_action(|_: &Reload, cx| reload(cx))
746 .on_action(|_: &Open, cx: &mut App| {
747 let app_state = AppState::global(cx);
748 prompt_and_open_paths(
749 app_state,
750 PathPromptOptions {
751 files: true,
752 directories: true,
753 multiple: true,
754 prompt: None,
755 },
756 cx,
757 );
758 })
759 .on_action(|_: &OpenFiles, cx: &mut App| {
760 let directories = cx.can_select_mixed_files_and_dirs();
761 let app_state = AppState::global(cx);
762 prompt_and_open_paths(
763 app_state,
764 PathPromptOptions {
765 files: true,
766 directories,
767 multiple: true,
768 prompt: None,
769 },
770 cx,
771 );
772 });
773}
774
775type BuildProjectItemFn =
776 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
777
778type BuildProjectItemForPathFn =
779 fn(
780 &Entity<Project>,
781 &ProjectPath,
782 &mut Window,
783 &mut App,
784 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
785
786#[derive(Clone, Default)]
787struct ProjectItemRegistry {
788 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
789 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
790}
791
792impl ProjectItemRegistry {
793 fn register<T: ProjectItem>(&mut self) {
794 self.build_project_item_fns_by_type.insert(
795 TypeId::of::<T::Item>(),
796 |item, project, pane, window, cx| {
797 let item = item.downcast().unwrap();
798 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
799 as Box<dyn ItemHandle>
800 },
801 );
802 self.build_project_item_for_path_fns
803 .push(|project, project_path, window, cx| {
804 let project_path = project_path.clone();
805 let is_file = project
806 .read(cx)
807 .entry_for_path(&project_path, cx)
808 .is_some_and(|entry| entry.is_file());
809 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
810 let is_local = project.read(cx).is_local();
811 let project_item =
812 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
813 let project = project.clone();
814 Some(window.spawn(cx, async move |cx| {
815 match project_item.await.with_context(|| {
816 format!(
817 "opening project path {:?}",
818 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
819 )
820 }) {
821 Ok(project_item) => {
822 let project_item = project_item;
823 let project_entry_id: Option<ProjectEntryId> =
824 project_item.read_with(cx, project::ProjectItem::entry_id);
825 let build_workspace_item = Box::new(
826 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
827 Box::new(cx.new(|cx| {
828 T::for_project_item(
829 project,
830 Some(pane),
831 project_item,
832 window,
833 cx,
834 )
835 })) as Box<dyn ItemHandle>
836 },
837 ) as Box<_>;
838 Ok((project_entry_id, build_workspace_item))
839 }
840 Err(e) => {
841 log::warn!("Failed to open a project item: {e:#}");
842 if e.error_code() == ErrorCode::Internal {
843 if let Some(abs_path) =
844 entry_abs_path.as_deref().filter(|_| is_file)
845 {
846 if let Some(broken_project_item_view) =
847 cx.update(|window, cx| {
848 T::for_broken_project_item(
849 abs_path, is_local, &e, window, cx,
850 )
851 })?
852 {
853 let build_workspace_item = Box::new(
854 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
855 cx.new(|_| broken_project_item_view).boxed_clone()
856 },
857 )
858 as Box<_>;
859 return Ok((None, build_workspace_item));
860 }
861 }
862 }
863 Err(e)
864 }
865 }
866 }))
867 });
868 }
869
870 fn open_path(
871 &self,
872 project: &Entity<Project>,
873 path: &ProjectPath,
874 window: &mut Window,
875 cx: &mut App,
876 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
877 let Some(open_project_item) = self
878 .build_project_item_for_path_fns
879 .iter()
880 .rev()
881 .find_map(|open_project_item| open_project_item(project, path, window, cx))
882 else {
883 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
884 };
885 open_project_item
886 }
887
888 fn build_item<T: project::ProjectItem>(
889 &self,
890 item: Entity<T>,
891 project: Entity<Project>,
892 pane: Option<&Pane>,
893 window: &mut Window,
894 cx: &mut App,
895 ) -> Option<Box<dyn ItemHandle>> {
896 let build = self
897 .build_project_item_fns_by_type
898 .get(&TypeId::of::<T>())?;
899 Some(build(item.into_any(), project, pane, window, cx))
900 }
901}
902
903type WorkspaceItemBuilder =
904 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
905
906impl Global for ProjectItemRegistry {}
907
908/// Registers a [ProjectItem] for the app. When opening a file, all the registered
909/// items will get a chance to open the file, starting from the project item that
910/// was added last.
911pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
912 cx.default_global::<ProjectItemRegistry>().register::<I>();
913}
914
915#[derive(Default)]
916pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
917
918struct FollowableViewDescriptor {
919 from_state_proto: fn(
920 Entity<Workspace>,
921 ViewId,
922 &mut Option<proto::view::Variant>,
923 &mut Window,
924 &mut App,
925 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
926 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
927}
928
929impl Global for FollowableViewRegistry {}
930
931impl FollowableViewRegistry {
932 pub fn register<I: FollowableItem>(cx: &mut App) {
933 cx.default_global::<Self>().0.insert(
934 TypeId::of::<I>(),
935 FollowableViewDescriptor {
936 from_state_proto: |workspace, id, state, window, cx| {
937 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
938 cx.foreground_executor()
939 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
940 })
941 },
942 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
943 },
944 );
945 }
946
947 pub fn from_state_proto(
948 workspace: Entity<Workspace>,
949 view_id: ViewId,
950 mut state: Option<proto::view::Variant>,
951 window: &mut Window,
952 cx: &mut App,
953 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
954 cx.update_default_global(|this: &mut Self, cx| {
955 this.0.values().find_map(|descriptor| {
956 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
957 })
958 })
959 }
960
961 pub fn to_followable_view(
962 view: impl Into<AnyView>,
963 cx: &App,
964 ) -> Option<Box<dyn FollowableItemHandle>> {
965 let this = cx.try_global::<Self>()?;
966 let view = view.into();
967 let descriptor = this.0.get(&view.entity_type())?;
968 Some((descriptor.to_followable_view)(&view))
969 }
970}
971
972#[derive(Copy, Clone)]
973struct SerializableItemDescriptor {
974 deserialize: fn(
975 Entity<Project>,
976 WeakEntity<Workspace>,
977 WorkspaceId,
978 ItemId,
979 &mut Window,
980 &mut Context<Pane>,
981 ) -> Task<Result<Box<dyn ItemHandle>>>,
982 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
983 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
984}
985
986#[derive(Default)]
987struct SerializableItemRegistry {
988 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
989 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
990}
991
992impl Global for SerializableItemRegistry {}
993
994impl SerializableItemRegistry {
995 fn deserialize(
996 item_kind: &str,
997 project: Entity<Project>,
998 workspace: WeakEntity<Workspace>,
999 workspace_id: WorkspaceId,
1000 item_item: ItemId,
1001 window: &mut Window,
1002 cx: &mut Context<Pane>,
1003 ) -> Task<Result<Box<dyn ItemHandle>>> {
1004 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1005 return Task::ready(Err(anyhow!(
1006 "cannot deserialize {}, descriptor not found",
1007 item_kind
1008 )));
1009 };
1010
1011 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1012 }
1013
1014 fn cleanup(
1015 item_kind: &str,
1016 workspace_id: WorkspaceId,
1017 loaded_items: Vec<ItemId>,
1018 window: &mut Window,
1019 cx: &mut App,
1020 ) -> Task<Result<()>> {
1021 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1022 return Task::ready(Err(anyhow!(
1023 "cannot cleanup {}, descriptor not found",
1024 item_kind
1025 )));
1026 };
1027
1028 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1029 }
1030
1031 fn view_to_serializable_item_handle(
1032 view: AnyView,
1033 cx: &App,
1034 ) -> Option<Box<dyn SerializableItemHandle>> {
1035 let this = cx.try_global::<Self>()?;
1036 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1037 Some((descriptor.view_to_serializable_item)(view))
1038 }
1039
1040 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1041 let this = cx.try_global::<Self>()?;
1042 this.descriptors_by_kind.get(item_kind).copied()
1043 }
1044}
1045
1046pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1047 let serialized_item_kind = I::serialized_item_kind();
1048
1049 let registry = cx.default_global::<SerializableItemRegistry>();
1050 let descriptor = SerializableItemDescriptor {
1051 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1052 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1053 cx.foreground_executor()
1054 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1055 },
1056 cleanup: |workspace_id, loaded_items, window, cx| {
1057 I::cleanup(workspace_id, loaded_items, window, cx)
1058 },
1059 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1060 };
1061 registry
1062 .descriptors_by_kind
1063 .insert(Arc::from(serialized_item_kind), descriptor);
1064 registry
1065 .descriptors_by_type
1066 .insert(TypeId::of::<I>(), descriptor);
1067}
1068
1069pub struct AppState {
1070 pub languages: Arc<LanguageRegistry>,
1071 pub client: Arc<Client>,
1072 pub user_store: Entity<UserStore>,
1073 pub workspace_store: Entity<WorkspaceStore>,
1074 pub fs: Arc<dyn fs::Fs>,
1075 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1076 pub node_runtime: NodeRuntime,
1077 pub session: Entity<AppSession>,
1078}
1079
1080struct GlobalAppState(Arc<AppState>);
1081
1082impl Global for GlobalAppState {}
1083
1084pub struct WorkspaceStore {
1085 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1086 client: Arc<Client>,
1087 _subscriptions: Vec<client::Subscription>,
1088}
1089
1090#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1091pub enum CollaboratorId {
1092 PeerId(PeerId),
1093 Agent,
1094}
1095
1096impl From<PeerId> for CollaboratorId {
1097 fn from(peer_id: PeerId) -> Self {
1098 CollaboratorId::PeerId(peer_id)
1099 }
1100}
1101
1102impl From<&PeerId> for CollaboratorId {
1103 fn from(peer_id: &PeerId) -> Self {
1104 CollaboratorId::PeerId(*peer_id)
1105 }
1106}
1107
1108#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1109struct Follower {
1110 project_id: Option<u64>,
1111 peer_id: PeerId,
1112}
1113
1114impl AppState {
1115 #[track_caller]
1116 pub fn global(cx: &App) -> Arc<Self> {
1117 cx.global::<GlobalAppState>().0.clone()
1118 }
1119 pub fn try_global(cx: &App) -> Option<Arc<Self>> {
1120 cx.try_global::<GlobalAppState>()
1121 .map(|state| state.0.clone())
1122 }
1123 pub fn set_global(state: Arc<AppState>, cx: &mut App) {
1124 cx.set_global(GlobalAppState(state));
1125 }
1126
1127 #[cfg(any(test, feature = "test-support"))]
1128 pub fn test(cx: &mut App) -> Arc<Self> {
1129 use fs::Fs;
1130 use node_runtime::NodeRuntime;
1131 use session::Session;
1132 use settings::SettingsStore;
1133
1134 if !cx.has_global::<SettingsStore>() {
1135 let settings_store = SettingsStore::test(cx);
1136 cx.set_global(settings_store);
1137 }
1138
1139 let fs = fs::FakeFs::new(cx.background_executor().clone());
1140 <dyn Fs>::set_global(fs.clone(), cx);
1141 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1142 let clock = Arc::new(clock::FakeSystemClock::new());
1143 let http_client = http_client::FakeHttpClient::with_404_response();
1144 let client = Client::new(clock, http_client, cx);
1145 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1146 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1147 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1148
1149 theme_settings::init(theme::LoadThemes::JustBase, cx);
1150 client::init(&client, cx);
1151
1152 Arc::new(Self {
1153 client,
1154 fs,
1155 languages,
1156 user_store,
1157 workspace_store,
1158 node_runtime: NodeRuntime::unavailable(),
1159 build_window_options: |_, _| Default::default(),
1160 session,
1161 })
1162 }
1163}
1164
1165struct DelayedDebouncedEditAction {
1166 task: Option<Task<()>>,
1167 cancel_channel: Option<oneshot::Sender<()>>,
1168}
1169
1170impl DelayedDebouncedEditAction {
1171 fn new() -> DelayedDebouncedEditAction {
1172 DelayedDebouncedEditAction {
1173 task: None,
1174 cancel_channel: None,
1175 }
1176 }
1177
1178 fn fire_new<F>(
1179 &mut self,
1180 delay: Duration,
1181 window: &mut Window,
1182 cx: &mut Context<Workspace>,
1183 func: F,
1184 ) where
1185 F: 'static
1186 + Send
1187 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1188 {
1189 if let Some(channel) = self.cancel_channel.take() {
1190 _ = channel.send(());
1191 }
1192
1193 let (sender, mut receiver) = oneshot::channel::<()>();
1194 self.cancel_channel = Some(sender);
1195
1196 let previous_task = self.task.take();
1197 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1198 let mut timer = cx.background_executor().timer(delay).fuse();
1199 if let Some(previous_task) = previous_task {
1200 previous_task.await;
1201 }
1202
1203 futures::select_biased! {
1204 _ = receiver => return,
1205 _ = timer => {}
1206 }
1207
1208 if let Some(result) = workspace
1209 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1210 .log_err()
1211 {
1212 result.await.log_err();
1213 }
1214 }));
1215 }
1216}
1217
1218pub enum Event {
1219 PaneAdded(Entity<Pane>),
1220 PaneRemoved,
1221 ItemAdded {
1222 item: Box<dyn ItemHandle>,
1223 },
1224 ActiveItemChanged,
1225 ItemRemoved {
1226 item_id: EntityId,
1227 },
1228 UserSavedItem {
1229 pane: WeakEntity<Pane>,
1230 item: Box<dyn WeakItemHandle>,
1231 save_intent: SaveIntent,
1232 },
1233 ContactRequestedJoin(u64),
1234 WorkspaceCreated(WeakEntity<Workspace>),
1235 OpenBundledFile {
1236 text: Cow<'static, str>,
1237 title: &'static str,
1238 language: &'static str,
1239 },
1240 ZoomChanged,
1241 ModalOpened,
1242 Activate,
1243 PanelAdded(AnyView),
1244}
1245
1246#[derive(Debug, Clone)]
1247pub enum OpenVisible {
1248 All,
1249 None,
1250 OnlyFiles,
1251 OnlyDirectories,
1252}
1253
1254enum WorkspaceLocation {
1255 // Valid local paths or SSH project to serialize
1256 Location(SerializedWorkspaceLocation, PathList),
1257 // No valid location found hence clear session id
1258 DetachFromSession,
1259 // No valid location found to serialize
1260 None,
1261}
1262
1263type PromptForNewPath = Box<
1264 dyn Fn(
1265 &mut Workspace,
1266 DirectoryLister,
1267 Option<String>,
1268 &mut Window,
1269 &mut Context<Workspace>,
1270 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1271>;
1272
1273type PromptForOpenPath = Box<
1274 dyn Fn(
1275 &mut Workspace,
1276 DirectoryLister,
1277 &mut Window,
1278 &mut Context<Workspace>,
1279 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1280>;
1281
1282#[derive(Default)]
1283struct DispatchingKeystrokes {
1284 dispatched: HashSet<Vec<Keystroke>>,
1285 queue: VecDeque<Keystroke>,
1286 task: Option<Shared<Task<()>>>,
1287}
1288
1289/// Collects everything project-related for a certain window opened.
1290/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1291///
1292/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1293/// The `Workspace` owns everybody's state and serves as a default, "global context",
1294/// that can be used to register a global action to be triggered from any place in the window.
1295pub struct Workspace {
1296 weak_self: WeakEntity<Self>,
1297 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1298 zoomed: Option<AnyWeakView>,
1299 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1300 zoomed_position: Option<DockPosition>,
1301 center: PaneGroup,
1302 left_dock: Entity<Dock>,
1303 bottom_dock: Entity<Dock>,
1304 right_dock: Entity<Dock>,
1305 panes: Vec<Entity<Pane>>,
1306 active_worktree_override: Option<WorktreeId>,
1307 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1308 active_pane: Entity<Pane>,
1309 last_active_center_pane: Option<WeakEntity<Pane>>,
1310 last_active_view_id: Option<proto::ViewId>,
1311 status_bar: Entity<StatusBar>,
1312 pub(crate) modal_layer: Entity<ModalLayer>,
1313 toast_layer: Entity<ToastLayer>,
1314 titlebar_item: Option<AnyView>,
1315 notifications: Notifications,
1316 suppressed_notifications: HashSet<NotificationId>,
1317 project: Entity<Project>,
1318 follower_states: HashMap<CollaboratorId, FollowerState>,
1319 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1320 window_edited: bool,
1321 last_window_title: Option<String>,
1322 dirty_items: HashMap<EntityId, Subscription>,
1323 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1324 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1325 database_id: Option<WorkspaceId>,
1326 app_state: Arc<AppState>,
1327 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1328 _subscriptions: Vec<Subscription>,
1329 _apply_leader_updates: Task<Result<()>>,
1330 _observe_current_user: Task<Result<()>>,
1331 _schedule_serialize_workspace: Option<Task<()>>,
1332 _serialize_workspace_task: Option<Task<()>>,
1333 _schedule_serialize_ssh_paths: Option<Task<()>>,
1334 pane_history_timestamp: Arc<AtomicUsize>,
1335 bounds: Bounds<Pixels>,
1336 pub centered_layout: bool,
1337 bounds_save_task_queued: Option<Task<()>>,
1338 on_prompt_for_new_path: Option<PromptForNewPath>,
1339 on_prompt_for_open_path: Option<PromptForOpenPath>,
1340 terminal_provider: Option<Box<dyn TerminalProvider>>,
1341 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1342 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1343 _items_serializer: Task<Result<()>>,
1344 session_id: Option<String>,
1345 scheduled_tasks: Vec<Task<()>>,
1346 last_open_dock_positions: Vec<DockPosition>,
1347 removing: bool,
1348 open_in_dev_container: bool,
1349 _dev_container_task: Option<Task<Result<()>>>,
1350 _panels_task: Option<Task<Result<()>>>,
1351 sidebar_focus_handle: Option<FocusHandle>,
1352 multi_workspace: Option<WeakEntity<MultiWorkspace>>,
1353}
1354
1355impl EventEmitter<Event> for Workspace {}
1356
1357#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1358pub struct ViewId {
1359 pub creator: CollaboratorId,
1360 pub id: u64,
1361}
1362
1363pub struct FollowerState {
1364 center_pane: Entity<Pane>,
1365 dock_pane: Option<Entity<Pane>>,
1366 active_view_id: Option<ViewId>,
1367 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1368}
1369
1370struct FollowerView {
1371 view: Box<dyn FollowableItemHandle>,
1372 location: Option<proto::PanelId>,
1373}
1374
1375#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1376pub enum OpenMode {
1377 /// Open the workspace in a new window.
1378 NewWindow,
1379 /// Add to the window's multi workspace without activating it (used during deserialization).
1380 Add,
1381 /// Add to the window's multi workspace and activate it.
1382 #[default]
1383 Activate,
1384}
1385
1386impl Workspace {
1387 pub fn new(
1388 workspace_id: Option<WorkspaceId>,
1389 project: Entity<Project>,
1390 app_state: Arc<AppState>,
1391 window: &mut Window,
1392 cx: &mut Context<Self>,
1393 ) -> Self {
1394 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1395 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1396 if let TrustedWorktreesEvent::Trusted(..) = e {
1397 // Do not persist auto trusted worktrees
1398 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1399 worktrees_store.update(cx, |worktrees_store, cx| {
1400 worktrees_store.schedule_serialization(
1401 cx,
1402 |new_trusted_worktrees, cx| {
1403 let timeout =
1404 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1405 let db = WorkspaceDb::global(cx);
1406 cx.background_spawn(async move {
1407 timeout.await;
1408 db.save_trusted_worktrees(new_trusted_worktrees)
1409 .await
1410 .log_err();
1411 })
1412 },
1413 )
1414 });
1415 }
1416 }
1417 })
1418 .detach();
1419
1420 cx.observe_global::<SettingsStore>(|_, cx| {
1421 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1422 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1423 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1424 trusted_worktrees.auto_trust_all(cx);
1425 })
1426 }
1427 }
1428 })
1429 .detach();
1430 }
1431
1432 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1433 match event {
1434 project::Event::RemoteIdChanged(_) => {
1435 this.update_window_title(window, cx);
1436 }
1437
1438 project::Event::CollaboratorLeft(peer_id) => {
1439 this.collaborator_left(*peer_id, window, cx);
1440 }
1441
1442 &project::Event::WorktreeRemoved(_) => {
1443 this.update_window_title(window, cx);
1444 this.serialize_workspace(window, cx);
1445 this.update_history(cx);
1446 }
1447
1448 &project::Event::WorktreeAdded(id) => {
1449 this.update_window_title(window, cx);
1450 if this
1451 .project()
1452 .read(cx)
1453 .worktree_for_id(id, cx)
1454 .is_some_and(|wt| wt.read(cx).is_visible())
1455 {
1456 this.serialize_workspace(window, cx);
1457 this.update_history(cx);
1458 }
1459 }
1460 project::Event::WorktreeUpdatedEntries(..) => {
1461 this.update_window_title(window, cx);
1462 this.serialize_workspace(window, cx);
1463 }
1464
1465 project::Event::DisconnectedFromHost => {
1466 this.update_window_edited(window, cx);
1467 let leaders_to_unfollow =
1468 this.follower_states.keys().copied().collect::<Vec<_>>();
1469 for leader_id in leaders_to_unfollow {
1470 this.unfollow(leader_id, window, cx);
1471 }
1472 }
1473
1474 project::Event::DisconnectedFromRemote {
1475 server_not_running: _,
1476 } => {
1477 this.update_window_edited(window, cx);
1478 }
1479
1480 project::Event::Closed => {
1481 window.remove_window();
1482 }
1483
1484 project::Event::DeletedEntry(_, entry_id) => {
1485 for pane in this.panes.iter() {
1486 pane.update(cx, |pane, cx| {
1487 pane.handle_deleted_project_item(*entry_id, window, cx)
1488 });
1489 }
1490 }
1491
1492 project::Event::Toast {
1493 notification_id,
1494 message,
1495 link,
1496 } => this.show_notification(
1497 NotificationId::named(notification_id.clone()),
1498 cx,
1499 |cx| {
1500 let mut notification = MessageNotification::new(message.clone(), cx);
1501 if let Some(link) = link {
1502 notification = notification
1503 .more_info_message(link.label)
1504 .more_info_url(link.url);
1505 }
1506
1507 cx.new(|_| notification)
1508 },
1509 ),
1510
1511 project::Event::HideToast { notification_id } => {
1512 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1513 }
1514
1515 project::Event::LanguageServerPrompt(request) => {
1516 struct LanguageServerPrompt;
1517
1518 this.show_notification(
1519 NotificationId::composite::<LanguageServerPrompt>(request.id),
1520 cx,
1521 |cx| {
1522 cx.new(|cx| {
1523 notifications::LanguageServerPrompt::new(request.clone(), cx)
1524 })
1525 },
1526 );
1527 }
1528
1529 project::Event::AgentLocationChanged => {
1530 this.handle_agent_location_changed(window, cx)
1531 }
1532
1533 _ => {}
1534 }
1535 cx.notify()
1536 })
1537 .detach();
1538
1539 cx.subscribe_in(
1540 &project.read(cx).breakpoint_store(),
1541 window,
1542 |workspace, _, event, window, cx| match event {
1543 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1544 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1545 workspace.serialize_workspace(window, cx);
1546 }
1547 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1548 },
1549 )
1550 .detach();
1551 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1552 cx.subscribe_in(
1553 &toolchain_store,
1554 window,
1555 |workspace, _, event, window, cx| match event {
1556 ToolchainStoreEvent::CustomToolchainsModified => {
1557 workspace.serialize_workspace(window, cx);
1558 }
1559 _ => {}
1560 },
1561 )
1562 .detach();
1563 }
1564
1565 cx.on_focus_lost(window, |this, window, cx| {
1566 let focus_handle = this.focus_handle(cx);
1567 window.focus(&focus_handle, cx);
1568 })
1569 .detach();
1570
1571 let weak_handle = cx.entity().downgrade();
1572 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1573
1574 let center_pane = cx.new(|cx| {
1575 let mut center_pane = Pane::new(
1576 weak_handle.clone(),
1577 project.clone(),
1578 pane_history_timestamp.clone(),
1579 None,
1580 NewFile.boxed_clone(),
1581 true,
1582 window,
1583 cx,
1584 );
1585 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1586 center_pane.set_should_display_welcome_page(true);
1587 center_pane
1588 });
1589 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1590 .detach();
1591
1592 window.focus(¢er_pane.focus_handle(cx), cx);
1593
1594 cx.emit(Event::PaneAdded(center_pane.clone()));
1595
1596 let any_window_handle = window.window_handle();
1597 app_state.workspace_store.update(cx, |store, _| {
1598 store
1599 .workspaces
1600 .insert((any_window_handle, weak_handle.clone()));
1601 });
1602
1603 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1604 let mut connection_status = app_state.client.status();
1605 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1606 current_user.next().await;
1607 connection_status.next().await;
1608 let mut stream =
1609 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1610
1611 while stream.recv().await.is_some() {
1612 this.update(cx, |_, cx| cx.notify())?;
1613 }
1614 anyhow::Ok(())
1615 });
1616
1617 // All leader updates are enqueued and then processed in a single task, so
1618 // that each asynchronous operation can be run in order.
1619 let (leader_updates_tx, mut leader_updates_rx) =
1620 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1621 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1622 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1623 Self::process_leader_update(&this, leader_id, update, cx)
1624 .await
1625 .log_err();
1626 }
1627
1628 Ok(())
1629 });
1630
1631 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1632 let modal_layer = cx.new(|_| ModalLayer::new());
1633 let toast_layer = cx.new(|_| ToastLayer::new());
1634 cx.subscribe(
1635 &modal_layer,
1636 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1637 cx.emit(Event::ModalOpened);
1638 },
1639 )
1640 .detach();
1641
1642 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1643 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1644 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1645 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1646 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1647 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1648 let multi_workspace = window
1649 .root::<MultiWorkspace>()
1650 .flatten()
1651 .map(|mw| mw.downgrade());
1652 let status_bar = cx.new(|cx| {
1653 let mut status_bar =
1654 StatusBar::new(¢er_pane.clone(), multi_workspace.clone(), window, cx);
1655 status_bar.add_left_item(left_dock_buttons, window, cx);
1656 status_bar.add_right_item(right_dock_buttons, window, cx);
1657 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1658 status_bar
1659 });
1660
1661 let session_id = app_state.session.read(cx).id().to_owned();
1662
1663 let mut active_call = None;
1664 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1665 let subscriptions =
1666 vec![
1667 call.0
1668 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1669 ];
1670 active_call = Some((call, subscriptions));
1671 }
1672
1673 let (serializable_items_tx, serializable_items_rx) =
1674 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1675 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1676 Self::serialize_items(&this, serializable_items_rx, cx).await
1677 });
1678
1679 let subscriptions = vec![
1680 cx.observe_window_activation(window, Self::on_window_activation_changed),
1681 cx.observe_window_bounds(window, move |this, window, cx| {
1682 if this.bounds_save_task_queued.is_some() {
1683 return;
1684 }
1685 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1686 cx.background_executor()
1687 .timer(Duration::from_millis(100))
1688 .await;
1689 this.update_in(cx, |this, window, cx| {
1690 this.save_window_bounds(window, cx).detach();
1691 this.bounds_save_task_queued.take();
1692 })
1693 .ok();
1694 }));
1695 cx.notify();
1696 }),
1697 cx.observe_window_appearance(window, |_, window, cx| {
1698 let window_appearance = window.appearance();
1699
1700 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1701
1702 theme_settings::reload_theme(cx);
1703 theme_settings::reload_icon_theme(cx);
1704 }),
1705 cx.on_release({
1706 let weak_handle = weak_handle.clone();
1707 move |this, cx| {
1708 this.app_state.workspace_store.update(cx, move |store, _| {
1709 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1710 })
1711 }
1712 }),
1713 ];
1714
1715 cx.defer_in(window, move |this, window, cx| {
1716 this.update_window_title(window, cx);
1717 this.show_initial_notifications(cx);
1718 });
1719
1720 let mut center = PaneGroup::new(center_pane.clone());
1721 center.set_is_center(true);
1722 center.mark_positions(cx);
1723
1724 Workspace {
1725 weak_self: weak_handle.clone(),
1726 zoomed: None,
1727 zoomed_position: None,
1728 previous_dock_drag_coordinates: None,
1729 center,
1730 panes: vec![center_pane.clone()],
1731 panes_by_item: Default::default(),
1732 active_pane: center_pane.clone(),
1733 last_active_center_pane: Some(center_pane.downgrade()),
1734 last_active_view_id: None,
1735 status_bar,
1736 modal_layer,
1737 toast_layer,
1738 titlebar_item: None,
1739 active_worktree_override: None,
1740 notifications: Notifications::default(),
1741 suppressed_notifications: HashSet::default(),
1742 left_dock,
1743 bottom_dock,
1744 right_dock,
1745 _panels_task: None,
1746 project: project.clone(),
1747 follower_states: Default::default(),
1748 last_leaders_by_pane: Default::default(),
1749 dispatching_keystrokes: Default::default(),
1750 window_edited: false,
1751 last_window_title: None,
1752 dirty_items: Default::default(),
1753 active_call,
1754 database_id: workspace_id,
1755 app_state,
1756 _observe_current_user,
1757 _apply_leader_updates,
1758 _schedule_serialize_workspace: None,
1759 _serialize_workspace_task: None,
1760 _schedule_serialize_ssh_paths: None,
1761 leader_updates_tx,
1762 _subscriptions: subscriptions,
1763 pane_history_timestamp,
1764 workspace_actions: Default::default(),
1765 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1766 bounds: Default::default(),
1767 centered_layout: false,
1768 bounds_save_task_queued: None,
1769 on_prompt_for_new_path: None,
1770 on_prompt_for_open_path: None,
1771 terminal_provider: None,
1772 debugger_provider: None,
1773 serializable_items_tx,
1774 _items_serializer,
1775 session_id: Some(session_id),
1776
1777 scheduled_tasks: Vec::new(),
1778 last_open_dock_positions: Vec::new(),
1779 removing: false,
1780 sidebar_focus_handle: None,
1781 multi_workspace,
1782 open_in_dev_container: false,
1783 _dev_container_task: None,
1784 }
1785 }
1786
1787 pub fn new_local(
1788 abs_paths: Vec<PathBuf>,
1789 app_state: Arc<AppState>,
1790 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1791 env: Option<HashMap<String, String>>,
1792 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1793 open_mode: OpenMode,
1794 cx: &mut App,
1795 ) -> Task<anyhow::Result<OpenResult>> {
1796 let project_handle = Project::local(
1797 app_state.client.clone(),
1798 app_state.node_runtime.clone(),
1799 app_state.user_store.clone(),
1800 app_state.languages.clone(),
1801 app_state.fs.clone(),
1802 env,
1803 Default::default(),
1804 cx,
1805 );
1806
1807 let db = WorkspaceDb::global(cx);
1808 let kvp = db::kvp::KeyValueStore::global(cx);
1809 cx.spawn(async move |cx| {
1810 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1811 for path in abs_paths.into_iter() {
1812 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1813 paths_to_open.push(canonical)
1814 } else {
1815 paths_to_open.push(path)
1816 }
1817 }
1818
1819 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1820
1821 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1822 paths_to_open = paths.ordered_paths().cloned().collect();
1823 if !paths.is_lexicographically_ordered() {
1824 project_handle.update(cx, |project, cx| {
1825 project.set_worktrees_reordered(true, cx);
1826 });
1827 }
1828 }
1829
1830 // Get project paths for all of the abs_paths
1831 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1832 Vec::with_capacity(paths_to_open.len());
1833
1834 for path in paths_to_open.into_iter() {
1835 if let Some((_, project_entry)) = cx
1836 .update(|cx| {
1837 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1838 })
1839 .await
1840 .log_err()
1841 {
1842 project_paths.push((path, Some(project_entry)));
1843 } else {
1844 project_paths.push((path, None));
1845 }
1846 }
1847
1848 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1849 serialized_workspace.id
1850 } else {
1851 db.next_id().await.unwrap_or_else(|_| Default::default())
1852 };
1853
1854 let toolchains = db.toolchains(workspace_id).await?;
1855
1856 for (toolchain, worktree_path, path) in toolchains {
1857 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1858 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1859 this.find_worktree(&worktree_path, cx)
1860 .and_then(|(worktree, rel_path)| {
1861 if rel_path.is_empty() {
1862 Some(worktree.read(cx).id())
1863 } else {
1864 None
1865 }
1866 })
1867 }) else {
1868 // We did not find a worktree with a given path, but that's whatever.
1869 continue;
1870 };
1871 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1872 continue;
1873 }
1874
1875 project_handle
1876 .update(cx, |this, cx| {
1877 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1878 })
1879 .await;
1880 }
1881 if let Some(workspace) = serialized_workspace.as_ref() {
1882 project_handle.update(cx, |this, cx| {
1883 for (scope, toolchains) in &workspace.user_toolchains {
1884 for toolchain in toolchains {
1885 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1886 }
1887 }
1888 });
1889 }
1890
1891 let window_to_replace = match open_mode {
1892 OpenMode::NewWindow => None,
1893 _ => requesting_window,
1894 };
1895
1896 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1897 if let Some(window) = window_to_replace {
1898 let centered_layout = serialized_workspace
1899 .as_ref()
1900 .map(|w| w.centered_layout)
1901 .unwrap_or(false);
1902
1903 let workspace = window.update(cx, |multi_workspace, window, cx| {
1904 let workspace = cx.new(|cx| {
1905 let mut workspace = Workspace::new(
1906 Some(workspace_id),
1907 project_handle.clone(),
1908 app_state.clone(),
1909 window,
1910 cx,
1911 );
1912
1913 workspace.centered_layout = centered_layout;
1914
1915 // Call init callback to add items before window renders
1916 if let Some(init) = init {
1917 init(&mut workspace, window, cx);
1918 }
1919
1920 workspace
1921 });
1922 match open_mode {
1923 OpenMode::Activate => {
1924 multi_workspace.activate(workspace.clone(), window, cx);
1925 }
1926 OpenMode::Add => {
1927 multi_workspace.add(workspace.clone(), &*window, cx);
1928 }
1929 OpenMode::NewWindow => {
1930 unreachable!()
1931 }
1932 }
1933 workspace
1934 })?;
1935 (window, workspace)
1936 } else {
1937 let window_bounds_override = window_bounds_env_override();
1938
1939 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1940 (Some(WindowBounds::Windowed(bounds)), None)
1941 } else if let Some(workspace) = serialized_workspace.as_ref()
1942 && let Some(display) = workspace.display
1943 && let Some(bounds) = workspace.window_bounds.as_ref()
1944 {
1945 // Reopening an existing workspace - restore its saved bounds
1946 (Some(bounds.0), Some(display))
1947 } else if let Some((display, bounds)) =
1948 persistence::read_default_window_bounds(&kvp)
1949 {
1950 // New or empty workspace - use the last known window bounds
1951 (Some(bounds), Some(display))
1952 } else {
1953 // New window - let GPUI's default_bounds() handle cascading
1954 (None, None)
1955 };
1956
1957 // Use the serialized workspace to construct the new window
1958 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1959 options.window_bounds = window_bounds;
1960 let centered_layout = serialized_workspace
1961 .as_ref()
1962 .map(|w| w.centered_layout)
1963 .unwrap_or(false);
1964 let window = cx.open_window(options, {
1965 let app_state = app_state.clone();
1966 let project_handle = project_handle.clone();
1967 move |window, cx| {
1968 let workspace = cx.new(|cx| {
1969 let mut workspace = Workspace::new(
1970 Some(workspace_id),
1971 project_handle,
1972 app_state,
1973 window,
1974 cx,
1975 );
1976 workspace.centered_layout = centered_layout;
1977
1978 // Call init callback to add items before window renders
1979 if let Some(init) = init {
1980 init(&mut workspace, window, cx);
1981 }
1982
1983 workspace
1984 });
1985 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1986 }
1987 })?;
1988 let workspace =
1989 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1990 multi_workspace.workspace().clone()
1991 })?;
1992 (window, workspace)
1993 };
1994
1995 notify_if_database_failed(window, cx);
1996 // Check if this is an empty workspace (no paths to open)
1997 // An empty workspace is one where project_paths is empty
1998 let is_empty_workspace = project_paths.is_empty();
1999 // Check if serialized workspace has paths before it's moved
2000 let serialized_workspace_has_paths = serialized_workspace
2001 .as_ref()
2002 .map(|ws| !ws.paths.is_empty())
2003 .unwrap_or(false);
2004
2005 let opened_items = window
2006 .update(cx, |_, window, cx| {
2007 workspace.update(cx, |_workspace: &mut Workspace, cx| {
2008 open_items(serialized_workspace, project_paths, window, cx)
2009 })
2010 })?
2011 .await
2012 .unwrap_or_default();
2013
2014 // Restore default dock state for empty workspaces
2015 // Only restore if:
2016 // 1. This is an empty workspace (no paths), AND
2017 // 2. The serialized workspace either doesn't exist or has no paths
2018 if is_empty_workspace && !serialized_workspace_has_paths {
2019 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
2020 window
2021 .update(cx, |_, window, cx| {
2022 workspace.update(cx, |workspace, cx| {
2023 for (dock, serialized_dock) in [
2024 (&workspace.right_dock, &default_docks.right),
2025 (&workspace.left_dock, &default_docks.left),
2026 (&workspace.bottom_dock, &default_docks.bottom),
2027 ] {
2028 dock.update(cx, |dock, cx| {
2029 dock.serialized_dock = Some(serialized_dock.clone());
2030 dock.restore_state(window, cx);
2031 });
2032 }
2033 cx.notify();
2034 });
2035 })
2036 .log_err();
2037 }
2038 }
2039
2040 window
2041 .update(cx, |_, _window, cx| {
2042 workspace.update(cx, |this: &mut Workspace, cx| {
2043 this.update_history(cx);
2044 });
2045 })
2046 .log_err();
2047 Ok(OpenResult {
2048 window,
2049 workspace,
2050 opened_items,
2051 })
2052 })
2053 }
2054
2055 pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
2056 self.project.read(cx).project_group_key(cx)
2057 }
2058
2059 pub fn weak_handle(&self) -> WeakEntity<Self> {
2060 self.weak_self.clone()
2061 }
2062
2063 pub fn left_dock(&self) -> &Entity<Dock> {
2064 &self.left_dock
2065 }
2066
2067 pub fn bottom_dock(&self) -> &Entity<Dock> {
2068 &self.bottom_dock
2069 }
2070
2071 pub fn set_bottom_dock_layout(
2072 &mut self,
2073 layout: BottomDockLayout,
2074 window: &mut Window,
2075 cx: &mut Context<Self>,
2076 ) {
2077 let fs = self.project().read(cx).fs();
2078 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2079 content.workspace.bottom_dock_layout = Some(layout);
2080 });
2081
2082 cx.notify();
2083 self.serialize_workspace(window, cx);
2084 }
2085
2086 pub fn right_dock(&self) -> &Entity<Dock> {
2087 &self.right_dock
2088 }
2089
2090 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2091 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2092 }
2093
2094 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2095 let left_dock = self.left_dock.read(cx);
2096 let left_visible = left_dock.is_open();
2097 let left_active_panel = left_dock
2098 .active_panel()
2099 .map(|panel| panel.persistent_name().to_string());
2100 // `zoomed_position` is kept in sync with individual panel zoom state
2101 // by the dock code in `Dock::new` and `Dock::add_panel`.
2102 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2103
2104 let right_dock = self.right_dock.read(cx);
2105 let right_visible = right_dock.is_open();
2106 let right_active_panel = right_dock
2107 .active_panel()
2108 .map(|panel| panel.persistent_name().to_string());
2109 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2110
2111 let bottom_dock = self.bottom_dock.read(cx);
2112 let bottom_visible = bottom_dock.is_open();
2113 let bottom_active_panel = bottom_dock
2114 .active_panel()
2115 .map(|panel| panel.persistent_name().to_string());
2116 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2117
2118 DockStructure {
2119 left: DockData {
2120 visible: left_visible,
2121 active_panel: left_active_panel,
2122 zoom: left_dock_zoom,
2123 },
2124 right: DockData {
2125 visible: right_visible,
2126 active_panel: right_active_panel,
2127 zoom: right_dock_zoom,
2128 },
2129 bottom: DockData {
2130 visible: bottom_visible,
2131 active_panel: bottom_active_panel,
2132 zoom: bottom_dock_zoom,
2133 },
2134 }
2135 }
2136
2137 pub fn set_dock_structure(
2138 &self,
2139 docks: DockStructure,
2140 window: &mut Window,
2141 cx: &mut Context<Self>,
2142 ) {
2143 for (dock, data) in [
2144 (&self.left_dock, docks.left),
2145 (&self.bottom_dock, docks.bottom),
2146 (&self.right_dock, docks.right),
2147 ] {
2148 dock.update(cx, |dock, cx| {
2149 dock.serialized_dock = Some(data);
2150 dock.restore_state(window, cx);
2151 });
2152 }
2153 }
2154
2155 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2156 self.items(cx)
2157 .filter_map(|item| {
2158 let project_path = item.project_path(cx)?;
2159 self.project.read(cx).absolute_path(&project_path, cx)
2160 })
2161 .collect()
2162 }
2163
2164 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2165 match position {
2166 DockPosition::Left => &self.left_dock,
2167 DockPosition::Bottom => &self.bottom_dock,
2168 DockPosition::Right => &self.right_dock,
2169 }
2170 }
2171
2172 pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
2173 self.all_docks().into_iter().find_map(|dock| {
2174 let dock = dock.read(cx);
2175 dock.has_agent_panel(cx).then_some(dock.position())
2176 })
2177 }
2178
2179 pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
2180 self.all_docks().into_iter().find_map(|dock| {
2181 let dock = dock.read(cx);
2182 let panel = dock.panel::<T>()?;
2183 dock.stored_panel_size_state(&panel)
2184 })
2185 }
2186
2187 pub fn persisted_panel_size_state(
2188 &self,
2189 panel_key: &'static str,
2190 cx: &App,
2191 ) -> Option<dock::PanelSizeState> {
2192 dock::Dock::load_persisted_size_state(self, panel_key, cx)
2193 }
2194
2195 pub fn persist_panel_size_state(
2196 &self,
2197 panel_key: &str,
2198 size_state: dock::PanelSizeState,
2199 cx: &mut App,
2200 ) {
2201 let Some(workspace_id) = self
2202 .database_id()
2203 .map(|id| i64::from(id).to_string())
2204 .or(self.session_id())
2205 else {
2206 return;
2207 };
2208
2209 let kvp = db::kvp::KeyValueStore::global(cx);
2210 let panel_key = panel_key.to_string();
2211 cx.background_spawn(async move {
2212 let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
2213 scope
2214 .write(
2215 format!("{workspace_id}:{panel_key}"),
2216 serde_json::to_string(&size_state)?,
2217 )
2218 .await
2219 })
2220 .detach_and_log_err(cx);
2221 }
2222
2223 pub fn set_panel_size_state<T: Panel>(
2224 &mut self,
2225 size_state: dock::PanelSizeState,
2226 window: &mut Window,
2227 cx: &mut Context<Self>,
2228 ) -> bool {
2229 let Some(panel) = self.panel::<T>(cx) else {
2230 return false;
2231 };
2232
2233 let dock = self.dock_at_position(panel.position(window, cx));
2234 let did_set = dock.update(cx, |dock, cx| {
2235 dock.set_panel_size_state(&panel, size_state, cx)
2236 });
2237
2238 if did_set {
2239 self.persist_panel_size_state(T::panel_key(), size_state, cx);
2240 }
2241
2242 did_set
2243 }
2244
2245 pub fn toggle_dock_panel_flexible_size(
2246 &self,
2247 dock: &Entity<Dock>,
2248 panel: &dyn PanelHandle,
2249 window: &mut Window,
2250 cx: &mut App,
2251 ) {
2252 let position = dock.read(cx).position();
2253 let current_size = self.dock_size(&dock.read(cx), window, cx);
2254 let current_flex =
2255 current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
2256 dock.update(cx, |dock, cx| {
2257 dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
2258 });
2259 }
2260
2261 fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
2262 let panel = dock.active_panel()?;
2263 let size_state = dock
2264 .stored_panel_size_state(panel.as_ref())
2265 .unwrap_or_default();
2266 let position = dock.position();
2267
2268 let use_flex = panel.has_flexible_size(window, cx);
2269
2270 if position.axis() == Axis::Horizontal
2271 && use_flex
2272 && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
2273 {
2274 let workspace_width = self.bounds.size.width;
2275 if workspace_width <= Pixels::ZERO {
2276 return None;
2277 }
2278 let flex = flex.max(0.001);
2279 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2280 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2281 // Both docks are flex items sharing the full workspace width.
2282 let total_flex = flex + 1.0 + opposite_flex;
2283 return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
2284 } else {
2285 // Opposite dock is fixed-width; flex items share (W - fixed).
2286 let opposite_fixed = opposite
2287 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2288 .unwrap_or_default();
2289 let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
2290 return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
2291 }
2292 }
2293
2294 Some(
2295 size_state
2296 .size
2297 .unwrap_or_else(|| panel.default_size(window, cx)),
2298 )
2299 }
2300
2301 pub fn dock_flex_for_size(
2302 &self,
2303 position: DockPosition,
2304 size: Pixels,
2305 window: &Window,
2306 cx: &App,
2307 ) -> Option<f32> {
2308 if position.axis() != Axis::Horizontal {
2309 return None;
2310 }
2311
2312 let workspace_width = self.bounds.size.width;
2313 if workspace_width <= Pixels::ZERO {
2314 return None;
2315 }
2316
2317 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2318 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2319 let size = size.clamp(px(0.), workspace_width - px(1.));
2320 Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
2321 } else {
2322 let opposite_width = opposite
2323 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2324 .unwrap_or_default();
2325 let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
2326 let remaining = (available - size).max(px(1.));
2327 Some((size / remaining).max(0.0))
2328 }
2329 }
2330
2331 fn opposite_dock_panel_and_size_state(
2332 &self,
2333 position: DockPosition,
2334 window: &Window,
2335 cx: &App,
2336 ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
2337 let opposite_position = match position {
2338 DockPosition::Left => DockPosition::Right,
2339 DockPosition::Right => DockPosition::Left,
2340 DockPosition::Bottom => return None,
2341 };
2342
2343 let opposite_dock = self.dock_at_position(opposite_position).read(cx);
2344 let panel = opposite_dock.visible_panel()?;
2345 let mut size_state = opposite_dock
2346 .stored_panel_size_state(panel.as_ref())
2347 .unwrap_or_default();
2348 if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
2349 size_state.flex = self.default_dock_flex(opposite_position);
2350 }
2351 Some((panel.clone(), size_state))
2352 }
2353
2354 pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
2355 if position.axis() != Axis::Horizontal {
2356 return None;
2357 }
2358
2359 let pane = self.last_active_center_pane.clone()?.upgrade()?;
2360 Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
2361 }
2362
2363 pub fn is_edited(&self) -> bool {
2364 self.window_edited
2365 }
2366
2367 pub fn add_panel<T: Panel>(
2368 &mut self,
2369 panel: Entity<T>,
2370 window: &mut Window,
2371 cx: &mut Context<Self>,
2372 ) {
2373 let focus_handle = panel.panel_focus_handle(cx);
2374 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2375 .detach();
2376
2377 let dock_position = panel.position(window, cx);
2378 let dock = self.dock_at_position(dock_position);
2379 let any_panel = panel.to_any();
2380 let persisted_size_state =
2381 self.persisted_panel_size_state(T::panel_key(), cx)
2382 .or_else(|| {
2383 load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
2384 let state = dock::PanelSizeState {
2385 size: Some(size),
2386 flex: None,
2387 };
2388 self.persist_panel_size_state(T::panel_key(), state, cx);
2389 state
2390 })
2391 });
2392
2393 dock.update(cx, |dock, cx| {
2394 let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
2395 if let Some(size_state) = persisted_size_state {
2396 dock.set_panel_size_state(&panel, size_state, cx);
2397 }
2398 index
2399 });
2400
2401 cx.emit(Event::PanelAdded(any_panel));
2402 }
2403
2404 pub fn remove_panel<T: Panel>(
2405 &mut self,
2406 panel: &Entity<T>,
2407 window: &mut Window,
2408 cx: &mut Context<Self>,
2409 ) {
2410 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2411 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2412 }
2413 }
2414
2415 pub fn status_bar(&self) -> &Entity<StatusBar> {
2416 &self.status_bar
2417 }
2418
2419 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2420 self.sidebar_focus_handle = handle;
2421 }
2422
2423 pub fn status_bar_visible(&self, cx: &App) -> bool {
2424 StatusBarSettings::get_global(cx).show
2425 }
2426
2427 pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
2428 self.multi_workspace.as_ref()
2429 }
2430
2431 pub fn set_multi_workspace(
2432 &mut self,
2433 multi_workspace: WeakEntity<MultiWorkspace>,
2434 cx: &mut App,
2435 ) {
2436 self.status_bar.update(cx, |status_bar, cx| {
2437 status_bar.set_multi_workspace(multi_workspace.clone(), cx);
2438 });
2439 self.multi_workspace = Some(multi_workspace);
2440 }
2441
2442 pub fn app_state(&self) -> &Arc<AppState> {
2443 &self.app_state
2444 }
2445
2446 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2447 self._panels_task = Some(task);
2448 }
2449
2450 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2451 self._panels_task.take()
2452 }
2453
2454 pub fn user_store(&self) -> &Entity<UserStore> {
2455 &self.app_state.user_store
2456 }
2457
2458 pub fn project(&self) -> &Entity<Project> {
2459 &self.project
2460 }
2461
2462 pub fn path_style(&self, cx: &App) -> PathStyle {
2463 self.project.read(cx).path_style(cx)
2464 }
2465
2466 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2467 let mut history: HashMap<EntityId, usize> = HashMap::default();
2468
2469 for pane_handle in &self.panes {
2470 let pane = pane_handle.read(cx);
2471
2472 for entry in pane.activation_history() {
2473 history.insert(
2474 entry.entity_id,
2475 history
2476 .get(&entry.entity_id)
2477 .cloned()
2478 .unwrap_or(0)
2479 .max(entry.timestamp),
2480 );
2481 }
2482 }
2483
2484 history
2485 }
2486
2487 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2488 let mut recent_item: Option<Entity<T>> = None;
2489 let mut recent_timestamp = 0;
2490 for pane_handle in &self.panes {
2491 let pane = pane_handle.read(cx);
2492 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2493 pane.items().map(|item| (item.item_id(), item)).collect();
2494 for entry in pane.activation_history() {
2495 if entry.timestamp > recent_timestamp
2496 && let Some(&item) = item_map.get(&entry.entity_id)
2497 && let Some(typed_item) = item.act_as::<T>(cx)
2498 {
2499 recent_timestamp = entry.timestamp;
2500 recent_item = Some(typed_item);
2501 }
2502 }
2503 }
2504 recent_item
2505 }
2506
2507 pub fn recent_navigation_history_iter(
2508 &self,
2509 cx: &App,
2510 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2511 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2512 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2513
2514 for pane in &self.panes {
2515 let pane = pane.read(cx);
2516
2517 pane.nav_history()
2518 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2519 if let Some(fs_path) = &fs_path {
2520 abs_paths_opened
2521 .entry(fs_path.clone())
2522 .or_default()
2523 .insert(project_path.clone());
2524 }
2525 let timestamp = entry.timestamp;
2526 match history.entry(project_path) {
2527 hash_map::Entry::Occupied(mut entry) => {
2528 let (_, old_timestamp) = entry.get();
2529 if ×tamp > old_timestamp {
2530 entry.insert((fs_path, timestamp));
2531 }
2532 }
2533 hash_map::Entry::Vacant(entry) => {
2534 entry.insert((fs_path, timestamp));
2535 }
2536 }
2537 });
2538
2539 if let Some(item) = pane.active_item()
2540 && let Some(project_path) = item.project_path(cx)
2541 {
2542 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2543
2544 if let Some(fs_path) = &fs_path {
2545 abs_paths_opened
2546 .entry(fs_path.clone())
2547 .or_default()
2548 .insert(project_path.clone());
2549 }
2550
2551 history.insert(project_path, (fs_path, std::usize::MAX));
2552 }
2553 }
2554
2555 history
2556 .into_iter()
2557 .sorted_by_key(|(_, (_, order))| *order)
2558 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2559 .rev()
2560 .filter(move |(history_path, abs_path)| {
2561 let latest_project_path_opened = abs_path
2562 .as_ref()
2563 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2564 .and_then(|project_paths| {
2565 project_paths
2566 .iter()
2567 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2568 });
2569
2570 latest_project_path_opened.is_none_or(|path| path == history_path)
2571 })
2572 }
2573
2574 pub fn recent_navigation_history(
2575 &self,
2576 limit: Option<usize>,
2577 cx: &App,
2578 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2579 self.recent_navigation_history_iter(cx)
2580 .take(limit.unwrap_or(usize::MAX))
2581 .collect()
2582 }
2583
2584 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2585 for pane in &self.panes {
2586 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2587 }
2588 }
2589
2590 fn navigate_history(
2591 &mut self,
2592 pane: WeakEntity<Pane>,
2593 mode: NavigationMode,
2594 window: &mut Window,
2595 cx: &mut Context<Workspace>,
2596 ) -> Task<Result<()>> {
2597 self.navigate_history_impl(
2598 pane,
2599 mode,
2600 window,
2601 &mut |history, cx| history.pop(mode, cx),
2602 cx,
2603 )
2604 }
2605
2606 fn navigate_tag_history(
2607 &mut self,
2608 pane: WeakEntity<Pane>,
2609 mode: TagNavigationMode,
2610 window: &mut Window,
2611 cx: &mut Context<Workspace>,
2612 ) -> Task<Result<()>> {
2613 self.navigate_history_impl(
2614 pane,
2615 NavigationMode::Normal,
2616 window,
2617 &mut |history, _cx| history.pop_tag(mode),
2618 cx,
2619 )
2620 }
2621
2622 fn navigate_history_impl(
2623 &mut self,
2624 pane: WeakEntity<Pane>,
2625 mode: NavigationMode,
2626 window: &mut Window,
2627 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2628 cx: &mut Context<Workspace>,
2629 ) -> Task<Result<()>> {
2630 let to_load = if let Some(pane) = pane.upgrade() {
2631 pane.update(cx, |pane, cx| {
2632 window.focus(&pane.focus_handle(cx), cx);
2633 loop {
2634 // Retrieve the weak item handle from the history.
2635 let entry = cb(pane.nav_history_mut(), cx)?;
2636
2637 // If the item is still present in this pane, then activate it.
2638 if let Some(index) = entry
2639 .item
2640 .upgrade()
2641 .and_then(|v| pane.index_for_item(v.as_ref()))
2642 {
2643 let prev_active_item_index = pane.active_item_index();
2644 pane.nav_history_mut().set_mode(mode);
2645 pane.activate_item(index, true, true, window, cx);
2646 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2647
2648 let mut navigated = prev_active_item_index != pane.active_item_index();
2649 if let Some(data) = entry.data {
2650 navigated |= pane.active_item()?.navigate(data, window, cx);
2651 }
2652
2653 if navigated {
2654 break None;
2655 }
2656 } else {
2657 // If the item is no longer present in this pane, then retrieve its
2658 // path info in order to reopen it.
2659 break pane
2660 .nav_history()
2661 .path_for_item(entry.item.id())
2662 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2663 }
2664 }
2665 })
2666 } else {
2667 None
2668 };
2669
2670 if let Some((project_path, abs_path, entry)) = to_load {
2671 // If the item was no longer present, then load it again from its previous path, first try the local path
2672 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2673
2674 cx.spawn_in(window, async move |workspace, cx| {
2675 let open_by_project_path = open_by_project_path.await;
2676 let mut navigated = false;
2677 match open_by_project_path
2678 .with_context(|| format!("Navigating to {project_path:?}"))
2679 {
2680 Ok((project_entry_id, build_item)) => {
2681 let prev_active_item_id = pane.update(cx, |pane, _| {
2682 pane.nav_history_mut().set_mode(mode);
2683 pane.active_item().map(|p| p.item_id())
2684 })?;
2685
2686 pane.update_in(cx, |pane, window, cx| {
2687 let item = pane.open_item(
2688 project_entry_id,
2689 project_path,
2690 true,
2691 entry.is_preview,
2692 true,
2693 None,
2694 window, cx,
2695 build_item,
2696 );
2697 navigated |= Some(item.item_id()) != prev_active_item_id;
2698 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2699 if let Some(data) = entry.data {
2700 navigated |= item.navigate(data, window, cx);
2701 }
2702 })?;
2703 }
2704 Err(open_by_project_path_e) => {
2705 // Fall back to opening by abs path, in case an external file was opened and closed,
2706 // and its worktree is now dropped
2707 if let Some(abs_path) = abs_path {
2708 let prev_active_item_id = pane.update(cx, |pane, _| {
2709 pane.nav_history_mut().set_mode(mode);
2710 pane.active_item().map(|p| p.item_id())
2711 })?;
2712 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2713 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2714 })?;
2715 match open_by_abs_path
2716 .await
2717 .with_context(|| format!("Navigating to {abs_path:?}"))
2718 {
2719 Ok(item) => {
2720 pane.update_in(cx, |pane, window, cx| {
2721 navigated |= Some(item.item_id()) != prev_active_item_id;
2722 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2723 if let Some(data) = entry.data {
2724 navigated |= item.navigate(data, window, cx);
2725 }
2726 })?;
2727 }
2728 Err(open_by_abs_path_e) => {
2729 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2730 }
2731 }
2732 }
2733 }
2734 }
2735
2736 if !navigated {
2737 workspace
2738 .update_in(cx, |workspace, window, cx| {
2739 Self::navigate_history(workspace, pane, mode, window, cx)
2740 })?
2741 .await?;
2742 }
2743
2744 Ok(())
2745 })
2746 } else {
2747 Task::ready(Ok(()))
2748 }
2749 }
2750
2751 pub fn go_back(
2752 &mut self,
2753 pane: WeakEntity<Pane>,
2754 window: &mut Window,
2755 cx: &mut Context<Workspace>,
2756 ) -> Task<Result<()>> {
2757 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2758 }
2759
2760 pub fn go_forward(
2761 &mut self,
2762 pane: WeakEntity<Pane>,
2763 window: &mut Window,
2764 cx: &mut Context<Workspace>,
2765 ) -> Task<Result<()>> {
2766 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2767 }
2768
2769 pub fn reopen_closed_item(
2770 &mut self,
2771 window: &mut Window,
2772 cx: &mut Context<Workspace>,
2773 ) -> Task<Result<()>> {
2774 self.navigate_history(
2775 self.active_pane().downgrade(),
2776 NavigationMode::ReopeningClosedItem,
2777 window,
2778 cx,
2779 )
2780 }
2781
2782 pub fn client(&self) -> &Arc<Client> {
2783 &self.app_state.client
2784 }
2785
2786 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2787 self.titlebar_item = Some(item);
2788 cx.notify();
2789 }
2790
2791 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2792 self.on_prompt_for_new_path = Some(prompt)
2793 }
2794
2795 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2796 self.on_prompt_for_open_path = Some(prompt)
2797 }
2798
2799 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2800 self.terminal_provider = Some(Box::new(provider));
2801 }
2802
2803 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2804 self.debugger_provider = Some(Arc::new(provider));
2805 }
2806
2807 pub fn set_open_in_dev_container(&mut self, value: bool) {
2808 self.open_in_dev_container = value;
2809 }
2810
2811 pub fn open_in_dev_container(&self) -> bool {
2812 self.open_in_dev_container
2813 }
2814
2815 pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
2816 self._dev_container_task = Some(task);
2817 }
2818
2819 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2820 self.debugger_provider.clone()
2821 }
2822
2823 pub fn prompt_for_open_path(
2824 &mut self,
2825 path_prompt_options: PathPromptOptions,
2826 lister: DirectoryLister,
2827 window: &mut Window,
2828 cx: &mut Context<Self>,
2829 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2830 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2831 let prompt = self.on_prompt_for_open_path.take().unwrap();
2832 let rx = prompt(self, lister, window, cx);
2833 self.on_prompt_for_open_path = Some(prompt);
2834 rx
2835 } else {
2836 let (tx, rx) = oneshot::channel();
2837 let abs_path = cx.prompt_for_paths(path_prompt_options);
2838
2839 cx.spawn_in(window, async move |workspace, cx| {
2840 let Ok(result) = abs_path.await else {
2841 return Ok(());
2842 };
2843
2844 match result {
2845 Ok(result) => {
2846 tx.send(result).ok();
2847 }
2848 Err(err) => {
2849 let rx = workspace.update_in(cx, |workspace, window, cx| {
2850 workspace.show_portal_error(err.to_string(), cx);
2851 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2852 let rx = prompt(workspace, lister, window, cx);
2853 workspace.on_prompt_for_open_path = Some(prompt);
2854 rx
2855 })?;
2856 if let Ok(path) = rx.await {
2857 tx.send(path).ok();
2858 }
2859 }
2860 };
2861 anyhow::Ok(())
2862 })
2863 .detach();
2864
2865 rx
2866 }
2867 }
2868
2869 pub fn prompt_for_new_path(
2870 &mut self,
2871 lister: DirectoryLister,
2872 suggested_name: Option<String>,
2873 window: &mut Window,
2874 cx: &mut Context<Self>,
2875 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2876 if self.project.read(cx).is_via_collab()
2877 || self.project.read(cx).is_via_remote_server()
2878 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2879 {
2880 let prompt = self.on_prompt_for_new_path.take().unwrap();
2881 let rx = prompt(self, lister, suggested_name, window, cx);
2882 self.on_prompt_for_new_path = Some(prompt);
2883 return rx;
2884 }
2885
2886 let (tx, rx) = oneshot::channel();
2887 cx.spawn_in(window, async move |workspace, cx| {
2888 let abs_path = workspace.update(cx, |workspace, cx| {
2889 let relative_to = workspace
2890 .most_recent_active_path(cx)
2891 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2892 .or_else(|| {
2893 let project = workspace.project.read(cx);
2894 project.visible_worktrees(cx).find_map(|worktree| {
2895 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2896 })
2897 })
2898 .or_else(std::env::home_dir)
2899 .unwrap_or_else(|| PathBuf::from(""));
2900 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2901 })?;
2902 let abs_path = match abs_path.await? {
2903 Ok(path) => path,
2904 Err(err) => {
2905 let rx = workspace.update_in(cx, |workspace, window, cx| {
2906 workspace.show_portal_error(err.to_string(), cx);
2907
2908 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2909 let rx = prompt(workspace, lister, suggested_name, window, cx);
2910 workspace.on_prompt_for_new_path = Some(prompt);
2911 rx
2912 })?;
2913 if let Ok(path) = rx.await {
2914 tx.send(path).ok();
2915 }
2916 return anyhow::Ok(());
2917 }
2918 };
2919
2920 tx.send(abs_path.map(|path| vec![path])).ok();
2921 anyhow::Ok(())
2922 })
2923 .detach();
2924
2925 rx
2926 }
2927
2928 pub fn titlebar_item(&self) -> Option<AnyView> {
2929 self.titlebar_item.clone()
2930 }
2931
2932 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2933 /// When set, git-related operations should use this worktree instead of deriving
2934 /// the active worktree from the focused file.
2935 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2936 self.active_worktree_override
2937 }
2938
2939 pub fn set_active_worktree_override(
2940 &mut self,
2941 worktree_id: Option<WorktreeId>,
2942 cx: &mut Context<Self>,
2943 ) {
2944 self.active_worktree_override = worktree_id;
2945 cx.notify();
2946 }
2947
2948 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2949 self.active_worktree_override = None;
2950 cx.notify();
2951 }
2952
2953 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2954 ///
2955 /// If the given workspace has a local project, then it will be passed
2956 /// to the callback. Otherwise, a new empty window will be created.
2957 pub fn with_local_workspace<T, F>(
2958 &mut self,
2959 window: &mut Window,
2960 cx: &mut Context<Self>,
2961 callback: F,
2962 ) -> Task<Result<T>>
2963 where
2964 T: 'static,
2965 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2966 {
2967 if self.project.read(cx).is_local() {
2968 Task::ready(Ok(callback(self, window, cx)))
2969 } else {
2970 let env = self.project.read(cx).cli_environment(cx);
2971 let task = Self::new_local(
2972 Vec::new(),
2973 self.app_state.clone(),
2974 None,
2975 env,
2976 None,
2977 OpenMode::Activate,
2978 cx,
2979 );
2980 cx.spawn_in(window, async move |_vh, cx| {
2981 let OpenResult {
2982 window: multi_workspace_window,
2983 ..
2984 } = task.await?;
2985 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2986 let workspace = multi_workspace.workspace().clone();
2987 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2988 })
2989 })
2990 }
2991 }
2992
2993 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2994 ///
2995 /// If the given workspace has a local project, then it will be passed
2996 /// to the callback. Otherwise, a new empty window will be created.
2997 pub fn with_local_or_wsl_workspace<T, F>(
2998 &mut self,
2999 window: &mut Window,
3000 cx: &mut Context<Self>,
3001 callback: F,
3002 ) -> Task<Result<T>>
3003 where
3004 T: 'static,
3005 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
3006 {
3007 let project = self.project.read(cx);
3008 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
3009 Task::ready(Ok(callback(self, window, cx)))
3010 } else {
3011 let env = self.project.read(cx).cli_environment(cx);
3012 let task = Self::new_local(
3013 Vec::new(),
3014 self.app_state.clone(),
3015 None,
3016 env,
3017 None,
3018 OpenMode::Activate,
3019 cx,
3020 );
3021 cx.spawn_in(window, async move |_vh, cx| {
3022 let OpenResult {
3023 window: multi_workspace_window,
3024 ..
3025 } = task.await?;
3026 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
3027 let workspace = multi_workspace.workspace().clone();
3028 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3029 })
3030 })
3031 }
3032 }
3033
3034 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3035 self.project.read(cx).worktrees(cx)
3036 }
3037
3038 pub fn visible_worktrees<'a>(
3039 &self,
3040 cx: &'a App,
3041 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3042 self.project.read(cx).visible_worktrees(cx)
3043 }
3044
3045 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
3046 let futures = self
3047 .worktrees(cx)
3048 .filter_map(|worktree| worktree.read(cx).as_local())
3049 .map(|worktree| worktree.scan_complete())
3050 .collect::<Vec<_>>();
3051 async move {
3052 for future in futures {
3053 future.await;
3054 }
3055 }
3056 }
3057
3058 pub fn close_global(cx: &mut App) {
3059 cx.defer(|cx| {
3060 cx.windows().iter().find(|window| {
3061 window
3062 .update(cx, |_, window, _| {
3063 if window.is_window_active() {
3064 //This can only get called when the window's project connection has been lost
3065 //so we don't need to prompt the user for anything and instead just close the window
3066 window.remove_window();
3067 true
3068 } else {
3069 false
3070 }
3071 })
3072 .unwrap_or(false)
3073 });
3074 });
3075 }
3076
3077 pub fn move_focused_panel_to_next_position(
3078 &mut self,
3079 _: &MoveFocusedPanelToNextPosition,
3080 window: &mut Window,
3081 cx: &mut Context<Self>,
3082 ) {
3083 let docks = self.all_docks();
3084 let active_dock = docks
3085 .into_iter()
3086 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
3087
3088 if let Some(dock) = active_dock {
3089 dock.update(cx, |dock, cx| {
3090 let active_panel = dock
3091 .active_panel()
3092 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
3093
3094 if let Some(panel) = active_panel {
3095 panel.move_to_next_position(window, cx);
3096 }
3097 })
3098 }
3099 }
3100
3101 pub fn prepare_to_close(
3102 &mut self,
3103 close_intent: CloseIntent,
3104 window: &mut Window,
3105 cx: &mut Context<Self>,
3106 ) -> Task<Result<bool>> {
3107 let active_call = self.active_global_call();
3108
3109 cx.spawn_in(window, async move |this, cx| {
3110 this.update(cx, |this, _| {
3111 if close_intent == CloseIntent::CloseWindow {
3112 this.removing = true;
3113 }
3114 })?;
3115
3116 let workspace_count = cx.update(|_window, cx| {
3117 cx.windows()
3118 .iter()
3119 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
3120 .count()
3121 })?;
3122
3123 #[cfg(target_os = "macos")]
3124 let save_last_workspace = false;
3125
3126 // On Linux and Windows, closing the last window should restore the last workspace.
3127 #[cfg(not(target_os = "macos"))]
3128 let save_last_workspace = {
3129 let remaining_workspaces = cx.update(|_window, cx| {
3130 cx.windows()
3131 .iter()
3132 .filter_map(|window| window.downcast::<MultiWorkspace>())
3133 .filter_map(|multi_workspace| {
3134 multi_workspace
3135 .update(cx, |multi_workspace, _, cx| {
3136 multi_workspace.workspace().read(cx).removing
3137 })
3138 .ok()
3139 })
3140 .filter(|removing| !removing)
3141 .count()
3142 })?;
3143
3144 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
3145 };
3146
3147 if let Some(active_call) = active_call
3148 && workspace_count == 1
3149 && cx
3150 .update(|_window, cx| active_call.0.is_in_room(cx))
3151 .unwrap_or(false)
3152 {
3153 if close_intent == CloseIntent::CloseWindow {
3154 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
3155 let answer = cx.update(|window, cx| {
3156 window.prompt(
3157 PromptLevel::Warning,
3158 "Do you want to leave the current call?",
3159 None,
3160 &["Close window and hang up", "Cancel"],
3161 cx,
3162 )
3163 })?;
3164
3165 if answer.await.log_err() == Some(1) {
3166 return anyhow::Ok(false);
3167 } else {
3168 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
3169 task.await.log_err();
3170 }
3171 }
3172 }
3173 if close_intent == CloseIntent::ReplaceWindow {
3174 _ = cx.update(|_window, cx| {
3175 let multi_workspace = cx
3176 .windows()
3177 .iter()
3178 .filter_map(|window| window.downcast::<MultiWorkspace>())
3179 .next()
3180 .unwrap();
3181 let project = multi_workspace
3182 .read(cx)?
3183 .workspace()
3184 .read(cx)
3185 .project
3186 .clone();
3187 if project.read(cx).is_shared() {
3188 active_call.0.unshare_project(project, cx)?;
3189 }
3190 Ok::<_, anyhow::Error>(())
3191 });
3192 }
3193 }
3194
3195 let save_result = this
3196 .update_in(cx, |this, window, cx| {
3197 this.save_all_internal(SaveIntent::Close, window, cx)
3198 })?
3199 .await;
3200
3201 // If we're not quitting, but closing, we remove the workspace from
3202 // the current session.
3203 if close_intent != CloseIntent::Quit
3204 && !save_last_workspace
3205 && save_result.as_ref().is_ok_and(|&res| res)
3206 {
3207 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
3208 .await;
3209 }
3210
3211 save_result
3212 })
3213 }
3214
3215 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
3216 self.save_all_internal(
3217 action.save_intent.unwrap_or(SaveIntent::SaveAll),
3218 window,
3219 cx,
3220 )
3221 .detach_and_log_err(cx);
3222 }
3223
3224 fn send_keystrokes(
3225 &mut self,
3226 action: &SendKeystrokes,
3227 window: &mut Window,
3228 cx: &mut Context<Self>,
3229 ) {
3230 let keystrokes: Vec<Keystroke> = action
3231 .0
3232 .split(' ')
3233 .flat_map(|k| Keystroke::parse(k).log_err())
3234 .map(|k| {
3235 cx.keyboard_mapper()
3236 .map_key_equivalent(k, false)
3237 .inner()
3238 .clone()
3239 })
3240 .collect();
3241 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
3242 }
3243
3244 pub fn send_keystrokes_impl(
3245 &mut self,
3246 keystrokes: Vec<Keystroke>,
3247 window: &mut Window,
3248 cx: &mut Context<Self>,
3249 ) -> Shared<Task<()>> {
3250 let mut state = self.dispatching_keystrokes.borrow_mut();
3251 if !state.dispatched.insert(keystrokes.clone()) {
3252 cx.propagate();
3253 return state.task.clone().unwrap();
3254 }
3255
3256 state.queue.extend(keystrokes);
3257
3258 let keystrokes = self.dispatching_keystrokes.clone();
3259 if state.task.is_none() {
3260 state.task = Some(
3261 window
3262 .spawn(cx, async move |cx| {
3263 // limit to 100 keystrokes to avoid infinite recursion.
3264 for _ in 0..100 {
3265 let keystroke = {
3266 let mut state = keystrokes.borrow_mut();
3267 let Some(keystroke) = state.queue.pop_front() else {
3268 state.dispatched.clear();
3269 state.task.take();
3270 return;
3271 };
3272 keystroke
3273 };
3274 cx.update(|window, cx| {
3275 let focused = window.focused(cx);
3276 window.dispatch_keystroke(keystroke.clone(), cx);
3277 if window.focused(cx) != focused {
3278 // dispatch_keystroke may cause the focus to change.
3279 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3280 // And we need that to happen before the next keystroke to keep vim mode happy...
3281 // (Note that the tests always do this implicitly, so you must manually test with something like:
3282 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3283 // )
3284 window.draw(cx).clear();
3285 }
3286 })
3287 .ok();
3288
3289 // Yield between synthetic keystrokes so deferred focus and
3290 // other effects can settle before dispatching the next key.
3291 yield_now().await;
3292 }
3293
3294 *keystrokes.borrow_mut() = Default::default();
3295 log::error!("over 100 keystrokes passed to send_keystrokes");
3296 })
3297 .shared(),
3298 );
3299 }
3300 state.task.clone().unwrap()
3301 }
3302
3303 fn save_all_internal(
3304 &mut self,
3305 mut save_intent: SaveIntent,
3306 window: &mut Window,
3307 cx: &mut Context<Self>,
3308 ) -> Task<Result<bool>> {
3309 if self.project.read(cx).is_disconnected(cx) {
3310 return Task::ready(Ok(true));
3311 }
3312 let dirty_items = self
3313 .panes
3314 .iter()
3315 .flat_map(|pane| {
3316 pane.read(cx).items().filter_map(|item| {
3317 if item.is_dirty(cx) {
3318 item.tab_content_text(0, cx);
3319 Some((pane.downgrade(), item.boxed_clone()))
3320 } else {
3321 None
3322 }
3323 })
3324 })
3325 .collect::<Vec<_>>();
3326
3327 let project = self.project.clone();
3328 cx.spawn_in(window, async move |workspace, cx| {
3329 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3330 let (serialize_tasks, remaining_dirty_items) =
3331 workspace.update_in(cx, |workspace, window, cx| {
3332 let mut remaining_dirty_items = Vec::new();
3333 let mut serialize_tasks = Vec::new();
3334 for (pane, item) in dirty_items {
3335 if let Some(task) = item
3336 .to_serializable_item_handle(cx)
3337 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3338 {
3339 serialize_tasks.push(task);
3340 } else {
3341 remaining_dirty_items.push((pane, item));
3342 }
3343 }
3344 (serialize_tasks, remaining_dirty_items)
3345 })?;
3346
3347 futures::future::try_join_all(serialize_tasks).await?;
3348
3349 if !remaining_dirty_items.is_empty() {
3350 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3351 }
3352
3353 if remaining_dirty_items.len() > 1 {
3354 let answer = workspace.update_in(cx, |_, window, cx| {
3355 let detail = Pane::file_names_for_prompt(
3356 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3357 cx,
3358 );
3359 window.prompt(
3360 PromptLevel::Warning,
3361 "Do you want to save all changes in the following files?",
3362 Some(&detail),
3363 &["Save all", "Discard all", "Cancel"],
3364 cx,
3365 )
3366 })?;
3367 match answer.await.log_err() {
3368 Some(0) => save_intent = SaveIntent::SaveAll,
3369 Some(1) => save_intent = SaveIntent::Skip,
3370 Some(2) => return Ok(false),
3371 _ => {}
3372 }
3373 }
3374
3375 remaining_dirty_items
3376 } else {
3377 dirty_items
3378 };
3379
3380 for (pane, item) in dirty_items {
3381 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3382 (
3383 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3384 item.project_entry_ids(cx),
3385 )
3386 })?;
3387 if (singleton || !project_entry_ids.is_empty())
3388 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3389 {
3390 return Ok(false);
3391 }
3392 }
3393 Ok(true)
3394 })
3395 }
3396
3397 pub fn open_workspace_for_paths(
3398 &mut self,
3399 // replace_current_window: bool,
3400 mut open_mode: OpenMode,
3401 paths: Vec<PathBuf>,
3402 window: &mut Window,
3403 cx: &mut Context<Self>,
3404 ) -> Task<Result<Entity<Workspace>>> {
3405 let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
3406 let is_remote = self.project.read(cx).is_via_collab();
3407 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3408 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3409
3410 let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
3411 if workspace_is_empty {
3412 open_mode = OpenMode::Activate;
3413 }
3414
3415 let app_state = self.app_state.clone();
3416
3417 cx.spawn(async move |_, cx| {
3418 let OpenResult { workspace, .. } = cx
3419 .update(|cx| {
3420 open_paths(
3421 &paths,
3422 app_state,
3423 OpenOptions {
3424 requesting_window,
3425 open_mode,
3426 ..Default::default()
3427 },
3428 cx,
3429 )
3430 })
3431 .await?;
3432 Ok(workspace)
3433 })
3434 }
3435
3436 #[allow(clippy::type_complexity)]
3437 pub fn open_paths(
3438 &mut self,
3439 mut abs_paths: Vec<PathBuf>,
3440 options: OpenOptions,
3441 pane: Option<WeakEntity<Pane>>,
3442 window: &mut Window,
3443 cx: &mut Context<Self>,
3444 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3445 let fs = self.app_state.fs.clone();
3446
3447 let caller_ordered_abs_paths = abs_paths.clone();
3448
3449 // Sort the paths to ensure we add worktrees for parents before their children.
3450 abs_paths.sort_unstable();
3451 cx.spawn_in(window, async move |this, cx| {
3452 let mut tasks = Vec::with_capacity(abs_paths.len());
3453
3454 for abs_path in &abs_paths {
3455 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3456 OpenVisible::All => Some(true),
3457 OpenVisible::None => Some(false),
3458 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3459 Some(Some(metadata)) => Some(!metadata.is_dir),
3460 Some(None) => Some(true),
3461 None => None,
3462 },
3463 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3464 Some(Some(metadata)) => Some(metadata.is_dir),
3465 Some(None) => Some(false),
3466 None => None,
3467 },
3468 };
3469 let project_path = match visible {
3470 Some(visible) => match this
3471 .update(cx, |this, cx| {
3472 Workspace::project_path_for_path(
3473 this.project.clone(),
3474 abs_path,
3475 visible,
3476 cx,
3477 )
3478 })
3479 .log_err()
3480 {
3481 Some(project_path) => project_path.await.log_err(),
3482 None => None,
3483 },
3484 None => None,
3485 };
3486
3487 let this = this.clone();
3488 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3489 let fs = fs.clone();
3490 let pane = pane.clone();
3491 let task = cx.spawn(async move |cx| {
3492 let (_worktree, project_path) = project_path?;
3493 if fs.is_dir(&abs_path).await {
3494 // Opening a directory should not race to update the active entry.
3495 // We'll select/reveal a deterministic final entry after all paths finish opening.
3496 None
3497 } else {
3498 Some(
3499 this.update_in(cx, |this, window, cx| {
3500 this.open_path(
3501 project_path,
3502 pane,
3503 options.focus.unwrap_or(true),
3504 window,
3505 cx,
3506 )
3507 })
3508 .ok()?
3509 .await,
3510 )
3511 }
3512 });
3513 tasks.push(task);
3514 }
3515
3516 let results = futures::future::join_all(tasks).await;
3517
3518 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3519 let mut winner: Option<(PathBuf, bool)> = None;
3520 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3521 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3522 if !metadata.is_dir {
3523 winner = Some((abs_path, false));
3524 break;
3525 }
3526 if winner.is_none() {
3527 winner = Some((abs_path, true));
3528 }
3529 } else if winner.is_none() {
3530 winner = Some((abs_path, false));
3531 }
3532 }
3533
3534 // Compute the winner entry id on the foreground thread and emit once, after all
3535 // paths finish opening. This avoids races between concurrently-opening paths
3536 // (directories in particular) and makes the resulting project panel selection
3537 // deterministic.
3538 if let Some((winner_abs_path, winner_is_dir)) = winner {
3539 'emit_winner: {
3540 let winner_abs_path: Arc<Path> =
3541 SanitizedPath::new(&winner_abs_path).as_path().into();
3542
3543 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3544 OpenVisible::All => true,
3545 OpenVisible::None => false,
3546 OpenVisible::OnlyFiles => !winner_is_dir,
3547 OpenVisible::OnlyDirectories => winner_is_dir,
3548 };
3549
3550 let Some(worktree_task) = this
3551 .update(cx, |workspace, cx| {
3552 workspace.project.update(cx, |project, cx| {
3553 project.find_or_create_worktree(
3554 winner_abs_path.as_ref(),
3555 visible,
3556 cx,
3557 )
3558 })
3559 })
3560 .ok()
3561 else {
3562 break 'emit_winner;
3563 };
3564
3565 let Ok((worktree, _)) = worktree_task.await else {
3566 break 'emit_winner;
3567 };
3568
3569 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3570 let worktree = worktree.read(cx);
3571 let worktree_abs_path = worktree.abs_path();
3572 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3573 worktree.root_entry()
3574 } else {
3575 winner_abs_path
3576 .strip_prefix(worktree_abs_path.as_ref())
3577 .ok()
3578 .and_then(|relative_path| {
3579 let relative_path =
3580 RelPath::new(relative_path, PathStyle::local())
3581 .log_err()?;
3582 worktree.entry_for_path(&relative_path)
3583 })
3584 }?;
3585 Some(entry.id)
3586 }) else {
3587 break 'emit_winner;
3588 };
3589
3590 this.update(cx, |workspace, cx| {
3591 workspace.project.update(cx, |_, cx| {
3592 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3593 });
3594 })
3595 .ok();
3596 }
3597 }
3598
3599 results
3600 })
3601 }
3602
3603 pub fn open_resolved_path(
3604 &mut self,
3605 path: ResolvedPath,
3606 window: &mut Window,
3607 cx: &mut Context<Self>,
3608 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3609 match path {
3610 ResolvedPath::ProjectPath { project_path, .. } => {
3611 self.open_path(project_path, None, true, window, cx)
3612 }
3613 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3614 PathBuf::from(path),
3615 OpenOptions {
3616 visible: Some(OpenVisible::None),
3617 ..Default::default()
3618 },
3619 window,
3620 cx,
3621 ),
3622 }
3623 }
3624
3625 pub fn absolute_path_of_worktree(
3626 &self,
3627 worktree_id: WorktreeId,
3628 cx: &mut Context<Self>,
3629 ) -> Option<PathBuf> {
3630 self.project
3631 .read(cx)
3632 .worktree_for_id(worktree_id, cx)
3633 // TODO: use `abs_path` or `root_dir`
3634 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3635 }
3636
3637 pub fn add_folder_to_project(
3638 &mut self,
3639 _: &AddFolderToProject,
3640 window: &mut Window,
3641 cx: &mut Context<Self>,
3642 ) {
3643 let project = self.project.read(cx);
3644 if project.is_via_collab() {
3645 self.show_error(
3646 &anyhow!("You cannot add folders to someone else's project"),
3647 cx,
3648 );
3649 return;
3650 }
3651 let paths = self.prompt_for_open_path(
3652 PathPromptOptions {
3653 files: false,
3654 directories: true,
3655 multiple: true,
3656 prompt: None,
3657 },
3658 DirectoryLister::Project(self.project.clone()),
3659 window,
3660 cx,
3661 );
3662 cx.spawn_in(window, async move |this, cx| {
3663 if let Some(paths) = paths.await.log_err().flatten() {
3664 let results = this
3665 .update_in(cx, |this, window, cx| {
3666 this.open_paths(
3667 paths,
3668 OpenOptions {
3669 visible: Some(OpenVisible::All),
3670 ..Default::default()
3671 },
3672 None,
3673 window,
3674 cx,
3675 )
3676 })?
3677 .await;
3678 for result in results.into_iter().flatten() {
3679 result.log_err();
3680 }
3681 }
3682 anyhow::Ok(())
3683 })
3684 .detach_and_log_err(cx);
3685 }
3686
3687 pub fn project_path_for_path(
3688 project: Entity<Project>,
3689 abs_path: &Path,
3690 visible: bool,
3691 cx: &mut App,
3692 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3693 let entry = project.update(cx, |project, cx| {
3694 project.find_or_create_worktree(abs_path, visible, cx)
3695 });
3696 cx.spawn(async move |cx| {
3697 let (worktree, path) = entry.await?;
3698 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3699 Ok((worktree, ProjectPath { worktree_id, path }))
3700 })
3701 }
3702
3703 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3704 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3705 }
3706
3707 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3708 self.items_of_type(cx).max_by_key(|item| item.item_id())
3709 }
3710
3711 pub fn items_of_type<'a, T: Item>(
3712 &'a self,
3713 cx: &'a App,
3714 ) -> impl 'a + Iterator<Item = Entity<T>> {
3715 self.panes
3716 .iter()
3717 .flat_map(|pane| pane.read(cx).items_of_type())
3718 }
3719
3720 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3721 self.active_pane().read(cx).active_item()
3722 }
3723
3724 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3725 let item = self.active_item(cx)?;
3726 item.to_any_view().downcast::<I>().ok()
3727 }
3728
3729 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3730 self.active_item(cx).and_then(|item| item.project_path(cx))
3731 }
3732
3733 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3734 self.recent_navigation_history_iter(cx)
3735 .filter_map(|(path, abs_path)| {
3736 let worktree = self
3737 .project
3738 .read(cx)
3739 .worktree_for_id(path.worktree_id, cx)?;
3740 if worktree.read(cx).is_visible() {
3741 abs_path
3742 } else {
3743 None
3744 }
3745 })
3746 .next()
3747 }
3748
3749 pub fn save_active_item(
3750 &mut self,
3751 save_intent: SaveIntent,
3752 window: &mut Window,
3753 cx: &mut App,
3754 ) -> Task<Result<()>> {
3755 let project = self.project.clone();
3756 let pane = self.active_pane();
3757 let item = pane.read(cx).active_item();
3758 let pane = pane.downgrade();
3759
3760 window.spawn(cx, async move |cx| {
3761 if let Some(item) = item {
3762 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3763 .await
3764 .map(|_| ())
3765 } else {
3766 Ok(())
3767 }
3768 })
3769 }
3770
3771 pub fn close_inactive_items_and_panes(
3772 &mut self,
3773 action: &CloseInactiveTabsAndPanes,
3774 window: &mut Window,
3775 cx: &mut Context<Self>,
3776 ) {
3777 if let Some(task) = self.close_all_internal(
3778 true,
3779 action.save_intent.unwrap_or(SaveIntent::Close),
3780 window,
3781 cx,
3782 ) {
3783 task.detach_and_log_err(cx)
3784 }
3785 }
3786
3787 pub fn close_all_items_and_panes(
3788 &mut self,
3789 action: &CloseAllItemsAndPanes,
3790 window: &mut Window,
3791 cx: &mut Context<Self>,
3792 ) {
3793 if let Some(task) = self.close_all_internal(
3794 false,
3795 action.save_intent.unwrap_or(SaveIntent::Close),
3796 window,
3797 cx,
3798 ) {
3799 task.detach_and_log_err(cx)
3800 }
3801 }
3802
3803 /// Closes the active item across all panes.
3804 pub fn close_item_in_all_panes(
3805 &mut self,
3806 action: &CloseItemInAllPanes,
3807 window: &mut Window,
3808 cx: &mut Context<Self>,
3809 ) {
3810 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3811 return;
3812 };
3813
3814 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3815 let close_pinned = action.close_pinned;
3816
3817 if let Some(project_path) = active_item.project_path(cx) {
3818 self.close_items_with_project_path(
3819 &project_path,
3820 save_intent,
3821 close_pinned,
3822 window,
3823 cx,
3824 );
3825 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3826 let item_id = active_item.item_id();
3827 self.active_pane().update(cx, |pane, cx| {
3828 pane.close_item_by_id(item_id, save_intent, window, cx)
3829 .detach_and_log_err(cx);
3830 });
3831 }
3832 }
3833
3834 /// Closes all items with the given project path across all panes.
3835 pub fn close_items_with_project_path(
3836 &mut self,
3837 project_path: &ProjectPath,
3838 save_intent: SaveIntent,
3839 close_pinned: bool,
3840 window: &mut Window,
3841 cx: &mut Context<Self>,
3842 ) {
3843 let panes = self.panes().to_vec();
3844 for pane in panes {
3845 pane.update(cx, |pane, cx| {
3846 pane.close_items_for_project_path(
3847 project_path,
3848 save_intent,
3849 close_pinned,
3850 window,
3851 cx,
3852 )
3853 .detach_and_log_err(cx);
3854 });
3855 }
3856 }
3857
3858 fn close_all_internal(
3859 &mut self,
3860 retain_active_pane: bool,
3861 save_intent: SaveIntent,
3862 window: &mut Window,
3863 cx: &mut Context<Self>,
3864 ) -> Option<Task<Result<()>>> {
3865 let current_pane = self.active_pane();
3866
3867 let mut tasks = Vec::new();
3868
3869 if retain_active_pane {
3870 let current_pane_close = current_pane.update(cx, |pane, cx| {
3871 pane.close_other_items(
3872 &CloseOtherItems {
3873 save_intent: None,
3874 close_pinned: false,
3875 },
3876 None,
3877 window,
3878 cx,
3879 )
3880 });
3881
3882 tasks.push(current_pane_close);
3883 }
3884
3885 for pane in self.panes() {
3886 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3887 continue;
3888 }
3889
3890 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3891 pane.close_all_items(
3892 &CloseAllItems {
3893 save_intent: Some(save_intent),
3894 close_pinned: false,
3895 },
3896 window,
3897 cx,
3898 )
3899 });
3900
3901 tasks.push(close_pane_items)
3902 }
3903
3904 if tasks.is_empty() {
3905 None
3906 } else {
3907 Some(cx.spawn_in(window, async move |_, _| {
3908 for task in tasks {
3909 task.await?
3910 }
3911 Ok(())
3912 }))
3913 }
3914 }
3915
3916 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3917 self.dock_at_position(position).read(cx).is_open()
3918 }
3919
3920 pub fn toggle_dock(
3921 &mut self,
3922 dock_side: DockPosition,
3923 window: &mut Window,
3924 cx: &mut Context<Self>,
3925 ) {
3926 let mut focus_center = false;
3927 let mut reveal_dock = false;
3928
3929 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3930 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3931
3932 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3933 telemetry::event!(
3934 "Panel Button Clicked",
3935 name = panel.persistent_name(),
3936 toggle_state = !was_visible
3937 );
3938 }
3939 if was_visible {
3940 self.save_open_dock_positions(cx);
3941 }
3942
3943 let dock = self.dock_at_position(dock_side);
3944 dock.update(cx, |dock, cx| {
3945 dock.set_open(!was_visible, window, cx);
3946
3947 if dock.active_panel().is_none() {
3948 let Some(panel_ix) = dock
3949 .first_enabled_panel_idx(cx)
3950 .log_with_level(log::Level::Info)
3951 else {
3952 return;
3953 };
3954 dock.activate_panel(panel_ix, window, cx);
3955 }
3956
3957 if let Some(active_panel) = dock.active_panel() {
3958 if was_visible {
3959 if active_panel
3960 .panel_focus_handle(cx)
3961 .contains_focused(window, cx)
3962 {
3963 focus_center = true;
3964 }
3965 } else {
3966 let focus_handle = &active_panel.panel_focus_handle(cx);
3967 window.focus(focus_handle, cx);
3968 reveal_dock = true;
3969 }
3970 }
3971 });
3972
3973 if reveal_dock {
3974 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3975 }
3976
3977 if focus_center {
3978 self.active_pane
3979 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3980 }
3981
3982 cx.notify();
3983 self.serialize_workspace(window, cx);
3984 }
3985
3986 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3987 self.all_docks().into_iter().find(|&dock| {
3988 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3989 })
3990 }
3991
3992 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3993 if let Some(dock) = self.active_dock(window, cx).cloned() {
3994 self.save_open_dock_positions(cx);
3995 dock.update(cx, |dock, cx| {
3996 dock.set_open(false, window, cx);
3997 });
3998 return true;
3999 }
4000 false
4001 }
4002
4003 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4004 self.save_open_dock_positions(cx);
4005 for dock in self.all_docks() {
4006 dock.update(cx, |dock, cx| {
4007 dock.set_open(false, window, cx);
4008 });
4009 }
4010
4011 cx.focus_self(window);
4012 cx.notify();
4013 self.serialize_workspace(window, cx);
4014 }
4015
4016 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
4017 self.all_docks()
4018 .into_iter()
4019 .filter_map(|dock| {
4020 let dock_ref = dock.read(cx);
4021 if dock_ref.is_open() {
4022 Some(dock_ref.position())
4023 } else {
4024 None
4025 }
4026 })
4027 .collect()
4028 }
4029
4030 /// Saves the positions of currently open docks.
4031 ///
4032 /// Updates `last_open_dock_positions` with positions of all currently open
4033 /// docks, to later be restored by the 'Toggle All Docks' action.
4034 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
4035 let open_dock_positions = self.get_open_dock_positions(cx);
4036 if !open_dock_positions.is_empty() {
4037 self.last_open_dock_positions = open_dock_positions;
4038 }
4039 }
4040
4041 /// Toggles all docks between open and closed states.
4042 ///
4043 /// If any docks are open, closes all and remembers their positions. If all
4044 /// docks are closed, restores the last remembered dock configuration.
4045 fn toggle_all_docks(
4046 &mut self,
4047 _: &ToggleAllDocks,
4048 window: &mut Window,
4049 cx: &mut Context<Self>,
4050 ) {
4051 let open_dock_positions = self.get_open_dock_positions(cx);
4052
4053 if !open_dock_positions.is_empty() {
4054 self.close_all_docks(window, cx);
4055 } else if !self.last_open_dock_positions.is_empty() {
4056 self.restore_last_open_docks(window, cx);
4057 }
4058 }
4059
4060 /// Reopens docks from the most recently remembered configuration.
4061 ///
4062 /// Opens all docks whose positions are stored in `last_open_dock_positions`
4063 /// and clears the stored positions.
4064 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4065 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
4066
4067 for position in positions_to_open {
4068 let dock = self.dock_at_position(position);
4069 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
4070 }
4071
4072 cx.focus_self(window);
4073 cx.notify();
4074 self.serialize_workspace(window, cx);
4075 }
4076
4077 /// Transfer focus to the panel of the given type.
4078 pub fn focus_panel<T: Panel>(
4079 &mut self,
4080 window: &mut Window,
4081 cx: &mut Context<Self>,
4082 ) -> Option<Entity<T>> {
4083 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
4084 panel.to_any().downcast().ok()
4085 }
4086
4087 /// Focus the panel of the given type if it isn't already focused. If it is
4088 /// already focused, then transfer focus back to the workspace center.
4089 /// When the `close_panel_on_toggle` setting is enabled, also closes the
4090 /// panel when transferring focus back to the center.
4091 pub fn toggle_panel_focus<T: Panel>(
4092 &mut self,
4093 window: &mut Window,
4094 cx: &mut Context<Self>,
4095 ) -> bool {
4096 let mut did_focus_panel = false;
4097 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
4098 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
4099 did_focus_panel
4100 });
4101
4102 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
4103 self.close_panel::<T>(window, cx);
4104 }
4105
4106 telemetry::event!(
4107 "Panel Button Clicked",
4108 name = T::persistent_name(),
4109 toggle_state = did_focus_panel
4110 );
4111
4112 did_focus_panel
4113 }
4114
4115 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4116 if let Some(item) = self.active_item(cx) {
4117 item.item_focus_handle(cx).focus(window, cx);
4118 } else {
4119 log::error!("Could not find a focus target when switching focus to the center panes",);
4120 }
4121 }
4122
4123 pub fn activate_panel_for_proto_id(
4124 &mut self,
4125 panel_id: PanelId,
4126 window: &mut Window,
4127 cx: &mut Context<Self>,
4128 ) -> Option<Arc<dyn PanelHandle>> {
4129 let mut panel = None;
4130 for dock in self.all_docks() {
4131 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
4132 panel = dock.update(cx, |dock, cx| {
4133 dock.activate_panel(panel_index, window, cx);
4134 dock.set_open(true, window, cx);
4135 dock.active_panel().cloned()
4136 });
4137 break;
4138 }
4139 }
4140
4141 if panel.is_some() {
4142 cx.notify();
4143 self.serialize_workspace(window, cx);
4144 }
4145
4146 panel
4147 }
4148
4149 /// Focus or unfocus the given panel type, depending on the given callback.
4150 fn focus_or_unfocus_panel<T: Panel>(
4151 &mut self,
4152 window: &mut Window,
4153 cx: &mut Context<Self>,
4154 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
4155 ) -> Option<Arc<dyn PanelHandle>> {
4156 let mut result_panel = None;
4157 let mut serialize = false;
4158 for dock in self.all_docks() {
4159 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4160 let mut focus_center = false;
4161 let panel = dock.update(cx, |dock, cx| {
4162 dock.activate_panel(panel_index, window, cx);
4163
4164 let panel = dock.active_panel().cloned();
4165 if let Some(panel) = panel.as_ref() {
4166 if should_focus(&**panel, window, cx) {
4167 dock.set_open(true, window, cx);
4168 panel.panel_focus_handle(cx).focus(window, cx);
4169 } else {
4170 focus_center = true;
4171 }
4172 }
4173 panel
4174 });
4175
4176 if focus_center {
4177 self.active_pane
4178 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4179 }
4180
4181 result_panel = panel;
4182 serialize = true;
4183 break;
4184 }
4185 }
4186
4187 if serialize {
4188 self.serialize_workspace(window, cx);
4189 }
4190
4191 cx.notify();
4192 result_panel
4193 }
4194
4195 /// Open the panel of the given type
4196 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4197 for dock in self.all_docks() {
4198 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4199 dock.update(cx, |dock, cx| {
4200 dock.activate_panel(panel_index, window, cx);
4201 dock.set_open(true, window, cx);
4202 });
4203 }
4204 }
4205 }
4206
4207 /// Open the panel of the given type, dismissing any zoomed items that
4208 /// would obscure it (e.g. a zoomed terminal).
4209 pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4210 let dock_position = self.all_docks().iter().find_map(|dock| {
4211 let dock = dock.read(cx);
4212 dock.panel_index_for_type::<T>().map(|_| dock.position())
4213 });
4214 self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
4215 self.open_panel::<T>(window, cx);
4216 }
4217
4218 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
4219 for dock in self.all_docks().iter() {
4220 dock.update(cx, |dock, cx| {
4221 if dock.panel::<T>().is_some() {
4222 dock.set_open(false, window, cx)
4223 }
4224 })
4225 }
4226 }
4227
4228 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
4229 self.all_docks()
4230 .iter()
4231 .find_map(|dock| dock.read(cx).panel::<T>())
4232 }
4233
4234 fn dismiss_zoomed_items_to_reveal(
4235 &mut self,
4236 dock_to_reveal: Option<DockPosition>,
4237 window: &mut Window,
4238 cx: &mut Context<Self>,
4239 ) {
4240 // If a center pane is zoomed, unzoom it.
4241 for pane in &self.panes {
4242 if pane != &self.active_pane || dock_to_reveal.is_some() {
4243 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4244 }
4245 }
4246
4247 // If another dock is zoomed, hide it.
4248 let mut focus_center = false;
4249 for dock in self.all_docks() {
4250 dock.update(cx, |dock, cx| {
4251 if Some(dock.position()) != dock_to_reveal
4252 && let Some(panel) = dock.active_panel()
4253 && panel.is_zoomed(window, cx)
4254 {
4255 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
4256 dock.set_open(false, window, cx);
4257 }
4258 });
4259 }
4260
4261 if focus_center {
4262 self.active_pane
4263 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4264 }
4265
4266 if self.zoomed_position != dock_to_reveal {
4267 self.zoomed = None;
4268 self.zoomed_position = None;
4269 cx.emit(Event::ZoomChanged);
4270 }
4271
4272 cx.notify();
4273 }
4274
4275 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4276 let pane = cx.new(|cx| {
4277 let mut pane = Pane::new(
4278 self.weak_handle(),
4279 self.project.clone(),
4280 self.pane_history_timestamp.clone(),
4281 None,
4282 NewFile.boxed_clone(),
4283 true,
4284 window,
4285 cx,
4286 );
4287 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4288 pane
4289 });
4290 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4291 .detach();
4292 self.panes.push(pane.clone());
4293
4294 window.focus(&pane.focus_handle(cx), cx);
4295
4296 cx.emit(Event::PaneAdded(pane.clone()));
4297 pane
4298 }
4299
4300 pub fn add_item_to_center(
4301 &mut self,
4302 item: Box<dyn ItemHandle>,
4303 window: &mut Window,
4304 cx: &mut Context<Self>,
4305 ) -> bool {
4306 if let Some(center_pane) = self.last_active_center_pane.clone() {
4307 if let Some(center_pane) = center_pane.upgrade() {
4308 center_pane.update(cx, |pane, cx| {
4309 pane.add_item(item, true, true, None, window, cx)
4310 });
4311 true
4312 } else {
4313 false
4314 }
4315 } else {
4316 false
4317 }
4318 }
4319
4320 pub fn add_item_to_active_pane(
4321 &mut self,
4322 item: Box<dyn ItemHandle>,
4323 destination_index: Option<usize>,
4324 focus_item: bool,
4325 window: &mut Window,
4326 cx: &mut App,
4327 ) {
4328 self.add_item(
4329 self.active_pane.clone(),
4330 item,
4331 destination_index,
4332 false,
4333 focus_item,
4334 window,
4335 cx,
4336 )
4337 }
4338
4339 pub fn add_item(
4340 &mut self,
4341 pane: Entity<Pane>,
4342 item: Box<dyn ItemHandle>,
4343 destination_index: Option<usize>,
4344 activate_pane: bool,
4345 focus_item: bool,
4346 window: &mut Window,
4347 cx: &mut App,
4348 ) {
4349 pane.update(cx, |pane, cx| {
4350 pane.add_item(
4351 item,
4352 activate_pane,
4353 focus_item,
4354 destination_index,
4355 window,
4356 cx,
4357 )
4358 });
4359 }
4360
4361 pub fn split_item(
4362 &mut self,
4363 split_direction: SplitDirection,
4364 item: Box<dyn ItemHandle>,
4365 window: &mut Window,
4366 cx: &mut Context<Self>,
4367 ) {
4368 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4369 self.add_item(new_pane, item, None, true, true, window, cx);
4370 }
4371
4372 pub fn open_abs_path(
4373 &mut self,
4374 abs_path: PathBuf,
4375 options: OpenOptions,
4376 window: &mut Window,
4377 cx: &mut Context<Self>,
4378 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4379 cx.spawn_in(window, async move |workspace, cx| {
4380 let open_paths_task_result = workspace
4381 .update_in(cx, |workspace, window, cx| {
4382 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4383 })
4384 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4385 .await;
4386 anyhow::ensure!(
4387 open_paths_task_result.len() == 1,
4388 "open abs path {abs_path:?} task returned incorrect number of results"
4389 );
4390 match open_paths_task_result
4391 .into_iter()
4392 .next()
4393 .expect("ensured single task result")
4394 {
4395 Some(open_result) => {
4396 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4397 }
4398 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4399 }
4400 })
4401 }
4402
4403 pub fn split_abs_path(
4404 &mut self,
4405 abs_path: PathBuf,
4406 visible: bool,
4407 window: &mut Window,
4408 cx: &mut Context<Self>,
4409 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4410 let project_path_task =
4411 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4412 cx.spawn_in(window, async move |this, cx| {
4413 let (_, path) = project_path_task.await?;
4414 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4415 .await
4416 })
4417 }
4418
4419 pub fn open_path(
4420 &mut self,
4421 path: impl Into<ProjectPath>,
4422 pane: Option<WeakEntity<Pane>>,
4423 focus_item: bool,
4424 window: &mut Window,
4425 cx: &mut App,
4426 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4427 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4428 }
4429
4430 pub fn open_path_preview(
4431 &mut self,
4432 path: impl Into<ProjectPath>,
4433 pane: Option<WeakEntity<Pane>>,
4434 focus_item: bool,
4435 allow_preview: bool,
4436 activate: bool,
4437 window: &mut Window,
4438 cx: &mut App,
4439 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4440 let pane = pane.unwrap_or_else(|| {
4441 self.last_active_center_pane.clone().unwrap_or_else(|| {
4442 self.panes
4443 .first()
4444 .expect("There must be an active pane")
4445 .downgrade()
4446 })
4447 });
4448
4449 let project_path = path.into();
4450 let task = self.load_path(project_path.clone(), window, cx);
4451 window.spawn(cx, async move |cx| {
4452 let (project_entry_id, build_item) = task.await?;
4453
4454 pane.update_in(cx, |pane, window, cx| {
4455 pane.open_item(
4456 project_entry_id,
4457 project_path,
4458 focus_item,
4459 allow_preview,
4460 activate,
4461 None,
4462 window,
4463 cx,
4464 build_item,
4465 )
4466 })
4467 })
4468 }
4469
4470 pub fn split_path(
4471 &mut self,
4472 path: impl Into<ProjectPath>,
4473 window: &mut Window,
4474 cx: &mut Context<Self>,
4475 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4476 self.split_path_preview(path, false, None, window, cx)
4477 }
4478
4479 pub fn split_path_preview(
4480 &mut self,
4481 path: impl Into<ProjectPath>,
4482 allow_preview: bool,
4483 split_direction: Option<SplitDirection>,
4484 window: &mut Window,
4485 cx: &mut Context<Self>,
4486 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4487 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4488 self.panes
4489 .first()
4490 .expect("There must be an active pane")
4491 .downgrade()
4492 });
4493
4494 if let Member::Pane(center_pane) = &self.center.root
4495 && center_pane.read(cx).items_len() == 0
4496 {
4497 return self.open_path(path, Some(pane), true, window, cx);
4498 }
4499
4500 let project_path = path.into();
4501 let task = self.load_path(project_path.clone(), window, cx);
4502 cx.spawn_in(window, async move |this, cx| {
4503 let (project_entry_id, build_item) = task.await?;
4504 this.update_in(cx, move |this, window, cx| -> Option<_> {
4505 let pane = pane.upgrade()?;
4506 let new_pane = this.split_pane(
4507 pane,
4508 split_direction.unwrap_or(SplitDirection::Right),
4509 window,
4510 cx,
4511 );
4512 new_pane.update(cx, |new_pane, cx| {
4513 Some(new_pane.open_item(
4514 project_entry_id,
4515 project_path,
4516 true,
4517 allow_preview,
4518 true,
4519 None,
4520 window,
4521 cx,
4522 build_item,
4523 ))
4524 })
4525 })
4526 .map(|option| option.context("pane was dropped"))?
4527 })
4528 }
4529
4530 fn load_path(
4531 &mut self,
4532 path: ProjectPath,
4533 window: &mut Window,
4534 cx: &mut App,
4535 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4536 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4537 registry.open_path(self.project(), &path, window, cx)
4538 }
4539
4540 pub fn find_project_item<T>(
4541 &self,
4542 pane: &Entity<Pane>,
4543 project_item: &Entity<T::Item>,
4544 cx: &App,
4545 ) -> Option<Entity<T>>
4546 where
4547 T: ProjectItem,
4548 {
4549 use project::ProjectItem as _;
4550 let project_item = project_item.read(cx);
4551 let entry_id = project_item.entry_id(cx);
4552 let project_path = project_item.project_path(cx);
4553
4554 let mut item = None;
4555 if let Some(entry_id) = entry_id {
4556 item = pane.read(cx).item_for_entry(entry_id, cx);
4557 }
4558 if item.is_none()
4559 && let Some(project_path) = project_path
4560 {
4561 item = pane.read(cx).item_for_path(project_path, cx);
4562 }
4563
4564 item.and_then(|item| item.downcast::<T>())
4565 }
4566
4567 pub fn is_project_item_open<T>(
4568 &self,
4569 pane: &Entity<Pane>,
4570 project_item: &Entity<T::Item>,
4571 cx: &App,
4572 ) -> bool
4573 where
4574 T: ProjectItem,
4575 {
4576 self.find_project_item::<T>(pane, project_item, cx)
4577 .is_some()
4578 }
4579
4580 pub fn open_project_item<T>(
4581 &mut self,
4582 pane: Entity<Pane>,
4583 project_item: Entity<T::Item>,
4584 activate_pane: bool,
4585 focus_item: bool,
4586 keep_old_preview: bool,
4587 allow_new_preview: bool,
4588 window: &mut Window,
4589 cx: &mut Context<Self>,
4590 ) -> Entity<T>
4591 where
4592 T: ProjectItem,
4593 {
4594 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4595
4596 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4597 if !keep_old_preview
4598 && let Some(old_id) = old_item_id
4599 && old_id != item.item_id()
4600 {
4601 // switching to a different item, so unpreview old active item
4602 pane.update(cx, |pane, _| {
4603 pane.unpreview_item_if_preview(old_id);
4604 });
4605 }
4606
4607 self.activate_item(&item, activate_pane, focus_item, window, cx);
4608 if !allow_new_preview {
4609 pane.update(cx, |pane, _| {
4610 pane.unpreview_item_if_preview(item.item_id());
4611 });
4612 }
4613 return item;
4614 }
4615
4616 let item = pane.update(cx, |pane, cx| {
4617 cx.new(|cx| {
4618 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4619 })
4620 });
4621 let mut destination_index = None;
4622 pane.update(cx, |pane, cx| {
4623 if !keep_old_preview && let Some(old_id) = old_item_id {
4624 pane.unpreview_item_if_preview(old_id);
4625 }
4626 if allow_new_preview {
4627 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4628 }
4629 });
4630
4631 self.add_item(
4632 pane,
4633 Box::new(item.clone()),
4634 destination_index,
4635 activate_pane,
4636 focus_item,
4637 window,
4638 cx,
4639 );
4640 item
4641 }
4642
4643 pub fn open_shared_screen(
4644 &mut self,
4645 peer_id: PeerId,
4646 window: &mut Window,
4647 cx: &mut Context<Self>,
4648 ) {
4649 if let Some(shared_screen) =
4650 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4651 {
4652 self.active_pane.update(cx, |pane, cx| {
4653 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4654 });
4655 }
4656 }
4657
4658 pub fn activate_item(
4659 &mut self,
4660 item: &dyn ItemHandle,
4661 activate_pane: bool,
4662 focus_item: bool,
4663 window: &mut Window,
4664 cx: &mut App,
4665 ) -> bool {
4666 let result = self.panes.iter().find_map(|pane| {
4667 pane.read(cx)
4668 .index_for_item(item)
4669 .map(|ix| (pane.clone(), ix))
4670 });
4671 if let Some((pane, ix)) = result {
4672 pane.update(cx, |pane, cx| {
4673 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4674 });
4675 true
4676 } else {
4677 false
4678 }
4679 }
4680
4681 fn activate_pane_at_index(
4682 &mut self,
4683 action: &ActivatePane,
4684 window: &mut Window,
4685 cx: &mut Context<Self>,
4686 ) {
4687 let panes = self.center.panes();
4688 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4689 window.focus(&pane.focus_handle(cx), cx);
4690 } else {
4691 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4692 .detach();
4693 }
4694 }
4695
4696 fn move_item_to_pane_at_index(
4697 &mut self,
4698 action: &MoveItemToPane,
4699 window: &mut Window,
4700 cx: &mut Context<Self>,
4701 ) {
4702 let panes = self.center.panes();
4703 let destination = match panes.get(action.destination) {
4704 Some(&destination) => destination.clone(),
4705 None => {
4706 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4707 return;
4708 }
4709 let direction = SplitDirection::Right;
4710 let split_off_pane = self
4711 .find_pane_in_direction(direction, cx)
4712 .unwrap_or_else(|| self.active_pane.clone());
4713 let new_pane = self.add_pane(window, cx);
4714 self.center.split(&split_off_pane, &new_pane, direction, cx);
4715 new_pane
4716 }
4717 };
4718
4719 if action.clone {
4720 if self
4721 .active_pane
4722 .read(cx)
4723 .active_item()
4724 .is_some_and(|item| item.can_split(cx))
4725 {
4726 clone_active_item(
4727 self.database_id(),
4728 &self.active_pane,
4729 &destination,
4730 action.focus,
4731 window,
4732 cx,
4733 );
4734 return;
4735 }
4736 }
4737 move_active_item(
4738 &self.active_pane,
4739 &destination,
4740 action.focus,
4741 true,
4742 window,
4743 cx,
4744 )
4745 }
4746
4747 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4748 let panes = self.center.panes();
4749 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4750 let next_ix = (ix + 1) % panes.len();
4751 let next_pane = panes[next_ix].clone();
4752 window.focus(&next_pane.focus_handle(cx), cx);
4753 }
4754 }
4755
4756 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4757 let panes = self.center.panes();
4758 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4759 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4760 let prev_pane = panes[prev_ix].clone();
4761 window.focus(&prev_pane.focus_handle(cx), cx);
4762 }
4763 }
4764
4765 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4766 let last_pane = self.center.last_pane();
4767 window.focus(&last_pane.focus_handle(cx), cx);
4768 }
4769
4770 pub fn activate_pane_in_direction(
4771 &mut self,
4772 direction: SplitDirection,
4773 window: &mut Window,
4774 cx: &mut App,
4775 ) {
4776 use ActivateInDirectionTarget as Target;
4777 enum Origin {
4778 Sidebar,
4779 LeftDock,
4780 RightDock,
4781 BottomDock,
4782 Center,
4783 }
4784
4785 let origin: Origin = if self
4786 .sidebar_focus_handle
4787 .as_ref()
4788 .is_some_and(|h| h.contains_focused(window, cx))
4789 {
4790 Origin::Sidebar
4791 } else {
4792 [
4793 (&self.left_dock, Origin::LeftDock),
4794 (&self.right_dock, Origin::RightDock),
4795 (&self.bottom_dock, Origin::BottomDock),
4796 ]
4797 .into_iter()
4798 .find_map(|(dock, origin)| {
4799 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4800 Some(origin)
4801 } else {
4802 None
4803 }
4804 })
4805 .unwrap_or(Origin::Center)
4806 };
4807
4808 let get_last_active_pane = || {
4809 let pane = self
4810 .last_active_center_pane
4811 .clone()
4812 .unwrap_or_else(|| {
4813 self.panes
4814 .first()
4815 .expect("There must be an active pane")
4816 .downgrade()
4817 })
4818 .upgrade()?;
4819 (pane.read(cx).items_len() != 0).then_some(pane)
4820 };
4821
4822 let try_dock =
4823 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4824
4825 let sidebar_target = self
4826 .sidebar_focus_handle
4827 .as_ref()
4828 .map(|h| Target::Sidebar(h.clone()));
4829
4830 let target = match (origin, direction) {
4831 // From the sidebar, only Right navigates into the workspace.
4832 (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
4833 .or_else(|| get_last_active_pane().map(Target::Pane))
4834 .or_else(|| try_dock(&self.bottom_dock))
4835 .or_else(|| try_dock(&self.right_dock)),
4836
4837 (Origin::Sidebar, _) => None,
4838
4839 // We're in the center, so we first try to go to a different pane,
4840 // otherwise try to go to a dock.
4841 (Origin::Center, direction) => {
4842 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4843 Some(Target::Pane(pane))
4844 } else {
4845 match direction {
4846 SplitDirection::Up => None,
4847 SplitDirection::Down => try_dock(&self.bottom_dock),
4848 SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
4849 SplitDirection::Right => try_dock(&self.right_dock),
4850 }
4851 }
4852 }
4853
4854 (Origin::LeftDock, SplitDirection::Right) => {
4855 if let Some(last_active_pane) = get_last_active_pane() {
4856 Some(Target::Pane(last_active_pane))
4857 } else {
4858 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4859 }
4860 }
4861
4862 (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
4863
4864 (Origin::LeftDock, SplitDirection::Down)
4865 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4866
4867 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4868 (Origin::BottomDock, SplitDirection::Left) => {
4869 try_dock(&self.left_dock).or(sidebar_target)
4870 }
4871 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4872
4873 (Origin::RightDock, SplitDirection::Left) => {
4874 if let Some(last_active_pane) = get_last_active_pane() {
4875 Some(Target::Pane(last_active_pane))
4876 } else {
4877 try_dock(&self.bottom_dock)
4878 .or_else(|| try_dock(&self.left_dock))
4879 .or(sidebar_target)
4880 }
4881 }
4882
4883 _ => None,
4884 };
4885
4886 match target {
4887 Some(ActivateInDirectionTarget::Pane(pane)) => {
4888 let pane = pane.read(cx);
4889 if let Some(item) = pane.active_item() {
4890 item.item_focus_handle(cx).focus(window, cx);
4891 } else {
4892 log::error!(
4893 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4894 );
4895 }
4896 }
4897 Some(ActivateInDirectionTarget::Dock(dock)) => {
4898 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4899 window.defer(cx, move |window, cx| {
4900 let dock = dock.read(cx);
4901 if let Some(panel) = dock.active_panel() {
4902 panel.panel_focus_handle(cx).focus(window, cx);
4903 } else {
4904 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4905 }
4906 })
4907 }
4908 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4909 focus_handle.focus(window, cx);
4910 }
4911 None => {}
4912 }
4913 }
4914
4915 pub fn move_item_to_pane_in_direction(
4916 &mut self,
4917 action: &MoveItemToPaneInDirection,
4918 window: &mut Window,
4919 cx: &mut Context<Self>,
4920 ) {
4921 let destination = match self.find_pane_in_direction(action.direction, cx) {
4922 Some(destination) => destination,
4923 None => {
4924 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4925 return;
4926 }
4927 let new_pane = self.add_pane(window, cx);
4928 self.center
4929 .split(&self.active_pane, &new_pane, action.direction, cx);
4930 new_pane
4931 }
4932 };
4933
4934 if action.clone {
4935 if self
4936 .active_pane
4937 .read(cx)
4938 .active_item()
4939 .is_some_and(|item| item.can_split(cx))
4940 {
4941 clone_active_item(
4942 self.database_id(),
4943 &self.active_pane,
4944 &destination,
4945 action.focus,
4946 window,
4947 cx,
4948 );
4949 return;
4950 }
4951 }
4952 move_active_item(
4953 &self.active_pane,
4954 &destination,
4955 action.focus,
4956 true,
4957 window,
4958 cx,
4959 );
4960 }
4961
4962 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4963 self.center.bounding_box_for_pane(pane)
4964 }
4965
4966 pub fn find_pane_in_direction(
4967 &mut self,
4968 direction: SplitDirection,
4969 cx: &App,
4970 ) -> Option<Entity<Pane>> {
4971 self.center
4972 .find_pane_in_direction(&self.active_pane, direction, cx)
4973 .cloned()
4974 }
4975
4976 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4977 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4978 self.center.swap(&self.active_pane, &to, cx);
4979 cx.notify();
4980 }
4981 }
4982
4983 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4984 if self
4985 .center
4986 .move_to_border(&self.active_pane, direction, cx)
4987 .unwrap()
4988 {
4989 cx.notify();
4990 }
4991 }
4992
4993 pub fn resize_pane(
4994 &mut self,
4995 axis: gpui::Axis,
4996 amount: Pixels,
4997 window: &mut Window,
4998 cx: &mut Context<Self>,
4999 ) {
5000 let docks = self.all_docks();
5001 let active_dock = docks
5002 .into_iter()
5003 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
5004
5005 if let Some(dock_entity) = active_dock {
5006 let dock = dock_entity.read(cx);
5007 let Some(panel_size) = self.dock_size(&dock, window, cx) else {
5008 return;
5009 };
5010 match dock.position() {
5011 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
5012 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
5013 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
5014 }
5015 } else {
5016 self.center
5017 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
5018 }
5019 cx.notify();
5020 }
5021
5022 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
5023 self.center.reset_pane_sizes(cx);
5024 cx.notify();
5025 }
5026
5027 fn handle_pane_focused(
5028 &mut self,
5029 pane: Entity<Pane>,
5030 window: &mut Window,
5031 cx: &mut Context<Self>,
5032 ) {
5033 // This is explicitly hoisted out of the following check for pane identity as
5034 // terminal panel panes are not registered as a center panes.
5035 self.status_bar.update(cx, |status_bar, cx| {
5036 status_bar.set_active_pane(&pane, window, cx);
5037 });
5038 if self.active_pane != pane {
5039 self.set_active_pane(&pane, window, cx);
5040 }
5041
5042 if self.last_active_center_pane.is_none() {
5043 self.last_active_center_pane = Some(pane.downgrade());
5044 }
5045
5046 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
5047 // This prevents the dock from closing when focus events fire during window activation.
5048 // We also preserve any dock whose active panel itself has focus — this covers
5049 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
5050 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
5051 let dock_read = dock.read(cx);
5052 if let Some(panel) = dock_read.active_panel() {
5053 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
5054 || panel.panel_focus_handle(cx).contains_focused(window, cx)
5055 {
5056 return Some(dock_read.position());
5057 }
5058 }
5059 None
5060 });
5061
5062 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
5063 if pane.read(cx).is_zoomed() {
5064 self.zoomed = Some(pane.downgrade().into());
5065 } else {
5066 self.zoomed = None;
5067 }
5068 self.zoomed_position = None;
5069 cx.emit(Event::ZoomChanged);
5070 self.update_active_view_for_followers(window, cx);
5071 pane.update(cx, |pane, _| {
5072 pane.track_alternate_file_items();
5073 });
5074
5075 cx.notify();
5076 }
5077
5078 fn set_active_pane(
5079 &mut self,
5080 pane: &Entity<Pane>,
5081 window: &mut Window,
5082 cx: &mut Context<Self>,
5083 ) {
5084 self.active_pane = pane.clone();
5085 self.active_item_path_changed(true, window, cx);
5086 self.last_active_center_pane = Some(pane.downgrade());
5087 }
5088
5089 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5090 self.update_active_view_for_followers(window, cx);
5091 }
5092
5093 fn handle_pane_event(
5094 &mut self,
5095 pane: &Entity<Pane>,
5096 event: &pane::Event,
5097 window: &mut Window,
5098 cx: &mut Context<Self>,
5099 ) {
5100 let mut serialize_workspace = true;
5101 match event {
5102 pane::Event::AddItem { item } => {
5103 item.added_to_pane(self, pane.clone(), window, cx);
5104 cx.emit(Event::ItemAdded {
5105 item: item.boxed_clone(),
5106 });
5107 }
5108 pane::Event::Split { direction, mode } => {
5109 match mode {
5110 SplitMode::ClonePane => {
5111 self.split_and_clone(pane.clone(), *direction, window, cx)
5112 .detach();
5113 }
5114 SplitMode::EmptyPane => {
5115 self.split_pane(pane.clone(), *direction, window, cx);
5116 }
5117 SplitMode::MovePane => {
5118 self.split_and_move(pane.clone(), *direction, window, cx);
5119 }
5120 };
5121 }
5122 pane::Event::JoinIntoNext => {
5123 self.join_pane_into_next(pane.clone(), window, cx);
5124 }
5125 pane::Event::JoinAll => {
5126 self.join_all_panes(window, cx);
5127 }
5128 pane::Event::Remove { focus_on_pane } => {
5129 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
5130 }
5131 pane::Event::ActivateItem {
5132 local,
5133 focus_changed,
5134 } => {
5135 window.invalidate_character_coordinates();
5136
5137 pane.update(cx, |pane, _| {
5138 pane.track_alternate_file_items();
5139 });
5140 if *local {
5141 self.unfollow_in_pane(pane, window, cx);
5142 }
5143 serialize_workspace = *focus_changed || pane != self.active_pane();
5144 if pane == self.active_pane() {
5145 self.active_item_path_changed(*focus_changed, window, cx);
5146 self.update_active_view_for_followers(window, cx);
5147 } else if *local {
5148 self.set_active_pane(pane, window, cx);
5149 }
5150 }
5151 pane::Event::UserSavedItem { item, save_intent } => {
5152 cx.emit(Event::UserSavedItem {
5153 pane: pane.downgrade(),
5154 item: item.boxed_clone(),
5155 save_intent: *save_intent,
5156 });
5157 serialize_workspace = false;
5158 }
5159 pane::Event::ChangeItemTitle => {
5160 if *pane == self.active_pane {
5161 self.active_item_path_changed(false, window, cx);
5162 }
5163 serialize_workspace = false;
5164 }
5165 pane::Event::RemovedItem { item } => {
5166 cx.emit(Event::ActiveItemChanged);
5167 self.update_window_edited(window, cx);
5168 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
5169 && entry.get().entity_id() == pane.entity_id()
5170 {
5171 entry.remove();
5172 }
5173 cx.emit(Event::ItemRemoved {
5174 item_id: item.item_id(),
5175 });
5176 }
5177 pane::Event::Focus => {
5178 window.invalidate_character_coordinates();
5179 self.handle_pane_focused(pane.clone(), window, cx);
5180 }
5181 pane::Event::ZoomIn => {
5182 if *pane == self.active_pane {
5183 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
5184 if pane.read(cx).has_focus(window, cx) {
5185 self.zoomed = Some(pane.downgrade().into());
5186 self.zoomed_position = None;
5187 cx.emit(Event::ZoomChanged);
5188 }
5189 cx.notify();
5190 }
5191 }
5192 pane::Event::ZoomOut => {
5193 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
5194 if self.zoomed_position.is_none() {
5195 self.zoomed = None;
5196 cx.emit(Event::ZoomChanged);
5197 }
5198 cx.notify();
5199 }
5200 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
5201 }
5202
5203 if serialize_workspace {
5204 self.serialize_workspace(window, cx);
5205 }
5206 }
5207
5208 pub fn unfollow_in_pane(
5209 &mut self,
5210 pane: &Entity<Pane>,
5211 window: &mut Window,
5212 cx: &mut Context<Workspace>,
5213 ) -> Option<CollaboratorId> {
5214 let leader_id = self.leader_for_pane(pane)?;
5215 self.unfollow(leader_id, window, cx);
5216 Some(leader_id)
5217 }
5218
5219 pub fn split_pane(
5220 &mut self,
5221 pane_to_split: Entity<Pane>,
5222 split_direction: SplitDirection,
5223 window: &mut Window,
5224 cx: &mut Context<Self>,
5225 ) -> Entity<Pane> {
5226 let new_pane = self.add_pane(window, cx);
5227 self.center
5228 .split(&pane_to_split, &new_pane, split_direction, cx);
5229 cx.notify();
5230 new_pane
5231 }
5232
5233 pub fn split_and_move(
5234 &mut self,
5235 pane: Entity<Pane>,
5236 direction: SplitDirection,
5237 window: &mut Window,
5238 cx: &mut Context<Self>,
5239 ) {
5240 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
5241 return;
5242 };
5243 let new_pane = self.add_pane(window, cx);
5244 new_pane.update(cx, |pane, cx| {
5245 pane.add_item(item, true, true, None, window, cx)
5246 });
5247 self.center.split(&pane, &new_pane, direction, cx);
5248 cx.notify();
5249 }
5250
5251 pub fn split_and_clone(
5252 &mut self,
5253 pane: Entity<Pane>,
5254 direction: SplitDirection,
5255 window: &mut Window,
5256 cx: &mut Context<Self>,
5257 ) -> Task<Option<Entity<Pane>>> {
5258 let Some(item) = pane.read(cx).active_item() else {
5259 return Task::ready(None);
5260 };
5261 if !item.can_split(cx) {
5262 return Task::ready(None);
5263 }
5264 let task = item.clone_on_split(self.database_id(), window, cx);
5265 cx.spawn_in(window, async move |this, cx| {
5266 if let Some(clone) = task.await {
5267 this.update_in(cx, |this, window, cx| {
5268 let new_pane = this.add_pane(window, cx);
5269 let nav_history = pane.read(cx).fork_nav_history();
5270 new_pane.update(cx, |pane, cx| {
5271 pane.set_nav_history(nav_history, cx);
5272 pane.add_item(clone, true, true, None, window, cx)
5273 });
5274 this.center.split(&pane, &new_pane, direction, cx);
5275 cx.notify();
5276 new_pane
5277 })
5278 .ok()
5279 } else {
5280 None
5281 }
5282 })
5283 }
5284
5285 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5286 let active_item = self.active_pane.read(cx).active_item();
5287 for pane in &self.panes {
5288 join_pane_into_active(&self.active_pane, pane, window, cx);
5289 }
5290 if let Some(active_item) = active_item {
5291 self.activate_item(active_item.as_ref(), true, true, window, cx);
5292 }
5293 cx.notify();
5294 }
5295
5296 pub fn join_pane_into_next(
5297 &mut self,
5298 pane: Entity<Pane>,
5299 window: &mut Window,
5300 cx: &mut Context<Self>,
5301 ) {
5302 let next_pane = self
5303 .find_pane_in_direction(SplitDirection::Right, cx)
5304 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5305 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5306 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5307 let Some(next_pane) = next_pane else {
5308 return;
5309 };
5310 move_all_items(&pane, &next_pane, window, cx);
5311 cx.notify();
5312 }
5313
5314 fn remove_pane(
5315 &mut self,
5316 pane: Entity<Pane>,
5317 focus_on: Option<Entity<Pane>>,
5318 window: &mut Window,
5319 cx: &mut Context<Self>,
5320 ) {
5321 if self.center.remove(&pane, cx).unwrap() {
5322 self.force_remove_pane(&pane, &focus_on, window, cx);
5323 self.unfollow_in_pane(&pane, window, cx);
5324 self.last_leaders_by_pane.remove(&pane.downgrade());
5325 for removed_item in pane.read(cx).items() {
5326 self.panes_by_item.remove(&removed_item.item_id());
5327 }
5328
5329 cx.notify();
5330 } else {
5331 self.active_item_path_changed(true, window, cx);
5332 }
5333 cx.emit(Event::PaneRemoved);
5334 }
5335
5336 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5337 &mut self.panes
5338 }
5339
5340 pub fn panes(&self) -> &[Entity<Pane>] {
5341 &self.panes
5342 }
5343
5344 pub fn active_pane(&self) -> &Entity<Pane> {
5345 &self.active_pane
5346 }
5347
5348 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5349 for dock in self.all_docks() {
5350 if dock.focus_handle(cx).contains_focused(window, cx)
5351 && let Some(pane) = dock
5352 .read(cx)
5353 .active_panel()
5354 .and_then(|panel| panel.pane(cx))
5355 {
5356 return pane;
5357 }
5358 }
5359 self.active_pane().clone()
5360 }
5361
5362 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5363 self.find_pane_in_direction(SplitDirection::Right, cx)
5364 .unwrap_or_else(|| {
5365 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5366 })
5367 }
5368
5369 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5370 self.pane_for_item_id(handle.item_id())
5371 }
5372
5373 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5374 let weak_pane = self.panes_by_item.get(&item_id)?;
5375 weak_pane.upgrade()
5376 }
5377
5378 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5379 self.panes
5380 .iter()
5381 .find(|pane| pane.entity_id() == entity_id)
5382 .cloned()
5383 }
5384
5385 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5386 self.follower_states.retain(|leader_id, state| {
5387 if *leader_id == CollaboratorId::PeerId(peer_id) {
5388 for item in state.items_by_leader_view_id.values() {
5389 item.view.set_leader_id(None, window, cx);
5390 }
5391 false
5392 } else {
5393 true
5394 }
5395 });
5396 cx.notify();
5397 }
5398
5399 pub fn start_following(
5400 &mut self,
5401 leader_id: impl Into<CollaboratorId>,
5402 window: &mut Window,
5403 cx: &mut Context<Self>,
5404 ) -> Option<Task<Result<()>>> {
5405 let leader_id = leader_id.into();
5406 let pane = self.active_pane().clone();
5407
5408 self.last_leaders_by_pane
5409 .insert(pane.downgrade(), leader_id);
5410 self.unfollow(leader_id, window, cx);
5411 self.unfollow_in_pane(&pane, window, cx);
5412 self.follower_states.insert(
5413 leader_id,
5414 FollowerState {
5415 center_pane: pane.clone(),
5416 dock_pane: None,
5417 active_view_id: None,
5418 items_by_leader_view_id: Default::default(),
5419 },
5420 );
5421 cx.notify();
5422
5423 match leader_id {
5424 CollaboratorId::PeerId(leader_peer_id) => {
5425 let room_id = self.active_call()?.room_id(cx)?;
5426 let project_id = self.project.read(cx).remote_id();
5427 let request = self.app_state.client.request(proto::Follow {
5428 room_id,
5429 project_id,
5430 leader_id: Some(leader_peer_id),
5431 });
5432
5433 Some(cx.spawn_in(window, async move |this, cx| {
5434 let response = request.await?;
5435 this.update(cx, |this, _| {
5436 let state = this
5437 .follower_states
5438 .get_mut(&leader_id)
5439 .context("following interrupted")?;
5440 state.active_view_id = response
5441 .active_view
5442 .as_ref()
5443 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5444 anyhow::Ok(())
5445 })??;
5446 if let Some(view) = response.active_view {
5447 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5448 }
5449 this.update_in(cx, |this, window, cx| {
5450 this.leader_updated(leader_id, window, cx)
5451 })?;
5452 Ok(())
5453 }))
5454 }
5455 CollaboratorId::Agent => {
5456 self.leader_updated(leader_id, window, cx)?;
5457 Some(Task::ready(Ok(())))
5458 }
5459 }
5460 }
5461
5462 pub fn follow_next_collaborator(
5463 &mut self,
5464 _: &FollowNextCollaborator,
5465 window: &mut Window,
5466 cx: &mut Context<Self>,
5467 ) {
5468 let collaborators = self.project.read(cx).collaborators();
5469 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5470 let mut collaborators = collaborators.keys().copied();
5471 for peer_id in collaborators.by_ref() {
5472 if CollaboratorId::PeerId(peer_id) == leader_id {
5473 break;
5474 }
5475 }
5476 collaborators.next().map(CollaboratorId::PeerId)
5477 } else if let Some(last_leader_id) =
5478 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5479 {
5480 match last_leader_id {
5481 CollaboratorId::PeerId(peer_id) => {
5482 if collaborators.contains_key(peer_id) {
5483 Some(*last_leader_id)
5484 } else {
5485 None
5486 }
5487 }
5488 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5489 }
5490 } else {
5491 None
5492 };
5493
5494 let pane = self.active_pane.clone();
5495 let Some(leader_id) = next_leader_id.or_else(|| {
5496 Some(CollaboratorId::PeerId(
5497 collaborators.keys().copied().next()?,
5498 ))
5499 }) else {
5500 return;
5501 };
5502 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5503 return;
5504 }
5505 if let Some(task) = self.start_following(leader_id, window, cx) {
5506 task.detach_and_log_err(cx)
5507 }
5508 }
5509
5510 pub fn follow(
5511 &mut self,
5512 leader_id: impl Into<CollaboratorId>,
5513 window: &mut Window,
5514 cx: &mut Context<Self>,
5515 ) {
5516 let leader_id = leader_id.into();
5517
5518 if let CollaboratorId::PeerId(peer_id) = leader_id {
5519 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5520 return;
5521 };
5522 let Some(remote_participant) =
5523 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5524 else {
5525 return;
5526 };
5527
5528 let project = self.project.read(cx);
5529
5530 let other_project_id = match remote_participant.location {
5531 ParticipantLocation::External => None,
5532 ParticipantLocation::UnsharedProject => None,
5533 ParticipantLocation::SharedProject { project_id } => {
5534 if Some(project_id) == project.remote_id() {
5535 None
5536 } else {
5537 Some(project_id)
5538 }
5539 }
5540 };
5541
5542 // if they are active in another project, follow there.
5543 if let Some(project_id) = other_project_id {
5544 let app_state = self.app_state.clone();
5545 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5546 .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
5547 Some(format!("{error:#}"))
5548 });
5549 }
5550 }
5551
5552 // if you're already following, find the right pane and focus it.
5553 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5554 window.focus(&follower_state.pane().focus_handle(cx), cx);
5555
5556 return;
5557 }
5558
5559 // Otherwise, follow.
5560 if let Some(task) = self.start_following(leader_id, window, cx) {
5561 task.detach_and_log_err(cx)
5562 }
5563 }
5564
5565 pub fn unfollow(
5566 &mut self,
5567 leader_id: impl Into<CollaboratorId>,
5568 window: &mut Window,
5569 cx: &mut Context<Self>,
5570 ) -> Option<()> {
5571 cx.notify();
5572
5573 let leader_id = leader_id.into();
5574 let state = self.follower_states.remove(&leader_id)?;
5575 for (_, item) in state.items_by_leader_view_id {
5576 item.view.set_leader_id(None, window, cx);
5577 }
5578
5579 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5580 let project_id = self.project.read(cx).remote_id();
5581 let room_id = self.active_call()?.room_id(cx)?;
5582 self.app_state
5583 .client
5584 .send(proto::Unfollow {
5585 room_id,
5586 project_id,
5587 leader_id: Some(leader_peer_id),
5588 })
5589 .log_err();
5590 }
5591
5592 Some(())
5593 }
5594
5595 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5596 self.follower_states.contains_key(&id.into())
5597 }
5598
5599 fn active_item_path_changed(
5600 &mut self,
5601 focus_changed: bool,
5602 window: &mut Window,
5603 cx: &mut Context<Self>,
5604 ) {
5605 cx.emit(Event::ActiveItemChanged);
5606 let active_entry = self.active_project_path(cx);
5607 self.project.update(cx, |project, cx| {
5608 project.set_active_path(active_entry.clone(), cx)
5609 });
5610
5611 if focus_changed && let Some(project_path) = &active_entry {
5612 let git_store_entity = self.project.read(cx).git_store().clone();
5613 git_store_entity.update(cx, |git_store, cx| {
5614 git_store.set_active_repo_for_path(project_path, cx);
5615 });
5616 }
5617
5618 self.update_window_title(window, cx);
5619 }
5620
5621 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5622 let project = self.project().read(cx);
5623 let mut title = String::new();
5624
5625 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5626 let name = {
5627 let settings_location = SettingsLocation {
5628 worktree_id: worktree.read(cx).id(),
5629 path: RelPath::empty(),
5630 };
5631
5632 let settings = WorktreeSettings::get(Some(settings_location), cx);
5633 match &settings.project_name {
5634 Some(name) => name.as_str(),
5635 None => worktree.read(cx).root_name_str(),
5636 }
5637 };
5638 if i > 0 {
5639 title.push_str(", ");
5640 }
5641 title.push_str(name);
5642 }
5643
5644 if title.is_empty() {
5645 title = "empty project".to_string();
5646 }
5647
5648 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5649 let filename = path.path.file_name().or_else(|| {
5650 Some(
5651 project
5652 .worktree_for_id(path.worktree_id, cx)?
5653 .read(cx)
5654 .root_name_str(),
5655 )
5656 });
5657
5658 if let Some(filename) = filename {
5659 title.push_str(" — ");
5660 title.push_str(filename.as_ref());
5661 }
5662 }
5663
5664 if project.is_via_collab() {
5665 title.push_str(" ↙");
5666 } else if project.is_shared() {
5667 title.push_str(" ↗");
5668 }
5669
5670 if let Some(last_title) = self.last_window_title.as_ref()
5671 && &title == last_title
5672 {
5673 return;
5674 }
5675 window.set_window_title(&title);
5676 SystemWindowTabController::update_tab_title(
5677 cx,
5678 window.window_handle().window_id(),
5679 SharedString::from(&title),
5680 );
5681 self.last_window_title = Some(title);
5682 }
5683
5684 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5685 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5686 if is_edited != self.window_edited {
5687 self.window_edited = is_edited;
5688 window.set_window_edited(self.window_edited)
5689 }
5690 }
5691
5692 fn update_item_dirty_state(
5693 &mut self,
5694 item: &dyn ItemHandle,
5695 window: &mut Window,
5696 cx: &mut App,
5697 ) {
5698 let is_dirty = item.is_dirty(cx);
5699 let item_id = item.item_id();
5700 let was_dirty = self.dirty_items.contains_key(&item_id);
5701 if is_dirty == was_dirty {
5702 return;
5703 }
5704 if was_dirty {
5705 self.dirty_items.remove(&item_id);
5706 self.update_window_edited(window, cx);
5707 return;
5708 }
5709
5710 let workspace = self.weak_handle();
5711 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5712 return;
5713 };
5714 let on_release_callback = Box::new(move |cx: &mut App| {
5715 window_handle
5716 .update(cx, |_, window, cx| {
5717 workspace
5718 .update(cx, |workspace, cx| {
5719 workspace.dirty_items.remove(&item_id);
5720 workspace.update_window_edited(window, cx)
5721 })
5722 .ok();
5723 })
5724 .ok();
5725 });
5726
5727 let s = item.on_release(cx, on_release_callback);
5728 self.dirty_items.insert(item_id, s);
5729 self.update_window_edited(window, cx);
5730 }
5731
5732 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5733 if self.notifications.is_empty() {
5734 None
5735 } else {
5736 Some(
5737 div()
5738 .absolute()
5739 .right_3()
5740 .bottom_3()
5741 .w_112()
5742 .h_full()
5743 .flex()
5744 .flex_col()
5745 .justify_end()
5746 .gap_2()
5747 .children(
5748 self.notifications
5749 .iter()
5750 .map(|(_, notification)| notification.clone().into_any()),
5751 ),
5752 )
5753 }
5754 }
5755
5756 // RPC handlers
5757
5758 fn active_view_for_follower(
5759 &self,
5760 follower_project_id: Option<u64>,
5761 window: &mut Window,
5762 cx: &mut Context<Self>,
5763 ) -> Option<proto::View> {
5764 let (item, panel_id) = self.active_item_for_followers(window, cx);
5765 let item = item?;
5766 let leader_id = self
5767 .pane_for(&*item)
5768 .and_then(|pane| self.leader_for_pane(&pane));
5769 let leader_peer_id = match leader_id {
5770 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5771 Some(CollaboratorId::Agent) | None => None,
5772 };
5773
5774 let item_handle = item.to_followable_item_handle(cx)?;
5775 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5776 let variant = item_handle.to_state_proto(window, cx)?;
5777
5778 if item_handle.is_project_item(window, cx)
5779 && (follower_project_id.is_none()
5780 || follower_project_id != self.project.read(cx).remote_id())
5781 {
5782 return None;
5783 }
5784
5785 Some(proto::View {
5786 id: id.to_proto(),
5787 leader_id: leader_peer_id,
5788 variant: Some(variant),
5789 panel_id: panel_id.map(|id| id as i32),
5790 })
5791 }
5792
5793 fn handle_follow(
5794 &mut self,
5795 follower_project_id: Option<u64>,
5796 window: &mut Window,
5797 cx: &mut Context<Self>,
5798 ) -> proto::FollowResponse {
5799 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5800
5801 cx.notify();
5802 proto::FollowResponse {
5803 views: active_view.iter().cloned().collect(),
5804 active_view,
5805 }
5806 }
5807
5808 fn handle_update_followers(
5809 &mut self,
5810 leader_id: PeerId,
5811 message: proto::UpdateFollowers,
5812 _window: &mut Window,
5813 _cx: &mut Context<Self>,
5814 ) {
5815 self.leader_updates_tx
5816 .unbounded_send((leader_id, message))
5817 .ok();
5818 }
5819
5820 async fn process_leader_update(
5821 this: &WeakEntity<Self>,
5822 leader_id: PeerId,
5823 update: proto::UpdateFollowers,
5824 cx: &mut AsyncWindowContext,
5825 ) -> Result<()> {
5826 match update.variant.context("invalid update")? {
5827 proto::update_followers::Variant::CreateView(view) => {
5828 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5829 let should_add_view = this.update(cx, |this, _| {
5830 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5831 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5832 } else {
5833 anyhow::Ok(false)
5834 }
5835 })??;
5836
5837 if should_add_view {
5838 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5839 }
5840 }
5841 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5842 let should_add_view = this.update(cx, |this, _| {
5843 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5844 state.active_view_id = update_active_view
5845 .view
5846 .as_ref()
5847 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5848
5849 if state.active_view_id.is_some_and(|view_id| {
5850 !state.items_by_leader_view_id.contains_key(&view_id)
5851 }) {
5852 anyhow::Ok(true)
5853 } else {
5854 anyhow::Ok(false)
5855 }
5856 } else {
5857 anyhow::Ok(false)
5858 }
5859 })??;
5860
5861 if should_add_view && let Some(view) = update_active_view.view {
5862 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5863 }
5864 }
5865 proto::update_followers::Variant::UpdateView(update_view) => {
5866 let variant = update_view.variant.context("missing update view variant")?;
5867 let id = update_view.id.context("missing update view id")?;
5868 let mut tasks = Vec::new();
5869 this.update_in(cx, |this, window, cx| {
5870 let project = this.project.clone();
5871 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5872 let view_id = ViewId::from_proto(id.clone())?;
5873 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5874 tasks.push(item.view.apply_update_proto(
5875 &project,
5876 variant.clone(),
5877 window,
5878 cx,
5879 ));
5880 }
5881 }
5882 anyhow::Ok(())
5883 })??;
5884 try_join_all(tasks).await.log_err();
5885 }
5886 }
5887 this.update_in(cx, |this, window, cx| {
5888 this.leader_updated(leader_id, window, cx)
5889 })?;
5890 Ok(())
5891 }
5892
5893 async fn add_view_from_leader(
5894 this: WeakEntity<Self>,
5895 leader_id: PeerId,
5896 view: &proto::View,
5897 cx: &mut AsyncWindowContext,
5898 ) -> Result<()> {
5899 let this = this.upgrade().context("workspace dropped")?;
5900
5901 let Some(id) = view.id.clone() else {
5902 anyhow::bail!("no id for view");
5903 };
5904 let id = ViewId::from_proto(id)?;
5905 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5906
5907 let pane = this.update(cx, |this, _cx| {
5908 let state = this
5909 .follower_states
5910 .get(&leader_id.into())
5911 .context("stopped following")?;
5912 anyhow::Ok(state.pane().clone())
5913 })?;
5914 let existing_item = pane.update_in(cx, |pane, window, cx| {
5915 let client = this.read(cx).client().clone();
5916 pane.items().find_map(|item| {
5917 let item = item.to_followable_item_handle(cx)?;
5918 if item.remote_id(&client, window, cx) == Some(id) {
5919 Some(item)
5920 } else {
5921 None
5922 }
5923 })
5924 })?;
5925 let item = if let Some(existing_item) = existing_item {
5926 existing_item
5927 } else {
5928 let variant = view.variant.clone();
5929 anyhow::ensure!(variant.is_some(), "missing view variant");
5930
5931 let task = cx.update(|window, cx| {
5932 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5933 })?;
5934
5935 let Some(task) = task else {
5936 anyhow::bail!(
5937 "failed to construct view from leader (maybe from a different version of zed?)"
5938 );
5939 };
5940
5941 let mut new_item = task.await?;
5942 pane.update_in(cx, |pane, window, cx| {
5943 let mut item_to_remove = None;
5944 for (ix, item) in pane.items().enumerate() {
5945 if let Some(item) = item.to_followable_item_handle(cx) {
5946 match new_item.dedup(item.as_ref(), window, cx) {
5947 Some(item::Dedup::KeepExisting) => {
5948 new_item =
5949 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5950 break;
5951 }
5952 Some(item::Dedup::ReplaceExisting) => {
5953 item_to_remove = Some((ix, item.item_id()));
5954 break;
5955 }
5956 None => {}
5957 }
5958 }
5959 }
5960
5961 if let Some((ix, id)) = item_to_remove {
5962 pane.remove_item(id, false, false, window, cx);
5963 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5964 }
5965 })?;
5966
5967 new_item
5968 };
5969
5970 this.update_in(cx, |this, window, cx| {
5971 let state = this.follower_states.get_mut(&leader_id.into())?;
5972 item.set_leader_id(Some(leader_id.into()), window, cx);
5973 state.items_by_leader_view_id.insert(
5974 id,
5975 FollowerView {
5976 view: item,
5977 location: panel_id,
5978 },
5979 );
5980
5981 Some(())
5982 })
5983 .context("no follower state")?;
5984
5985 Ok(())
5986 }
5987
5988 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5989 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5990 return;
5991 };
5992
5993 if let Some(agent_location) = self.project.read(cx).agent_location() {
5994 let buffer_entity_id = agent_location.buffer.entity_id();
5995 let view_id = ViewId {
5996 creator: CollaboratorId::Agent,
5997 id: buffer_entity_id.as_u64(),
5998 };
5999 follower_state.active_view_id = Some(view_id);
6000
6001 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
6002 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
6003 hash_map::Entry::Vacant(entry) => {
6004 let existing_view =
6005 follower_state
6006 .center_pane
6007 .read(cx)
6008 .items()
6009 .find_map(|item| {
6010 let item = item.to_followable_item_handle(cx)?;
6011 if item.buffer_kind(cx) == ItemBufferKind::Singleton
6012 && item.project_item_model_ids(cx).as_slice()
6013 == [buffer_entity_id]
6014 {
6015 Some(item)
6016 } else {
6017 None
6018 }
6019 });
6020 let view = existing_view.or_else(|| {
6021 agent_location.buffer.upgrade().and_then(|buffer| {
6022 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
6023 registry.build_item(buffer, self.project.clone(), None, window, cx)
6024 })?
6025 .to_followable_item_handle(cx)
6026 })
6027 });
6028
6029 view.map(|view| {
6030 entry.insert(FollowerView {
6031 view,
6032 location: None,
6033 })
6034 })
6035 }
6036 };
6037
6038 if let Some(item) = item {
6039 item.view
6040 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
6041 item.view
6042 .update_agent_location(agent_location.position, window, cx);
6043 }
6044 } else {
6045 follower_state.active_view_id = None;
6046 }
6047
6048 self.leader_updated(CollaboratorId::Agent, window, cx);
6049 }
6050
6051 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
6052 let mut is_project_item = true;
6053 let mut update = proto::UpdateActiveView::default();
6054 if window.is_window_active() {
6055 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
6056
6057 if let Some(item) = active_item
6058 && item.item_focus_handle(cx).contains_focused(window, cx)
6059 {
6060 let leader_id = self
6061 .pane_for(&*item)
6062 .and_then(|pane| self.leader_for_pane(&pane));
6063 let leader_peer_id = match leader_id {
6064 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
6065 Some(CollaboratorId::Agent) | None => None,
6066 };
6067
6068 if let Some(item) = item.to_followable_item_handle(cx) {
6069 let id = item
6070 .remote_id(&self.app_state.client, window, cx)
6071 .map(|id| id.to_proto());
6072
6073 if let Some(id) = id
6074 && let Some(variant) = item.to_state_proto(window, cx)
6075 {
6076 let view = Some(proto::View {
6077 id,
6078 leader_id: leader_peer_id,
6079 variant: Some(variant),
6080 panel_id: panel_id.map(|id| id as i32),
6081 });
6082
6083 is_project_item = item.is_project_item(window, cx);
6084 update = proto::UpdateActiveView { view };
6085 };
6086 }
6087 }
6088 }
6089
6090 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
6091 if active_view_id != self.last_active_view_id.as_ref() {
6092 self.last_active_view_id = active_view_id.cloned();
6093 self.update_followers(
6094 is_project_item,
6095 proto::update_followers::Variant::UpdateActiveView(update),
6096 window,
6097 cx,
6098 );
6099 }
6100 }
6101
6102 fn active_item_for_followers(
6103 &self,
6104 window: &mut Window,
6105 cx: &mut App,
6106 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
6107 let mut active_item = None;
6108 let mut panel_id = None;
6109 for dock in self.all_docks() {
6110 if dock.focus_handle(cx).contains_focused(window, cx)
6111 && let Some(panel) = dock.read(cx).active_panel()
6112 && let Some(pane) = panel.pane(cx)
6113 && let Some(item) = pane.read(cx).active_item()
6114 {
6115 active_item = Some(item);
6116 panel_id = panel.remote_id();
6117 break;
6118 }
6119 }
6120
6121 if active_item.is_none() {
6122 active_item = self.active_pane().read(cx).active_item();
6123 }
6124 (active_item, panel_id)
6125 }
6126
6127 fn update_followers(
6128 &self,
6129 project_only: bool,
6130 update: proto::update_followers::Variant,
6131 _: &mut Window,
6132 cx: &mut App,
6133 ) -> Option<()> {
6134 // If this update only applies to for followers in the current project,
6135 // then skip it unless this project is shared. If it applies to all
6136 // followers, regardless of project, then set `project_id` to none,
6137 // indicating that it goes to all followers.
6138 let project_id = if project_only {
6139 Some(self.project.read(cx).remote_id()?)
6140 } else {
6141 None
6142 };
6143 self.app_state().workspace_store.update(cx, |store, cx| {
6144 store.update_followers(project_id, update, cx)
6145 })
6146 }
6147
6148 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
6149 self.follower_states.iter().find_map(|(leader_id, state)| {
6150 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
6151 Some(*leader_id)
6152 } else {
6153 None
6154 }
6155 })
6156 }
6157
6158 fn leader_updated(
6159 &mut self,
6160 leader_id: impl Into<CollaboratorId>,
6161 window: &mut Window,
6162 cx: &mut Context<Self>,
6163 ) -> Option<Box<dyn ItemHandle>> {
6164 cx.notify();
6165
6166 let leader_id = leader_id.into();
6167 let (panel_id, item) = match leader_id {
6168 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
6169 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
6170 };
6171
6172 let state = self.follower_states.get(&leader_id)?;
6173 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
6174 let pane;
6175 if let Some(panel_id) = panel_id {
6176 pane = self
6177 .activate_panel_for_proto_id(panel_id, window, cx)?
6178 .pane(cx)?;
6179 let state = self.follower_states.get_mut(&leader_id)?;
6180 state.dock_pane = Some(pane.clone());
6181 } else {
6182 pane = state.center_pane.clone();
6183 let state = self.follower_states.get_mut(&leader_id)?;
6184 if let Some(dock_pane) = state.dock_pane.take() {
6185 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
6186 }
6187 }
6188
6189 pane.update(cx, |pane, cx| {
6190 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
6191 if let Some(index) = pane.index_for_item(item.as_ref()) {
6192 pane.activate_item(index, false, false, window, cx);
6193 } else {
6194 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
6195 }
6196
6197 if focus_active_item {
6198 pane.focus_active_item(window, cx)
6199 }
6200 });
6201
6202 Some(item)
6203 }
6204
6205 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
6206 let state = self.follower_states.get(&CollaboratorId::Agent)?;
6207 let active_view_id = state.active_view_id?;
6208 Some(
6209 state
6210 .items_by_leader_view_id
6211 .get(&active_view_id)?
6212 .view
6213 .boxed_clone(),
6214 )
6215 }
6216
6217 fn active_item_for_peer(
6218 &self,
6219 peer_id: PeerId,
6220 window: &mut Window,
6221 cx: &mut Context<Self>,
6222 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
6223 let call = self.active_call()?;
6224 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
6225 let leader_in_this_app;
6226 let leader_in_this_project;
6227 match participant.location {
6228 ParticipantLocation::SharedProject { project_id } => {
6229 leader_in_this_app = true;
6230 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
6231 }
6232 ParticipantLocation::UnsharedProject => {
6233 leader_in_this_app = true;
6234 leader_in_this_project = false;
6235 }
6236 ParticipantLocation::External => {
6237 leader_in_this_app = false;
6238 leader_in_this_project = false;
6239 }
6240 };
6241 let state = self.follower_states.get(&peer_id.into())?;
6242 let mut item_to_activate = None;
6243 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
6244 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
6245 && (leader_in_this_project || !item.view.is_project_item(window, cx))
6246 {
6247 item_to_activate = Some((item.location, item.view.boxed_clone()));
6248 }
6249 } else if let Some(shared_screen) =
6250 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
6251 {
6252 item_to_activate = Some((None, Box::new(shared_screen)));
6253 }
6254 item_to_activate
6255 }
6256
6257 fn shared_screen_for_peer(
6258 &self,
6259 peer_id: PeerId,
6260 pane: &Entity<Pane>,
6261 window: &mut Window,
6262 cx: &mut App,
6263 ) -> Option<Entity<SharedScreen>> {
6264 self.active_call()?
6265 .create_shared_screen(peer_id, pane, window, cx)
6266 }
6267
6268 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6269 if window.is_window_active() {
6270 self.update_active_view_for_followers(window, cx);
6271
6272 if let Some(database_id) = self.database_id {
6273 let db = WorkspaceDb::global(cx);
6274 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6275 .detach();
6276 }
6277 } else {
6278 for pane in &self.panes {
6279 pane.update(cx, |pane, cx| {
6280 if let Some(item) = pane.active_item() {
6281 item.workspace_deactivated(window, cx);
6282 }
6283 for item in pane.items() {
6284 if matches!(
6285 item.workspace_settings(cx).autosave,
6286 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6287 ) {
6288 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6289 .detach_and_log_err(cx);
6290 }
6291 }
6292 });
6293 }
6294 }
6295 }
6296
6297 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6298 self.active_call.as_ref().map(|(call, _)| &*call.0)
6299 }
6300
6301 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6302 self.active_call.as_ref().map(|(call, _)| call.clone())
6303 }
6304
6305 fn on_active_call_event(
6306 &mut self,
6307 event: &ActiveCallEvent,
6308 window: &mut Window,
6309 cx: &mut Context<Self>,
6310 ) {
6311 match event {
6312 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6313 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6314 self.leader_updated(participant_id, window, cx);
6315 }
6316 }
6317 }
6318
6319 pub fn database_id(&self) -> Option<WorkspaceId> {
6320 self.database_id
6321 }
6322
6323 #[cfg(any(test, feature = "test-support"))]
6324 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6325 self.database_id = Some(id);
6326 }
6327
6328 pub fn session_id(&self) -> Option<String> {
6329 self.session_id.clone()
6330 }
6331
6332 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6333 let Some(display) = window.display(cx) else {
6334 return Task::ready(());
6335 };
6336 let Ok(display_uuid) = display.uuid() else {
6337 return Task::ready(());
6338 };
6339
6340 let window_bounds = window.inner_window_bounds();
6341 let database_id = self.database_id;
6342 let has_paths = !self.root_paths(cx).is_empty();
6343 let db = WorkspaceDb::global(cx);
6344 let kvp = db::kvp::KeyValueStore::global(cx);
6345
6346 cx.background_executor().spawn(async move {
6347 if !has_paths {
6348 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6349 .await
6350 .log_err();
6351 }
6352 if let Some(database_id) = database_id {
6353 db.set_window_open_status(
6354 database_id,
6355 SerializedWindowBounds(window_bounds),
6356 display_uuid,
6357 )
6358 .await
6359 .log_err();
6360 } else {
6361 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6362 .await
6363 .log_err();
6364 }
6365 })
6366 }
6367
6368 /// Bypass the 200ms serialization throttle and write workspace state to
6369 /// the DB immediately. Returns a task the caller can await to ensure the
6370 /// write completes. Used by the quit handler so the most recent state
6371 /// isn't lost to a pending throttle timer when the process exits.
6372 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6373 self._schedule_serialize_workspace.take();
6374 self._serialize_workspace_task.take();
6375 self.bounds_save_task_queued.take();
6376
6377 let bounds_task = self.save_window_bounds(window, cx);
6378 let serialize_task = self.serialize_workspace_internal(window, cx);
6379 cx.spawn(async move |_| {
6380 bounds_task.await;
6381 serialize_task.await;
6382 })
6383 }
6384
6385 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6386 let project = self.project().read(cx);
6387 project
6388 .visible_worktrees(cx)
6389 .map(|worktree| worktree.read(cx).abs_path())
6390 .collect::<Vec<_>>()
6391 }
6392
6393 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6394 match member {
6395 Member::Axis(PaneAxis { members, .. }) => {
6396 for child in members.iter() {
6397 self.remove_panes(child.clone(), window, cx)
6398 }
6399 }
6400 Member::Pane(pane) => {
6401 self.force_remove_pane(&pane, &None, window, cx);
6402 }
6403 }
6404 }
6405
6406 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6407 self.session_id.take();
6408 self.serialize_workspace_internal(window, cx)
6409 }
6410
6411 fn force_remove_pane(
6412 &mut self,
6413 pane: &Entity<Pane>,
6414 focus_on: &Option<Entity<Pane>>,
6415 window: &mut Window,
6416 cx: &mut Context<Workspace>,
6417 ) {
6418 self.panes.retain(|p| p != pane);
6419 if let Some(focus_on) = focus_on {
6420 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6421 } else if self.active_pane() == pane {
6422 self.panes
6423 .last()
6424 .unwrap()
6425 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6426 }
6427 if self.last_active_center_pane == Some(pane.downgrade()) {
6428 self.last_active_center_pane = None;
6429 }
6430 cx.notify();
6431 }
6432
6433 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6434 if self._schedule_serialize_workspace.is_none() {
6435 self._schedule_serialize_workspace =
6436 Some(cx.spawn_in(window, async move |this, cx| {
6437 cx.background_executor()
6438 .timer(SERIALIZATION_THROTTLE_TIME)
6439 .await;
6440 this.update_in(cx, |this, window, cx| {
6441 this._serialize_workspace_task =
6442 Some(this.serialize_workspace_internal(window, cx));
6443 this._schedule_serialize_workspace.take();
6444 })
6445 .log_err();
6446 }));
6447 }
6448 }
6449
6450 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6451 let Some(database_id) = self.database_id() else {
6452 return Task::ready(());
6453 };
6454
6455 fn serialize_pane_handle(
6456 pane_handle: &Entity<Pane>,
6457 window: &mut Window,
6458 cx: &mut App,
6459 ) -> SerializedPane {
6460 let (items, active, pinned_count) = {
6461 let pane = pane_handle.read(cx);
6462 let active_item_id = pane.active_item().map(|item| item.item_id());
6463 (
6464 pane.items()
6465 .filter_map(|handle| {
6466 let handle = handle.to_serializable_item_handle(cx)?;
6467
6468 Some(SerializedItem {
6469 kind: Arc::from(handle.serialized_item_kind()),
6470 item_id: handle.item_id().as_u64(),
6471 active: Some(handle.item_id()) == active_item_id,
6472 preview: pane.is_active_preview_item(handle.item_id()),
6473 })
6474 })
6475 .collect::<Vec<_>>(),
6476 pane.has_focus(window, cx),
6477 pane.pinned_count(),
6478 )
6479 };
6480
6481 SerializedPane::new(items, active, pinned_count)
6482 }
6483
6484 fn build_serialized_pane_group(
6485 pane_group: &Member,
6486 window: &mut Window,
6487 cx: &mut App,
6488 ) -> SerializedPaneGroup {
6489 match pane_group {
6490 Member::Axis(PaneAxis {
6491 axis,
6492 members,
6493 flexes,
6494 bounding_boxes: _,
6495 }) => SerializedPaneGroup::Group {
6496 axis: SerializedAxis(*axis),
6497 children: members
6498 .iter()
6499 .map(|member| build_serialized_pane_group(member, window, cx))
6500 .collect::<Vec<_>>(),
6501 flexes: Some(flexes.lock().clone()),
6502 },
6503 Member::Pane(pane_handle) => {
6504 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6505 }
6506 }
6507 }
6508
6509 fn build_serialized_docks(
6510 this: &Workspace,
6511 window: &mut Window,
6512 cx: &mut App,
6513 ) -> DockStructure {
6514 this.capture_dock_state(window, cx)
6515 }
6516
6517 match self.workspace_location(cx) {
6518 WorkspaceLocation::Location(location, paths) => {
6519 let breakpoints = self.project.update(cx, |project, cx| {
6520 project
6521 .breakpoint_store()
6522 .read(cx)
6523 .all_source_breakpoints(cx)
6524 });
6525 let user_toolchains = self
6526 .project
6527 .read(cx)
6528 .user_toolchains(cx)
6529 .unwrap_or_default();
6530
6531 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6532 let docks = build_serialized_docks(self, window, cx);
6533 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6534
6535 let serialized_workspace = SerializedWorkspace {
6536 id: database_id,
6537 location,
6538 paths,
6539 center_group,
6540 window_bounds,
6541 display: Default::default(),
6542 docks,
6543 centered_layout: self.centered_layout,
6544 session_id: self.session_id.clone(),
6545 breakpoints,
6546 window_id: Some(window.window_handle().window_id().as_u64()),
6547 user_toolchains,
6548 };
6549
6550 let db = WorkspaceDb::global(cx);
6551 window.spawn(cx, async move |_| {
6552 db.save_workspace(serialized_workspace).await;
6553 })
6554 }
6555 WorkspaceLocation::DetachFromSession => {
6556 let window_bounds = SerializedWindowBounds(window.window_bounds());
6557 let display = window.display(cx).and_then(|d| d.uuid().ok());
6558 // Save dock state for empty local workspaces
6559 let docks = build_serialized_docks(self, window, cx);
6560 let db = WorkspaceDb::global(cx);
6561 let kvp = db::kvp::KeyValueStore::global(cx);
6562 window.spawn(cx, async move |_| {
6563 db.set_window_open_status(
6564 database_id,
6565 window_bounds,
6566 display.unwrap_or_default(),
6567 )
6568 .await
6569 .log_err();
6570 db.set_session_id(database_id, None).await.log_err();
6571 persistence::write_default_dock_state(&kvp, docks)
6572 .await
6573 .log_err();
6574 })
6575 }
6576 WorkspaceLocation::None => {
6577 // Save dock state for empty non-local workspaces
6578 let docks = build_serialized_docks(self, window, cx);
6579 let kvp = db::kvp::KeyValueStore::global(cx);
6580 window.spawn(cx, async move |_| {
6581 persistence::write_default_dock_state(&kvp, docks)
6582 .await
6583 .log_err();
6584 })
6585 }
6586 }
6587 }
6588
6589 fn has_any_items_open(&self, cx: &App) -> bool {
6590 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6591 }
6592
6593 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6594 let paths = PathList::new(&self.root_paths(cx));
6595 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6596 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6597 } else if self.project.read(cx).is_local() {
6598 if !paths.is_empty() || self.has_any_items_open(cx) {
6599 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6600 } else {
6601 WorkspaceLocation::DetachFromSession
6602 }
6603 } else {
6604 WorkspaceLocation::None
6605 }
6606 }
6607
6608 fn update_history(&self, cx: &mut App) {
6609 let Some(id) = self.database_id() else {
6610 return;
6611 };
6612 if !self.project.read(cx).is_local() {
6613 return;
6614 }
6615 if let Some(manager) = HistoryManager::global(cx) {
6616 let paths = PathList::new(&self.root_paths(cx));
6617 manager.update(cx, |this, cx| {
6618 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6619 });
6620 }
6621 }
6622
6623 async fn serialize_items(
6624 this: &WeakEntity<Self>,
6625 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6626 cx: &mut AsyncWindowContext,
6627 ) -> Result<()> {
6628 const CHUNK_SIZE: usize = 200;
6629
6630 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6631
6632 while let Some(items_received) = serializable_items.next().await {
6633 let unique_items =
6634 items_received
6635 .into_iter()
6636 .fold(HashMap::default(), |mut acc, item| {
6637 acc.entry(item.item_id()).or_insert(item);
6638 acc
6639 });
6640
6641 // We use into_iter() here so that the references to the items are moved into
6642 // the tasks and not kept alive while we're sleeping.
6643 for (_, item) in unique_items.into_iter() {
6644 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6645 item.serialize(workspace, false, window, cx)
6646 }) {
6647 cx.background_spawn(async move { task.await.log_err() })
6648 .detach();
6649 }
6650 }
6651
6652 cx.background_executor()
6653 .timer(SERIALIZATION_THROTTLE_TIME)
6654 .await;
6655 }
6656
6657 Ok(())
6658 }
6659
6660 pub(crate) fn enqueue_item_serialization(
6661 &mut self,
6662 item: Box<dyn SerializableItemHandle>,
6663 ) -> Result<()> {
6664 self.serializable_items_tx
6665 .unbounded_send(item)
6666 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6667 }
6668
6669 pub(crate) fn load_workspace(
6670 serialized_workspace: SerializedWorkspace,
6671 paths_to_open: Vec<Option<ProjectPath>>,
6672 window: &mut Window,
6673 cx: &mut Context<Workspace>,
6674 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6675 cx.spawn_in(window, async move |workspace, cx| {
6676 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6677
6678 let mut center_group = None;
6679 let mut center_items = None;
6680
6681 // Traverse the splits tree and add to things
6682 if let Some((group, active_pane, items)) = serialized_workspace
6683 .center_group
6684 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6685 .await
6686 {
6687 center_items = Some(items);
6688 center_group = Some((group, active_pane))
6689 }
6690
6691 let mut items_by_project_path = HashMap::default();
6692 let mut item_ids_by_kind = HashMap::default();
6693 let mut all_deserialized_items = Vec::default();
6694 cx.update(|_, cx| {
6695 for item in center_items.unwrap_or_default().into_iter().flatten() {
6696 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6697 item_ids_by_kind
6698 .entry(serializable_item_handle.serialized_item_kind())
6699 .or_insert(Vec::new())
6700 .push(item.item_id().as_u64() as ItemId);
6701 }
6702
6703 if let Some(project_path) = item.project_path(cx) {
6704 items_by_project_path.insert(project_path, item.clone());
6705 }
6706 all_deserialized_items.push(item);
6707 }
6708 })?;
6709
6710 let opened_items = paths_to_open
6711 .into_iter()
6712 .map(|path_to_open| {
6713 path_to_open
6714 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6715 })
6716 .collect::<Vec<_>>();
6717
6718 // Remove old panes from workspace panes list
6719 workspace.update_in(cx, |workspace, window, cx| {
6720 if let Some((center_group, active_pane)) = center_group {
6721 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6722
6723 // Swap workspace center group
6724 workspace.center = PaneGroup::with_root(center_group);
6725 workspace.center.set_is_center(true);
6726 workspace.center.mark_positions(cx);
6727
6728 if let Some(active_pane) = active_pane {
6729 workspace.set_active_pane(&active_pane, window, cx);
6730 cx.focus_self(window);
6731 } else {
6732 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6733 }
6734 }
6735
6736 let docks = serialized_workspace.docks;
6737
6738 for (dock, serialized_dock) in [
6739 (&mut workspace.right_dock, docks.right),
6740 (&mut workspace.left_dock, docks.left),
6741 (&mut workspace.bottom_dock, docks.bottom),
6742 ]
6743 .iter_mut()
6744 {
6745 dock.update(cx, |dock, cx| {
6746 dock.serialized_dock = Some(serialized_dock.clone());
6747 dock.restore_state(window, cx);
6748 });
6749 }
6750
6751 cx.notify();
6752 })?;
6753
6754 let _ = project
6755 .update(cx, |project, cx| {
6756 project
6757 .breakpoint_store()
6758 .update(cx, |breakpoint_store, cx| {
6759 breakpoint_store
6760 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6761 })
6762 })
6763 .await;
6764
6765 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6766 // after loading the items, we might have different items and in order to avoid
6767 // the database filling up, we delete items that haven't been loaded now.
6768 //
6769 // The items that have been loaded, have been saved after they've been added to the workspace.
6770 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6771 item_ids_by_kind
6772 .into_iter()
6773 .map(|(item_kind, loaded_items)| {
6774 SerializableItemRegistry::cleanup(
6775 item_kind,
6776 serialized_workspace.id,
6777 loaded_items,
6778 window,
6779 cx,
6780 )
6781 .log_err()
6782 })
6783 .collect::<Vec<_>>()
6784 })?;
6785
6786 futures::future::join_all(clean_up_tasks).await;
6787
6788 workspace
6789 .update_in(cx, |workspace, window, cx| {
6790 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6791 workspace.serialize_workspace_internal(window, cx).detach();
6792
6793 // Ensure that we mark the window as edited if we did load dirty items
6794 workspace.update_window_edited(window, cx);
6795 })
6796 .ok();
6797
6798 Ok(opened_items)
6799 })
6800 }
6801
6802 pub fn key_context(&self, cx: &App) -> KeyContext {
6803 let mut context = KeyContext::new_with_defaults();
6804 context.add("Workspace");
6805 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6806 if let Some(status) = self
6807 .debugger_provider
6808 .as_ref()
6809 .and_then(|provider| provider.active_thread_state(cx))
6810 {
6811 match status {
6812 ThreadStatus::Running | ThreadStatus::Stepping => {
6813 context.add("debugger_running");
6814 }
6815 ThreadStatus::Stopped => context.add("debugger_stopped"),
6816 ThreadStatus::Exited | ThreadStatus::Ended => {}
6817 }
6818 }
6819
6820 if self.left_dock.read(cx).is_open() {
6821 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6822 context.set("left_dock", active_panel.panel_key());
6823 }
6824 }
6825
6826 if self.right_dock.read(cx).is_open() {
6827 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6828 context.set("right_dock", active_panel.panel_key());
6829 }
6830 }
6831
6832 if self.bottom_dock.read(cx).is_open() {
6833 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6834 context.set("bottom_dock", active_panel.panel_key());
6835 }
6836 }
6837
6838 context
6839 }
6840
6841 /// Multiworkspace uses this to add workspace action handling to itself
6842 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6843 self.add_workspace_actions_listeners(div, window, cx)
6844 .on_action(cx.listener(
6845 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6846 for action in &action_sequence.0 {
6847 window.dispatch_action(action.boxed_clone(), cx);
6848 }
6849 },
6850 ))
6851 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6852 .on_action(cx.listener(Self::close_all_items_and_panes))
6853 .on_action(cx.listener(Self::close_item_in_all_panes))
6854 .on_action(cx.listener(Self::save_all))
6855 .on_action(cx.listener(Self::send_keystrokes))
6856 .on_action(cx.listener(Self::add_folder_to_project))
6857 .on_action(cx.listener(Self::follow_next_collaborator))
6858 .on_action(cx.listener(Self::activate_pane_at_index))
6859 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6860 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6861 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6862 .on_action(cx.listener(Self::toggle_theme_mode))
6863 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6864 let pane = workspace.active_pane().clone();
6865 workspace.unfollow_in_pane(&pane, window, cx);
6866 }))
6867 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6868 workspace
6869 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6870 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6871 }))
6872 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6873 workspace
6874 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6875 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6876 }))
6877 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6878 workspace
6879 .save_active_item(SaveIntent::SaveAs, window, cx)
6880 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6881 }))
6882 .on_action(
6883 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6884 workspace.activate_previous_pane(window, cx)
6885 }),
6886 )
6887 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6888 workspace.activate_next_pane(window, cx)
6889 }))
6890 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6891 workspace.activate_last_pane(window, cx)
6892 }))
6893 .on_action(
6894 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6895 workspace.activate_next_window(cx)
6896 }),
6897 )
6898 .on_action(
6899 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6900 workspace.activate_previous_window(cx)
6901 }),
6902 )
6903 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6904 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6905 }))
6906 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6907 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6908 }))
6909 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6910 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6911 }))
6912 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6913 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6914 }))
6915 .on_action(cx.listener(
6916 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6917 workspace.move_item_to_pane_in_direction(action, window, cx)
6918 },
6919 ))
6920 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6921 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6922 }))
6923 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6924 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6925 }))
6926 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6927 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6928 }))
6929 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6930 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6931 }))
6932 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6933 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6934 SplitDirection::Down,
6935 SplitDirection::Up,
6936 SplitDirection::Right,
6937 SplitDirection::Left,
6938 ];
6939 for dir in DIRECTION_PRIORITY {
6940 if workspace.find_pane_in_direction(dir, cx).is_some() {
6941 workspace.swap_pane_in_direction(dir, cx);
6942 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6943 break;
6944 }
6945 }
6946 }))
6947 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6948 workspace.move_pane_to_border(SplitDirection::Left, cx)
6949 }))
6950 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6951 workspace.move_pane_to_border(SplitDirection::Right, cx)
6952 }))
6953 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6954 workspace.move_pane_to_border(SplitDirection::Up, cx)
6955 }))
6956 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6957 workspace.move_pane_to_border(SplitDirection::Down, cx)
6958 }))
6959 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6960 this.toggle_dock(DockPosition::Left, window, cx);
6961 }))
6962 .on_action(cx.listener(
6963 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6964 workspace.toggle_dock(DockPosition::Right, window, cx);
6965 },
6966 ))
6967 .on_action(cx.listener(
6968 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6969 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6970 },
6971 ))
6972 .on_action(cx.listener(
6973 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6974 if !workspace.close_active_dock(window, cx) {
6975 cx.propagate();
6976 }
6977 },
6978 ))
6979 .on_action(
6980 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6981 workspace.close_all_docks(window, cx);
6982 }),
6983 )
6984 .on_action(cx.listener(Self::toggle_all_docks))
6985 .on_action(cx.listener(
6986 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6987 workspace.clear_all_notifications(cx);
6988 },
6989 ))
6990 .on_action(cx.listener(
6991 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6992 workspace.clear_navigation_history(window, cx);
6993 },
6994 ))
6995 .on_action(cx.listener(
6996 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6997 if let Some((notification_id, _)) = workspace.notifications.pop() {
6998 workspace.suppress_notification(¬ification_id, cx);
6999 }
7000 },
7001 ))
7002 .on_action(cx.listener(
7003 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
7004 workspace.show_worktree_trust_security_modal(true, window, cx);
7005 },
7006 ))
7007 .on_action(
7008 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
7009 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
7010 trusted_worktrees.update(cx, |trusted_worktrees, _| {
7011 trusted_worktrees.clear_trusted_paths()
7012 });
7013 let db = WorkspaceDb::global(cx);
7014 cx.spawn(async move |_, cx| {
7015 if db.clear_trusted_worktrees().await.log_err().is_some() {
7016 cx.update(|cx| reload(cx));
7017 }
7018 })
7019 .detach();
7020 }
7021 }),
7022 )
7023 .on_action(cx.listener(
7024 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
7025 workspace.reopen_closed_item(window, cx).detach();
7026 },
7027 ))
7028 .on_action(cx.listener(
7029 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
7030 for dock in workspace.all_docks() {
7031 if dock.focus_handle(cx).contains_focused(window, cx) {
7032 let panel = dock.read(cx).active_panel().cloned();
7033 if let Some(panel) = panel {
7034 dock.update(cx, |dock, cx| {
7035 dock.set_panel_size_state(
7036 panel.as_ref(),
7037 dock::PanelSizeState::default(),
7038 cx,
7039 );
7040 });
7041 }
7042 return;
7043 }
7044 }
7045 },
7046 ))
7047 .on_action(cx.listener(
7048 |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
7049 for dock in workspace.all_docks() {
7050 let panel = dock.read(cx).visible_panel().cloned();
7051 if let Some(panel) = panel {
7052 dock.update(cx, |dock, cx| {
7053 dock.set_panel_size_state(
7054 panel.as_ref(),
7055 dock::PanelSizeState::default(),
7056 cx,
7057 );
7058 });
7059 }
7060 }
7061 },
7062 ))
7063 .on_action(cx.listener(
7064 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
7065 adjust_active_dock_size_by_px(
7066 px_with_ui_font_fallback(act.px, cx),
7067 workspace,
7068 window,
7069 cx,
7070 );
7071 },
7072 ))
7073 .on_action(cx.listener(
7074 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
7075 adjust_active_dock_size_by_px(
7076 px_with_ui_font_fallback(act.px, cx) * -1.,
7077 workspace,
7078 window,
7079 cx,
7080 );
7081 },
7082 ))
7083 .on_action(cx.listener(
7084 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
7085 adjust_open_docks_size_by_px(
7086 px_with_ui_font_fallback(act.px, cx),
7087 workspace,
7088 window,
7089 cx,
7090 );
7091 },
7092 ))
7093 .on_action(cx.listener(
7094 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
7095 adjust_open_docks_size_by_px(
7096 px_with_ui_font_fallback(act.px, cx) * -1.,
7097 workspace,
7098 window,
7099 cx,
7100 );
7101 },
7102 ))
7103 .on_action(cx.listener(Workspace::toggle_centered_layout))
7104 .on_action(cx.listener(
7105 |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
7106 if let Some(active_dock) = workspace.active_dock(window, cx) {
7107 let dock = active_dock.read(cx);
7108 if let Some(active_panel) = dock.active_panel() {
7109 if active_panel.pane(cx).is_none() {
7110 let mut recent_pane: Option<Entity<Pane>> = None;
7111 let mut recent_timestamp = 0;
7112 for pane_handle in workspace.panes() {
7113 let pane = pane_handle.read(cx);
7114 for entry in pane.activation_history() {
7115 if entry.timestamp > recent_timestamp {
7116 recent_timestamp = entry.timestamp;
7117 recent_pane = Some(pane_handle.clone());
7118 }
7119 }
7120 }
7121
7122 if let Some(pane) = recent_pane {
7123 let wrap_around = action.wrap_around;
7124 pane.update(cx, |pane, cx| {
7125 let current_index = pane.active_item_index();
7126 let items_len = pane.items_len();
7127 if items_len > 0 {
7128 let next_index = if current_index + 1 < items_len {
7129 current_index + 1
7130 } else if wrap_around {
7131 0
7132 } else {
7133 return;
7134 };
7135 pane.activate_item(
7136 next_index, false, false, window, cx,
7137 );
7138 }
7139 });
7140 return;
7141 }
7142 }
7143 }
7144 }
7145 cx.propagate();
7146 },
7147 ))
7148 .on_action(cx.listener(
7149 |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
7150 if let Some(active_dock) = workspace.active_dock(window, cx) {
7151 let dock = active_dock.read(cx);
7152 if let Some(active_panel) = dock.active_panel() {
7153 if active_panel.pane(cx).is_none() {
7154 let mut recent_pane: Option<Entity<Pane>> = None;
7155 let mut recent_timestamp = 0;
7156 for pane_handle in workspace.panes() {
7157 let pane = pane_handle.read(cx);
7158 for entry in pane.activation_history() {
7159 if entry.timestamp > recent_timestamp {
7160 recent_timestamp = entry.timestamp;
7161 recent_pane = Some(pane_handle.clone());
7162 }
7163 }
7164 }
7165
7166 if let Some(pane) = recent_pane {
7167 let wrap_around = action.wrap_around;
7168 pane.update(cx, |pane, cx| {
7169 let current_index = pane.active_item_index();
7170 let items_len = pane.items_len();
7171 if items_len > 0 {
7172 let prev_index = if current_index > 0 {
7173 current_index - 1
7174 } else if wrap_around {
7175 items_len.saturating_sub(1)
7176 } else {
7177 return;
7178 };
7179 pane.activate_item(
7180 prev_index, false, false, window, cx,
7181 );
7182 }
7183 });
7184 return;
7185 }
7186 }
7187 }
7188 }
7189 cx.propagate();
7190 },
7191 ))
7192 .on_action(cx.listener(
7193 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
7194 if let Some(active_dock) = workspace.active_dock(window, cx) {
7195 let dock = active_dock.read(cx);
7196 if let Some(active_panel) = dock.active_panel() {
7197 if active_panel.pane(cx).is_none() {
7198 let active_pane = workspace.active_pane().clone();
7199 active_pane.update(cx, |pane, cx| {
7200 pane.close_active_item(action, window, cx)
7201 .detach_and_log_err(cx);
7202 });
7203 return;
7204 }
7205 }
7206 }
7207 cx.propagate();
7208 },
7209 ))
7210 .on_action(
7211 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
7212 let pane = workspace.active_pane().clone();
7213 if let Some(item) = pane.read(cx).active_item() {
7214 item.toggle_read_only(window, cx);
7215 }
7216 }),
7217 )
7218 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
7219 workspace.focus_center_pane(window, cx);
7220 }))
7221 .on_action(cx.listener(Workspace::cancel))
7222 }
7223
7224 #[cfg(any(test, feature = "test-support"))]
7225 pub fn set_random_database_id(&mut self) {
7226 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
7227 }
7228
7229 #[cfg(any(test, feature = "test-support"))]
7230 pub(crate) fn test_new(
7231 project: Entity<Project>,
7232 window: &mut Window,
7233 cx: &mut Context<Self>,
7234 ) -> Self {
7235 use node_runtime::NodeRuntime;
7236 use session::Session;
7237
7238 let client = project.read(cx).client();
7239 let user_store = project.read(cx).user_store();
7240 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
7241 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
7242 window.activate_window();
7243 let app_state = Arc::new(AppState {
7244 languages: project.read(cx).languages().clone(),
7245 workspace_store,
7246 client,
7247 user_store,
7248 fs: project.read(cx).fs().clone(),
7249 build_window_options: |_, _| Default::default(),
7250 node_runtime: NodeRuntime::unavailable(),
7251 session,
7252 });
7253 let workspace = Self::new(Default::default(), project, app_state, window, cx);
7254 workspace
7255 .active_pane
7256 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
7257 workspace
7258 }
7259
7260 pub fn register_action<A: Action>(
7261 &mut self,
7262 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
7263 ) -> &mut Self {
7264 let callback = Arc::new(callback);
7265
7266 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
7267 let callback = callback.clone();
7268 div.on_action(cx.listener(move |workspace, event, window, cx| {
7269 (callback)(workspace, event, window, cx)
7270 }))
7271 }));
7272 self
7273 }
7274 pub fn register_action_renderer(
7275 &mut self,
7276 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
7277 ) -> &mut Self {
7278 self.workspace_actions.push(Box::new(callback));
7279 self
7280 }
7281
7282 fn add_workspace_actions_listeners(
7283 &self,
7284 mut div: Div,
7285 window: &mut Window,
7286 cx: &mut Context<Self>,
7287 ) -> Div {
7288 for action in self.workspace_actions.iter() {
7289 div = (action)(div, self, window, cx)
7290 }
7291 div
7292 }
7293
7294 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7295 self.modal_layer.read(cx).has_active_modal()
7296 }
7297
7298 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7299 self.modal_layer
7300 .read(cx)
7301 .is_active_modal_command_palette(cx)
7302 }
7303
7304 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7305 self.modal_layer.read(cx).active_modal()
7306 }
7307
7308 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7309 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7310 /// If no modal is active, the new modal will be shown.
7311 ///
7312 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7313 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7314 /// will not be shown.
7315 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7316 where
7317 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7318 {
7319 self.modal_layer.update(cx, |modal_layer, cx| {
7320 modal_layer.toggle_modal(window, cx, build)
7321 })
7322 }
7323
7324 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7325 self.modal_layer
7326 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7327 }
7328
7329 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7330 self.toast_layer
7331 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7332 }
7333
7334 pub fn toggle_centered_layout(
7335 &mut self,
7336 _: &ToggleCenteredLayout,
7337 _: &mut Window,
7338 cx: &mut Context<Self>,
7339 ) {
7340 self.centered_layout = !self.centered_layout;
7341 if let Some(database_id) = self.database_id() {
7342 let db = WorkspaceDb::global(cx);
7343 let centered_layout = self.centered_layout;
7344 cx.background_spawn(async move {
7345 db.set_centered_layout(database_id, centered_layout).await
7346 })
7347 .detach_and_log_err(cx);
7348 }
7349 cx.notify();
7350 }
7351
7352 fn adjust_padding(padding: Option<f32>) -> f32 {
7353 padding
7354 .unwrap_or(CenteredPaddingSettings::default().0)
7355 .clamp(
7356 CenteredPaddingSettings::MIN_PADDING,
7357 CenteredPaddingSettings::MAX_PADDING,
7358 )
7359 }
7360
7361 fn render_dock(
7362 &self,
7363 position: DockPosition,
7364 dock: &Entity<Dock>,
7365 window: &mut Window,
7366 cx: &mut App,
7367 ) -> Option<Div> {
7368 if self.zoomed_position == Some(position) {
7369 return None;
7370 }
7371
7372 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7373 let pane = panel.pane(cx)?;
7374 let follower_states = &self.follower_states;
7375 leader_border_for_pane(follower_states, &pane, window, cx)
7376 });
7377
7378 let mut container = div()
7379 .flex()
7380 .overflow_hidden()
7381 .flex_none()
7382 .child(dock.clone())
7383 .children(leader_border);
7384
7385 // Apply sizing only when the dock is open. When closed the dock is still
7386 // included in the element tree so its focus handle remains mounted — without
7387 // this, toggle_panel_focus cannot focus the panel when the dock is closed.
7388 let dock = dock.read(cx);
7389 if let Some(panel) = dock.visible_panel() {
7390 let size_state = dock.stored_panel_size_state(panel.as_ref());
7391 if position.axis() == Axis::Horizontal {
7392 let use_flexible = panel.has_flexible_size(window, cx);
7393 let flex_grow = if use_flexible {
7394 size_state
7395 .and_then(|state| state.flex)
7396 .or_else(|| self.default_dock_flex(position))
7397 } else {
7398 None
7399 };
7400 if let Some(grow) = flex_grow {
7401 let grow = grow.max(0.001);
7402 let style = container.style();
7403 style.flex_grow = Some(grow);
7404 style.flex_shrink = Some(1.0);
7405 style.flex_basis = Some(relative(0.).into());
7406 } else {
7407 let size = size_state
7408 .and_then(|state| state.size)
7409 .unwrap_or_else(|| panel.default_size(window, cx));
7410 container = container.w(size);
7411 }
7412 } else {
7413 let size = size_state
7414 .and_then(|state| state.size)
7415 .unwrap_or_else(|| panel.default_size(window, cx));
7416 container = container.h(size);
7417 }
7418 }
7419
7420 Some(container)
7421 }
7422
7423 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7424 window
7425 .root::<MultiWorkspace>()
7426 .flatten()
7427 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7428 }
7429
7430 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7431 self.zoomed.as_ref()
7432 }
7433
7434 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7435 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7436 return;
7437 };
7438 let windows = cx.windows();
7439 let next_window =
7440 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7441 || {
7442 windows
7443 .iter()
7444 .cycle()
7445 .skip_while(|window| window.window_id() != current_window_id)
7446 .nth(1)
7447 },
7448 );
7449
7450 if let Some(window) = next_window {
7451 window
7452 .update(cx, |_, window, _| window.activate_window())
7453 .ok();
7454 }
7455 }
7456
7457 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7458 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7459 return;
7460 };
7461 let windows = cx.windows();
7462 let prev_window =
7463 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7464 || {
7465 windows
7466 .iter()
7467 .rev()
7468 .cycle()
7469 .skip_while(|window| window.window_id() != current_window_id)
7470 .nth(1)
7471 },
7472 );
7473
7474 if let Some(window) = prev_window {
7475 window
7476 .update(cx, |_, window, _| window.activate_window())
7477 .ok();
7478 }
7479 }
7480
7481 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7482 if cx.stop_active_drag(window) {
7483 } else if let Some((notification_id, _)) = self.notifications.pop() {
7484 dismiss_app_notification(¬ification_id, cx);
7485 } else {
7486 cx.propagate();
7487 }
7488 }
7489
7490 fn resize_dock(
7491 &mut self,
7492 dock_pos: DockPosition,
7493 new_size: Pixels,
7494 window: &mut Window,
7495 cx: &mut Context<Self>,
7496 ) {
7497 match dock_pos {
7498 DockPosition::Left => self.resize_left_dock(new_size, window, cx),
7499 DockPosition::Right => self.resize_right_dock(new_size, window, cx),
7500 DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
7501 }
7502 }
7503
7504 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7505 let workspace_width = self.bounds.size.width;
7506 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7507
7508 self.right_dock.read_with(cx, |right_dock, cx| {
7509 let right_dock_size = right_dock
7510 .stored_active_panel_size(window, cx)
7511 .unwrap_or(Pixels::ZERO);
7512 if right_dock_size + size > workspace_width {
7513 size = workspace_width - right_dock_size
7514 }
7515 });
7516
7517 let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
7518 self.left_dock.update(cx, |left_dock, cx| {
7519 if WorkspaceSettings::get_global(cx)
7520 .resize_all_panels_in_dock
7521 .contains(&DockPosition::Left)
7522 {
7523 left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7524 } else {
7525 left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7526 }
7527 });
7528 }
7529
7530 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7531 let workspace_width = self.bounds.size.width;
7532 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7533 self.left_dock.read_with(cx, |left_dock, cx| {
7534 let left_dock_size = left_dock
7535 .stored_active_panel_size(window, cx)
7536 .unwrap_or(Pixels::ZERO);
7537 if left_dock_size + size > workspace_width {
7538 size = workspace_width - left_dock_size
7539 }
7540 });
7541 let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
7542 self.right_dock.update(cx, |right_dock, cx| {
7543 if WorkspaceSettings::get_global(cx)
7544 .resize_all_panels_in_dock
7545 .contains(&DockPosition::Right)
7546 {
7547 right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7548 } else {
7549 right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7550 }
7551 });
7552 }
7553
7554 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7555 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7556 self.bottom_dock.update(cx, |bottom_dock, cx| {
7557 if WorkspaceSettings::get_global(cx)
7558 .resize_all_panels_in_dock
7559 .contains(&DockPosition::Bottom)
7560 {
7561 bottom_dock.resize_all_panels(Some(size), None, window, cx);
7562 } else {
7563 bottom_dock.resize_active_panel(Some(size), None, window, cx);
7564 }
7565 });
7566 }
7567
7568 fn toggle_edit_predictions_all_files(
7569 &mut self,
7570 _: &ToggleEditPrediction,
7571 _window: &mut Window,
7572 cx: &mut Context<Self>,
7573 ) {
7574 let fs = self.project().read(cx).fs().clone();
7575 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7576 update_settings_file(fs, cx, move |file, _| {
7577 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7578 });
7579 }
7580
7581 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7582 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7583 let next_mode = match current_mode {
7584 Some(theme_settings::ThemeAppearanceMode::Light) => {
7585 theme_settings::ThemeAppearanceMode::Dark
7586 }
7587 Some(theme_settings::ThemeAppearanceMode::Dark) => {
7588 theme_settings::ThemeAppearanceMode::Light
7589 }
7590 Some(theme_settings::ThemeAppearanceMode::System) | None => {
7591 match cx.theme().appearance() {
7592 theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
7593 theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
7594 }
7595 }
7596 };
7597
7598 let fs = self.project().read(cx).fs().clone();
7599 settings::update_settings_file(fs, cx, move |settings, _cx| {
7600 theme_settings::set_mode(settings, next_mode);
7601 });
7602 }
7603
7604 pub fn show_worktree_trust_security_modal(
7605 &mut self,
7606 toggle: bool,
7607 window: &mut Window,
7608 cx: &mut Context<Self>,
7609 ) {
7610 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7611 if toggle {
7612 security_modal.update(cx, |security_modal, cx| {
7613 security_modal.dismiss(cx);
7614 })
7615 } else {
7616 security_modal.update(cx, |security_modal, cx| {
7617 security_modal.refresh_restricted_paths(cx);
7618 });
7619 }
7620 } else {
7621 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7622 .map(|trusted_worktrees| {
7623 trusted_worktrees
7624 .read(cx)
7625 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7626 })
7627 .unwrap_or(false);
7628 if has_restricted_worktrees {
7629 let project = self.project().read(cx);
7630 let remote_host = project
7631 .remote_connection_options(cx)
7632 .map(RemoteHostLocation::from);
7633 let worktree_store = project.worktree_store().downgrade();
7634 self.toggle_modal(window, cx, |_, cx| {
7635 SecurityModal::new(worktree_store, remote_host, cx)
7636 });
7637 }
7638 }
7639 }
7640}
7641
7642pub trait AnyActiveCall {
7643 fn entity(&self) -> AnyEntity;
7644 fn is_in_room(&self, _: &App) -> bool;
7645 fn room_id(&self, _: &App) -> Option<u64>;
7646 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7647 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7648 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7649 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7650 fn is_sharing_project(&self, _: &App) -> bool;
7651 fn has_remote_participants(&self, _: &App) -> bool;
7652 fn local_participant_is_guest(&self, _: &App) -> bool;
7653 fn client(&self, _: &App) -> Arc<Client>;
7654 fn share_on_join(&self, _: &App) -> bool;
7655 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7656 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7657 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7658 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7659 fn join_project(
7660 &self,
7661 _: u64,
7662 _: Arc<LanguageRegistry>,
7663 _: Arc<dyn Fs>,
7664 _: &mut App,
7665 ) -> Task<Result<Entity<Project>>>;
7666 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7667 fn subscribe(
7668 &self,
7669 _: &mut Window,
7670 _: &mut Context<Workspace>,
7671 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7672 ) -> Subscription;
7673 fn create_shared_screen(
7674 &self,
7675 _: PeerId,
7676 _: &Entity<Pane>,
7677 _: &mut Window,
7678 _: &mut App,
7679 ) -> Option<Entity<SharedScreen>>;
7680}
7681
7682#[derive(Clone)]
7683pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7684impl Global for GlobalAnyActiveCall {}
7685
7686impl GlobalAnyActiveCall {
7687 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7688 cx.try_global()
7689 }
7690
7691 pub(crate) fn global(cx: &App) -> &Self {
7692 cx.global()
7693 }
7694}
7695
7696pub fn merge_conflict_notification_id() -> NotificationId {
7697 struct MergeConflictNotification;
7698 NotificationId::unique::<MergeConflictNotification>()
7699}
7700
7701/// Workspace-local view of a remote participant's location.
7702#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7703pub enum ParticipantLocation {
7704 SharedProject { project_id: u64 },
7705 UnsharedProject,
7706 External,
7707}
7708
7709impl ParticipantLocation {
7710 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7711 match location
7712 .and_then(|l| l.variant)
7713 .context("participant location was not provided")?
7714 {
7715 proto::participant_location::Variant::SharedProject(project) => {
7716 Ok(Self::SharedProject {
7717 project_id: project.id,
7718 })
7719 }
7720 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7721 proto::participant_location::Variant::External(_) => Ok(Self::External),
7722 }
7723 }
7724}
7725/// Workspace-local view of a remote collaborator's state.
7726/// This is the subset of `call::RemoteParticipant` that workspace needs.
7727#[derive(Clone)]
7728pub struct RemoteCollaborator {
7729 pub user: Arc<User>,
7730 pub peer_id: PeerId,
7731 pub location: ParticipantLocation,
7732 pub participant_index: ParticipantIndex,
7733}
7734
7735pub enum ActiveCallEvent {
7736 ParticipantLocationChanged { participant_id: PeerId },
7737 RemoteVideoTracksChanged { participant_id: PeerId },
7738}
7739
7740fn leader_border_for_pane(
7741 follower_states: &HashMap<CollaboratorId, FollowerState>,
7742 pane: &Entity<Pane>,
7743 _: &Window,
7744 cx: &App,
7745) -> Option<Div> {
7746 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7747 if state.pane() == pane {
7748 Some((*leader_id, state))
7749 } else {
7750 None
7751 }
7752 })?;
7753
7754 let mut leader_color = match leader_id {
7755 CollaboratorId::PeerId(leader_peer_id) => {
7756 let leader = GlobalAnyActiveCall::try_global(cx)?
7757 .0
7758 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7759
7760 cx.theme()
7761 .players()
7762 .color_for_participant(leader.participant_index.0)
7763 .cursor
7764 }
7765 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7766 };
7767 leader_color.fade_out(0.3);
7768 Some(
7769 div()
7770 .absolute()
7771 .size_full()
7772 .left_0()
7773 .top_0()
7774 .border_2()
7775 .border_color(leader_color),
7776 )
7777}
7778
7779fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7780 ZED_WINDOW_POSITION
7781 .zip(*ZED_WINDOW_SIZE)
7782 .map(|(position, size)| Bounds {
7783 origin: position,
7784 size,
7785 })
7786}
7787
7788fn open_items(
7789 serialized_workspace: Option<SerializedWorkspace>,
7790 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7791 window: &mut Window,
7792 cx: &mut Context<Workspace>,
7793) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7794 let restored_items = serialized_workspace.map(|serialized_workspace| {
7795 Workspace::load_workspace(
7796 serialized_workspace,
7797 project_paths_to_open
7798 .iter()
7799 .map(|(_, project_path)| project_path)
7800 .cloned()
7801 .collect(),
7802 window,
7803 cx,
7804 )
7805 });
7806
7807 cx.spawn_in(window, async move |workspace, cx| {
7808 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7809
7810 if let Some(restored_items) = restored_items {
7811 let restored_items = restored_items.await?;
7812
7813 let restored_project_paths = restored_items
7814 .iter()
7815 .filter_map(|item| {
7816 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7817 .ok()
7818 .flatten()
7819 })
7820 .collect::<HashSet<_>>();
7821
7822 for restored_item in restored_items {
7823 opened_items.push(restored_item.map(Ok));
7824 }
7825
7826 project_paths_to_open
7827 .iter_mut()
7828 .for_each(|(_, project_path)| {
7829 if let Some(project_path_to_open) = project_path
7830 && restored_project_paths.contains(project_path_to_open)
7831 {
7832 *project_path = None;
7833 }
7834 });
7835 } else {
7836 for _ in 0..project_paths_to_open.len() {
7837 opened_items.push(None);
7838 }
7839 }
7840 assert!(opened_items.len() == project_paths_to_open.len());
7841
7842 let tasks =
7843 project_paths_to_open
7844 .into_iter()
7845 .enumerate()
7846 .map(|(ix, (abs_path, project_path))| {
7847 let workspace = workspace.clone();
7848 cx.spawn(async move |cx| {
7849 let file_project_path = project_path?;
7850 let abs_path_task = workspace.update(cx, |workspace, cx| {
7851 workspace.project().update(cx, |project, cx| {
7852 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7853 })
7854 });
7855
7856 // We only want to open file paths here. If one of the items
7857 // here is a directory, it was already opened further above
7858 // with a `find_or_create_worktree`.
7859 if let Ok(task) = abs_path_task
7860 && task.await.is_none_or(|p| p.is_file())
7861 {
7862 return Some((
7863 ix,
7864 workspace
7865 .update_in(cx, |workspace, window, cx| {
7866 workspace.open_path(
7867 file_project_path,
7868 None,
7869 true,
7870 window,
7871 cx,
7872 )
7873 })
7874 .log_err()?
7875 .await,
7876 ));
7877 }
7878 None
7879 })
7880 });
7881
7882 let tasks = tasks.collect::<Vec<_>>();
7883
7884 let tasks = futures::future::join_all(tasks);
7885 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7886 opened_items[ix] = Some(path_open_result);
7887 }
7888
7889 Ok(opened_items)
7890 })
7891}
7892
7893#[derive(Clone)]
7894enum ActivateInDirectionTarget {
7895 Pane(Entity<Pane>),
7896 Dock(Entity<Dock>),
7897 Sidebar(FocusHandle),
7898}
7899
7900fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7901 window
7902 .update(cx, |multi_workspace, _, cx| {
7903 let workspace = multi_workspace.workspace().clone();
7904 workspace.update(cx, |workspace, cx| {
7905 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7906 struct DatabaseFailedNotification;
7907
7908 workspace.show_notification(
7909 NotificationId::unique::<DatabaseFailedNotification>(),
7910 cx,
7911 |cx| {
7912 cx.new(|cx| {
7913 MessageNotification::new("Failed to load the database file.", cx)
7914 .primary_message("File an Issue")
7915 .primary_icon(IconName::Plus)
7916 .primary_on_click(|window, cx| {
7917 window.dispatch_action(Box::new(FileBugReport), cx)
7918 })
7919 })
7920 },
7921 );
7922 }
7923 });
7924 })
7925 .log_err();
7926}
7927
7928fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7929 if val == 0 {
7930 ThemeSettings::get_global(cx).ui_font_size(cx)
7931 } else {
7932 px(val as f32)
7933 }
7934}
7935
7936fn adjust_active_dock_size_by_px(
7937 px: Pixels,
7938 workspace: &mut Workspace,
7939 window: &mut Window,
7940 cx: &mut Context<Workspace>,
7941) {
7942 let Some(active_dock) = workspace
7943 .all_docks()
7944 .into_iter()
7945 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7946 else {
7947 return;
7948 };
7949 let dock = active_dock.read(cx);
7950 let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
7951 return;
7952 };
7953 workspace.resize_dock(dock.position(), panel_size + px, window, cx);
7954}
7955
7956fn adjust_open_docks_size_by_px(
7957 px: Pixels,
7958 workspace: &mut Workspace,
7959 window: &mut Window,
7960 cx: &mut Context<Workspace>,
7961) {
7962 let docks = workspace
7963 .all_docks()
7964 .into_iter()
7965 .filter_map(|dock_entity| {
7966 let dock = dock_entity.read(cx);
7967 if dock.is_open() {
7968 let dock_pos = dock.position();
7969 let panel_size = workspace.dock_size(&dock, window, cx)?;
7970 Some((dock_pos, panel_size + px))
7971 } else {
7972 None
7973 }
7974 })
7975 .collect::<Vec<_>>();
7976
7977 for (position, new_size) in docks {
7978 workspace.resize_dock(position, new_size, window, cx);
7979 }
7980}
7981
7982impl Focusable for Workspace {
7983 fn focus_handle(&self, cx: &App) -> FocusHandle {
7984 self.active_pane.focus_handle(cx)
7985 }
7986}
7987
7988#[derive(Clone)]
7989struct DraggedDock(DockPosition);
7990
7991impl Render for DraggedDock {
7992 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7993 gpui::Empty
7994 }
7995}
7996
7997impl Render for Workspace {
7998 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7999 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
8000 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
8001 log::info!("Rendered first frame");
8002 }
8003
8004 let centered_layout = self.centered_layout
8005 && self.center.panes().len() == 1
8006 && self.active_item(cx).is_some();
8007 let render_padding = |size| {
8008 (size > 0.0).then(|| {
8009 div()
8010 .h_full()
8011 .w(relative(size))
8012 .bg(cx.theme().colors().editor_background)
8013 .border_color(cx.theme().colors().pane_group_border)
8014 })
8015 };
8016 let paddings = if centered_layout {
8017 let settings = WorkspaceSettings::get_global(cx).centered_layout;
8018 (
8019 render_padding(Self::adjust_padding(
8020 settings.left_padding.map(|padding| padding.0),
8021 )),
8022 render_padding(Self::adjust_padding(
8023 settings.right_padding.map(|padding| padding.0),
8024 )),
8025 )
8026 } else {
8027 (None, None)
8028 };
8029 let ui_font = theme_settings::setup_ui_font(window, cx);
8030
8031 let theme = cx.theme().clone();
8032 let colors = theme.colors();
8033 let notification_entities = self
8034 .notifications
8035 .iter()
8036 .map(|(_, notification)| notification.entity_id())
8037 .collect::<Vec<_>>();
8038 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
8039
8040 div()
8041 .relative()
8042 .size_full()
8043 .flex()
8044 .flex_col()
8045 .font(ui_font)
8046 .gap_0()
8047 .justify_start()
8048 .items_start()
8049 .text_color(colors.text)
8050 .overflow_hidden()
8051 .children(self.titlebar_item.clone())
8052 .on_modifiers_changed(move |_, _, cx| {
8053 for &id in ¬ification_entities {
8054 cx.notify(id);
8055 }
8056 })
8057 .child(
8058 div()
8059 .size_full()
8060 .relative()
8061 .flex_1()
8062 .flex()
8063 .flex_col()
8064 .child(
8065 div()
8066 .id("workspace")
8067 .bg(colors.background)
8068 .relative()
8069 .flex_1()
8070 .w_full()
8071 .flex()
8072 .flex_col()
8073 .overflow_hidden()
8074 .border_t_1()
8075 .border_b_1()
8076 .border_color(colors.border)
8077 .child({
8078 let this = cx.entity();
8079 canvas(
8080 move |bounds, window, cx| {
8081 this.update(cx, |this, cx| {
8082 let bounds_changed = this.bounds != bounds;
8083 this.bounds = bounds;
8084
8085 if bounds_changed {
8086 this.left_dock.update(cx, |dock, cx| {
8087 dock.clamp_panel_size(
8088 bounds.size.width,
8089 window,
8090 cx,
8091 )
8092 });
8093
8094 this.right_dock.update(cx, |dock, cx| {
8095 dock.clamp_panel_size(
8096 bounds.size.width,
8097 window,
8098 cx,
8099 )
8100 });
8101
8102 this.bottom_dock.update(cx, |dock, cx| {
8103 dock.clamp_panel_size(
8104 bounds.size.height,
8105 window,
8106 cx,
8107 )
8108 });
8109 }
8110 })
8111 },
8112 |_, _, _, _| {},
8113 )
8114 .absolute()
8115 .size_full()
8116 })
8117 .when(self.zoomed.is_none(), |this| {
8118 this.on_drag_move(cx.listener(
8119 move |workspace,
8120 e: &DragMoveEvent<DraggedDock>,
8121 window,
8122 cx| {
8123 if workspace.previous_dock_drag_coordinates
8124 != Some(e.event.position)
8125 {
8126 workspace.previous_dock_drag_coordinates =
8127 Some(e.event.position);
8128
8129 match e.drag(cx).0 {
8130 DockPosition::Left => {
8131 workspace.resize_left_dock(
8132 e.event.position.x
8133 - workspace.bounds.left(),
8134 window,
8135 cx,
8136 );
8137 }
8138 DockPosition::Right => {
8139 workspace.resize_right_dock(
8140 workspace.bounds.right()
8141 - e.event.position.x,
8142 window,
8143 cx,
8144 );
8145 }
8146 DockPosition::Bottom => {
8147 workspace.resize_bottom_dock(
8148 workspace.bounds.bottom()
8149 - e.event.position.y,
8150 window,
8151 cx,
8152 );
8153 }
8154 };
8155 workspace.serialize_workspace(window, cx);
8156 }
8157 },
8158 ))
8159
8160 })
8161 .child({
8162 match bottom_dock_layout {
8163 BottomDockLayout::Full => div()
8164 .flex()
8165 .flex_col()
8166 .h_full()
8167 .child(
8168 div()
8169 .flex()
8170 .flex_row()
8171 .flex_1()
8172 .overflow_hidden()
8173 .children(self.render_dock(
8174 DockPosition::Left,
8175 &self.left_dock,
8176 window,
8177 cx,
8178 ))
8179
8180 .child(
8181 div()
8182 .flex()
8183 .flex_col()
8184 .flex_1()
8185 .overflow_hidden()
8186 .child(
8187 h_flex()
8188 .flex_1()
8189 .when_some(
8190 paddings.0,
8191 |this, p| {
8192 this.child(
8193 p.border_r_1(),
8194 )
8195 },
8196 )
8197 .child(self.center.render(
8198 self.zoomed.as_ref(),
8199 &PaneRenderContext {
8200 follower_states:
8201 &self.follower_states,
8202 active_call: self.active_call(),
8203 active_pane: &self.active_pane,
8204 app_state: &self.app_state,
8205 project: &self.project,
8206 workspace: &self.weak_self,
8207 },
8208 window,
8209 cx,
8210 ))
8211 .when_some(
8212 paddings.1,
8213 |this, p| {
8214 this.child(
8215 p.border_l_1(),
8216 )
8217 },
8218 ),
8219 ),
8220 )
8221
8222 .children(self.render_dock(
8223 DockPosition::Right,
8224 &self.right_dock,
8225 window,
8226 cx,
8227 )),
8228 )
8229 .child(div().w_full().children(self.render_dock(
8230 DockPosition::Bottom,
8231 &self.bottom_dock,
8232 window,
8233 cx
8234 ))),
8235
8236 BottomDockLayout::LeftAligned => div()
8237 .flex()
8238 .flex_row()
8239 .h_full()
8240 .child(
8241 div()
8242 .flex()
8243 .flex_col()
8244 .flex_1()
8245 .h_full()
8246 .child(
8247 div()
8248 .flex()
8249 .flex_row()
8250 .flex_1()
8251 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
8252
8253 .child(
8254 div()
8255 .flex()
8256 .flex_col()
8257 .flex_1()
8258 .overflow_hidden()
8259 .child(
8260 h_flex()
8261 .flex_1()
8262 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8263 .child(self.center.render(
8264 self.zoomed.as_ref(),
8265 &PaneRenderContext {
8266 follower_states:
8267 &self.follower_states,
8268 active_call: self.active_call(),
8269 active_pane: &self.active_pane,
8270 app_state: &self.app_state,
8271 project: &self.project,
8272 workspace: &self.weak_self,
8273 },
8274 window,
8275 cx,
8276 ))
8277 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8278 )
8279 )
8280
8281 )
8282 .child(
8283 div()
8284 .w_full()
8285 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8286 ),
8287 )
8288 .children(self.render_dock(
8289 DockPosition::Right,
8290 &self.right_dock,
8291 window,
8292 cx,
8293 )),
8294 BottomDockLayout::RightAligned => div()
8295 .flex()
8296 .flex_row()
8297 .h_full()
8298 .children(self.render_dock(
8299 DockPosition::Left,
8300 &self.left_dock,
8301 window,
8302 cx,
8303 ))
8304
8305 .child(
8306 div()
8307 .flex()
8308 .flex_col()
8309 .flex_1()
8310 .h_full()
8311 .child(
8312 div()
8313 .flex()
8314 .flex_row()
8315 .flex_1()
8316 .child(
8317 div()
8318 .flex()
8319 .flex_col()
8320 .flex_1()
8321 .overflow_hidden()
8322 .child(
8323 h_flex()
8324 .flex_1()
8325 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8326 .child(self.center.render(
8327 self.zoomed.as_ref(),
8328 &PaneRenderContext {
8329 follower_states:
8330 &self.follower_states,
8331 active_call: self.active_call(),
8332 active_pane: &self.active_pane,
8333 app_state: &self.app_state,
8334 project: &self.project,
8335 workspace: &self.weak_self,
8336 },
8337 window,
8338 cx,
8339 ))
8340 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8341 )
8342 )
8343
8344 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8345 )
8346 .child(
8347 div()
8348 .w_full()
8349 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8350 ),
8351 ),
8352 BottomDockLayout::Contained => div()
8353 .flex()
8354 .flex_row()
8355 .h_full()
8356 .children(self.render_dock(
8357 DockPosition::Left,
8358 &self.left_dock,
8359 window,
8360 cx,
8361 ))
8362
8363 .child(
8364 div()
8365 .flex()
8366 .flex_col()
8367 .flex_1()
8368 .overflow_hidden()
8369 .child(
8370 h_flex()
8371 .flex_1()
8372 .when_some(paddings.0, |this, p| {
8373 this.child(p.border_r_1())
8374 })
8375 .child(self.center.render(
8376 self.zoomed.as_ref(),
8377 &PaneRenderContext {
8378 follower_states:
8379 &self.follower_states,
8380 active_call: self.active_call(),
8381 active_pane: &self.active_pane,
8382 app_state: &self.app_state,
8383 project: &self.project,
8384 workspace: &self.weak_self,
8385 },
8386 window,
8387 cx,
8388 ))
8389 .when_some(paddings.1, |this, p| {
8390 this.child(p.border_l_1())
8391 }),
8392 )
8393 .children(self.render_dock(
8394 DockPosition::Bottom,
8395 &self.bottom_dock,
8396 window,
8397 cx,
8398 )),
8399 )
8400
8401 .children(self.render_dock(
8402 DockPosition::Right,
8403 &self.right_dock,
8404 window,
8405 cx,
8406 )),
8407 }
8408 })
8409 .children(self.zoomed.as_ref().and_then(|view| {
8410 let zoomed_view = view.upgrade()?;
8411 let div = div()
8412 .occlude()
8413 .absolute()
8414 .overflow_hidden()
8415 .border_color(colors.border)
8416 .bg(colors.background)
8417 .child(zoomed_view)
8418 .inset_0()
8419 .shadow_lg();
8420
8421 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8422 return Some(div);
8423 }
8424
8425 Some(match self.zoomed_position {
8426 Some(DockPosition::Left) => div.right_2().border_r_1(),
8427 Some(DockPosition::Right) => div.left_2().border_l_1(),
8428 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8429 None => {
8430 div.top_2().bottom_2().left_2().right_2().border_1()
8431 }
8432 })
8433 }))
8434 .children(self.render_notifications(window, cx)),
8435 )
8436 .when(self.status_bar_visible(cx), |parent| {
8437 parent.child(self.status_bar.clone())
8438 })
8439 .child(self.toast_layer.clone()),
8440 )
8441 }
8442}
8443
8444impl WorkspaceStore {
8445 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8446 Self {
8447 workspaces: Default::default(),
8448 _subscriptions: vec![
8449 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8450 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8451 ],
8452 client,
8453 }
8454 }
8455
8456 pub fn update_followers(
8457 &self,
8458 project_id: Option<u64>,
8459 update: proto::update_followers::Variant,
8460 cx: &App,
8461 ) -> Option<()> {
8462 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8463 let room_id = active_call.0.room_id(cx)?;
8464 self.client
8465 .send(proto::UpdateFollowers {
8466 room_id,
8467 project_id,
8468 variant: Some(update),
8469 })
8470 .log_err()
8471 }
8472
8473 pub async fn handle_follow(
8474 this: Entity<Self>,
8475 envelope: TypedEnvelope<proto::Follow>,
8476 mut cx: AsyncApp,
8477 ) -> Result<proto::FollowResponse> {
8478 this.update(&mut cx, |this, cx| {
8479 let follower = Follower {
8480 project_id: envelope.payload.project_id,
8481 peer_id: envelope.original_sender_id()?,
8482 };
8483
8484 let mut response = proto::FollowResponse::default();
8485
8486 this.workspaces.retain(|(window_handle, weak_workspace)| {
8487 let Some(workspace) = weak_workspace.upgrade() else {
8488 return false;
8489 };
8490 window_handle
8491 .update(cx, |_, window, cx| {
8492 workspace.update(cx, |workspace, cx| {
8493 let handler_response =
8494 workspace.handle_follow(follower.project_id, window, cx);
8495 if let Some(active_view) = handler_response.active_view
8496 && workspace.project.read(cx).remote_id() == follower.project_id
8497 {
8498 response.active_view = Some(active_view)
8499 }
8500 });
8501 })
8502 .is_ok()
8503 });
8504
8505 Ok(response)
8506 })
8507 }
8508
8509 async fn handle_update_followers(
8510 this: Entity<Self>,
8511 envelope: TypedEnvelope<proto::UpdateFollowers>,
8512 mut cx: AsyncApp,
8513 ) -> Result<()> {
8514 let leader_id = envelope.original_sender_id()?;
8515 let update = envelope.payload;
8516
8517 this.update(&mut cx, |this, cx| {
8518 this.workspaces.retain(|(window_handle, weak_workspace)| {
8519 let Some(workspace) = weak_workspace.upgrade() else {
8520 return false;
8521 };
8522 window_handle
8523 .update(cx, |_, window, cx| {
8524 workspace.update(cx, |workspace, cx| {
8525 let project_id = workspace.project.read(cx).remote_id();
8526 if update.project_id != project_id && update.project_id.is_some() {
8527 return;
8528 }
8529 workspace.handle_update_followers(
8530 leader_id,
8531 update.clone(),
8532 window,
8533 cx,
8534 );
8535 });
8536 })
8537 .is_ok()
8538 });
8539 Ok(())
8540 })
8541 }
8542
8543 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8544 self.workspaces.iter().map(|(_, weak)| weak)
8545 }
8546
8547 pub fn workspaces_with_windows(
8548 &self,
8549 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8550 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8551 }
8552}
8553
8554impl ViewId {
8555 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8556 Ok(Self {
8557 creator: message
8558 .creator
8559 .map(CollaboratorId::PeerId)
8560 .context("creator is missing")?,
8561 id: message.id,
8562 })
8563 }
8564
8565 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8566 if let CollaboratorId::PeerId(peer_id) = self.creator {
8567 Some(proto::ViewId {
8568 creator: Some(peer_id),
8569 id: self.id,
8570 })
8571 } else {
8572 None
8573 }
8574 }
8575}
8576
8577impl FollowerState {
8578 fn pane(&self) -> &Entity<Pane> {
8579 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8580 }
8581}
8582
8583pub trait WorkspaceHandle {
8584 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8585}
8586
8587impl WorkspaceHandle for Entity<Workspace> {
8588 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8589 self.read(cx)
8590 .worktrees(cx)
8591 .flat_map(|worktree| {
8592 let worktree_id = worktree.read(cx).id();
8593 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8594 worktree_id,
8595 path: f.path.clone(),
8596 })
8597 })
8598 .collect::<Vec<_>>()
8599 }
8600}
8601
8602pub async fn last_opened_workspace_location(
8603 db: &WorkspaceDb,
8604 fs: &dyn fs::Fs,
8605) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8606 db.last_workspace(fs)
8607 .await
8608 .log_err()
8609 .flatten()
8610 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8611}
8612
8613pub async fn last_session_workspace_locations(
8614 db: &WorkspaceDb,
8615 last_session_id: &str,
8616 last_session_window_stack: Option<Vec<WindowId>>,
8617 fs: &dyn fs::Fs,
8618) -> Option<Vec<SessionWorkspace>> {
8619 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8620 .await
8621 .log_err()
8622}
8623
8624pub async fn restore_multiworkspace(
8625 multi_workspace: SerializedMultiWorkspace,
8626 app_state: Arc<AppState>,
8627 cx: &mut AsyncApp,
8628) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8629 let SerializedMultiWorkspace {
8630 active_workspace,
8631 state,
8632 } = multi_workspace;
8633 let MultiWorkspaceState {
8634 sidebar_open,
8635 project_group_keys,
8636 sidebar_state,
8637 ..
8638 } = state;
8639
8640 let window_handle = if active_workspace.paths.is_empty() {
8641 cx.update(|cx| {
8642 open_workspace_by_id(active_workspace.workspace_id, app_state.clone(), None, cx)
8643 })
8644 .await?
8645 } else {
8646 let OpenResult { window, .. } = cx
8647 .update(|cx| {
8648 Workspace::new_local(
8649 active_workspace.paths.paths().to_vec(),
8650 app_state.clone(),
8651 None,
8652 None,
8653 None,
8654 OpenMode::Activate,
8655 cx,
8656 )
8657 })
8658 .await?;
8659 window
8660 };
8661
8662 if !project_group_keys.is_empty() {
8663 let restored_keys: Vec<ProjectGroupKey> =
8664 project_group_keys.into_iter().map(Into::into).collect();
8665 window_handle
8666 .update(cx, |multi_workspace, _window, _cx| {
8667 multi_workspace.restore_project_group_keys(restored_keys);
8668 })
8669 .ok();
8670 }
8671
8672 if sidebar_open {
8673 window_handle
8674 .update(cx, |multi_workspace, _, cx| {
8675 multi_workspace.open_sidebar(cx);
8676 })
8677 .ok();
8678 }
8679
8680 if let Some(sidebar_state) = sidebar_state {
8681 window_handle
8682 .update(cx, |multi_workspace, window, cx| {
8683 if let Some(sidebar) = multi_workspace.sidebar() {
8684 sidebar.restore_serialized_state(&sidebar_state, window, cx);
8685 }
8686 multi_workspace.serialize(cx);
8687 })
8688 .ok();
8689 }
8690
8691 window_handle
8692 .update(cx, |_, window, _cx| {
8693 window.activate_window();
8694 })
8695 .ok();
8696
8697 Ok(window_handle)
8698}
8699
8700actions!(
8701 collab,
8702 [
8703 /// Opens the channel notes for the current call.
8704 ///
8705 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8706 /// channel in the collab panel.
8707 ///
8708 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8709 /// can be copied via "Copy link to section" in the context menu of the channel notes
8710 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8711 OpenChannelNotes,
8712 /// Mutes your microphone.
8713 Mute,
8714 /// Deafens yourself (mute both microphone and speakers).
8715 Deafen,
8716 /// Leaves the current call.
8717 LeaveCall,
8718 /// Shares the current project with collaborators.
8719 ShareProject,
8720 /// Shares your screen with collaborators.
8721 ScreenShare,
8722 /// Copies the current room name and session id for debugging purposes.
8723 CopyRoomId,
8724 ]
8725);
8726
8727/// Opens the channel notes for a specific channel by its ID.
8728#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8729#[action(namespace = collab)]
8730#[serde(deny_unknown_fields)]
8731pub struct OpenChannelNotesById {
8732 pub channel_id: u64,
8733}
8734
8735actions!(
8736 zed,
8737 [
8738 /// Opens the Zed log file.
8739 OpenLog,
8740 /// Reveals the Zed log file in the system file manager.
8741 RevealLogInFileManager
8742 ]
8743);
8744
8745async fn join_channel_internal(
8746 channel_id: ChannelId,
8747 app_state: &Arc<AppState>,
8748 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8749 requesting_workspace: Option<WeakEntity<Workspace>>,
8750 active_call: &dyn AnyActiveCall,
8751 cx: &mut AsyncApp,
8752) -> Result<bool> {
8753 let (should_prompt, already_in_channel) = cx.update(|cx| {
8754 if !active_call.is_in_room(cx) {
8755 return (false, false);
8756 }
8757
8758 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8759 let should_prompt = active_call.is_sharing_project(cx)
8760 && active_call.has_remote_participants(cx)
8761 && !already_in_channel;
8762 (should_prompt, already_in_channel)
8763 });
8764
8765 if already_in_channel {
8766 let task = cx.update(|cx| {
8767 if let Some((project, host)) = active_call.most_active_project(cx) {
8768 Some(join_in_room_project(project, host, app_state.clone(), cx))
8769 } else {
8770 None
8771 }
8772 });
8773 if let Some(task) = task {
8774 task.await?;
8775 }
8776 return anyhow::Ok(true);
8777 }
8778
8779 if should_prompt {
8780 if let Some(multi_workspace) = requesting_window {
8781 let answer = multi_workspace
8782 .update(cx, |_, window, cx| {
8783 window.prompt(
8784 PromptLevel::Warning,
8785 "Do you want to switch channels?",
8786 Some("Leaving this call will unshare your current project."),
8787 &["Yes, Join Channel", "Cancel"],
8788 cx,
8789 )
8790 })?
8791 .await;
8792
8793 if answer == Ok(1) {
8794 return Ok(false);
8795 }
8796 } else {
8797 return Ok(false);
8798 }
8799 }
8800
8801 let client = cx.update(|cx| active_call.client(cx));
8802
8803 let mut client_status = client.status();
8804
8805 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8806 'outer: loop {
8807 let Some(status) = client_status.recv().await else {
8808 anyhow::bail!("error connecting");
8809 };
8810
8811 match status {
8812 Status::Connecting
8813 | Status::Authenticating
8814 | Status::Authenticated
8815 | Status::Reconnecting
8816 | Status::Reauthenticating
8817 | Status::Reauthenticated => continue,
8818 Status::Connected { .. } => break 'outer,
8819 Status::SignedOut | Status::AuthenticationError => {
8820 return Err(ErrorCode::SignedOut.into());
8821 }
8822 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8823 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8824 return Err(ErrorCode::Disconnected.into());
8825 }
8826 }
8827 }
8828
8829 let joined = cx
8830 .update(|cx| active_call.join_channel(channel_id, cx))
8831 .await?;
8832
8833 if !joined {
8834 return anyhow::Ok(true);
8835 }
8836
8837 cx.update(|cx| active_call.room_update_completed(cx)).await;
8838
8839 let task = cx.update(|cx| {
8840 if let Some((project, host)) = active_call.most_active_project(cx) {
8841 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8842 }
8843
8844 // If you are the first to join a channel, see if you should share your project.
8845 if !active_call.has_remote_participants(cx)
8846 && !active_call.local_participant_is_guest(cx)
8847 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8848 {
8849 let project = workspace.update(cx, |workspace, cx| {
8850 let project = workspace.project.read(cx);
8851
8852 if !active_call.share_on_join(cx) {
8853 return None;
8854 }
8855
8856 if (project.is_local() || project.is_via_remote_server())
8857 && project.visible_worktrees(cx).any(|tree| {
8858 tree.read(cx)
8859 .root_entry()
8860 .is_some_and(|entry| entry.is_dir())
8861 })
8862 {
8863 Some(workspace.project.clone())
8864 } else {
8865 None
8866 }
8867 });
8868 if let Some(project) = project {
8869 let share_task = active_call.share_project(project, cx);
8870 return Some(cx.spawn(async move |_cx| -> Result<()> {
8871 share_task.await?;
8872 Ok(())
8873 }));
8874 }
8875 }
8876
8877 None
8878 });
8879 if let Some(task) = task {
8880 task.await?;
8881 return anyhow::Ok(true);
8882 }
8883 anyhow::Ok(false)
8884}
8885
8886pub fn join_channel(
8887 channel_id: ChannelId,
8888 app_state: Arc<AppState>,
8889 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8890 requesting_workspace: Option<WeakEntity<Workspace>>,
8891 cx: &mut App,
8892) -> Task<Result<()>> {
8893 let active_call = GlobalAnyActiveCall::global(cx).clone();
8894 cx.spawn(async move |cx| {
8895 let result = join_channel_internal(
8896 channel_id,
8897 &app_state,
8898 requesting_window,
8899 requesting_workspace,
8900 &*active_call.0,
8901 cx,
8902 )
8903 .await;
8904
8905 // join channel succeeded, and opened a window
8906 if matches!(result, Ok(true)) {
8907 return anyhow::Ok(());
8908 }
8909
8910 // find an existing workspace to focus and show call controls
8911 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8912 if active_window.is_none() {
8913 // no open workspaces, make one to show the error in (blergh)
8914 let OpenResult {
8915 window: window_handle,
8916 ..
8917 } = cx
8918 .update(|cx| {
8919 Workspace::new_local(
8920 vec![],
8921 app_state.clone(),
8922 requesting_window,
8923 None,
8924 None,
8925 OpenMode::Activate,
8926 cx,
8927 )
8928 })
8929 .await?;
8930
8931 window_handle
8932 .update(cx, |_, window, _cx| {
8933 window.activate_window();
8934 })
8935 .ok();
8936
8937 if result.is_ok() {
8938 cx.update(|cx| {
8939 cx.dispatch_action(&OpenChannelNotes);
8940 });
8941 }
8942
8943 active_window = Some(window_handle);
8944 }
8945
8946 if let Err(err) = result {
8947 log::error!("failed to join channel: {}", err);
8948 if let Some(active_window) = active_window {
8949 active_window
8950 .update(cx, |_, window, cx| {
8951 let detail: SharedString = match err.error_code() {
8952 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8953 ErrorCode::UpgradeRequired => concat!(
8954 "Your are running an unsupported version of Zed. ",
8955 "Please update to continue."
8956 )
8957 .into(),
8958 ErrorCode::NoSuchChannel => concat!(
8959 "No matching channel was found. ",
8960 "Please check the link and try again."
8961 )
8962 .into(),
8963 ErrorCode::Forbidden => concat!(
8964 "This channel is private, and you do not have access. ",
8965 "Please ask someone to add you and try again."
8966 )
8967 .into(),
8968 ErrorCode::Disconnected => {
8969 "Please check your internet connection and try again.".into()
8970 }
8971 _ => format!("{}\n\nPlease try again.", err).into(),
8972 };
8973 window.prompt(
8974 PromptLevel::Critical,
8975 "Failed to join channel",
8976 Some(&detail),
8977 &["Ok"],
8978 cx,
8979 )
8980 })?
8981 .await
8982 .ok();
8983 }
8984 }
8985
8986 // return ok, we showed the error to the user.
8987 anyhow::Ok(())
8988 })
8989}
8990
8991pub async fn get_any_active_multi_workspace(
8992 app_state: Arc<AppState>,
8993 mut cx: AsyncApp,
8994) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8995 // find an existing workspace to focus and show call controls
8996 let active_window = activate_any_workspace_window(&mut cx);
8997 if active_window.is_none() {
8998 cx.update(|cx| {
8999 Workspace::new_local(
9000 vec![],
9001 app_state.clone(),
9002 None,
9003 None,
9004 None,
9005 OpenMode::Activate,
9006 cx,
9007 )
9008 })
9009 .await?;
9010 }
9011 activate_any_workspace_window(&mut cx).context("could not open zed")
9012}
9013
9014fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
9015 cx.update(|cx| {
9016 if let Some(workspace_window) = cx
9017 .active_window()
9018 .and_then(|window| window.downcast::<MultiWorkspace>())
9019 {
9020 return Some(workspace_window);
9021 }
9022
9023 for window in cx.windows() {
9024 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
9025 workspace_window
9026 .update(cx, |_, window, _| window.activate_window())
9027 .ok();
9028 return Some(workspace_window);
9029 }
9030 }
9031 None
9032 })
9033}
9034
9035pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
9036 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
9037}
9038
9039pub fn workspace_windows_for_location(
9040 serialized_location: &SerializedWorkspaceLocation,
9041 cx: &App,
9042) -> Vec<WindowHandle<MultiWorkspace>> {
9043 cx.windows()
9044 .into_iter()
9045 .filter_map(|window| window.downcast::<MultiWorkspace>())
9046 .filter(|multi_workspace| {
9047 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
9048 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
9049 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
9050 }
9051 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
9052 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
9053 a.distro_name == b.distro_name
9054 }
9055 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
9056 a.container_id == b.container_id
9057 }
9058 #[cfg(any(test, feature = "test-support"))]
9059 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
9060 a.id == b.id
9061 }
9062 _ => false,
9063 };
9064
9065 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
9066 multi_workspace.workspaces().iter().any(|workspace| {
9067 match workspace.read(cx).workspace_location(cx) {
9068 WorkspaceLocation::Location(location, _) => {
9069 match (&location, serialized_location) {
9070 (
9071 SerializedWorkspaceLocation::Local,
9072 SerializedWorkspaceLocation::Local,
9073 ) => true,
9074 (
9075 SerializedWorkspaceLocation::Remote(a),
9076 SerializedWorkspaceLocation::Remote(b),
9077 ) => same_host(a, b),
9078 _ => false,
9079 }
9080 }
9081 _ => false,
9082 }
9083 })
9084 })
9085 })
9086 .collect()
9087}
9088
9089pub async fn find_existing_workspace(
9090 abs_paths: &[PathBuf],
9091 open_options: &OpenOptions,
9092 location: &SerializedWorkspaceLocation,
9093 cx: &mut AsyncApp,
9094) -> (
9095 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
9096 OpenVisible,
9097) {
9098 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
9099 let mut open_visible = OpenVisible::All;
9100 let mut best_match = None;
9101
9102 if open_options.open_new_workspace != Some(true) {
9103 cx.update(|cx| {
9104 for window in workspace_windows_for_location(location, cx) {
9105 if let Ok(multi_workspace) = window.read(cx) {
9106 for workspace in multi_workspace.workspaces() {
9107 let project = workspace.read(cx).project.read(cx);
9108 let m = project.visibility_for_paths(
9109 abs_paths,
9110 open_options.open_new_workspace == None,
9111 cx,
9112 );
9113 if m > best_match {
9114 existing = Some((window, workspace.clone()));
9115 best_match = m;
9116 } else if best_match.is_none()
9117 && open_options.open_new_workspace == Some(false)
9118 {
9119 existing = Some((window, workspace.clone()))
9120 }
9121 }
9122 }
9123 }
9124 });
9125
9126 let all_paths_are_files = existing
9127 .as_ref()
9128 .and_then(|(_, target_workspace)| {
9129 cx.update(|cx| {
9130 let workspace = target_workspace.read(cx);
9131 let project = workspace.project.read(cx);
9132 let path_style = workspace.path_style(cx);
9133 Some(!abs_paths.iter().any(|path| {
9134 let path = util::paths::SanitizedPath::new(path);
9135 project.worktrees(cx).any(|worktree| {
9136 let worktree = worktree.read(cx);
9137 let abs_path = worktree.abs_path();
9138 path_style
9139 .strip_prefix(path.as_ref(), abs_path.as_ref())
9140 .and_then(|rel| worktree.entry_for_path(&rel))
9141 .is_some_and(|e| e.is_dir())
9142 })
9143 }))
9144 })
9145 })
9146 .unwrap_or(false);
9147
9148 if open_options.open_new_workspace.is_none()
9149 && existing.is_some()
9150 && open_options.wait
9151 && all_paths_are_files
9152 {
9153 cx.update(|cx| {
9154 let windows = workspace_windows_for_location(location, cx);
9155 let window = cx
9156 .active_window()
9157 .and_then(|window| window.downcast::<MultiWorkspace>())
9158 .filter(|window| windows.contains(window))
9159 .or_else(|| windows.into_iter().next());
9160 if let Some(window) = window {
9161 if let Ok(multi_workspace) = window.read(cx) {
9162 let active_workspace = multi_workspace.workspace().clone();
9163 existing = Some((window, active_workspace));
9164 open_visible = OpenVisible::None;
9165 }
9166 }
9167 });
9168 }
9169 }
9170 (existing, open_visible)
9171}
9172
9173#[derive(Default, Clone)]
9174pub struct OpenOptions {
9175 pub visible: Option<OpenVisible>,
9176 pub focus: Option<bool>,
9177 pub open_new_workspace: Option<bool>,
9178 pub wait: bool,
9179 pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
9180 pub open_mode: OpenMode,
9181 pub env: Option<HashMap<String, String>>,
9182 pub open_in_dev_container: bool,
9183}
9184
9185/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
9186/// or [`Workspace::open_workspace_for_paths`].
9187pub struct OpenResult {
9188 pub window: WindowHandle<MultiWorkspace>,
9189 pub workspace: Entity<Workspace>,
9190 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
9191}
9192
9193/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
9194pub fn open_workspace_by_id(
9195 workspace_id: WorkspaceId,
9196 app_state: Arc<AppState>,
9197 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9198 cx: &mut App,
9199) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
9200 let project_handle = Project::local(
9201 app_state.client.clone(),
9202 app_state.node_runtime.clone(),
9203 app_state.user_store.clone(),
9204 app_state.languages.clone(),
9205 app_state.fs.clone(),
9206 None,
9207 project::LocalProjectFlags {
9208 init_worktree_trust: true,
9209 ..project::LocalProjectFlags::default()
9210 },
9211 cx,
9212 );
9213
9214 let db = WorkspaceDb::global(cx);
9215 let kvp = db::kvp::KeyValueStore::global(cx);
9216 cx.spawn(async move |cx| {
9217 let serialized_workspace = db
9218 .workspace_for_id(workspace_id)
9219 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
9220
9221 let centered_layout = serialized_workspace.centered_layout;
9222
9223 let (window, workspace) = if let Some(window) = requesting_window {
9224 let workspace = window.update(cx, |multi_workspace, window, cx| {
9225 let workspace = cx.new(|cx| {
9226 let mut workspace = Workspace::new(
9227 Some(workspace_id),
9228 project_handle.clone(),
9229 app_state.clone(),
9230 window,
9231 cx,
9232 );
9233 workspace.centered_layout = centered_layout;
9234 workspace
9235 });
9236 multi_workspace.add(workspace.clone(), &*window, cx);
9237 workspace
9238 })?;
9239 (window, workspace)
9240 } else {
9241 let window_bounds_override = window_bounds_env_override();
9242
9243 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
9244 (Some(WindowBounds::Windowed(bounds)), None)
9245 } else if let Some(display) = serialized_workspace.display
9246 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
9247 {
9248 (Some(bounds.0), Some(display))
9249 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
9250 (Some(bounds), Some(display))
9251 } else {
9252 (None, None)
9253 };
9254
9255 let options = cx.update(|cx| {
9256 let mut options = (app_state.build_window_options)(display, cx);
9257 options.window_bounds = window_bounds;
9258 options
9259 });
9260
9261 let window = cx.open_window(options, {
9262 let app_state = app_state.clone();
9263 let project_handle = project_handle.clone();
9264 move |window, cx| {
9265 let workspace = cx.new(|cx| {
9266 let mut workspace = Workspace::new(
9267 Some(workspace_id),
9268 project_handle,
9269 app_state,
9270 window,
9271 cx,
9272 );
9273 workspace.centered_layout = centered_layout;
9274 workspace
9275 });
9276 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9277 }
9278 })?;
9279
9280 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9281 multi_workspace.workspace().clone()
9282 })?;
9283
9284 (window, workspace)
9285 };
9286
9287 notify_if_database_failed(window, cx);
9288
9289 // Restore items from the serialized workspace
9290 window
9291 .update(cx, |_, window, cx| {
9292 workspace.update(cx, |_workspace, cx| {
9293 open_items(Some(serialized_workspace), vec![], window, cx)
9294 })
9295 })?
9296 .await?;
9297
9298 window.update(cx, |_, window, cx| {
9299 workspace.update(cx, |workspace, cx| {
9300 workspace.serialize_workspace(window, cx);
9301 });
9302 })?;
9303
9304 Ok(window)
9305 })
9306}
9307
9308#[allow(clippy::type_complexity)]
9309pub fn open_paths(
9310 abs_paths: &[PathBuf],
9311 app_state: Arc<AppState>,
9312 open_options: OpenOptions,
9313 cx: &mut App,
9314) -> Task<anyhow::Result<OpenResult>> {
9315 let abs_paths = abs_paths.to_vec();
9316 #[cfg(target_os = "windows")]
9317 let wsl_path = abs_paths
9318 .iter()
9319 .find_map(|p| util::paths::WslPath::from_path(p));
9320
9321 cx.spawn(async move |cx| {
9322 let (mut existing, mut open_visible) = find_existing_workspace(
9323 &abs_paths,
9324 &open_options,
9325 &SerializedWorkspaceLocation::Local,
9326 cx,
9327 )
9328 .await;
9329
9330 // Fallback: if no workspace contains the paths and all paths are files,
9331 // prefer an existing local workspace window (active window first).
9332 if open_options.open_new_workspace.is_none() && existing.is_none() {
9333 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9334 let all_metadatas = futures::future::join_all(all_paths)
9335 .await
9336 .into_iter()
9337 .filter_map(|result| result.ok().flatten())
9338 .collect::<Vec<_>>();
9339
9340 if all_metadatas.iter().all(|file| !file.is_dir) {
9341 cx.update(|cx| {
9342 let windows = workspace_windows_for_location(
9343 &SerializedWorkspaceLocation::Local,
9344 cx,
9345 );
9346 let window = cx
9347 .active_window()
9348 .and_then(|window| window.downcast::<MultiWorkspace>())
9349 .filter(|window| windows.contains(window))
9350 .or_else(|| windows.into_iter().next());
9351 if let Some(window) = window {
9352 if let Ok(multi_workspace) = window.read(cx) {
9353 let active_workspace = multi_workspace.workspace().clone();
9354 existing = Some((window, active_workspace));
9355 open_visible = OpenVisible::None;
9356 }
9357 }
9358 });
9359 }
9360 }
9361
9362 let open_in_dev_container = open_options.open_in_dev_container;
9363
9364 let result = if let Some((existing, target_workspace)) = existing {
9365 let open_task = existing
9366 .update(cx, |multi_workspace, window, cx| {
9367 window.activate_window();
9368 multi_workspace.activate(target_workspace.clone(), window, cx);
9369 target_workspace.update(cx, |workspace, cx| {
9370 if open_in_dev_container {
9371 workspace.set_open_in_dev_container(true);
9372 }
9373 workspace.open_paths(
9374 abs_paths,
9375 OpenOptions {
9376 visible: Some(open_visible),
9377 ..Default::default()
9378 },
9379 None,
9380 window,
9381 cx,
9382 )
9383 })
9384 })?
9385 .await;
9386
9387 _ = existing.update(cx, |multi_workspace, _, cx| {
9388 let workspace = multi_workspace.workspace().clone();
9389 workspace.update(cx, |workspace, cx| {
9390 for item in open_task.iter().flatten() {
9391 if let Err(e) = item {
9392 workspace.show_error(&e, cx);
9393 }
9394 }
9395 });
9396 });
9397
9398 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9399 } else {
9400 let init = if open_in_dev_container {
9401 Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {
9402 workspace.set_open_in_dev_container(true);
9403 }) as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>)
9404 } else {
9405 None
9406 };
9407 let result = cx
9408 .update(move |cx| {
9409 Workspace::new_local(
9410 abs_paths,
9411 app_state.clone(),
9412 open_options.requesting_window,
9413 open_options.env,
9414 init,
9415 open_options.open_mode,
9416 cx,
9417 )
9418 })
9419 .await;
9420
9421 if let Ok(ref result) = result {
9422 result.window
9423 .update(cx, |_, window, _cx| {
9424 window.activate_window();
9425 })
9426 .log_err();
9427 }
9428
9429 result
9430 };
9431
9432 #[cfg(target_os = "windows")]
9433 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9434 && let Ok(ref result) = result
9435 {
9436 result.window
9437 .update(cx, move |multi_workspace, _window, cx| {
9438 struct OpenInWsl;
9439 let workspace = multi_workspace.workspace().clone();
9440 workspace.update(cx, |workspace, cx| {
9441 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9442 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9443 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9444 cx.new(move |cx| {
9445 MessageNotification::new(msg, cx)
9446 .primary_message("Open in WSL")
9447 .primary_icon(IconName::FolderOpen)
9448 .primary_on_click(move |window, cx| {
9449 window.dispatch_action(Box::new(remote::OpenWslPath {
9450 distro: remote::WslConnectionOptions {
9451 distro_name: distro.clone(),
9452 user: None,
9453 },
9454 paths: vec![path.clone().into()],
9455 }), cx)
9456 })
9457 })
9458 });
9459 });
9460 })
9461 .unwrap();
9462 };
9463 result
9464 })
9465}
9466
9467pub fn open_new(
9468 open_options: OpenOptions,
9469 app_state: Arc<AppState>,
9470 cx: &mut App,
9471 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9472) -> Task<anyhow::Result<()>> {
9473 let addition = open_options.open_mode;
9474 let task = Workspace::new_local(
9475 Vec::new(),
9476 app_state,
9477 open_options.requesting_window,
9478 open_options.env,
9479 Some(Box::new(init)),
9480 addition,
9481 cx,
9482 );
9483 cx.spawn(async move |cx| {
9484 let OpenResult { window, .. } = task.await?;
9485 window
9486 .update(cx, |_, window, _cx| {
9487 window.activate_window();
9488 })
9489 .ok();
9490 Ok(())
9491 })
9492}
9493
9494pub fn create_and_open_local_file(
9495 path: &'static Path,
9496 window: &mut Window,
9497 cx: &mut Context<Workspace>,
9498 default_content: impl 'static + Send + FnOnce() -> Rope,
9499) -> Task<Result<Box<dyn ItemHandle>>> {
9500 cx.spawn_in(window, async move |workspace, cx| {
9501 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9502 if !fs.is_file(path).await {
9503 fs.create_file(path, Default::default()).await?;
9504 fs.save(path, &default_content(), Default::default())
9505 .await?;
9506 }
9507
9508 workspace
9509 .update_in(cx, |workspace, window, cx| {
9510 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9511 let path = workspace
9512 .project
9513 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9514 cx.spawn_in(window, async move |workspace, cx| {
9515 let path = path.await?;
9516
9517 let path = fs.canonicalize(&path).await.unwrap_or(path);
9518
9519 let mut items = workspace
9520 .update_in(cx, |workspace, window, cx| {
9521 workspace.open_paths(
9522 vec![path.to_path_buf()],
9523 OpenOptions {
9524 visible: Some(OpenVisible::None),
9525 ..Default::default()
9526 },
9527 None,
9528 window,
9529 cx,
9530 )
9531 })?
9532 .await;
9533 let item = items.pop().flatten();
9534 item.with_context(|| format!("path {path:?} is not a file"))?
9535 })
9536 })
9537 })?
9538 .await?
9539 .await
9540 })
9541}
9542
9543pub fn open_remote_project_with_new_connection(
9544 window: WindowHandle<MultiWorkspace>,
9545 remote_connection: Arc<dyn RemoteConnection>,
9546 cancel_rx: oneshot::Receiver<()>,
9547 delegate: Arc<dyn RemoteClientDelegate>,
9548 app_state: Arc<AppState>,
9549 paths: Vec<PathBuf>,
9550 cx: &mut App,
9551) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9552 cx.spawn(async move |cx| {
9553 let (workspace_id, serialized_workspace) =
9554 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9555 .await?;
9556
9557 let session = match cx
9558 .update(|cx| {
9559 remote::RemoteClient::new(
9560 ConnectionIdentifier::Workspace(workspace_id.0),
9561 remote_connection,
9562 cancel_rx,
9563 delegate,
9564 cx,
9565 )
9566 })
9567 .await?
9568 {
9569 Some(result) => result,
9570 None => return Ok(Vec::new()),
9571 };
9572
9573 let project = cx.update(|cx| {
9574 project::Project::remote(
9575 session,
9576 app_state.client.clone(),
9577 app_state.node_runtime.clone(),
9578 app_state.user_store.clone(),
9579 app_state.languages.clone(),
9580 app_state.fs.clone(),
9581 true,
9582 cx,
9583 )
9584 });
9585
9586 open_remote_project_inner(
9587 project,
9588 paths,
9589 workspace_id,
9590 serialized_workspace,
9591 app_state,
9592 window,
9593 cx,
9594 )
9595 .await
9596 })
9597}
9598
9599pub fn open_remote_project_with_existing_connection(
9600 connection_options: RemoteConnectionOptions,
9601 project: Entity<Project>,
9602 paths: Vec<PathBuf>,
9603 app_state: Arc<AppState>,
9604 window: WindowHandle<MultiWorkspace>,
9605 cx: &mut AsyncApp,
9606) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9607 cx.spawn(async move |cx| {
9608 let (workspace_id, serialized_workspace) =
9609 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9610
9611 open_remote_project_inner(
9612 project,
9613 paths,
9614 workspace_id,
9615 serialized_workspace,
9616 app_state,
9617 window,
9618 cx,
9619 )
9620 .await
9621 })
9622}
9623
9624async fn open_remote_project_inner(
9625 project: Entity<Project>,
9626 paths: Vec<PathBuf>,
9627 workspace_id: WorkspaceId,
9628 serialized_workspace: Option<SerializedWorkspace>,
9629 app_state: Arc<AppState>,
9630 window: WindowHandle<MultiWorkspace>,
9631 cx: &mut AsyncApp,
9632) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9633 let db = cx.update(|cx| WorkspaceDb::global(cx));
9634 let toolchains = db.toolchains(workspace_id).await?;
9635 for (toolchain, worktree_path, path) in toolchains {
9636 project
9637 .update(cx, |this, cx| {
9638 let Some(worktree_id) =
9639 this.find_worktree(&worktree_path, cx)
9640 .and_then(|(worktree, rel_path)| {
9641 if rel_path.is_empty() {
9642 Some(worktree.read(cx).id())
9643 } else {
9644 None
9645 }
9646 })
9647 else {
9648 return Task::ready(None);
9649 };
9650
9651 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9652 })
9653 .await;
9654 }
9655 let mut project_paths_to_open = vec![];
9656 let mut project_path_errors = vec![];
9657
9658 for path in paths {
9659 let result = cx
9660 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9661 .await;
9662 match result {
9663 Ok((_, project_path)) => {
9664 project_paths_to_open.push((path.clone(), Some(project_path)));
9665 }
9666 Err(error) => {
9667 project_path_errors.push(error);
9668 }
9669 };
9670 }
9671
9672 if project_paths_to_open.is_empty() {
9673 return Err(project_path_errors.pop().context("no paths given")?);
9674 }
9675
9676 let workspace = window.update(cx, |multi_workspace, window, cx| {
9677 telemetry::event!("SSH Project Opened");
9678
9679 let new_workspace = cx.new(|cx| {
9680 let mut workspace =
9681 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9682 workspace.update_history(cx);
9683
9684 if let Some(ref serialized) = serialized_workspace {
9685 workspace.centered_layout = serialized.centered_layout;
9686 }
9687
9688 workspace
9689 });
9690
9691 multi_workspace.activate(new_workspace.clone(), window, cx);
9692 new_workspace
9693 })?;
9694
9695 let items = window
9696 .update(cx, |_, window, cx| {
9697 window.activate_window();
9698 workspace.update(cx, |_workspace, cx| {
9699 open_items(serialized_workspace, project_paths_to_open, window, cx)
9700 })
9701 })?
9702 .await?;
9703
9704 workspace.update(cx, |workspace, cx| {
9705 for error in project_path_errors {
9706 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9707 if let Some(path) = error.error_tag("path") {
9708 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9709 }
9710 } else {
9711 workspace.show_error(&error, cx)
9712 }
9713 }
9714 });
9715
9716 Ok(items.into_iter().map(|item| item?.ok()).collect())
9717}
9718
9719fn deserialize_remote_project(
9720 connection_options: RemoteConnectionOptions,
9721 paths: Vec<PathBuf>,
9722 cx: &AsyncApp,
9723) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9724 let db = cx.update(|cx| WorkspaceDb::global(cx));
9725 cx.background_spawn(async move {
9726 let remote_connection_id = db
9727 .get_or_create_remote_connection(connection_options)
9728 .await?;
9729
9730 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9731
9732 let workspace_id = if let Some(workspace_id) =
9733 serialized_workspace.as_ref().map(|workspace| workspace.id)
9734 {
9735 workspace_id
9736 } else {
9737 db.next_id().await?
9738 };
9739
9740 Ok((workspace_id, serialized_workspace))
9741 })
9742}
9743
9744pub fn join_in_room_project(
9745 project_id: u64,
9746 follow_user_id: u64,
9747 app_state: Arc<AppState>,
9748 cx: &mut App,
9749) -> Task<Result<()>> {
9750 let windows = cx.windows();
9751 cx.spawn(async move |cx| {
9752 let existing_window_and_workspace: Option<(
9753 WindowHandle<MultiWorkspace>,
9754 Entity<Workspace>,
9755 )> = windows.into_iter().find_map(|window_handle| {
9756 window_handle
9757 .downcast::<MultiWorkspace>()
9758 .and_then(|window_handle| {
9759 window_handle
9760 .update(cx, |multi_workspace, _window, cx| {
9761 for workspace in multi_workspace.workspaces() {
9762 if workspace.read(cx).project().read(cx).remote_id()
9763 == Some(project_id)
9764 {
9765 return Some((window_handle, workspace.clone()));
9766 }
9767 }
9768 None
9769 })
9770 .unwrap_or(None)
9771 })
9772 });
9773
9774 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9775 existing_window_and_workspace
9776 {
9777 existing_window
9778 .update(cx, |multi_workspace, window, cx| {
9779 multi_workspace.activate(target_workspace, window, cx);
9780 })
9781 .ok();
9782 existing_window
9783 } else {
9784 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9785 let project = cx
9786 .update(|cx| {
9787 active_call.0.join_project(
9788 project_id,
9789 app_state.languages.clone(),
9790 app_state.fs.clone(),
9791 cx,
9792 )
9793 })
9794 .await?;
9795
9796 let window_bounds_override = window_bounds_env_override();
9797 cx.update(|cx| {
9798 let mut options = (app_state.build_window_options)(None, cx);
9799 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9800 cx.open_window(options, |window, cx| {
9801 let workspace = cx.new(|cx| {
9802 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9803 });
9804 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9805 })
9806 })?
9807 };
9808
9809 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9810 cx.activate(true);
9811 window.activate_window();
9812
9813 // We set the active workspace above, so this is the correct workspace.
9814 let workspace = multi_workspace.workspace().clone();
9815 workspace.update(cx, |workspace, cx| {
9816 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9817 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9818 .or_else(|| {
9819 // If we couldn't follow the given user, follow the host instead.
9820 let collaborator = workspace
9821 .project()
9822 .read(cx)
9823 .collaborators()
9824 .values()
9825 .find(|collaborator| collaborator.is_host)?;
9826 Some(collaborator.peer_id)
9827 });
9828
9829 if let Some(follow_peer_id) = follow_peer_id {
9830 workspace.follow(follow_peer_id, window, cx);
9831 }
9832 });
9833 })?;
9834
9835 anyhow::Ok(())
9836 })
9837}
9838
9839pub fn reload(cx: &mut App) {
9840 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9841 let mut workspace_windows = cx
9842 .windows()
9843 .into_iter()
9844 .filter_map(|window| window.downcast::<MultiWorkspace>())
9845 .collect::<Vec<_>>();
9846
9847 // If multiple windows have unsaved changes, and need a save prompt,
9848 // prompt in the active window before switching to a different window.
9849 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9850
9851 let mut prompt = None;
9852 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9853 prompt = window
9854 .update(cx, |_, window, cx| {
9855 window.prompt(
9856 PromptLevel::Info,
9857 "Are you sure you want to restart?",
9858 None,
9859 &["Restart", "Cancel"],
9860 cx,
9861 )
9862 })
9863 .ok();
9864 }
9865
9866 cx.spawn(async move |cx| {
9867 if let Some(prompt) = prompt {
9868 let answer = prompt.await?;
9869 if answer != 0 {
9870 return anyhow::Ok(());
9871 }
9872 }
9873
9874 // If the user cancels any save prompt, then keep the app open.
9875 for window in workspace_windows {
9876 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9877 let workspace = multi_workspace.workspace().clone();
9878 workspace.update(cx, |workspace, cx| {
9879 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9880 })
9881 }) && !should_close.await?
9882 {
9883 return anyhow::Ok(());
9884 }
9885 }
9886 cx.update(|cx| cx.restart());
9887 anyhow::Ok(())
9888 })
9889 .detach_and_log_err(cx);
9890}
9891
9892fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9893 let mut parts = value.split(',');
9894 let x: usize = parts.next()?.parse().ok()?;
9895 let y: usize = parts.next()?.parse().ok()?;
9896 Some(point(px(x as f32), px(y as f32)))
9897}
9898
9899fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9900 let mut parts = value.split(',');
9901 let width: usize = parts.next()?.parse().ok()?;
9902 let height: usize = parts.next()?.parse().ok()?;
9903 Some(size(px(width as f32), px(height as f32)))
9904}
9905
9906/// Add client-side decorations (rounded corners, shadows, resize handling) when
9907/// appropriate.
9908///
9909/// The `border_radius_tiling` parameter allows overriding which corners get
9910/// rounded, independently of the actual window tiling state. This is used
9911/// specifically for the workspace switcher sidebar: when the sidebar is open,
9912/// we want square corners on the left (so the sidebar appears flush with the
9913/// window edge) but we still need the shadow padding for proper visual
9914/// appearance. Unlike actual window tiling, this only affects border radius -
9915/// not padding or shadows.
9916pub fn client_side_decorations(
9917 element: impl IntoElement,
9918 window: &mut Window,
9919 cx: &mut App,
9920 border_radius_tiling: Tiling,
9921) -> Stateful<Div> {
9922 const BORDER_SIZE: Pixels = px(1.0);
9923 let decorations = window.window_decorations();
9924 let tiling = match decorations {
9925 Decorations::Server => Tiling::default(),
9926 Decorations::Client { tiling } => tiling,
9927 };
9928
9929 match decorations {
9930 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9931 Decorations::Server => window.set_client_inset(px(0.0)),
9932 }
9933
9934 struct GlobalResizeEdge(ResizeEdge);
9935 impl Global for GlobalResizeEdge {}
9936
9937 div()
9938 .id("window-backdrop")
9939 .bg(transparent_black())
9940 .map(|div| match decorations {
9941 Decorations::Server => div,
9942 Decorations::Client { .. } => div
9943 .when(
9944 !(tiling.top
9945 || tiling.right
9946 || border_radius_tiling.top
9947 || border_radius_tiling.right),
9948 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9949 )
9950 .when(
9951 !(tiling.top
9952 || tiling.left
9953 || border_radius_tiling.top
9954 || border_radius_tiling.left),
9955 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9956 )
9957 .when(
9958 !(tiling.bottom
9959 || tiling.right
9960 || border_radius_tiling.bottom
9961 || border_radius_tiling.right),
9962 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9963 )
9964 .when(
9965 !(tiling.bottom
9966 || tiling.left
9967 || border_radius_tiling.bottom
9968 || border_radius_tiling.left),
9969 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9970 )
9971 .when(!tiling.top, |div| {
9972 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9973 })
9974 .when(!tiling.bottom, |div| {
9975 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9976 })
9977 .when(!tiling.left, |div| {
9978 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9979 })
9980 .when(!tiling.right, |div| {
9981 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9982 })
9983 .on_mouse_move(move |e, window, cx| {
9984 let size = window.window_bounds().get_bounds().size;
9985 let pos = e.position;
9986
9987 let new_edge =
9988 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9989
9990 let edge = cx.try_global::<GlobalResizeEdge>();
9991 if new_edge != edge.map(|edge| edge.0) {
9992 window
9993 .window_handle()
9994 .update(cx, |workspace, _, cx| {
9995 cx.notify(workspace.entity_id());
9996 })
9997 .ok();
9998 }
9999 })
10000 .on_mouse_down(MouseButton::Left, move |e, window, _| {
10001 let size = window.window_bounds().get_bounds().size;
10002 let pos = e.position;
10003
10004 let edge = match resize_edge(
10005 pos,
10006 theme::CLIENT_SIDE_DECORATION_SHADOW,
10007 size,
10008 tiling,
10009 ) {
10010 Some(value) => value,
10011 None => return,
10012 };
10013
10014 window.start_window_resize(edge);
10015 }),
10016 })
10017 .size_full()
10018 .child(
10019 div()
10020 .cursor(CursorStyle::Arrow)
10021 .map(|div| match decorations {
10022 Decorations::Server => div,
10023 Decorations::Client { .. } => div
10024 .border_color(cx.theme().colors().border)
10025 .when(
10026 !(tiling.top
10027 || tiling.right
10028 || border_radius_tiling.top
10029 || border_radius_tiling.right),
10030 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10031 )
10032 .when(
10033 !(tiling.top
10034 || tiling.left
10035 || border_radius_tiling.top
10036 || border_radius_tiling.left),
10037 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10038 )
10039 .when(
10040 !(tiling.bottom
10041 || tiling.right
10042 || border_radius_tiling.bottom
10043 || border_radius_tiling.right),
10044 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10045 )
10046 .when(
10047 !(tiling.bottom
10048 || tiling.left
10049 || border_radius_tiling.bottom
10050 || border_radius_tiling.left),
10051 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10052 )
10053 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10054 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10055 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10056 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10057 .when(!tiling.is_tiled(), |div| {
10058 div.shadow(vec![gpui::BoxShadow {
10059 color: Hsla {
10060 h: 0.,
10061 s: 0.,
10062 l: 0.,
10063 a: 0.4,
10064 },
10065 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10066 spread_radius: px(0.),
10067 offset: point(px(0.0), px(0.0)),
10068 }])
10069 }),
10070 })
10071 .on_mouse_move(|_e, _, cx| {
10072 cx.stop_propagation();
10073 })
10074 .size_full()
10075 .child(element),
10076 )
10077 .map(|div| match decorations {
10078 Decorations::Server => div,
10079 Decorations::Client { tiling, .. } => div.child(
10080 canvas(
10081 |_bounds, window, _| {
10082 window.insert_hitbox(
10083 Bounds::new(
10084 point(px(0.0), px(0.0)),
10085 window.window_bounds().get_bounds().size,
10086 ),
10087 HitboxBehavior::Normal,
10088 )
10089 },
10090 move |_bounds, hitbox, window, cx| {
10091 let mouse = window.mouse_position();
10092 let size = window.window_bounds().get_bounds().size;
10093 let Some(edge) =
10094 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10095 else {
10096 return;
10097 };
10098 cx.set_global(GlobalResizeEdge(edge));
10099 window.set_cursor_style(
10100 match edge {
10101 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10102 ResizeEdge::Left | ResizeEdge::Right => {
10103 CursorStyle::ResizeLeftRight
10104 }
10105 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10106 CursorStyle::ResizeUpLeftDownRight
10107 }
10108 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10109 CursorStyle::ResizeUpRightDownLeft
10110 }
10111 },
10112 &hitbox,
10113 );
10114 },
10115 )
10116 .size_full()
10117 .absolute(),
10118 ),
10119 })
10120}
10121
10122fn resize_edge(
10123 pos: Point<Pixels>,
10124 shadow_size: Pixels,
10125 window_size: Size<Pixels>,
10126 tiling: Tiling,
10127) -> Option<ResizeEdge> {
10128 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10129 if bounds.contains(&pos) {
10130 return None;
10131 }
10132
10133 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10134 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10135 if !tiling.top && top_left_bounds.contains(&pos) {
10136 return Some(ResizeEdge::TopLeft);
10137 }
10138
10139 let top_right_bounds = Bounds::new(
10140 Point::new(window_size.width - corner_size.width, px(0.)),
10141 corner_size,
10142 );
10143 if !tiling.top && top_right_bounds.contains(&pos) {
10144 return Some(ResizeEdge::TopRight);
10145 }
10146
10147 let bottom_left_bounds = Bounds::new(
10148 Point::new(px(0.), window_size.height - corner_size.height),
10149 corner_size,
10150 );
10151 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10152 return Some(ResizeEdge::BottomLeft);
10153 }
10154
10155 let bottom_right_bounds = Bounds::new(
10156 Point::new(
10157 window_size.width - corner_size.width,
10158 window_size.height - corner_size.height,
10159 ),
10160 corner_size,
10161 );
10162 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10163 return Some(ResizeEdge::BottomRight);
10164 }
10165
10166 if !tiling.top && pos.y < shadow_size {
10167 Some(ResizeEdge::Top)
10168 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10169 Some(ResizeEdge::Bottom)
10170 } else if !tiling.left && pos.x < shadow_size {
10171 Some(ResizeEdge::Left)
10172 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10173 Some(ResizeEdge::Right)
10174 } else {
10175 None
10176 }
10177}
10178
10179fn join_pane_into_active(
10180 active_pane: &Entity<Pane>,
10181 pane: &Entity<Pane>,
10182 window: &mut Window,
10183 cx: &mut App,
10184) {
10185 if pane == active_pane {
10186 } else if pane.read(cx).items_len() == 0 {
10187 pane.update(cx, |_, cx| {
10188 cx.emit(pane::Event::Remove {
10189 focus_on_pane: None,
10190 });
10191 })
10192 } else {
10193 move_all_items(pane, active_pane, window, cx);
10194 }
10195}
10196
10197fn move_all_items(
10198 from_pane: &Entity<Pane>,
10199 to_pane: &Entity<Pane>,
10200 window: &mut Window,
10201 cx: &mut App,
10202) {
10203 let destination_is_different = from_pane != to_pane;
10204 let mut moved_items = 0;
10205 for (item_ix, item_handle) in from_pane
10206 .read(cx)
10207 .items()
10208 .enumerate()
10209 .map(|(ix, item)| (ix, item.clone()))
10210 .collect::<Vec<_>>()
10211 {
10212 let ix = item_ix - moved_items;
10213 if destination_is_different {
10214 // Close item from previous pane
10215 from_pane.update(cx, |source, cx| {
10216 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10217 });
10218 moved_items += 1;
10219 }
10220
10221 // This automatically removes duplicate items in the pane
10222 to_pane.update(cx, |destination, cx| {
10223 destination.add_item(item_handle, true, true, None, window, cx);
10224 window.focus(&destination.focus_handle(cx), cx)
10225 });
10226 }
10227}
10228
10229pub fn move_item(
10230 source: &Entity<Pane>,
10231 destination: &Entity<Pane>,
10232 item_id_to_move: EntityId,
10233 destination_index: usize,
10234 activate: bool,
10235 window: &mut Window,
10236 cx: &mut App,
10237) {
10238 let Some((item_ix, item_handle)) = source
10239 .read(cx)
10240 .items()
10241 .enumerate()
10242 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10243 .map(|(ix, item)| (ix, item.clone()))
10244 else {
10245 // Tab was closed during drag
10246 return;
10247 };
10248
10249 if source != destination {
10250 // Close item from previous pane
10251 source.update(cx, |source, cx| {
10252 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10253 });
10254 }
10255
10256 // This automatically removes duplicate items in the pane
10257 destination.update(cx, |destination, cx| {
10258 destination.add_item_inner(
10259 item_handle,
10260 activate,
10261 activate,
10262 activate,
10263 Some(destination_index),
10264 window,
10265 cx,
10266 );
10267 if activate {
10268 window.focus(&destination.focus_handle(cx), cx)
10269 }
10270 });
10271}
10272
10273pub fn move_active_item(
10274 source: &Entity<Pane>,
10275 destination: &Entity<Pane>,
10276 focus_destination: bool,
10277 close_if_empty: bool,
10278 window: &mut Window,
10279 cx: &mut App,
10280) {
10281 if source == destination {
10282 return;
10283 }
10284 let Some(active_item) = source.read(cx).active_item() else {
10285 return;
10286 };
10287 source.update(cx, |source_pane, cx| {
10288 let item_id = active_item.item_id();
10289 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10290 destination.update(cx, |target_pane, cx| {
10291 target_pane.add_item(
10292 active_item,
10293 focus_destination,
10294 focus_destination,
10295 Some(target_pane.items_len()),
10296 window,
10297 cx,
10298 );
10299 });
10300 });
10301}
10302
10303pub fn clone_active_item(
10304 workspace_id: Option<WorkspaceId>,
10305 source: &Entity<Pane>,
10306 destination: &Entity<Pane>,
10307 focus_destination: bool,
10308 window: &mut Window,
10309 cx: &mut App,
10310) {
10311 if source == destination {
10312 return;
10313 }
10314 let Some(active_item) = source.read(cx).active_item() else {
10315 return;
10316 };
10317 if !active_item.can_split(cx) {
10318 return;
10319 }
10320 let destination = destination.downgrade();
10321 let task = active_item.clone_on_split(workspace_id, window, cx);
10322 window
10323 .spawn(cx, async move |cx| {
10324 let Some(clone) = task.await else {
10325 return;
10326 };
10327 destination
10328 .update_in(cx, |target_pane, window, cx| {
10329 target_pane.add_item(
10330 clone,
10331 focus_destination,
10332 focus_destination,
10333 Some(target_pane.items_len()),
10334 window,
10335 cx,
10336 );
10337 })
10338 .log_err();
10339 })
10340 .detach();
10341}
10342
10343#[derive(Debug)]
10344pub struct WorkspacePosition {
10345 pub window_bounds: Option<WindowBounds>,
10346 pub display: Option<Uuid>,
10347 pub centered_layout: bool,
10348}
10349
10350pub fn remote_workspace_position_from_db(
10351 connection_options: RemoteConnectionOptions,
10352 paths_to_open: &[PathBuf],
10353 cx: &App,
10354) -> Task<Result<WorkspacePosition>> {
10355 let paths = paths_to_open.to_vec();
10356 let db = WorkspaceDb::global(cx);
10357 let kvp = db::kvp::KeyValueStore::global(cx);
10358
10359 cx.background_spawn(async move {
10360 let remote_connection_id = db
10361 .get_or_create_remote_connection(connection_options)
10362 .await
10363 .context("fetching serialized ssh project")?;
10364 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10365
10366 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10367 (Some(WindowBounds::Windowed(bounds)), None)
10368 } else {
10369 let restorable_bounds = serialized_workspace
10370 .as_ref()
10371 .and_then(|workspace| {
10372 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10373 })
10374 .or_else(|| persistence::read_default_window_bounds(&kvp));
10375
10376 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10377 (Some(serialized_bounds), Some(serialized_display))
10378 } else {
10379 (None, None)
10380 }
10381 };
10382
10383 let centered_layout = serialized_workspace
10384 .as_ref()
10385 .map(|w| w.centered_layout)
10386 .unwrap_or(false);
10387
10388 Ok(WorkspacePosition {
10389 window_bounds,
10390 display,
10391 centered_layout,
10392 })
10393 })
10394}
10395
10396pub fn with_active_or_new_workspace(
10397 cx: &mut App,
10398 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10399) {
10400 match cx
10401 .active_window()
10402 .and_then(|w| w.downcast::<MultiWorkspace>())
10403 {
10404 Some(multi_workspace) => {
10405 cx.defer(move |cx| {
10406 multi_workspace
10407 .update(cx, |multi_workspace, window, cx| {
10408 let workspace = multi_workspace.workspace().clone();
10409 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10410 })
10411 .log_err();
10412 });
10413 }
10414 None => {
10415 let app_state = AppState::global(cx);
10416 open_new(
10417 OpenOptions::default(),
10418 app_state,
10419 cx,
10420 move |workspace, window, cx| f(workspace, window, cx),
10421 )
10422 .detach_and_log_err(cx);
10423 }
10424 }
10425}
10426
10427/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10428/// key. This migration path only runs once per panel per workspace.
10429fn load_legacy_panel_size(
10430 panel_key: &str,
10431 dock_position: DockPosition,
10432 workspace: &Workspace,
10433 cx: &mut App,
10434) -> Option<Pixels> {
10435 #[derive(Deserialize)]
10436 struct LegacyPanelState {
10437 #[serde(default)]
10438 width: Option<Pixels>,
10439 #[serde(default)]
10440 height: Option<Pixels>,
10441 }
10442
10443 let workspace_id = workspace
10444 .database_id()
10445 .map(|id| i64::from(id).to_string())
10446 .or_else(|| workspace.session_id())?;
10447
10448 let legacy_key = match panel_key {
10449 "ProjectPanel" => {
10450 format!("{}-{:?}", "ProjectPanel", workspace_id)
10451 }
10452 "OutlinePanel" => {
10453 format!("{}-{:?}", "OutlinePanel", workspace_id)
10454 }
10455 "GitPanel" => {
10456 format!("{}-{:?}", "GitPanel", workspace_id)
10457 }
10458 "TerminalPanel" => {
10459 format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10460 }
10461 _ => return None,
10462 };
10463
10464 let kvp = db::kvp::KeyValueStore::global(cx);
10465 let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10466 let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10467 let size = match dock_position {
10468 DockPosition::Bottom => state.height,
10469 DockPosition::Left | DockPosition::Right => state.width,
10470 }?;
10471
10472 cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10473 .detach_and_log_err(cx);
10474
10475 Some(size)
10476}
10477
10478#[cfg(test)]
10479mod tests {
10480 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10481
10482 use super::*;
10483 use crate::{
10484 dock::{PanelEvent, test::TestPanel},
10485 item::{
10486 ItemBufferKind, ItemEvent,
10487 test::{TestItem, TestProjectItem},
10488 },
10489 };
10490 use fs::FakeFs;
10491 use gpui::{
10492 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10493 UpdateGlobal, VisualTestContext, px,
10494 };
10495 use project::{Project, ProjectEntryId};
10496 use serde_json::json;
10497 use settings::SettingsStore;
10498 use util::path;
10499 use util::rel_path::rel_path;
10500
10501 #[gpui::test]
10502 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10503 init_test(cx);
10504
10505 let fs = FakeFs::new(cx.executor());
10506 let project = Project::test(fs, [], cx).await;
10507 let (workspace, cx) =
10508 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10509
10510 // Adding an item with no ambiguity renders the tab without detail.
10511 let item1 = cx.new(|cx| {
10512 let mut item = TestItem::new(cx);
10513 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10514 item
10515 });
10516 workspace.update_in(cx, |workspace, window, cx| {
10517 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10518 });
10519 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10520
10521 // Adding an item that creates ambiguity increases the level of detail on
10522 // both tabs.
10523 let item2 = cx.new_window_entity(|_window, cx| {
10524 let mut item = TestItem::new(cx);
10525 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10526 item
10527 });
10528 workspace.update_in(cx, |workspace, window, cx| {
10529 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10530 });
10531 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10532 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10533
10534 // Adding an item that creates ambiguity increases the level of detail only
10535 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10536 // we stop at the highest detail available.
10537 let item3 = cx.new(|cx| {
10538 let mut item = TestItem::new(cx);
10539 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10540 item
10541 });
10542 workspace.update_in(cx, |workspace, window, cx| {
10543 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10544 });
10545 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10546 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10547 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10548 }
10549
10550 #[gpui::test]
10551 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10552 init_test(cx);
10553
10554 let fs = FakeFs::new(cx.executor());
10555 fs.insert_tree(
10556 "/root1",
10557 json!({
10558 "one.txt": "",
10559 "two.txt": "",
10560 }),
10561 )
10562 .await;
10563 fs.insert_tree(
10564 "/root2",
10565 json!({
10566 "three.txt": "",
10567 }),
10568 )
10569 .await;
10570
10571 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10572 let (workspace, cx) =
10573 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10574 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10575 let worktree_id = project.update(cx, |project, cx| {
10576 project.worktrees(cx).next().unwrap().read(cx).id()
10577 });
10578
10579 let item1 = cx.new(|cx| {
10580 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10581 });
10582 let item2 = cx.new(|cx| {
10583 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10584 });
10585
10586 // Add an item to an empty pane
10587 workspace.update_in(cx, |workspace, window, cx| {
10588 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10589 });
10590 project.update(cx, |project, cx| {
10591 assert_eq!(
10592 project.active_entry(),
10593 project
10594 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10595 .map(|e| e.id)
10596 );
10597 });
10598 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10599
10600 // Add a second item to a non-empty pane
10601 workspace.update_in(cx, |workspace, window, cx| {
10602 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10603 });
10604 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10605 project.update(cx, |project, cx| {
10606 assert_eq!(
10607 project.active_entry(),
10608 project
10609 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10610 .map(|e| e.id)
10611 );
10612 });
10613
10614 // Close the active item
10615 pane.update_in(cx, |pane, window, cx| {
10616 pane.close_active_item(&Default::default(), window, cx)
10617 })
10618 .await
10619 .unwrap();
10620 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10621 project.update(cx, |project, cx| {
10622 assert_eq!(
10623 project.active_entry(),
10624 project
10625 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10626 .map(|e| e.id)
10627 );
10628 });
10629
10630 // Add a project folder
10631 project
10632 .update(cx, |project, cx| {
10633 project.find_or_create_worktree("root2", true, cx)
10634 })
10635 .await
10636 .unwrap();
10637 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10638
10639 // Remove a project folder
10640 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10641 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10642 }
10643
10644 #[gpui::test]
10645 async fn test_close_window(cx: &mut TestAppContext) {
10646 init_test(cx);
10647
10648 let fs = FakeFs::new(cx.executor());
10649 fs.insert_tree("/root", json!({ "one": "" })).await;
10650
10651 let project = Project::test(fs, ["root".as_ref()], cx).await;
10652 let (workspace, cx) =
10653 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10654
10655 // When there are no dirty items, there's nothing to do.
10656 let item1 = cx.new(TestItem::new);
10657 workspace.update_in(cx, |w, window, cx| {
10658 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10659 });
10660 let task = workspace.update_in(cx, |w, window, cx| {
10661 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10662 });
10663 assert!(task.await.unwrap());
10664
10665 // When there are dirty untitled items, prompt to save each one. If the user
10666 // cancels any prompt, then abort.
10667 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10668 let item3 = cx.new(|cx| {
10669 TestItem::new(cx)
10670 .with_dirty(true)
10671 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10672 });
10673 workspace.update_in(cx, |w, window, cx| {
10674 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10675 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10676 });
10677 let task = workspace.update_in(cx, |w, window, cx| {
10678 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10679 });
10680 cx.executor().run_until_parked();
10681 cx.simulate_prompt_answer("Cancel"); // cancel save all
10682 cx.executor().run_until_parked();
10683 assert!(!cx.has_pending_prompt());
10684 assert!(!task.await.unwrap());
10685 }
10686
10687 #[gpui::test]
10688 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10689 init_test(cx);
10690
10691 let fs = FakeFs::new(cx.executor());
10692 fs.insert_tree("/root", json!({ "one": "" })).await;
10693
10694 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10695 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10696 let multi_workspace_handle =
10697 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10698 cx.run_until_parked();
10699
10700 let workspace_a = multi_workspace_handle
10701 .read_with(cx, |mw, _| mw.workspace().clone())
10702 .unwrap();
10703
10704 let workspace_b = multi_workspace_handle
10705 .update(cx, |mw, window, cx| {
10706 mw.test_add_workspace(project_b, window, cx)
10707 })
10708 .unwrap();
10709
10710 // Activate workspace A
10711 multi_workspace_handle
10712 .update(cx, |mw, window, cx| {
10713 let workspace = mw.workspaces()[0].clone();
10714 mw.activate(workspace, window, cx);
10715 })
10716 .unwrap();
10717
10718 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10719
10720 // Workspace A has a clean item
10721 let item_a = cx.new(TestItem::new);
10722 workspace_a.update_in(cx, |w, window, cx| {
10723 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10724 });
10725
10726 // Workspace B has a dirty item
10727 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10728 workspace_b.update_in(cx, |w, window, cx| {
10729 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10730 });
10731
10732 // Verify workspace A is active
10733 multi_workspace_handle
10734 .read_with(cx, |mw, _| {
10735 assert_eq!(mw.active_workspace_index(), 0);
10736 })
10737 .unwrap();
10738
10739 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10740 multi_workspace_handle
10741 .update(cx, |mw, window, cx| {
10742 mw.close_window(&CloseWindow, window, cx);
10743 })
10744 .unwrap();
10745 cx.run_until_parked();
10746
10747 // Workspace B should now be active since it has dirty items that need attention
10748 multi_workspace_handle
10749 .read_with(cx, |mw, _| {
10750 assert_eq!(
10751 mw.active_workspace_index(),
10752 1,
10753 "workspace B should be activated when it prompts"
10754 );
10755 })
10756 .unwrap();
10757
10758 // User cancels the save prompt from workspace B
10759 cx.simulate_prompt_answer("Cancel");
10760 cx.run_until_parked();
10761
10762 // Window should still exist because workspace B's close was cancelled
10763 assert!(
10764 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10765 "window should still exist after cancelling one workspace's close"
10766 );
10767 }
10768
10769 #[gpui::test]
10770 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10771 init_test(cx);
10772
10773 // Register TestItem as a serializable item
10774 cx.update(|cx| {
10775 register_serializable_item::<TestItem>(cx);
10776 });
10777
10778 let fs = FakeFs::new(cx.executor());
10779 fs.insert_tree("/root", json!({ "one": "" })).await;
10780
10781 let project = Project::test(fs, ["root".as_ref()], cx).await;
10782 let (workspace, cx) =
10783 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10784
10785 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10786 let item1 = cx.new(|cx| {
10787 TestItem::new(cx)
10788 .with_dirty(true)
10789 .with_serialize(|| Some(Task::ready(Ok(()))))
10790 });
10791 let item2 = cx.new(|cx| {
10792 TestItem::new(cx)
10793 .with_dirty(true)
10794 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10795 .with_serialize(|| Some(Task::ready(Ok(()))))
10796 });
10797 workspace.update_in(cx, |w, window, cx| {
10798 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10799 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10800 });
10801 let task = workspace.update_in(cx, |w, window, cx| {
10802 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10803 });
10804 assert!(task.await.unwrap());
10805 }
10806
10807 #[gpui::test]
10808 async fn test_close_pane_items(cx: &mut TestAppContext) {
10809 init_test(cx);
10810
10811 let fs = FakeFs::new(cx.executor());
10812
10813 let project = Project::test(fs, None, cx).await;
10814 let (workspace, cx) =
10815 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10816
10817 let item1 = cx.new(|cx| {
10818 TestItem::new(cx)
10819 .with_dirty(true)
10820 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10821 });
10822 let item2 = cx.new(|cx| {
10823 TestItem::new(cx)
10824 .with_dirty(true)
10825 .with_conflict(true)
10826 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10827 });
10828 let item3 = cx.new(|cx| {
10829 TestItem::new(cx)
10830 .with_dirty(true)
10831 .with_conflict(true)
10832 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10833 });
10834 let item4 = cx.new(|cx| {
10835 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10836 let project_item = TestProjectItem::new_untitled(cx);
10837 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10838 project_item
10839 }])
10840 });
10841 let pane = workspace.update_in(cx, |workspace, window, cx| {
10842 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10843 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10844 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10845 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10846 workspace.active_pane().clone()
10847 });
10848
10849 let close_items = pane.update_in(cx, |pane, window, cx| {
10850 pane.activate_item(1, true, true, window, cx);
10851 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10852 let item1_id = item1.item_id();
10853 let item3_id = item3.item_id();
10854 let item4_id = item4.item_id();
10855 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10856 [item1_id, item3_id, item4_id].contains(&id)
10857 })
10858 });
10859 cx.executor().run_until_parked();
10860
10861 assert!(cx.has_pending_prompt());
10862 cx.simulate_prompt_answer("Save all");
10863
10864 cx.executor().run_until_parked();
10865
10866 // Item 1 is saved. There's a prompt to save item 3.
10867 pane.update(cx, |pane, cx| {
10868 assert_eq!(item1.read(cx).save_count, 1);
10869 assert_eq!(item1.read(cx).save_as_count, 0);
10870 assert_eq!(item1.read(cx).reload_count, 0);
10871 assert_eq!(pane.items_len(), 3);
10872 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10873 });
10874 assert!(cx.has_pending_prompt());
10875
10876 // Cancel saving item 3.
10877 cx.simulate_prompt_answer("Discard");
10878 cx.executor().run_until_parked();
10879
10880 // Item 3 is reloaded. There's a prompt to save item 4.
10881 pane.update(cx, |pane, cx| {
10882 assert_eq!(item3.read(cx).save_count, 0);
10883 assert_eq!(item3.read(cx).save_as_count, 0);
10884 assert_eq!(item3.read(cx).reload_count, 1);
10885 assert_eq!(pane.items_len(), 2);
10886 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10887 });
10888
10889 // There's a prompt for a path for item 4.
10890 cx.simulate_new_path_selection(|_| Some(Default::default()));
10891 close_items.await.unwrap();
10892
10893 // The requested items are closed.
10894 pane.update(cx, |pane, cx| {
10895 assert_eq!(item4.read(cx).save_count, 0);
10896 assert_eq!(item4.read(cx).save_as_count, 1);
10897 assert_eq!(item4.read(cx).reload_count, 0);
10898 assert_eq!(pane.items_len(), 1);
10899 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10900 });
10901 }
10902
10903 #[gpui::test]
10904 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10905 init_test(cx);
10906
10907 let fs = FakeFs::new(cx.executor());
10908 let project = Project::test(fs, [], cx).await;
10909 let (workspace, cx) =
10910 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10911
10912 // Create several workspace items with single project entries, and two
10913 // workspace items with multiple project entries.
10914 let single_entry_items = (0..=4)
10915 .map(|project_entry_id| {
10916 cx.new(|cx| {
10917 TestItem::new(cx)
10918 .with_dirty(true)
10919 .with_project_items(&[dirty_project_item(
10920 project_entry_id,
10921 &format!("{project_entry_id}.txt"),
10922 cx,
10923 )])
10924 })
10925 })
10926 .collect::<Vec<_>>();
10927 let item_2_3 = cx.new(|cx| {
10928 TestItem::new(cx)
10929 .with_dirty(true)
10930 .with_buffer_kind(ItemBufferKind::Multibuffer)
10931 .with_project_items(&[
10932 single_entry_items[2].read(cx).project_items[0].clone(),
10933 single_entry_items[3].read(cx).project_items[0].clone(),
10934 ])
10935 });
10936 let item_3_4 = cx.new(|cx| {
10937 TestItem::new(cx)
10938 .with_dirty(true)
10939 .with_buffer_kind(ItemBufferKind::Multibuffer)
10940 .with_project_items(&[
10941 single_entry_items[3].read(cx).project_items[0].clone(),
10942 single_entry_items[4].read(cx).project_items[0].clone(),
10943 ])
10944 });
10945
10946 // Create two panes that contain the following project entries:
10947 // left pane:
10948 // multi-entry items: (2, 3)
10949 // single-entry items: 0, 2, 3, 4
10950 // right pane:
10951 // single-entry items: 4, 1
10952 // multi-entry items: (3, 4)
10953 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10954 let left_pane = workspace.active_pane().clone();
10955 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10956 workspace.add_item_to_active_pane(
10957 single_entry_items[0].boxed_clone(),
10958 None,
10959 true,
10960 window,
10961 cx,
10962 );
10963 workspace.add_item_to_active_pane(
10964 single_entry_items[2].boxed_clone(),
10965 None,
10966 true,
10967 window,
10968 cx,
10969 );
10970 workspace.add_item_to_active_pane(
10971 single_entry_items[3].boxed_clone(),
10972 None,
10973 true,
10974 window,
10975 cx,
10976 );
10977 workspace.add_item_to_active_pane(
10978 single_entry_items[4].boxed_clone(),
10979 None,
10980 true,
10981 window,
10982 cx,
10983 );
10984
10985 let right_pane =
10986 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10987
10988 let boxed_clone = single_entry_items[1].boxed_clone();
10989 let right_pane = window.spawn(cx, async move |cx| {
10990 right_pane.await.inspect(|right_pane| {
10991 right_pane
10992 .update_in(cx, |pane, window, cx| {
10993 pane.add_item(boxed_clone, true, true, None, window, cx);
10994 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10995 })
10996 .unwrap();
10997 })
10998 });
10999
11000 (left_pane, right_pane)
11001 });
11002 let right_pane = right_pane.await.unwrap();
11003 cx.focus(&right_pane);
11004
11005 let close = right_pane.update_in(cx, |pane, window, cx| {
11006 pane.close_all_items(&CloseAllItems::default(), window, cx)
11007 .unwrap()
11008 });
11009 cx.executor().run_until_parked();
11010
11011 let msg = cx.pending_prompt().unwrap().0;
11012 assert!(msg.contains("1.txt"));
11013 assert!(!msg.contains("2.txt"));
11014 assert!(!msg.contains("3.txt"));
11015 assert!(!msg.contains("4.txt"));
11016
11017 // With best-effort close, cancelling item 1 keeps it open but items 4
11018 // and (3,4) still close since their entries exist in left pane.
11019 cx.simulate_prompt_answer("Cancel");
11020 close.await;
11021
11022 right_pane.read_with(cx, |pane, _| {
11023 assert_eq!(pane.items_len(), 1);
11024 });
11025
11026 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11027 left_pane
11028 .update_in(cx, |left_pane, window, cx| {
11029 left_pane.close_item_by_id(
11030 single_entry_items[3].entity_id(),
11031 SaveIntent::Skip,
11032 window,
11033 cx,
11034 )
11035 })
11036 .await
11037 .unwrap();
11038
11039 let close = left_pane.update_in(cx, |pane, window, cx| {
11040 pane.close_all_items(&CloseAllItems::default(), window, cx)
11041 .unwrap()
11042 });
11043 cx.executor().run_until_parked();
11044
11045 let details = cx.pending_prompt().unwrap().1;
11046 assert!(details.contains("0.txt"));
11047 assert!(details.contains("3.txt"));
11048 assert!(details.contains("4.txt"));
11049 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11050 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11051 // assert!(!details.contains("2.txt"));
11052
11053 cx.simulate_prompt_answer("Save all");
11054 cx.executor().run_until_parked();
11055 close.await;
11056
11057 left_pane.read_with(cx, |pane, _| {
11058 assert_eq!(pane.items_len(), 0);
11059 });
11060 }
11061
11062 #[gpui::test]
11063 async fn test_autosave(cx: &mut gpui::TestAppContext) {
11064 init_test(cx);
11065
11066 let fs = FakeFs::new(cx.executor());
11067 let project = Project::test(fs, [], cx).await;
11068 let (workspace, cx) =
11069 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11070 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11071
11072 let item = cx.new(|cx| {
11073 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11074 });
11075 let item_id = item.entity_id();
11076 workspace.update_in(cx, |workspace, window, cx| {
11077 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11078 });
11079
11080 // Autosave on window change.
11081 item.update(cx, |item, cx| {
11082 SettingsStore::update_global(cx, |settings, cx| {
11083 settings.update_user_settings(cx, |settings| {
11084 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11085 })
11086 });
11087 item.is_dirty = true;
11088 });
11089
11090 // Deactivating the window saves the file.
11091 cx.deactivate_window();
11092 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11093
11094 // Re-activating the window doesn't save the file.
11095 cx.update(|window, _| window.activate_window());
11096 cx.executor().run_until_parked();
11097 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11098
11099 // Autosave on focus change.
11100 item.update_in(cx, |item, window, cx| {
11101 cx.focus_self(window);
11102 SettingsStore::update_global(cx, |settings, cx| {
11103 settings.update_user_settings(cx, |settings| {
11104 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11105 })
11106 });
11107 item.is_dirty = true;
11108 });
11109 // Blurring the item saves the file.
11110 item.update_in(cx, |_, window, _| window.blur());
11111 cx.executor().run_until_parked();
11112 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11113
11114 // Deactivating the window still saves the file.
11115 item.update_in(cx, |item, window, cx| {
11116 cx.focus_self(window);
11117 item.is_dirty = true;
11118 });
11119 cx.deactivate_window();
11120 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11121
11122 // Autosave after delay.
11123 item.update(cx, |item, cx| {
11124 SettingsStore::update_global(cx, |settings, cx| {
11125 settings.update_user_settings(cx, |settings| {
11126 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11127 milliseconds: 500.into(),
11128 });
11129 })
11130 });
11131 item.is_dirty = true;
11132 cx.emit(ItemEvent::Edit);
11133 });
11134
11135 // Delay hasn't fully expired, so the file is still dirty and unsaved.
11136 cx.executor().advance_clock(Duration::from_millis(250));
11137 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11138
11139 // After delay expires, the file is saved.
11140 cx.executor().advance_clock(Duration::from_millis(250));
11141 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11142
11143 // Autosave after delay, should save earlier than delay if tab is closed
11144 item.update(cx, |item, cx| {
11145 item.is_dirty = true;
11146 cx.emit(ItemEvent::Edit);
11147 });
11148 cx.executor().advance_clock(Duration::from_millis(250));
11149 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11150
11151 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11152 pane.update_in(cx, |pane, window, cx| {
11153 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11154 })
11155 .await
11156 .unwrap();
11157 assert!(!cx.has_pending_prompt());
11158 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11159
11160 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11161 workspace.update_in(cx, |workspace, window, cx| {
11162 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11163 });
11164 item.update_in(cx, |item, _window, cx| {
11165 item.is_dirty = true;
11166 for project_item in &mut item.project_items {
11167 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11168 }
11169 });
11170 cx.run_until_parked();
11171 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11172
11173 // Autosave on focus change, ensuring closing the tab counts as such.
11174 item.update(cx, |item, cx| {
11175 SettingsStore::update_global(cx, |settings, cx| {
11176 settings.update_user_settings(cx, |settings| {
11177 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11178 })
11179 });
11180 item.is_dirty = true;
11181 for project_item in &mut item.project_items {
11182 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11183 }
11184 });
11185
11186 pane.update_in(cx, |pane, window, cx| {
11187 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11188 })
11189 .await
11190 .unwrap();
11191 assert!(!cx.has_pending_prompt());
11192 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11193
11194 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11195 workspace.update_in(cx, |workspace, window, cx| {
11196 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11197 });
11198 item.update_in(cx, |item, window, cx| {
11199 item.project_items[0].update(cx, |item, _| {
11200 item.entry_id = None;
11201 });
11202 item.is_dirty = true;
11203 window.blur();
11204 });
11205 cx.run_until_parked();
11206 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11207
11208 // Ensure autosave is prevented for deleted files also when closing the buffer.
11209 let _close_items = pane.update_in(cx, |pane, window, cx| {
11210 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11211 });
11212 cx.run_until_parked();
11213 assert!(cx.has_pending_prompt());
11214 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11215 }
11216
11217 #[gpui::test]
11218 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11219 init_test(cx);
11220
11221 let fs = FakeFs::new(cx.executor());
11222 let project = Project::test(fs, [], cx).await;
11223 let (workspace, cx) =
11224 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11225
11226 // Create a multibuffer-like item with two child focus handles,
11227 // simulating individual buffer editors within a multibuffer.
11228 let item = cx.new(|cx| {
11229 TestItem::new(cx)
11230 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11231 .with_child_focus_handles(2, cx)
11232 });
11233 workspace.update_in(cx, |workspace, window, cx| {
11234 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11235 });
11236
11237 // Set autosave to OnFocusChange and focus the first child handle,
11238 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11239 item.update_in(cx, |item, window, cx| {
11240 SettingsStore::update_global(cx, |settings, cx| {
11241 settings.update_user_settings(cx, |settings| {
11242 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11243 })
11244 });
11245 item.is_dirty = true;
11246 window.focus(&item.child_focus_handles[0], cx);
11247 });
11248 cx.executor().run_until_parked();
11249 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11250
11251 // Moving focus from one child to another within the same item should
11252 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11253 item.update_in(cx, |item, window, cx| {
11254 window.focus(&item.child_focus_handles[1], cx);
11255 });
11256 cx.executor().run_until_parked();
11257 item.read_with(cx, |item, _| {
11258 assert_eq!(
11259 item.save_count, 0,
11260 "Switching focus between children within the same item should not autosave"
11261 );
11262 });
11263
11264 // Blurring the item saves the file. This is the core regression scenario:
11265 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11266 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11267 // the leaf is always a child focus handle, so `on_blur` never detected
11268 // focus leaving the item.
11269 item.update_in(cx, |_, window, _| window.blur());
11270 cx.executor().run_until_parked();
11271 item.read_with(cx, |item, _| {
11272 assert_eq!(
11273 item.save_count, 1,
11274 "Blurring should trigger autosave when focus was on a child of the item"
11275 );
11276 });
11277
11278 // Deactivating the window should also trigger autosave when a child of
11279 // the multibuffer item currently owns focus.
11280 item.update_in(cx, |item, window, cx| {
11281 item.is_dirty = true;
11282 window.focus(&item.child_focus_handles[0], cx);
11283 });
11284 cx.executor().run_until_parked();
11285 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11286
11287 cx.deactivate_window();
11288 item.read_with(cx, |item, _| {
11289 assert_eq!(
11290 item.save_count, 2,
11291 "Deactivating window should trigger autosave when focus was on a child"
11292 );
11293 });
11294 }
11295
11296 #[gpui::test]
11297 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11298 init_test(cx);
11299
11300 let fs = FakeFs::new(cx.executor());
11301
11302 let project = Project::test(fs, [], cx).await;
11303 let (workspace, cx) =
11304 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11305
11306 let item = cx.new(|cx| {
11307 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11308 });
11309 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11310 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11311 let toolbar_notify_count = Rc::new(RefCell::new(0));
11312
11313 workspace.update_in(cx, |workspace, window, cx| {
11314 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11315 let toolbar_notification_count = toolbar_notify_count.clone();
11316 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11317 *toolbar_notification_count.borrow_mut() += 1
11318 })
11319 .detach();
11320 });
11321
11322 pane.read_with(cx, |pane, _| {
11323 assert!(!pane.can_navigate_backward());
11324 assert!(!pane.can_navigate_forward());
11325 });
11326
11327 item.update_in(cx, |item, _, cx| {
11328 item.set_state("one".to_string(), cx);
11329 });
11330
11331 // Toolbar must be notified to re-render the navigation buttons
11332 assert_eq!(*toolbar_notify_count.borrow(), 1);
11333
11334 pane.read_with(cx, |pane, _| {
11335 assert!(pane.can_navigate_backward());
11336 assert!(!pane.can_navigate_forward());
11337 });
11338
11339 workspace
11340 .update_in(cx, |workspace, window, cx| {
11341 workspace.go_back(pane.downgrade(), window, cx)
11342 })
11343 .await
11344 .unwrap();
11345
11346 assert_eq!(*toolbar_notify_count.borrow(), 2);
11347 pane.read_with(cx, |pane, _| {
11348 assert!(!pane.can_navigate_backward());
11349 assert!(pane.can_navigate_forward());
11350 });
11351 }
11352
11353 /// Tests that the navigation history deduplicates entries for the same item.
11354 ///
11355 /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11356 /// the navigation history deduplicates by keeping only the most recent visit to each item,
11357 /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11358 /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11359 /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11360 ///
11361 /// This behavior prevents the navigation history from growing unnecessarily large and provides
11362 /// a better user experience by eliminating redundant navigation steps when jumping between files.
11363 #[gpui::test]
11364 async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11365 init_test(cx);
11366
11367 let fs = FakeFs::new(cx.executor());
11368 let project = Project::test(fs, [], cx).await;
11369 let (workspace, cx) =
11370 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11371
11372 let item_a = cx.new(|cx| {
11373 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11374 });
11375 let item_b = cx.new(|cx| {
11376 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11377 });
11378 let item_c = cx.new(|cx| {
11379 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11380 });
11381
11382 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11383
11384 workspace.update_in(cx, |workspace, window, cx| {
11385 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11386 workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11387 workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11388 });
11389
11390 workspace.update_in(cx, |workspace, window, cx| {
11391 workspace.activate_item(&item_a, false, false, window, cx);
11392 });
11393 cx.run_until_parked();
11394
11395 workspace.update_in(cx, |workspace, window, cx| {
11396 workspace.activate_item(&item_b, false, false, window, cx);
11397 });
11398 cx.run_until_parked();
11399
11400 workspace.update_in(cx, |workspace, window, cx| {
11401 workspace.activate_item(&item_a, false, false, window, cx);
11402 });
11403 cx.run_until_parked();
11404
11405 workspace.update_in(cx, |workspace, window, cx| {
11406 workspace.activate_item(&item_b, false, false, window, cx);
11407 });
11408 cx.run_until_parked();
11409
11410 workspace.update_in(cx, |workspace, window, cx| {
11411 workspace.activate_item(&item_a, false, false, window, cx);
11412 });
11413 cx.run_until_parked();
11414
11415 workspace.update_in(cx, |workspace, window, cx| {
11416 workspace.activate_item(&item_b, false, false, window, cx);
11417 });
11418 cx.run_until_parked();
11419
11420 workspace.update_in(cx, |workspace, window, cx| {
11421 workspace.activate_item(&item_c, false, false, window, cx);
11422 });
11423 cx.run_until_parked();
11424
11425 let backward_count = pane.read_with(cx, |pane, cx| {
11426 let mut count = 0;
11427 pane.nav_history().for_each_entry(cx, &mut |_, _| {
11428 count += 1;
11429 });
11430 count
11431 });
11432 assert!(
11433 backward_count <= 4,
11434 "Should have at most 4 entries, got {}",
11435 backward_count
11436 );
11437
11438 workspace
11439 .update_in(cx, |workspace, window, cx| {
11440 workspace.go_back(pane.downgrade(), window, cx)
11441 })
11442 .await
11443 .unwrap();
11444
11445 let active_item = workspace.read_with(cx, |workspace, cx| {
11446 workspace.active_item(cx).unwrap().item_id()
11447 });
11448 assert_eq!(
11449 active_item,
11450 item_b.entity_id(),
11451 "After first go_back, should be at item B"
11452 );
11453
11454 workspace
11455 .update_in(cx, |workspace, window, cx| {
11456 workspace.go_back(pane.downgrade(), window, cx)
11457 })
11458 .await
11459 .unwrap();
11460
11461 let active_item = workspace.read_with(cx, |workspace, cx| {
11462 workspace.active_item(cx).unwrap().item_id()
11463 });
11464 assert_eq!(
11465 active_item,
11466 item_a.entity_id(),
11467 "After second go_back, should be at item A"
11468 );
11469
11470 pane.read_with(cx, |pane, _| {
11471 assert!(pane.can_navigate_forward(), "Should be able to go forward");
11472 });
11473 }
11474
11475 #[gpui::test]
11476 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11477 init_test(cx);
11478 let fs = FakeFs::new(cx.executor());
11479 let project = Project::test(fs, [], cx).await;
11480 let (multi_workspace, cx) =
11481 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11482 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11483
11484 workspace.update_in(cx, |workspace, window, cx| {
11485 let first_item = cx.new(|cx| {
11486 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11487 });
11488 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11489 workspace.split_pane(
11490 workspace.active_pane().clone(),
11491 SplitDirection::Right,
11492 window,
11493 cx,
11494 );
11495 workspace.split_pane(
11496 workspace.active_pane().clone(),
11497 SplitDirection::Right,
11498 window,
11499 cx,
11500 );
11501 });
11502
11503 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11504 let panes = workspace.center.panes();
11505 assert!(panes.len() >= 2);
11506 (
11507 panes.first().expect("at least one pane").entity_id(),
11508 panes.last().expect("at least one pane").entity_id(),
11509 )
11510 });
11511
11512 workspace.update_in(cx, |workspace, window, cx| {
11513 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11514 });
11515 workspace.update(cx, |workspace, _| {
11516 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11517 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11518 });
11519
11520 cx.dispatch_action(ActivateLastPane);
11521
11522 workspace.update(cx, |workspace, _| {
11523 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11524 });
11525 }
11526
11527 #[gpui::test]
11528 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11529 init_test(cx);
11530 let fs = FakeFs::new(cx.executor());
11531
11532 let project = Project::test(fs, [], cx).await;
11533 let (workspace, cx) =
11534 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11535
11536 let panel = workspace.update_in(cx, |workspace, window, cx| {
11537 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11538 workspace.add_panel(panel.clone(), window, cx);
11539
11540 workspace
11541 .right_dock()
11542 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11543
11544 panel
11545 });
11546
11547 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11548 pane.update_in(cx, |pane, window, cx| {
11549 let item = cx.new(TestItem::new);
11550 pane.add_item(Box::new(item), true, true, None, window, cx);
11551 });
11552
11553 // Transfer focus from center to panel
11554 workspace.update_in(cx, |workspace, window, cx| {
11555 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11556 });
11557
11558 workspace.update_in(cx, |workspace, window, cx| {
11559 assert!(workspace.right_dock().read(cx).is_open());
11560 assert!(!panel.is_zoomed(window, cx));
11561 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11562 });
11563
11564 // Transfer focus from panel to center
11565 workspace.update_in(cx, |workspace, window, cx| {
11566 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11567 });
11568
11569 workspace.update_in(cx, |workspace, window, cx| {
11570 assert!(workspace.right_dock().read(cx).is_open());
11571 assert!(!panel.is_zoomed(window, cx));
11572 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11573 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11574 });
11575
11576 // Close the dock
11577 workspace.update_in(cx, |workspace, window, cx| {
11578 workspace.toggle_dock(DockPosition::Right, window, cx);
11579 });
11580
11581 workspace.update_in(cx, |workspace, window, cx| {
11582 assert!(!workspace.right_dock().read(cx).is_open());
11583 assert!(!panel.is_zoomed(window, cx));
11584 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11585 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11586 });
11587
11588 // Open the dock
11589 workspace.update_in(cx, |workspace, window, cx| {
11590 workspace.toggle_dock(DockPosition::Right, window, cx);
11591 });
11592
11593 workspace.update_in(cx, |workspace, window, cx| {
11594 assert!(workspace.right_dock().read(cx).is_open());
11595 assert!(!panel.is_zoomed(window, cx));
11596 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11597 });
11598
11599 // Focus and zoom panel
11600 panel.update_in(cx, |panel, window, cx| {
11601 cx.focus_self(window);
11602 panel.set_zoomed(true, window, cx)
11603 });
11604
11605 workspace.update_in(cx, |workspace, window, cx| {
11606 assert!(workspace.right_dock().read(cx).is_open());
11607 assert!(panel.is_zoomed(window, cx));
11608 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11609 });
11610
11611 // Transfer focus to the center closes the dock
11612 workspace.update_in(cx, |workspace, window, cx| {
11613 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11614 });
11615
11616 workspace.update_in(cx, |workspace, window, cx| {
11617 assert!(!workspace.right_dock().read(cx).is_open());
11618 assert!(panel.is_zoomed(window, cx));
11619 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11620 });
11621
11622 // Transferring focus back to the panel keeps it zoomed
11623 workspace.update_in(cx, |workspace, window, cx| {
11624 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11625 });
11626
11627 workspace.update_in(cx, |workspace, window, cx| {
11628 assert!(workspace.right_dock().read(cx).is_open());
11629 assert!(panel.is_zoomed(window, cx));
11630 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11631 });
11632
11633 // Close the dock while it is zoomed
11634 workspace.update_in(cx, |workspace, window, cx| {
11635 workspace.toggle_dock(DockPosition::Right, window, cx)
11636 });
11637
11638 workspace.update_in(cx, |workspace, window, cx| {
11639 assert!(!workspace.right_dock().read(cx).is_open());
11640 assert!(panel.is_zoomed(window, cx));
11641 assert!(workspace.zoomed.is_none());
11642 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11643 });
11644
11645 // Opening the dock, when it's zoomed, retains focus
11646 workspace.update_in(cx, |workspace, window, cx| {
11647 workspace.toggle_dock(DockPosition::Right, window, cx)
11648 });
11649
11650 workspace.update_in(cx, |workspace, window, cx| {
11651 assert!(workspace.right_dock().read(cx).is_open());
11652 assert!(panel.is_zoomed(window, cx));
11653 assert!(workspace.zoomed.is_some());
11654 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11655 });
11656
11657 // Unzoom and close the panel, zoom the active pane.
11658 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11659 workspace.update_in(cx, |workspace, window, cx| {
11660 workspace.toggle_dock(DockPosition::Right, window, cx)
11661 });
11662 pane.update_in(cx, |pane, window, cx| {
11663 pane.toggle_zoom(&Default::default(), window, cx)
11664 });
11665
11666 // Opening a dock unzooms the pane.
11667 workspace.update_in(cx, |workspace, window, cx| {
11668 workspace.toggle_dock(DockPosition::Right, window, cx)
11669 });
11670 workspace.update_in(cx, |workspace, window, cx| {
11671 let pane = pane.read(cx);
11672 assert!(!pane.is_zoomed());
11673 assert!(!pane.focus_handle(cx).is_focused(window));
11674 assert!(workspace.right_dock().read(cx).is_open());
11675 assert!(workspace.zoomed.is_none());
11676 });
11677 }
11678
11679 #[gpui::test]
11680 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11681 init_test(cx);
11682 let fs = FakeFs::new(cx.executor());
11683
11684 let project = Project::test(fs, [], cx).await;
11685 let (workspace, cx) =
11686 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11687
11688 let panel = workspace.update_in(cx, |workspace, window, cx| {
11689 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11690 workspace.add_panel(panel.clone(), window, cx);
11691 panel
11692 });
11693
11694 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11695 pane.update_in(cx, |pane, window, cx| {
11696 let item = cx.new(TestItem::new);
11697 pane.add_item(Box::new(item), true, true, None, window, cx);
11698 });
11699
11700 // Enable close_panel_on_toggle
11701 cx.update_global(|store: &mut SettingsStore, cx| {
11702 store.update_user_settings(cx, |settings| {
11703 settings.workspace.close_panel_on_toggle = Some(true);
11704 });
11705 });
11706
11707 // Panel starts closed. Toggling should open and focus it.
11708 workspace.update_in(cx, |workspace, window, cx| {
11709 assert!(!workspace.right_dock().read(cx).is_open());
11710 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11711 });
11712
11713 workspace.update_in(cx, |workspace, window, cx| {
11714 assert!(
11715 workspace.right_dock().read(cx).is_open(),
11716 "Dock should be open after toggling from center"
11717 );
11718 assert!(
11719 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11720 "Panel should be focused after toggling from center"
11721 );
11722 });
11723
11724 // Panel is open and focused. Toggling should close the panel and
11725 // return focus to the center.
11726 workspace.update_in(cx, |workspace, window, cx| {
11727 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11728 });
11729
11730 workspace.update_in(cx, |workspace, window, cx| {
11731 assert!(
11732 !workspace.right_dock().read(cx).is_open(),
11733 "Dock should be closed after toggling from focused panel"
11734 );
11735 assert!(
11736 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11737 "Panel should not be focused after toggling from focused panel"
11738 );
11739 });
11740
11741 // Open the dock and focus something else so the panel is open but not
11742 // focused. Toggling should focus the panel (not close it).
11743 workspace.update_in(cx, |workspace, window, cx| {
11744 workspace
11745 .right_dock()
11746 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11747 window.focus(&pane.read(cx).focus_handle(cx), cx);
11748 });
11749
11750 workspace.update_in(cx, |workspace, window, cx| {
11751 assert!(workspace.right_dock().read(cx).is_open());
11752 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11753 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11754 });
11755
11756 workspace.update_in(cx, |workspace, window, cx| {
11757 assert!(
11758 workspace.right_dock().read(cx).is_open(),
11759 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11760 );
11761 assert!(
11762 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11763 "Panel should be focused after toggling an open-but-unfocused panel"
11764 );
11765 });
11766
11767 // Now disable the setting and verify the original behavior: toggling
11768 // from a focused panel moves focus to center but leaves the dock open.
11769 cx.update_global(|store: &mut SettingsStore, cx| {
11770 store.update_user_settings(cx, |settings| {
11771 settings.workspace.close_panel_on_toggle = Some(false);
11772 });
11773 });
11774
11775 workspace.update_in(cx, |workspace, window, cx| {
11776 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11777 });
11778
11779 workspace.update_in(cx, |workspace, window, cx| {
11780 assert!(
11781 workspace.right_dock().read(cx).is_open(),
11782 "Dock should remain open when setting is disabled"
11783 );
11784 assert!(
11785 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11786 "Panel should not be focused after toggling with setting disabled"
11787 );
11788 });
11789 }
11790
11791 #[gpui::test]
11792 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11793 init_test(cx);
11794 let fs = FakeFs::new(cx.executor());
11795
11796 let project = Project::test(fs, [], cx).await;
11797 let (workspace, cx) =
11798 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11799
11800 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11801 workspace.active_pane().clone()
11802 });
11803
11804 // Add an item to the pane so it can be zoomed
11805 workspace.update_in(cx, |workspace, window, cx| {
11806 let item = cx.new(TestItem::new);
11807 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11808 });
11809
11810 // Initially not zoomed
11811 workspace.update_in(cx, |workspace, _window, cx| {
11812 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11813 assert!(
11814 workspace.zoomed.is_none(),
11815 "Workspace should track no zoomed pane"
11816 );
11817 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11818 });
11819
11820 // Zoom In
11821 pane.update_in(cx, |pane, window, cx| {
11822 pane.zoom_in(&crate::ZoomIn, window, cx);
11823 });
11824
11825 workspace.update_in(cx, |workspace, window, cx| {
11826 assert!(
11827 pane.read(cx).is_zoomed(),
11828 "Pane should be zoomed after ZoomIn"
11829 );
11830 assert!(
11831 workspace.zoomed.is_some(),
11832 "Workspace should track the zoomed pane"
11833 );
11834 assert!(
11835 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11836 "ZoomIn should focus the pane"
11837 );
11838 });
11839
11840 // Zoom In again is a no-op
11841 pane.update_in(cx, |pane, window, cx| {
11842 pane.zoom_in(&crate::ZoomIn, window, cx);
11843 });
11844
11845 workspace.update_in(cx, |workspace, window, cx| {
11846 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11847 assert!(
11848 workspace.zoomed.is_some(),
11849 "Workspace still tracks zoomed pane"
11850 );
11851 assert!(
11852 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11853 "Pane remains focused after repeated ZoomIn"
11854 );
11855 });
11856
11857 // Zoom Out
11858 pane.update_in(cx, |pane, window, cx| {
11859 pane.zoom_out(&crate::ZoomOut, window, cx);
11860 });
11861
11862 workspace.update_in(cx, |workspace, _window, cx| {
11863 assert!(
11864 !pane.read(cx).is_zoomed(),
11865 "Pane should unzoom after ZoomOut"
11866 );
11867 assert!(
11868 workspace.zoomed.is_none(),
11869 "Workspace clears zoom tracking after ZoomOut"
11870 );
11871 });
11872
11873 // Zoom Out again is a no-op
11874 pane.update_in(cx, |pane, window, cx| {
11875 pane.zoom_out(&crate::ZoomOut, window, cx);
11876 });
11877
11878 workspace.update_in(cx, |workspace, _window, cx| {
11879 assert!(
11880 !pane.read(cx).is_zoomed(),
11881 "Second ZoomOut keeps pane unzoomed"
11882 );
11883 assert!(
11884 workspace.zoomed.is_none(),
11885 "Workspace remains without zoomed pane"
11886 );
11887 });
11888 }
11889
11890 #[gpui::test]
11891 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11892 init_test(cx);
11893 let fs = FakeFs::new(cx.executor());
11894
11895 let project = Project::test(fs, [], cx).await;
11896 let (workspace, cx) =
11897 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11898 workspace.update_in(cx, |workspace, window, cx| {
11899 // Open two docks
11900 let left_dock = workspace.dock_at_position(DockPosition::Left);
11901 let right_dock = workspace.dock_at_position(DockPosition::Right);
11902
11903 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11904 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11905
11906 assert!(left_dock.read(cx).is_open());
11907 assert!(right_dock.read(cx).is_open());
11908 });
11909
11910 workspace.update_in(cx, |workspace, window, cx| {
11911 // Toggle all docks - should close both
11912 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11913
11914 let left_dock = workspace.dock_at_position(DockPosition::Left);
11915 let right_dock = workspace.dock_at_position(DockPosition::Right);
11916 assert!(!left_dock.read(cx).is_open());
11917 assert!(!right_dock.read(cx).is_open());
11918 });
11919
11920 workspace.update_in(cx, |workspace, window, cx| {
11921 // Toggle again - should reopen both
11922 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11923
11924 let left_dock = workspace.dock_at_position(DockPosition::Left);
11925 let right_dock = workspace.dock_at_position(DockPosition::Right);
11926 assert!(left_dock.read(cx).is_open());
11927 assert!(right_dock.read(cx).is_open());
11928 });
11929 }
11930
11931 #[gpui::test]
11932 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11933 init_test(cx);
11934 let fs = FakeFs::new(cx.executor());
11935
11936 let project = Project::test(fs, [], cx).await;
11937 let (workspace, cx) =
11938 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11939 workspace.update_in(cx, |workspace, window, cx| {
11940 // Open two docks
11941 let left_dock = workspace.dock_at_position(DockPosition::Left);
11942 let right_dock = workspace.dock_at_position(DockPosition::Right);
11943
11944 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11945 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11946
11947 assert!(left_dock.read(cx).is_open());
11948 assert!(right_dock.read(cx).is_open());
11949 });
11950
11951 workspace.update_in(cx, |workspace, window, cx| {
11952 // Close them manually
11953 workspace.toggle_dock(DockPosition::Left, window, cx);
11954 workspace.toggle_dock(DockPosition::Right, window, cx);
11955
11956 let left_dock = workspace.dock_at_position(DockPosition::Left);
11957 let right_dock = workspace.dock_at_position(DockPosition::Right);
11958 assert!(!left_dock.read(cx).is_open());
11959 assert!(!right_dock.read(cx).is_open());
11960 });
11961
11962 workspace.update_in(cx, |workspace, window, cx| {
11963 // Toggle all docks - only last closed (right dock) should reopen
11964 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11965
11966 let left_dock = workspace.dock_at_position(DockPosition::Left);
11967 let right_dock = workspace.dock_at_position(DockPosition::Right);
11968 assert!(!left_dock.read(cx).is_open());
11969 assert!(right_dock.read(cx).is_open());
11970 });
11971 }
11972
11973 #[gpui::test]
11974 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11975 init_test(cx);
11976 let fs = FakeFs::new(cx.executor());
11977 let project = Project::test(fs, [], cx).await;
11978 let (multi_workspace, cx) =
11979 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11980 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11981
11982 // Open two docks (left and right) with one panel each
11983 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11984 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11985 workspace.add_panel(left_panel.clone(), window, cx);
11986
11987 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11988 workspace.add_panel(right_panel.clone(), window, cx);
11989
11990 workspace.toggle_dock(DockPosition::Left, window, cx);
11991 workspace.toggle_dock(DockPosition::Right, window, cx);
11992
11993 // Verify initial state
11994 assert!(
11995 workspace.left_dock().read(cx).is_open(),
11996 "Left dock should be open"
11997 );
11998 assert_eq!(
11999 workspace
12000 .left_dock()
12001 .read(cx)
12002 .visible_panel()
12003 .unwrap()
12004 .panel_id(),
12005 left_panel.panel_id(),
12006 "Left panel should be visible in left dock"
12007 );
12008 assert!(
12009 workspace.right_dock().read(cx).is_open(),
12010 "Right dock should be open"
12011 );
12012 assert_eq!(
12013 workspace
12014 .right_dock()
12015 .read(cx)
12016 .visible_panel()
12017 .unwrap()
12018 .panel_id(),
12019 right_panel.panel_id(),
12020 "Right panel should be visible in right dock"
12021 );
12022 assert!(
12023 !workspace.bottom_dock().read(cx).is_open(),
12024 "Bottom dock should be closed"
12025 );
12026
12027 (left_panel, right_panel)
12028 });
12029
12030 // Focus the left panel and move it to the next position (bottom dock)
12031 workspace.update_in(cx, |workspace, window, cx| {
12032 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12033 assert!(
12034 left_panel.read(cx).focus_handle(cx).is_focused(window),
12035 "Left panel should be focused"
12036 );
12037 });
12038
12039 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12040
12041 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12042 workspace.update(cx, |workspace, cx| {
12043 assert!(
12044 !workspace.left_dock().read(cx).is_open(),
12045 "Left dock should be closed"
12046 );
12047 assert!(
12048 workspace.bottom_dock().read(cx).is_open(),
12049 "Bottom dock should now be open"
12050 );
12051 assert_eq!(
12052 left_panel.read(cx).position,
12053 DockPosition::Bottom,
12054 "Left panel should now be in the bottom dock"
12055 );
12056 assert_eq!(
12057 workspace
12058 .bottom_dock()
12059 .read(cx)
12060 .visible_panel()
12061 .unwrap()
12062 .panel_id(),
12063 left_panel.panel_id(),
12064 "Left panel should be the visible panel in the bottom dock"
12065 );
12066 });
12067
12068 // Toggle all docks off
12069 workspace.update_in(cx, |workspace, window, cx| {
12070 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12071 assert!(
12072 !workspace.left_dock().read(cx).is_open(),
12073 "Left dock should be closed"
12074 );
12075 assert!(
12076 !workspace.right_dock().read(cx).is_open(),
12077 "Right dock should be closed"
12078 );
12079 assert!(
12080 !workspace.bottom_dock().read(cx).is_open(),
12081 "Bottom dock should be closed"
12082 );
12083 });
12084
12085 // Toggle all docks back on and verify positions are restored
12086 workspace.update_in(cx, |workspace, window, cx| {
12087 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12088 assert!(
12089 !workspace.left_dock().read(cx).is_open(),
12090 "Left dock should remain closed"
12091 );
12092 assert!(
12093 workspace.right_dock().read(cx).is_open(),
12094 "Right dock should remain open"
12095 );
12096 assert!(
12097 workspace.bottom_dock().read(cx).is_open(),
12098 "Bottom dock should remain open"
12099 );
12100 assert_eq!(
12101 left_panel.read(cx).position,
12102 DockPosition::Bottom,
12103 "Left panel should remain in the bottom dock"
12104 );
12105 assert_eq!(
12106 right_panel.read(cx).position,
12107 DockPosition::Right,
12108 "Right panel should remain in the right dock"
12109 );
12110 assert_eq!(
12111 workspace
12112 .bottom_dock()
12113 .read(cx)
12114 .visible_panel()
12115 .unwrap()
12116 .panel_id(),
12117 left_panel.panel_id(),
12118 "Left panel should be the visible panel in the right dock"
12119 );
12120 });
12121 }
12122
12123 #[gpui::test]
12124 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12125 init_test(cx);
12126
12127 let fs = FakeFs::new(cx.executor());
12128
12129 let project = Project::test(fs, None, cx).await;
12130 let (workspace, cx) =
12131 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12132
12133 // Let's arrange the panes like this:
12134 //
12135 // +-----------------------+
12136 // | top |
12137 // +------+--------+-------+
12138 // | left | center | right |
12139 // +------+--------+-------+
12140 // | bottom |
12141 // +-----------------------+
12142
12143 let top_item = cx.new(|cx| {
12144 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12145 });
12146 let bottom_item = cx.new(|cx| {
12147 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12148 });
12149 let left_item = cx.new(|cx| {
12150 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12151 });
12152 let right_item = cx.new(|cx| {
12153 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12154 });
12155 let center_item = cx.new(|cx| {
12156 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12157 });
12158
12159 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12160 let top_pane_id = workspace.active_pane().entity_id();
12161 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12162 workspace.split_pane(
12163 workspace.active_pane().clone(),
12164 SplitDirection::Down,
12165 window,
12166 cx,
12167 );
12168 top_pane_id
12169 });
12170 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12171 let bottom_pane_id = workspace.active_pane().entity_id();
12172 workspace.add_item_to_active_pane(
12173 Box::new(bottom_item.clone()),
12174 None,
12175 false,
12176 window,
12177 cx,
12178 );
12179 workspace.split_pane(
12180 workspace.active_pane().clone(),
12181 SplitDirection::Up,
12182 window,
12183 cx,
12184 );
12185 bottom_pane_id
12186 });
12187 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12188 let left_pane_id = workspace.active_pane().entity_id();
12189 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12190 workspace.split_pane(
12191 workspace.active_pane().clone(),
12192 SplitDirection::Right,
12193 window,
12194 cx,
12195 );
12196 left_pane_id
12197 });
12198 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12199 let right_pane_id = workspace.active_pane().entity_id();
12200 workspace.add_item_to_active_pane(
12201 Box::new(right_item.clone()),
12202 None,
12203 false,
12204 window,
12205 cx,
12206 );
12207 workspace.split_pane(
12208 workspace.active_pane().clone(),
12209 SplitDirection::Left,
12210 window,
12211 cx,
12212 );
12213 right_pane_id
12214 });
12215 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12216 let center_pane_id = workspace.active_pane().entity_id();
12217 workspace.add_item_to_active_pane(
12218 Box::new(center_item.clone()),
12219 None,
12220 false,
12221 window,
12222 cx,
12223 );
12224 center_pane_id
12225 });
12226 cx.executor().run_until_parked();
12227
12228 workspace.update_in(cx, |workspace, window, cx| {
12229 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12230
12231 // Join into next from center pane into right
12232 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12233 });
12234
12235 workspace.update_in(cx, |workspace, window, cx| {
12236 let active_pane = workspace.active_pane();
12237 assert_eq!(right_pane_id, active_pane.entity_id());
12238 assert_eq!(2, active_pane.read(cx).items_len());
12239 let item_ids_in_pane =
12240 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12241 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12242 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12243
12244 // Join into next from right pane into bottom
12245 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12246 });
12247
12248 workspace.update_in(cx, |workspace, window, cx| {
12249 let active_pane = workspace.active_pane();
12250 assert_eq!(bottom_pane_id, active_pane.entity_id());
12251 assert_eq!(3, active_pane.read(cx).items_len());
12252 let item_ids_in_pane =
12253 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12254 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12255 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12256 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12257
12258 // Join into next from bottom pane into left
12259 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12260 });
12261
12262 workspace.update_in(cx, |workspace, window, cx| {
12263 let active_pane = workspace.active_pane();
12264 assert_eq!(left_pane_id, active_pane.entity_id());
12265 assert_eq!(4, active_pane.read(cx).items_len());
12266 let item_ids_in_pane =
12267 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12268 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12269 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12270 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12271 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12272
12273 // Join into next from left pane into top
12274 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12275 });
12276
12277 workspace.update_in(cx, |workspace, window, cx| {
12278 let active_pane = workspace.active_pane();
12279 assert_eq!(top_pane_id, active_pane.entity_id());
12280 assert_eq!(5, active_pane.read(cx).items_len());
12281 let item_ids_in_pane =
12282 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12283 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12284 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12285 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12286 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12287 assert!(item_ids_in_pane.contains(&top_item.item_id()));
12288
12289 // Single pane left: no-op
12290 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12291 });
12292
12293 workspace.update(cx, |workspace, _cx| {
12294 let active_pane = workspace.active_pane();
12295 assert_eq!(top_pane_id, active_pane.entity_id());
12296 });
12297 }
12298
12299 fn add_an_item_to_active_pane(
12300 cx: &mut VisualTestContext,
12301 workspace: &Entity<Workspace>,
12302 item_id: u64,
12303 ) -> Entity<TestItem> {
12304 let item = cx.new(|cx| {
12305 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12306 item_id,
12307 "item{item_id}.txt",
12308 cx,
12309 )])
12310 });
12311 workspace.update_in(cx, |workspace, window, cx| {
12312 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12313 });
12314 item
12315 }
12316
12317 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12318 workspace.update_in(cx, |workspace, window, cx| {
12319 workspace.split_pane(
12320 workspace.active_pane().clone(),
12321 SplitDirection::Right,
12322 window,
12323 cx,
12324 )
12325 })
12326 }
12327
12328 #[gpui::test]
12329 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12330 init_test(cx);
12331 let fs = FakeFs::new(cx.executor());
12332 let project = Project::test(fs, None, cx).await;
12333 let (workspace, cx) =
12334 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12335
12336 add_an_item_to_active_pane(cx, &workspace, 1);
12337 split_pane(cx, &workspace);
12338 add_an_item_to_active_pane(cx, &workspace, 2);
12339 split_pane(cx, &workspace); // empty pane
12340 split_pane(cx, &workspace);
12341 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12342
12343 cx.executor().run_until_parked();
12344
12345 workspace.update(cx, |workspace, cx| {
12346 let num_panes = workspace.panes().len();
12347 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12348 let active_item = workspace
12349 .active_pane()
12350 .read(cx)
12351 .active_item()
12352 .expect("item is in focus");
12353
12354 assert_eq!(num_panes, 4);
12355 assert_eq!(num_items_in_current_pane, 1);
12356 assert_eq!(active_item.item_id(), last_item.item_id());
12357 });
12358
12359 workspace.update_in(cx, |workspace, window, cx| {
12360 workspace.join_all_panes(window, cx);
12361 });
12362
12363 workspace.update(cx, |workspace, cx| {
12364 let num_panes = workspace.panes().len();
12365 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12366 let active_item = workspace
12367 .active_pane()
12368 .read(cx)
12369 .active_item()
12370 .expect("item is in focus");
12371
12372 assert_eq!(num_panes, 1);
12373 assert_eq!(num_items_in_current_pane, 3);
12374 assert_eq!(active_item.item_id(), last_item.item_id());
12375 });
12376 }
12377
12378 #[gpui::test]
12379 async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12380 init_test(cx);
12381 let fs = FakeFs::new(cx.executor());
12382
12383 let project = Project::test(fs, [], cx).await;
12384 let (multi_workspace, cx) =
12385 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12386 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12387
12388 workspace.update(cx, |workspace, _cx| {
12389 workspace.bounds.size.width = px(800.);
12390 });
12391
12392 workspace.update_in(cx, |workspace, window, cx| {
12393 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12394 workspace.add_panel(panel, window, cx);
12395 workspace.toggle_dock(DockPosition::Right, window, cx);
12396 });
12397
12398 let (panel, resized_width, ratio_basis_width) =
12399 workspace.update_in(cx, |workspace, window, cx| {
12400 let item = cx.new(|cx| {
12401 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12402 });
12403 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12404
12405 let dock = workspace.right_dock().read(cx);
12406 let workspace_width = workspace.bounds.size.width;
12407 let initial_width = workspace
12408 .dock_size(&dock, window, cx)
12409 .expect("flexible dock should have an initial width");
12410
12411 assert_eq!(initial_width, workspace_width / 2.);
12412
12413 workspace.resize_right_dock(px(300.), window, cx);
12414
12415 let dock = workspace.right_dock().read(cx);
12416 let resized_width = workspace
12417 .dock_size(&dock, window, cx)
12418 .expect("flexible dock should keep its resized width");
12419
12420 assert_eq!(resized_width, px(300.));
12421
12422 let panel = workspace
12423 .right_dock()
12424 .read(cx)
12425 .visible_panel()
12426 .expect("flexible dock should have a visible panel")
12427 .panel_id();
12428
12429 (panel, resized_width, workspace_width)
12430 });
12431
12432 workspace.update_in(cx, |workspace, window, cx| {
12433 workspace.toggle_dock(DockPosition::Right, window, cx);
12434 workspace.toggle_dock(DockPosition::Right, window, cx);
12435
12436 let dock = workspace.right_dock().read(cx);
12437 let reopened_width = workspace
12438 .dock_size(&dock, window, cx)
12439 .expect("flexible dock should restore when reopened");
12440
12441 assert_eq!(reopened_width, resized_width);
12442
12443 let right_dock = workspace.right_dock().read(cx);
12444 let flexible_panel = right_dock
12445 .visible_panel()
12446 .expect("flexible dock should still have a visible panel");
12447 assert_eq!(flexible_panel.panel_id(), panel);
12448 assert_eq!(
12449 right_dock
12450 .stored_panel_size_state(flexible_panel.as_ref())
12451 .and_then(|size_state| size_state.flex),
12452 Some(
12453 resized_width.to_f64() as f32
12454 / (workspace.bounds.size.width - resized_width).to_f64() as f32
12455 )
12456 );
12457 });
12458
12459 workspace.update_in(cx, |workspace, window, cx| {
12460 workspace.split_pane(
12461 workspace.active_pane().clone(),
12462 SplitDirection::Right,
12463 window,
12464 cx,
12465 );
12466
12467 let dock = workspace.right_dock().read(cx);
12468 let split_width = workspace
12469 .dock_size(&dock, window, cx)
12470 .expect("flexible dock should keep its user-resized proportion");
12471
12472 assert_eq!(split_width, px(300.));
12473
12474 workspace.bounds.size.width = px(1600.);
12475
12476 let dock = workspace.right_dock().read(cx);
12477 let resized_window_width = workspace
12478 .dock_size(&dock, window, cx)
12479 .expect("flexible dock should preserve proportional size on window resize");
12480
12481 assert_eq!(
12482 resized_window_width,
12483 workspace.bounds.size.width
12484 * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12485 );
12486 });
12487 }
12488
12489 #[gpui::test]
12490 async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12491 init_test(cx);
12492 let fs = FakeFs::new(cx.executor());
12493
12494 // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12495 {
12496 let project = Project::test(fs.clone(), [], cx).await;
12497 let (multi_workspace, cx) =
12498 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12499 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12500
12501 workspace.update(cx, |workspace, _cx| {
12502 workspace.set_random_database_id();
12503 workspace.bounds.size.width = px(800.);
12504 });
12505
12506 let panel = workspace.update_in(cx, |workspace, window, cx| {
12507 let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12508 workspace.add_panel(panel.clone(), window, cx);
12509 workspace.toggle_dock(DockPosition::Left, window, cx);
12510 panel
12511 });
12512
12513 workspace.update_in(cx, |workspace, window, cx| {
12514 workspace.resize_left_dock(px(350.), window, cx);
12515 });
12516
12517 cx.run_until_parked();
12518
12519 let persisted = workspace.read_with(cx, |workspace, cx| {
12520 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12521 });
12522 assert_eq!(
12523 persisted.and_then(|s| s.size),
12524 Some(px(350.)),
12525 "fixed-width panel size should be persisted to KVP"
12526 );
12527
12528 // Remove the panel and re-add a fresh instance with the same key.
12529 // The new instance should have its size state restored from KVP.
12530 workspace.update_in(cx, |workspace, window, cx| {
12531 workspace.remove_panel(&panel, window, cx);
12532 });
12533
12534 workspace.update_in(cx, |workspace, window, cx| {
12535 let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12536 workspace.add_panel(new_panel, window, cx);
12537
12538 let left_dock = workspace.left_dock().read(cx);
12539 let size_state = left_dock
12540 .panel::<TestPanel>()
12541 .and_then(|p| left_dock.stored_panel_size_state(&p));
12542 assert_eq!(
12543 size_state.and_then(|s| s.size),
12544 Some(px(350.)),
12545 "re-added fixed-width panel should restore persisted size from KVP"
12546 );
12547 });
12548 }
12549
12550 // Flexible panel: both pixel size and ratio are persisted and restored.
12551 {
12552 let project = Project::test(fs.clone(), [], cx).await;
12553 let (multi_workspace, cx) =
12554 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12555 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12556
12557 workspace.update(cx, |workspace, _cx| {
12558 workspace.set_random_database_id();
12559 workspace.bounds.size.width = px(800.);
12560 });
12561
12562 let panel = workspace.update_in(cx, |workspace, window, cx| {
12563 let item = cx.new(|cx| {
12564 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12565 });
12566 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12567
12568 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12569 workspace.add_panel(panel.clone(), window, cx);
12570 workspace.toggle_dock(DockPosition::Right, window, cx);
12571 panel
12572 });
12573
12574 workspace.update_in(cx, |workspace, window, cx| {
12575 workspace.resize_right_dock(px(300.), window, cx);
12576 });
12577
12578 cx.run_until_parked();
12579
12580 let persisted = workspace
12581 .read_with(cx, |workspace, cx| {
12582 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12583 })
12584 .expect("flexible panel state should be persisted to KVP");
12585 assert_eq!(
12586 persisted.size, None,
12587 "flexible panel should not persist a redundant pixel size"
12588 );
12589 let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12590
12591 // Remove the panel and re-add: both size and ratio should be restored.
12592 workspace.update_in(cx, |workspace, window, cx| {
12593 workspace.remove_panel(&panel, window, cx);
12594 });
12595
12596 workspace.update_in(cx, |workspace, window, cx| {
12597 let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12598 workspace.add_panel(new_panel, window, cx);
12599
12600 let right_dock = workspace.right_dock().read(cx);
12601 let size_state = right_dock
12602 .panel::<TestPanel>()
12603 .and_then(|p| right_dock.stored_panel_size_state(&p))
12604 .expect("re-added flexible panel should have restored size state from KVP");
12605 assert_eq!(
12606 size_state.size, None,
12607 "re-added flexible panel should not have a persisted pixel size"
12608 );
12609 assert_eq!(
12610 size_state.flex,
12611 Some(original_ratio),
12612 "re-added flexible panel should restore persisted flex"
12613 );
12614 });
12615 }
12616 }
12617
12618 #[gpui::test]
12619 async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12620 init_test(cx);
12621 let fs = FakeFs::new(cx.executor());
12622
12623 let project = Project::test(fs, [], cx).await;
12624 let (multi_workspace, cx) =
12625 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12626 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12627
12628 workspace.update(cx, |workspace, _cx| {
12629 workspace.bounds.size.width = px(900.);
12630 });
12631
12632 // Step 1: Add a tab to the center pane then open a flexible panel in the left
12633 // dock. With one full-width center pane the default ratio is 0.5, so the panel
12634 // and the center pane each take half the workspace width.
12635 workspace.update_in(cx, |workspace, window, cx| {
12636 let item = cx.new(|cx| {
12637 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12638 });
12639 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12640
12641 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12642 workspace.add_panel(panel, window, cx);
12643 workspace.toggle_dock(DockPosition::Left, window, cx);
12644
12645 let left_dock = workspace.left_dock().read(cx);
12646 let left_width = workspace
12647 .dock_size(&left_dock, window, cx)
12648 .expect("left dock should have an active panel");
12649
12650 assert_eq!(
12651 left_width,
12652 workspace.bounds.size.width / 2.,
12653 "flexible left panel should split evenly with the center pane"
12654 );
12655 });
12656
12657 // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12658 // change horizontal width fractions, so the flexible panel stays at the same
12659 // width as each half of the split.
12660 workspace.update_in(cx, |workspace, window, cx| {
12661 workspace.split_pane(
12662 workspace.active_pane().clone(),
12663 SplitDirection::Down,
12664 window,
12665 cx,
12666 );
12667
12668 let left_dock = workspace.left_dock().read(cx);
12669 let left_width = workspace
12670 .dock_size(&left_dock, window, cx)
12671 .expect("left dock should still have an active panel after vertical split");
12672
12673 assert_eq!(
12674 left_width,
12675 workspace.bounds.size.width / 2.,
12676 "flexible left panel width should match each vertically-split pane"
12677 );
12678 });
12679
12680 // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12681 // size reduces the available width, so the flexible left panel and the center
12682 // panes all shrink proportionally to accommodate it.
12683 workspace.update_in(cx, |workspace, window, cx| {
12684 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12685 workspace.add_panel(panel, window, cx);
12686 workspace.toggle_dock(DockPosition::Right, window, cx);
12687
12688 let right_dock = workspace.right_dock().read(cx);
12689 let right_width = workspace
12690 .dock_size(&right_dock, window, cx)
12691 .expect("right dock should have an active panel");
12692
12693 let left_dock = workspace.left_dock().read(cx);
12694 let left_width = workspace
12695 .dock_size(&left_dock, window, cx)
12696 .expect("left dock should still have an active panel");
12697
12698 let available_width = workspace.bounds.size.width - right_width;
12699 assert_eq!(
12700 left_width,
12701 available_width / 2.,
12702 "flexible left panel should shrink proportionally as the right dock takes space"
12703 );
12704 });
12705
12706 // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12707 // flex sizing and the workspace width is divided among left-flex, center
12708 // (implicit flex 1.0), and right-flex.
12709 workspace.update_in(cx, |workspace, window, cx| {
12710 let right_dock = workspace.right_dock().clone();
12711 let right_panel = right_dock
12712 .read(cx)
12713 .visible_panel()
12714 .expect("right dock should have a visible panel")
12715 .clone();
12716 workspace.toggle_dock_panel_flexible_size(
12717 &right_dock,
12718 right_panel.as_ref(),
12719 window,
12720 cx,
12721 );
12722
12723 let right_dock = right_dock.read(cx);
12724 let right_panel = right_dock
12725 .visible_panel()
12726 .expect("right dock should still have a visible panel");
12727 assert!(
12728 right_panel.has_flexible_size(window, cx),
12729 "right panel should now be flexible"
12730 );
12731
12732 let right_size_state = right_dock
12733 .stored_panel_size_state(right_panel.as_ref())
12734 .expect("right panel should have a stored size state after toggling");
12735 let right_flex = right_size_state
12736 .flex
12737 .expect("right panel should have a flex value after toggling");
12738
12739 let left_dock = workspace.left_dock().read(cx);
12740 let left_width = workspace
12741 .dock_size(&left_dock, window, cx)
12742 .expect("left dock should still have an active panel");
12743 let right_width = workspace
12744 .dock_size(&right_dock, window, cx)
12745 .expect("right dock should still have an active panel");
12746
12747 let left_flex = workspace
12748 .default_dock_flex(DockPosition::Left)
12749 .expect("left dock should have a default flex");
12750
12751 let total_flex = left_flex + 1.0 + right_flex;
12752 let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12753 let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12754 assert_eq!(
12755 left_width, expected_left,
12756 "flexible left panel should share workspace width via flex ratios"
12757 );
12758 assert_eq!(
12759 right_width, expected_right,
12760 "flexible right panel should share workspace width via flex ratios"
12761 );
12762 });
12763 }
12764
12765 struct TestModal(FocusHandle);
12766
12767 impl TestModal {
12768 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12769 Self(cx.focus_handle())
12770 }
12771 }
12772
12773 impl EventEmitter<DismissEvent> for TestModal {}
12774
12775 impl Focusable for TestModal {
12776 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12777 self.0.clone()
12778 }
12779 }
12780
12781 impl ModalView for TestModal {}
12782
12783 impl Render for TestModal {
12784 fn render(
12785 &mut self,
12786 _window: &mut Window,
12787 _cx: &mut Context<TestModal>,
12788 ) -> impl IntoElement {
12789 div().track_focus(&self.0)
12790 }
12791 }
12792
12793 #[gpui::test]
12794 async fn test_panels(cx: &mut gpui::TestAppContext) {
12795 init_test(cx);
12796 let fs = FakeFs::new(cx.executor());
12797
12798 let project = Project::test(fs, [], cx).await;
12799 let (multi_workspace, cx) =
12800 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12801 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12802
12803 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12804 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12805 workspace.add_panel(panel_1.clone(), window, cx);
12806 workspace.toggle_dock(DockPosition::Left, window, cx);
12807 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12808 workspace.add_panel(panel_2.clone(), window, cx);
12809 workspace.toggle_dock(DockPosition::Right, window, cx);
12810
12811 let left_dock = workspace.left_dock();
12812 assert_eq!(
12813 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12814 panel_1.panel_id()
12815 );
12816 assert_eq!(
12817 workspace.dock_size(&left_dock.read(cx), window, cx),
12818 Some(px(300.))
12819 );
12820
12821 workspace.resize_left_dock(px(1337.), window, cx);
12822 assert_eq!(
12823 workspace
12824 .right_dock()
12825 .read(cx)
12826 .visible_panel()
12827 .unwrap()
12828 .panel_id(),
12829 panel_2.panel_id(),
12830 );
12831
12832 (panel_1, panel_2)
12833 });
12834
12835 // Move panel_1 to the right
12836 panel_1.update_in(cx, |panel_1, window, cx| {
12837 panel_1.set_position(DockPosition::Right, window, cx)
12838 });
12839
12840 workspace.update_in(cx, |workspace, window, cx| {
12841 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12842 // Since it was the only panel on the left, the left dock should now be closed.
12843 assert!(!workspace.left_dock().read(cx).is_open());
12844 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12845 let right_dock = workspace.right_dock();
12846 assert_eq!(
12847 right_dock.read(cx).visible_panel().unwrap().panel_id(),
12848 panel_1.panel_id()
12849 );
12850 assert_eq!(
12851 right_dock
12852 .read(cx)
12853 .active_panel_size()
12854 .unwrap()
12855 .size
12856 .unwrap(),
12857 px(1337.)
12858 );
12859
12860 // Now we move panel_2 to the left
12861 panel_2.set_position(DockPosition::Left, window, cx);
12862 });
12863
12864 workspace.update(cx, |workspace, cx| {
12865 // Since panel_2 was not visible on the right, we don't open the left dock.
12866 assert!(!workspace.left_dock().read(cx).is_open());
12867 // And the right dock is unaffected in its displaying of panel_1
12868 assert!(workspace.right_dock().read(cx).is_open());
12869 assert_eq!(
12870 workspace
12871 .right_dock()
12872 .read(cx)
12873 .visible_panel()
12874 .unwrap()
12875 .panel_id(),
12876 panel_1.panel_id(),
12877 );
12878 });
12879
12880 // Move panel_1 back to the left
12881 panel_1.update_in(cx, |panel_1, window, cx| {
12882 panel_1.set_position(DockPosition::Left, window, cx)
12883 });
12884
12885 workspace.update_in(cx, |workspace, window, cx| {
12886 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12887 let left_dock = workspace.left_dock();
12888 assert!(left_dock.read(cx).is_open());
12889 assert_eq!(
12890 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12891 panel_1.panel_id()
12892 );
12893 assert_eq!(
12894 workspace.dock_size(&left_dock.read(cx), window, cx),
12895 Some(px(1337.))
12896 );
12897 // And the right dock should be closed as it no longer has any panels.
12898 assert!(!workspace.right_dock().read(cx).is_open());
12899
12900 // Now we move panel_1 to the bottom
12901 panel_1.set_position(DockPosition::Bottom, window, cx);
12902 });
12903
12904 workspace.update_in(cx, |workspace, window, cx| {
12905 // Since panel_1 was visible on the left, we close the left dock.
12906 assert!(!workspace.left_dock().read(cx).is_open());
12907 // The bottom dock is sized based on the panel's default size,
12908 // since the panel orientation changed from vertical to horizontal.
12909 let bottom_dock = workspace.bottom_dock();
12910 assert_eq!(
12911 workspace.dock_size(&bottom_dock.read(cx), window, cx),
12912 Some(px(300.))
12913 );
12914 // Close bottom dock and move panel_1 back to the left.
12915 bottom_dock.update(cx, |bottom_dock, cx| {
12916 bottom_dock.set_open(false, window, cx)
12917 });
12918 panel_1.set_position(DockPosition::Left, window, cx);
12919 });
12920
12921 // Emit activated event on panel 1
12922 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12923
12924 // Now the left dock is open and panel_1 is active and focused.
12925 workspace.update_in(cx, |workspace, window, cx| {
12926 let left_dock = workspace.left_dock();
12927 assert!(left_dock.read(cx).is_open());
12928 assert_eq!(
12929 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12930 panel_1.panel_id(),
12931 );
12932 assert!(panel_1.focus_handle(cx).is_focused(window));
12933 });
12934
12935 // Emit closed event on panel 2, which is not active
12936 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12937
12938 // Wo don't close the left dock, because panel_2 wasn't the active panel
12939 workspace.update(cx, |workspace, cx| {
12940 let left_dock = workspace.left_dock();
12941 assert!(left_dock.read(cx).is_open());
12942 assert_eq!(
12943 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12944 panel_1.panel_id(),
12945 );
12946 });
12947
12948 // Emitting a ZoomIn event shows the panel as zoomed.
12949 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12950 workspace.read_with(cx, |workspace, _| {
12951 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12952 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12953 });
12954
12955 // Move panel to another dock while it is zoomed
12956 panel_1.update_in(cx, |panel, window, cx| {
12957 panel.set_position(DockPosition::Right, window, cx)
12958 });
12959 workspace.read_with(cx, |workspace, _| {
12960 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12961
12962 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12963 });
12964
12965 // This is a helper for getting a:
12966 // - valid focus on an element,
12967 // - that isn't a part of the panes and panels system of the Workspace,
12968 // - and doesn't trigger the 'on_focus_lost' API.
12969 let focus_other_view = {
12970 let workspace = workspace.clone();
12971 move |cx: &mut VisualTestContext| {
12972 workspace.update_in(cx, |workspace, window, cx| {
12973 if workspace.active_modal::<TestModal>(cx).is_some() {
12974 workspace.toggle_modal(window, cx, TestModal::new);
12975 workspace.toggle_modal(window, cx, TestModal::new);
12976 } else {
12977 workspace.toggle_modal(window, cx, TestModal::new);
12978 }
12979 })
12980 }
12981 };
12982
12983 // If focus is transferred to another view that's not a panel or another pane, we still show
12984 // the panel as zoomed.
12985 focus_other_view(cx);
12986 workspace.read_with(cx, |workspace, _| {
12987 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12988 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12989 });
12990
12991 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12992 workspace.update_in(cx, |_workspace, window, cx| {
12993 cx.focus_self(window);
12994 });
12995 workspace.read_with(cx, |workspace, _| {
12996 assert_eq!(workspace.zoomed, None);
12997 assert_eq!(workspace.zoomed_position, None);
12998 });
12999
13000 // If focus is transferred again to another view that's not a panel or a pane, we won't
13001 // show the panel as zoomed because it wasn't zoomed before.
13002 focus_other_view(cx);
13003 workspace.read_with(cx, |workspace, _| {
13004 assert_eq!(workspace.zoomed, None);
13005 assert_eq!(workspace.zoomed_position, None);
13006 });
13007
13008 // When the panel is activated, it is zoomed again.
13009 cx.dispatch_action(ToggleRightDock);
13010 workspace.read_with(cx, |workspace, _| {
13011 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13012 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13013 });
13014
13015 // Emitting a ZoomOut event unzooms the panel.
13016 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13017 workspace.read_with(cx, |workspace, _| {
13018 assert_eq!(workspace.zoomed, None);
13019 assert_eq!(workspace.zoomed_position, None);
13020 });
13021
13022 // Emit closed event on panel 1, which is active
13023 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13024
13025 // Now the left dock is closed, because panel_1 was the active panel
13026 workspace.update(cx, |workspace, cx| {
13027 let right_dock = workspace.right_dock();
13028 assert!(!right_dock.read(cx).is_open());
13029 });
13030 }
13031
13032 #[gpui::test]
13033 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13034 init_test(cx);
13035
13036 let fs = FakeFs::new(cx.background_executor.clone());
13037 let project = Project::test(fs, [], cx).await;
13038 let (workspace, cx) =
13039 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13040 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13041
13042 let dirty_regular_buffer = cx.new(|cx| {
13043 TestItem::new(cx)
13044 .with_dirty(true)
13045 .with_label("1.txt")
13046 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13047 });
13048 let dirty_regular_buffer_2 = cx.new(|cx| {
13049 TestItem::new(cx)
13050 .with_dirty(true)
13051 .with_label("2.txt")
13052 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13053 });
13054 let dirty_multi_buffer_with_both = cx.new(|cx| {
13055 TestItem::new(cx)
13056 .with_dirty(true)
13057 .with_buffer_kind(ItemBufferKind::Multibuffer)
13058 .with_label("Fake Project Search")
13059 .with_project_items(&[
13060 dirty_regular_buffer.read(cx).project_items[0].clone(),
13061 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13062 ])
13063 });
13064 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13065 workspace.update_in(cx, |workspace, window, cx| {
13066 workspace.add_item(
13067 pane.clone(),
13068 Box::new(dirty_regular_buffer.clone()),
13069 None,
13070 false,
13071 false,
13072 window,
13073 cx,
13074 );
13075 workspace.add_item(
13076 pane.clone(),
13077 Box::new(dirty_regular_buffer_2.clone()),
13078 None,
13079 false,
13080 false,
13081 window,
13082 cx,
13083 );
13084 workspace.add_item(
13085 pane.clone(),
13086 Box::new(dirty_multi_buffer_with_both.clone()),
13087 None,
13088 false,
13089 false,
13090 window,
13091 cx,
13092 );
13093 });
13094
13095 pane.update_in(cx, |pane, window, cx| {
13096 pane.activate_item(2, true, true, window, cx);
13097 assert_eq!(
13098 pane.active_item().unwrap().item_id(),
13099 multi_buffer_with_both_files_id,
13100 "Should select the multi buffer in the pane"
13101 );
13102 });
13103 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13104 pane.close_other_items(
13105 &CloseOtherItems {
13106 save_intent: Some(SaveIntent::Save),
13107 close_pinned: true,
13108 },
13109 None,
13110 window,
13111 cx,
13112 )
13113 });
13114 cx.background_executor.run_until_parked();
13115 assert!(!cx.has_pending_prompt());
13116 close_all_but_multi_buffer_task
13117 .await
13118 .expect("Closing all buffers but the multi buffer failed");
13119 pane.update(cx, |pane, cx| {
13120 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13121 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13122 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13123 assert_eq!(pane.items_len(), 1);
13124 assert_eq!(
13125 pane.active_item().unwrap().item_id(),
13126 multi_buffer_with_both_files_id,
13127 "Should have only the multi buffer left in the pane"
13128 );
13129 assert!(
13130 dirty_multi_buffer_with_both.read(cx).is_dirty,
13131 "The multi buffer containing the unsaved buffer should still be dirty"
13132 );
13133 });
13134
13135 dirty_regular_buffer.update(cx, |buffer, cx| {
13136 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13137 });
13138
13139 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13140 pane.close_active_item(
13141 &CloseActiveItem {
13142 save_intent: Some(SaveIntent::Close),
13143 close_pinned: false,
13144 },
13145 window,
13146 cx,
13147 )
13148 });
13149 cx.background_executor.run_until_parked();
13150 assert!(
13151 cx.has_pending_prompt(),
13152 "Dirty multi buffer should prompt a save dialog"
13153 );
13154 cx.simulate_prompt_answer("Save");
13155 cx.background_executor.run_until_parked();
13156 close_multi_buffer_task
13157 .await
13158 .expect("Closing the multi buffer failed");
13159 pane.update(cx, |pane, cx| {
13160 assert_eq!(
13161 dirty_multi_buffer_with_both.read(cx).save_count,
13162 1,
13163 "Multi buffer item should get be saved"
13164 );
13165 // Test impl does not save inner items, so we do not assert them
13166 assert_eq!(
13167 pane.items_len(),
13168 0,
13169 "No more items should be left in the pane"
13170 );
13171 assert!(pane.active_item().is_none());
13172 });
13173 }
13174
13175 #[gpui::test]
13176 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13177 cx: &mut TestAppContext,
13178 ) {
13179 init_test(cx);
13180
13181 let fs = FakeFs::new(cx.background_executor.clone());
13182 let project = Project::test(fs, [], cx).await;
13183 let (workspace, cx) =
13184 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13185 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13186
13187 let dirty_regular_buffer = cx.new(|cx| {
13188 TestItem::new(cx)
13189 .with_dirty(true)
13190 .with_label("1.txt")
13191 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13192 });
13193 let dirty_regular_buffer_2 = cx.new(|cx| {
13194 TestItem::new(cx)
13195 .with_dirty(true)
13196 .with_label("2.txt")
13197 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13198 });
13199 let clear_regular_buffer = cx.new(|cx| {
13200 TestItem::new(cx)
13201 .with_label("3.txt")
13202 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13203 });
13204
13205 let dirty_multi_buffer_with_both = cx.new(|cx| {
13206 TestItem::new(cx)
13207 .with_dirty(true)
13208 .with_buffer_kind(ItemBufferKind::Multibuffer)
13209 .with_label("Fake Project Search")
13210 .with_project_items(&[
13211 dirty_regular_buffer.read(cx).project_items[0].clone(),
13212 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13213 clear_regular_buffer.read(cx).project_items[0].clone(),
13214 ])
13215 });
13216 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13217 workspace.update_in(cx, |workspace, window, cx| {
13218 workspace.add_item(
13219 pane.clone(),
13220 Box::new(dirty_regular_buffer.clone()),
13221 None,
13222 false,
13223 false,
13224 window,
13225 cx,
13226 );
13227 workspace.add_item(
13228 pane.clone(),
13229 Box::new(dirty_multi_buffer_with_both.clone()),
13230 None,
13231 false,
13232 false,
13233 window,
13234 cx,
13235 );
13236 });
13237
13238 pane.update_in(cx, |pane, window, cx| {
13239 pane.activate_item(1, true, true, window, cx);
13240 assert_eq!(
13241 pane.active_item().unwrap().item_id(),
13242 multi_buffer_with_both_files_id,
13243 "Should select the multi buffer in the pane"
13244 );
13245 });
13246 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13247 pane.close_active_item(
13248 &CloseActiveItem {
13249 save_intent: None,
13250 close_pinned: false,
13251 },
13252 window,
13253 cx,
13254 )
13255 });
13256 cx.background_executor.run_until_parked();
13257 assert!(
13258 cx.has_pending_prompt(),
13259 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13260 );
13261 }
13262
13263 /// Tests that when `close_on_file_delete` is enabled, files are automatically
13264 /// closed when they are deleted from disk.
13265 #[gpui::test]
13266 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13267 init_test(cx);
13268
13269 // Enable the close_on_disk_deletion setting
13270 cx.update_global(|store: &mut SettingsStore, cx| {
13271 store.update_user_settings(cx, |settings| {
13272 settings.workspace.close_on_file_delete = Some(true);
13273 });
13274 });
13275
13276 let fs = FakeFs::new(cx.background_executor.clone());
13277 let project = Project::test(fs, [], cx).await;
13278 let (workspace, cx) =
13279 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13280 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13281
13282 // Create a test item that simulates a file
13283 let item = cx.new(|cx| {
13284 TestItem::new(cx)
13285 .with_label("test.txt")
13286 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13287 });
13288
13289 // Add item to workspace
13290 workspace.update_in(cx, |workspace, window, cx| {
13291 workspace.add_item(
13292 pane.clone(),
13293 Box::new(item.clone()),
13294 None,
13295 false,
13296 false,
13297 window,
13298 cx,
13299 );
13300 });
13301
13302 // Verify the item is in the pane
13303 pane.read_with(cx, |pane, _| {
13304 assert_eq!(pane.items().count(), 1);
13305 });
13306
13307 // Simulate file deletion by setting the item's deleted state
13308 item.update(cx, |item, _| {
13309 item.set_has_deleted_file(true);
13310 });
13311
13312 // Emit UpdateTab event to trigger the close behavior
13313 cx.run_until_parked();
13314 item.update(cx, |_, cx| {
13315 cx.emit(ItemEvent::UpdateTab);
13316 });
13317
13318 // Allow the close operation to complete
13319 cx.run_until_parked();
13320
13321 // Verify the item was automatically closed
13322 pane.read_with(cx, |pane, _| {
13323 assert_eq!(
13324 pane.items().count(),
13325 0,
13326 "Item should be automatically closed when file is deleted"
13327 );
13328 });
13329 }
13330
13331 /// Tests that when `close_on_file_delete` is disabled (default), files remain
13332 /// open with a strikethrough when they are deleted from disk.
13333 #[gpui::test]
13334 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13335 init_test(cx);
13336
13337 // Ensure close_on_disk_deletion is disabled (default)
13338 cx.update_global(|store: &mut SettingsStore, cx| {
13339 store.update_user_settings(cx, |settings| {
13340 settings.workspace.close_on_file_delete = Some(false);
13341 });
13342 });
13343
13344 let fs = FakeFs::new(cx.background_executor.clone());
13345 let project = Project::test(fs, [], cx).await;
13346 let (workspace, cx) =
13347 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13348 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13349
13350 // Create a test item that simulates a file
13351 let item = cx.new(|cx| {
13352 TestItem::new(cx)
13353 .with_label("test.txt")
13354 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13355 });
13356
13357 // Add item to workspace
13358 workspace.update_in(cx, |workspace, window, cx| {
13359 workspace.add_item(
13360 pane.clone(),
13361 Box::new(item.clone()),
13362 None,
13363 false,
13364 false,
13365 window,
13366 cx,
13367 );
13368 });
13369
13370 // Verify the item is in the pane
13371 pane.read_with(cx, |pane, _| {
13372 assert_eq!(pane.items().count(), 1);
13373 });
13374
13375 // Simulate file deletion
13376 item.update(cx, |item, _| {
13377 item.set_has_deleted_file(true);
13378 });
13379
13380 // Emit UpdateTab event
13381 cx.run_until_parked();
13382 item.update(cx, |_, cx| {
13383 cx.emit(ItemEvent::UpdateTab);
13384 });
13385
13386 // Allow any potential close operation to complete
13387 cx.run_until_parked();
13388
13389 // Verify the item remains open (with strikethrough)
13390 pane.read_with(cx, |pane, _| {
13391 assert_eq!(
13392 pane.items().count(),
13393 1,
13394 "Item should remain open when close_on_disk_deletion is disabled"
13395 );
13396 });
13397
13398 // Verify the item shows as deleted
13399 item.read_with(cx, |item, _| {
13400 assert!(
13401 item.has_deleted_file,
13402 "Item should be marked as having deleted file"
13403 );
13404 });
13405 }
13406
13407 /// Tests that dirty files are not automatically closed when deleted from disk,
13408 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13409 /// unsaved changes without being prompted.
13410 #[gpui::test]
13411 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13412 init_test(cx);
13413
13414 // Enable the close_on_file_delete setting
13415 cx.update_global(|store: &mut SettingsStore, cx| {
13416 store.update_user_settings(cx, |settings| {
13417 settings.workspace.close_on_file_delete = Some(true);
13418 });
13419 });
13420
13421 let fs = FakeFs::new(cx.background_executor.clone());
13422 let project = Project::test(fs, [], cx).await;
13423 let (workspace, cx) =
13424 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13425 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13426
13427 // Create a dirty test item
13428 let item = cx.new(|cx| {
13429 TestItem::new(cx)
13430 .with_dirty(true)
13431 .with_label("test.txt")
13432 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13433 });
13434
13435 // Add item to workspace
13436 workspace.update_in(cx, |workspace, window, cx| {
13437 workspace.add_item(
13438 pane.clone(),
13439 Box::new(item.clone()),
13440 None,
13441 false,
13442 false,
13443 window,
13444 cx,
13445 );
13446 });
13447
13448 // Simulate file deletion
13449 item.update(cx, |item, _| {
13450 item.set_has_deleted_file(true);
13451 });
13452
13453 // Emit UpdateTab event to trigger the close behavior
13454 cx.run_until_parked();
13455 item.update(cx, |_, cx| {
13456 cx.emit(ItemEvent::UpdateTab);
13457 });
13458
13459 // Allow any potential close operation to complete
13460 cx.run_until_parked();
13461
13462 // Verify the item remains open (dirty files are not auto-closed)
13463 pane.read_with(cx, |pane, _| {
13464 assert_eq!(
13465 pane.items().count(),
13466 1,
13467 "Dirty items should not be automatically closed even when file is deleted"
13468 );
13469 });
13470
13471 // Verify the item is marked as deleted and still dirty
13472 item.read_with(cx, |item, _| {
13473 assert!(
13474 item.has_deleted_file,
13475 "Item should be marked as having deleted file"
13476 );
13477 assert!(item.is_dirty, "Item should still be dirty");
13478 });
13479 }
13480
13481 /// Tests that navigation history is cleaned up when files are auto-closed
13482 /// due to deletion from disk.
13483 #[gpui::test]
13484 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13485 init_test(cx);
13486
13487 // Enable the close_on_file_delete setting
13488 cx.update_global(|store: &mut SettingsStore, cx| {
13489 store.update_user_settings(cx, |settings| {
13490 settings.workspace.close_on_file_delete = Some(true);
13491 });
13492 });
13493
13494 let fs = FakeFs::new(cx.background_executor.clone());
13495 let project = Project::test(fs, [], cx).await;
13496 let (workspace, cx) =
13497 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13498 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13499
13500 // Create test items
13501 let item1 = cx.new(|cx| {
13502 TestItem::new(cx)
13503 .with_label("test1.txt")
13504 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13505 });
13506 let item1_id = item1.item_id();
13507
13508 let item2 = cx.new(|cx| {
13509 TestItem::new(cx)
13510 .with_label("test2.txt")
13511 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13512 });
13513
13514 // Add items to workspace
13515 workspace.update_in(cx, |workspace, window, cx| {
13516 workspace.add_item(
13517 pane.clone(),
13518 Box::new(item1.clone()),
13519 None,
13520 false,
13521 false,
13522 window,
13523 cx,
13524 );
13525 workspace.add_item(
13526 pane.clone(),
13527 Box::new(item2.clone()),
13528 None,
13529 false,
13530 false,
13531 window,
13532 cx,
13533 );
13534 });
13535
13536 // Activate item1 to ensure it gets navigation entries
13537 pane.update_in(cx, |pane, window, cx| {
13538 pane.activate_item(0, true, true, window, cx);
13539 });
13540
13541 // Switch to item2 and back to create navigation history
13542 pane.update_in(cx, |pane, window, cx| {
13543 pane.activate_item(1, true, true, window, cx);
13544 });
13545 cx.run_until_parked();
13546
13547 pane.update_in(cx, |pane, window, cx| {
13548 pane.activate_item(0, true, true, window, cx);
13549 });
13550 cx.run_until_parked();
13551
13552 // Simulate file deletion for item1
13553 item1.update(cx, |item, _| {
13554 item.set_has_deleted_file(true);
13555 });
13556
13557 // Emit UpdateTab event to trigger the close behavior
13558 item1.update(cx, |_, cx| {
13559 cx.emit(ItemEvent::UpdateTab);
13560 });
13561 cx.run_until_parked();
13562
13563 // Verify item1 was closed
13564 pane.read_with(cx, |pane, _| {
13565 assert_eq!(
13566 pane.items().count(),
13567 1,
13568 "Should have 1 item remaining after auto-close"
13569 );
13570 });
13571
13572 // Check navigation history after close
13573 let has_item = pane.read_with(cx, |pane, cx| {
13574 let mut has_item = false;
13575 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13576 if entry.item.id() == item1_id {
13577 has_item = true;
13578 }
13579 });
13580 has_item
13581 });
13582
13583 assert!(
13584 !has_item,
13585 "Navigation history should not contain closed item entries"
13586 );
13587 }
13588
13589 #[gpui::test]
13590 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13591 cx: &mut TestAppContext,
13592 ) {
13593 init_test(cx);
13594
13595 let fs = FakeFs::new(cx.background_executor.clone());
13596 let project = Project::test(fs, [], cx).await;
13597 let (workspace, cx) =
13598 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13599 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13600
13601 let dirty_regular_buffer = cx.new(|cx| {
13602 TestItem::new(cx)
13603 .with_dirty(true)
13604 .with_label("1.txt")
13605 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13606 });
13607 let dirty_regular_buffer_2 = cx.new(|cx| {
13608 TestItem::new(cx)
13609 .with_dirty(true)
13610 .with_label("2.txt")
13611 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13612 });
13613 let clear_regular_buffer = cx.new(|cx| {
13614 TestItem::new(cx)
13615 .with_label("3.txt")
13616 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13617 });
13618
13619 let dirty_multi_buffer = cx.new(|cx| {
13620 TestItem::new(cx)
13621 .with_dirty(true)
13622 .with_buffer_kind(ItemBufferKind::Multibuffer)
13623 .with_label("Fake Project Search")
13624 .with_project_items(&[
13625 dirty_regular_buffer.read(cx).project_items[0].clone(),
13626 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13627 clear_regular_buffer.read(cx).project_items[0].clone(),
13628 ])
13629 });
13630 workspace.update_in(cx, |workspace, window, cx| {
13631 workspace.add_item(
13632 pane.clone(),
13633 Box::new(dirty_regular_buffer.clone()),
13634 None,
13635 false,
13636 false,
13637 window,
13638 cx,
13639 );
13640 workspace.add_item(
13641 pane.clone(),
13642 Box::new(dirty_regular_buffer_2.clone()),
13643 None,
13644 false,
13645 false,
13646 window,
13647 cx,
13648 );
13649 workspace.add_item(
13650 pane.clone(),
13651 Box::new(dirty_multi_buffer.clone()),
13652 None,
13653 false,
13654 false,
13655 window,
13656 cx,
13657 );
13658 });
13659
13660 pane.update_in(cx, |pane, window, cx| {
13661 pane.activate_item(2, true, true, window, cx);
13662 assert_eq!(
13663 pane.active_item().unwrap().item_id(),
13664 dirty_multi_buffer.item_id(),
13665 "Should select the multi buffer in the pane"
13666 );
13667 });
13668 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13669 pane.close_active_item(
13670 &CloseActiveItem {
13671 save_intent: None,
13672 close_pinned: false,
13673 },
13674 window,
13675 cx,
13676 )
13677 });
13678 cx.background_executor.run_until_parked();
13679 assert!(
13680 !cx.has_pending_prompt(),
13681 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13682 );
13683 close_multi_buffer_task
13684 .await
13685 .expect("Closing multi buffer failed");
13686 pane.update(cx, |pane, cx| {
13687 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13688 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13689 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13690 assert_eq!(
13691 pane.items()
13692 .map(|item| item.item_id())
13693 .sorted()
13694 .collect::<Vec<_>>(),
13695 vec![
13696 dirty_regular_buffer.item_id(),
13697 dirty_regular_buffer_2.item_id(),
13698 ],
13699 "Should have no multi buffer left in the pane"
13700 );
13701 assert!(dirty_regular_buffer.read(cx).is_dirty);
13702 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13703 });
13704 }
13705
13706 #[gpui::test]
13707 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13708 init_test(cx);
13709 let fs = FakeFs::new(cx.executor());
13710 let project = Project::test(fs, [], cx).await;
13711 let (multi_workspace, cx) =
13712 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13713 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13714
13715 // Add a new panel to the right dock, opening the dock and setting the
13716 // focus to the new panel.
13717 let panel = workspace.update_in(cx, |workspace, window, cx| {
13718 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13719 workspace.add_panel(panel.clone(), window, cx);
13720
13721 workspace
13722 .right_dock()
13723 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13724
13725 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13726
13727 panel
13728 });
13729
13730 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13731 // panel to the next valid position which, in this case, is the left
13732 // dock.
13733 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13734 workspace.update(cx, |workspace, cx| {
13735 assert!(workspace.left_dock().read(cx).is_open());
13736 assert_eq!(panel.read(cx).position, DockPosition::Left);
13737 });
13738
13739 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13740 // panel to the next valid position which, in this case, is the bottom
13741 // dock.
13742 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13743 workspace.update(cx, |workspace, cx| {
13744 assert!(workspace.bottom_dock().read(cx).is_open());
13745 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13746 });
13747
13748 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13749 // around moving the panel to its initial position, the right dock.
13750 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13751 workspace.update(cx, |workspace, cx| {
13752 assert!(workspace.right_dock().read(cx).is_open());
13753 assert_eq!(panel.read(cx).position, DockPosition::Right);
13754 });
13755
13756 // Remove focus from the panel, ensuring that, if the panel is not
13757 // focused, the `MoveFocusedPanelToNextPosition` action does not update
13758 // the panel's position, so the panel is still in the right dock.
13759 workspace.update_in(cx, |workspace, window, cx| {
13760 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13761 });
13762
13763 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13764 workspace.update(cx, |workspace, cx| {
13765 assert!(workspace.right_dock().read(cx).is_open());
13766 assert_eq!(panel.read(cx).position, DockPosition::Right);
13767 });
13768 }
13769
13770 #[gpui::test]
13771 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13772 init_test(cx);
13773
13774 let fs = FakeFs::new(cx.executor());
13775 let project = Project::test(fs, [], cx).await;
13776 let (workspace, cx) =
13777 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13778
13779 let item_1 = cx.new(|cx| {
13780 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13781 });
13782 workspace.update_in(cx, |workspace, window, cx| {
13783 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13784 workspace.move_item_to_pane_in_direction(
13785 &MoveItemToPaneInDirection {
13786 direction: SplitDirection::Right,
13787 focus: true,
13788 clone: false,
13789 },
13790 window,
13791 cx,
13792 );
13793 workspace.move_item_to_pane_at_index(
13794 &MoveItemToPane {
13795 destination: 3,
13796 focus: true,
13797 clone: false,
13798 },
13799 window,
13800 cx,
13801 );
13802
13803 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13804 assert_eq!(
13805 pane_items_paths(&workspace.active_pane, cx),
13806 vec!["first.txt".to_string()],
13807 "Single item was not moved anywhere"
13808 );
13809 });
13810
13811 let item_2 = cx.new(|cx| {
13812 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13813 });
13814 workspace.update_in(cx, |workspace, window, cx| {
13815 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13816 assert_eq!(
13817 pane_items_paths(&workspace.panes[0], cx),
13818 vec!["first.txt".to_string(), "second.txt".to_string()],
13819 );
13820 workspace.move_item_to_pane_in_direction(
13821 &MoveItemToPaneInDirection {
13822 direction: SplitDirection::Right,
13823 focus: true,
13824 clone: false,
13825 },
13826 window,
13827 cx,
13828 );
13829
13830 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13831 assert_eq!(
13832 pane_items_paths(&workspace.panes[0], cx),
13833 vec!["first.txt".to_string()],
13834 "After moving, one item should be left in the original pane"
13835 );
13836 assert_eq!(
13837 pane_items_paths(&workspace.panes[1], cx),
13838 vec!["second.txt".to_string()],
13839 "New item should have been moved to the new pane"
13840 );
13841 });
13842
13843 let item_3 = cx.new(|cx| {
13844 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13845 });
13846 workspace.update_in(cx, |workspace, window, cx| {
13847 let original_pane = workspace.panes[0].clone();
13848 workspace.set_active_pane(&original_pane, window, cx);
13849 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13850 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13851 assert_eq!(
13852 pane_items_paths(&workspace.active_pane, cx),
13853 vec!["first.txt".to_string(), "third.txt".to_string()],
13854 "New pane should be ready to move one item out"
13855 );
13856
13857 workspace.move_item_to_pane_at_index(
13858 &MoveItemToPane {
13859 destination: 3,
13860 focus: true,
13861 clone: false,
13862 },
13863 window,
13864 cx,
13865 );
13866 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13867 assert_eq!(
13868 pane_items_paths(&workspace.active_pane, cx),
13869 vec!["first.txt".to_string()],
13870 "After moving, one item should be left in the original pane"
13871 );
13872 assert_eq!(
13873 pane_items_paths(&workspace.panes[1], cx),
13874 vec!["second.txt".to_string()],
13875 "Previously created pane should be unchanged"
13876 );
13877 assert_eq!(
13878 pane_items_paths(&workspace.panes[2], cx),
13879 vec!["third.txt".to_string()],
13880 "New item should have been moved to the new pane"
13881 );
13882 });
13883 }
13884
13885 #[gpui::test]
13886 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13887 init_test(cx);
13888
13889 let fs = FakeFs::new(cx.executor());
13890 let project = Project::test(fs, [], cx).await;
13891 let (workspace, cx) =
13892 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13893
13894 let item_1 = cx.new(|cx| {
13895 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13896 });
13897 workspace.update_in(cx, |workspace, window, cx| {
13898 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13899 workspace.move_item_to_pane_in_direction(
13900 &MoveItemToPaneInDirection {
13901 direction: SplitDirection::Right,
13902 focus: true,
13903 clone: true,
13904 },
13905 window,
13906 cx,
13907 );
13908 });
13909 cx.run_until_parked();
13910 workspace.update_in(cx, |workspace, window, cx| {
13911 workspace.move_item_to_pane_at_index(
13912 &MoveItemToPane {
13913 destination: 3,
13914 focus: true,
13915 clone: true,
13916 },
13917 window,
13918 cx,
13919 );
13920 });
13921 cx.run_until_parked();
13922
13923 workspace.update(cx, |workspace, cx| {
13924 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13925 for pane in workspace.panes() {
13926 assert_eq!(
13927 pane_items_paths(pane, cx),
13928 vec!["first.txt".to_string()],
13929 "Single item exists in all panes"
13930 );
13931 }
13932 });
13933
13934 // verify that the active pane has been updated after waiting for the
13935 // pane focus event to fire and resolve
13936 workspace.read_with(cx, |workspace, _app| {
13937 assert_eq!(
13938 workspace.active_pane(),
13939 &workspace.panes[2],
13940 "The third pane should be the active one: {:?}",
13941 workspace.panes
13942 );
13943 })
13944 }
13945
13946 #[gpui::test]
13947 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13948 init_test(cx);
13949
13950 let fs = FakeFs::new(cx.executor());
13951 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13952
13953 let project = Project::test(fs, ["root".as_ref()], cx).await;
13954 let (workspace, cx) =
13955 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13956
13957 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13958 // Add item to pane A with project path
13959 let item_a = cx.new(|cx| {
13960 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13961 });
13962 workspace.update_in(cx, |workspace, window, cx| {
13963 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13964 });
13965
13966 // Split to create pane B
13967 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13968 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13969 });
13970
13971 // Add item with SAME project path to pane B, and pin it
13972 let item_b = cx.new(|cx| {
13973 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13974 });
13975 pane_b.update_in(cx, |pane, window, cx| {
13976 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13977 pane.set_pinned_count(1);
13978 });
13979
13980 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13981 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13982
13983 // close_pinned: false should only close the unpinned copy
13984 workspace.update_in(cx, |workspace, window, cx| {
13985 workspace.close_item_in_all_panes(
13986 &CloseItemInAllPanes {
13987 save_intent: Some(SaveIntent::Close),
13988 close_pinned: false,
13989 },
13990 window,
13991 cx,
13992 )
13993 });
13994 cx.executor().run_until_parked();
13995
13996 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13997 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13998 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13999 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14000
14001 // Split again, seeing as closing the previous item also closed its
14002 // pane, so only pane remains, which does not allow us to properly test
14003 // that both items close when `close_pinned: true`.
14004 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14005 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14006 });
14007
14008 // Add an item with the same project path to pane C so that
14009 // close_item_in_all_panes can determine what to close across all panes
14010 // (it reads the active item from the active pane, and split_pane
14011 // creates an empty pane).
14012 let item_c = cx.new(|cx| {
14013 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14014 });
14015 pane_c.update_in(cx, |pane, window, cx| {
14016 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14017 });
14018
14019 // close_pinned: true should close the pinned copy too
14020 workspace.update_in(cx, |workspace, window, cx| {
14021 let panes_count = workspace.panes().len();
14022 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14023
14024 workspace.close_item_in_all_panes(
14025 &CloseItemInAllPanes {
14026 save_intent: Some(SaveIntent::Close),
14027 close_pinned: true,
14028 },
14029 window,
14030 cx,
14031 )
14032 });
14033 cx.executor().run_until_parked();
14034
14035 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14036 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14037 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14038 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14039 }
14040
14041 mod register_project_item_tests {
14042
14043 use super::*;
14044
14045 // View
14046 struct TestPngItemView {
14047 focus_handle: FocusHandle,
14048 }
14049 // Model
14050 struct TestPngItem {}
14051
14052 impl project::ProjectItem for TestPngItem {
14053 fn try_open(
14054 _project: &Entity<Project>,
14055 path: &ProjectPath,
14056 cx: &mut App,
14057 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14058 if path.path.extension().unwrap() == "png" {
14059 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14060 } else {
14061 None
14062 }
14063 }
14064
14065 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14066 None
14067 }
14068
14069 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14070 None
14071 }
14072
14073 fn is_dirty(&self) -> bool {
14074 false
14075 }
14076 }
14077
14078 impl Item for TestPngItemView {
14079 type Event = ();
14080 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14081 "".into()
14082 }
14083 }
14084 impl EventEmitter<()> for TestPngItemView {}
14085 impl Focusable for TestPngItemView {
14086 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14087 self.focus_handle.clone()
14088 }
14089 }
14090
14091 impl Render for TestPngItemView {
14092 fn render(
14093 &mut self,
14094 _window: &mut Window,
14095 _cx: &mut Context<Self>,
14096 ) -> impl IntoElement {
14097 Empty
14098 }
14099 }
14100
14101 impl ProjectItem for TestPngItemView {
14102 type Item = TestPngItem;
14103
14104 fn for_project_item(
14105 _project: Entity<Project>,
14106 _pane: Option<&Pane>,
14107 _item: Entity<Self::Item>,
14108 _: &mut Window,
14109 cx: &mut Context<Self>,
14110 ) -> Self
14111 where
14112 Self: Sized,
14113 {
14114 Self {
14115 focus_handle: cx.focus_handle(),
14116 }
14117 }
14118 }
14119
14120 // View
14121 struct TestIpynbItemView {
14122 focus_handle: FocusHandle,
14123 }
14124 // Model
14125 struct TestIpynbItem {}
14126
14127 impl project::ProjectItem for TestIpynbItem {
14128 fn try_open(
14129 _project: &Entity<Project>,
14130 path: &ProjectPath,
14131 cx: &mut App,
14132 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14133 if path.path.extension().unwrap() == "ipynb" {
14134 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14135 } else {
14136 None
14137 }
14138 }
14139
14140 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14141 None
14142 }
14143
14144 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14145 None
14146 }
14147
14148 fn is_dirty(&self) -> bool {
14149 false
14150 }
14151 }
14152
14153 impl Item for TestIpynbItemView {
14154 type Event = ();
14155 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14156 "".into()
14157 }
14158 }
14159 impl EventEmitter<()> for TestIpynbItemView {}
14160 impl Focusable for TestIpynbItemView {
14161 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14162 self.focus_handle.clone()
14163 }
14164 }
14165
14166 impl Render for TestIpynbItemView {
14167 fn render(
14168 &mut self,
14169 _window: &mut Window,
14170 _cx: &mut Context<Self>,
14171 ) -> impl IntoElement {
14172 Empty
14173 }
14174 }
14175
14176 impl ProjectItem for TestIpynbItemView {
14177 type Item = TestIpynbItem;
14178
14179 fn for_project_item(
14180 _project: Entity<Project>,
14181 _pane: Option<&Pane>,
14182 _item: Entity<Self::Item>,
14183 _: &mut Window,
14184 cx: &mut Context<Self>,
14185 ) -> Self
14186 where
14187 Self: Sized,
14188 {
14189 Self {
14190 focus_handle: cx.focus_handle(),
14191 }
14192 }
14193 }
14194
14195 struct TestAlternatePngItemView {
14196 focus_handle: FocusHandle,
14197 }
14198
14199 impl Item for TestAlternatePngItemView {
14200 type Event = ();
14201 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14202 "".into()
14203 }
14204 }
14205
14206 impl EventEmitter<()> for TestAlternatePngItemView {}
14207 impl Focusable for TestAlternatePngItemView {
14208 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14209 self.focus_handle.clone()
14210 }
14211 }
14212
14213 impl Render for TestAlternatePngItemView {
14214 fn render(
14215 &mut self,
14216 _window: &mut Window,
14217 _cx: &mut Context<Self>,
14218 ) -> impl IntoElement {
14219 Empty
14220 }
14221 }
14222
14223 impl ProjectItem for TestAlternatePngItemView {
14224 type Item = TestPngItem;
14225
14226 fn for_project_item(
14227 _project: Entity<Project>,
14228 _pane: Option<&Pane>,
14229 _item: Entity<Self::Item>,
14230 _: &mut Window,
14231 cx: &mut Context<Self>,
14232 ) -> Self
14233 where
14234 Self: Sized,
14235 {
14236 Self {
14237 focus_handle: cx.focus_handle(),
14238 }
14239 }
14240 }
14241
14242 #[gpui::test]
14243 async fn test_register_project_item(cx: &mut TestAppContext) {
14244 init_test(cx);
14245
14246 cx.update(|cx| {
14247 register_project_item::<TestPngItemView>(cx);
14248 register_project_item::<TestIpynbItemView>(cx);
14249 });
14250
14251 let fs = FakeFs::new(cx.executor());
14252 fs.insert_tree(
14253 "/root1",
14254 json!({
14255 "one.png": "BINARYDATAHERE",
14256 "two.ipynb": "{ totally a notebook }",
14257 "three.txt": "editing text, sure why not?"
14258 }),
14259 )
14260 .await;
14261
14262 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14263 let (workspace, cx) =
14264 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14265
14266 let worktree_id = project.update(cx, |project, cx| {
14267 project.worktrees(cx).next().unwrap().read(cx).id()
14268 });
14269
14270 let handle = workspace
14271 .update_in(cx, |workspace, window, cx| {
14272 let project_path = (worktree_id, rel_path("one.png"));
14273 workspace.open_path(project_path, None, true, window, cx)
14274 })
14275 .await
14276 .unwrap();
14277
14278 // Now we can check if the handle we got back errored or not
14279 assert_eq!(
14280 handle.to_any_view().entity_type(),
14281 TypeId::of::<TestPngItemView>()
14282 );
14283
14284 let handle = workspace
14285 .update_in(cx, |workspace, window, cx| {
14286 let project_path = (worktree_id, rel_path("two.ipynb"));
14287 workspace.open_path(project_path, None, true, window, cx)
14288 })
14289 .await
14290 .unwrap();
14291
14292 assert_eq!(
14293 handle.to_any_view().entity_type(),
14294 TypeId::of::<TestIpynbItemView>()
14295 );
14296
14297 let handle = workspace
14298 .update_in(cx, |workspace, window, cx| {
14299 let project_path = (worktree_id, rel_path("three.txt"));
14300 workspace.open_path(project_path, None, true, window, cx)
14301 })
14302 .await;
14303 assert!(handle.is_err());
14304 }
14305
14306 #[gpui::test]
14307 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14308 init_test(cx);
14309
14310 cx.update(|cx| {
14311 register_project_item::<TestPngItemView>(cx);
14312 register_project_item::<TestAlternatePngItemView>(cx);
14313 });
14314
14315 let fs = FakeFs::new(cx.executor());
14316 fs.insert_tree(
14317 "/root1",
14318 json!({
14319 "one.png": "BINARYDATAHERE",
14320 "two.ipynb": "{ totally a notebook }",
14321 "three.txt": "editing text, sure why not?"
14322 }),
14323 )
14324 .await;
14325 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14326 let (workspace, cx) =
14327 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14328 let worktree_id = project.update(cx, |project, cx| {
14329 project.worktrees(cx).next().unwrap().read(cx).id()
14330 });
14331
14332 let handle = workspace
14333 .update_in(cx, |workspace, window, cx| {
14334 let project_path = (worktree_id, rel_path("one.png"));
14335 workspace.open_path(project_path, None, true, window, cx)
14336 })
14337 .await
14338 .unwrap();
14339
14340 // This _must_ be the second item registered
14341 assert_eq!(
14342 handle.to_any_view().entity_type(),
14343 TypeId::of::<TestAlternatePngItemView>()
14344 );
14345
14346 let handle = workspace
14347 .update_in(cx, |workspace, window, cx| {
14348 let project_path = (worktree_id, rel_path("three.txt"));
14349 workspace.open_path(project_path, None, true, window, cx)
14350 })
14351 .await;
14352 assert!(handle.is_err());
14353 }
14354 }
14355
14356 #[gpui::test]
14357 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14358 init_test(cx);
14359
14360 let fs = FakeFs::new(cx.executor());
14361 let project = Project::test(fs, [], cx).await;
14362 let (workspace, _cx) =
14363 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14364
14365 // Test with status bar shown (default)
14366 workspace.read_with(cx, |workspace, cx| {
14367 let visible = workspace.status_bar_visible(cx);
14368 assert!(visible, "Status bar should be visible by default");
14369 });
14370
14371 // Test with status bar hidden
14372 cx.update_global(|store: &mut SettingsStore, cx| {
14373 store.update_user_settings(cx, |settings| {
14374 settings.status_bar.get_or_insert_default().show = Some(false);
14375 });
14376 });
14377
14378 workspace.read_with(cx, |workspace, cx| {
14379 let visible = workspace.status_bar_visible(cx);
14380 assert!(!visible, "Status bar should be hidden when show is false");
14381 });
14382
14383 // Test with status bar shown explicitly
14384 cx.update_global(|store: &mut SettingsStore, cx| {
14385 store.update_user_settings(cx, |settings| {
14386 settings.status_bar.get_or_insert_default().show = Some(true);
14387 });
14388 });
14389
14390 workspace.read_with(cx, |workspace, cx| {
14391 let visible = workspace.status_bar_visible(cx);
14392 assert!(visible, "Status bar should be visible when show is true");
14393 });
14394 }
14395
14396 #[gpui::test]
14397 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14398 init_test(cx);
14399
14400 let fs = FakeFs::new(cx.executor());
14401 let project = Project::test(fs, [], cx).await;
14402 let (multi_workspace, cx) =
14403 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14404 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14405 let panel = workspace.update_in(cx, |workspace, window, cx| {
14406 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14407 workspace.add_panel(panel.clone(), window, cx);
14408
14409 workspace
14410 .right_dock()
14411 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14412
14413 panel
14414 });
14415
14416 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14417 let item_a = cx.new(TestItem::new);
14418 let item_b = cx.new(TestItem::new);
14419 let item_a_id = item_a.entity_id();
14420 let item_b_id = item_b.entity_id();
14421
14422 pane.update_in(cx, |pane, window, cx| {
14423 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14424 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14425 });
14426
14427 pane.read_with(cx, |pane, _| {
14428 assert_eq!(pane.items_len(), 2);
14429 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14430 });
14431
14432 workspace.update_in(cx, |workspace, window, cx| {
14433 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14434 });
14435
14436 workspace.update_in(cx, |_, window, cx| {
14437 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14438 });
14439
14440 // Assert that the `pane::CloseActiveItem` action is handled at the
14441 // workspace level when one of the dock panels is focused and, in that
14442 // case, the center pane's active item is closed but the focus is not
14443 // moved.
14444 cx.dispatch_action(pane::CloseActiveItem::default());
14445 cx.run_until_parked();
14446
14447 pane.read_with(cx, |pane, _| {
14448 assert_eq!(pane.items_len(), 1);
14449 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14450 });
14451
14452 workspace.update_in(cx, |workspace, window, cx| {
14453 assert!(workspace.right_dock().read(cx).is_open());
14454 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14455 });
14456 }
14457
14458 #[gpui::test]
14459 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14460 init_test(cx);
14461 let fs = FakeFs::new(cx.executor());
14462
14463 let project_a = Project::test(fs.clone(), [], cx).await;
14464 let project_b = Project::test(fs, [], cx).await;
14465
14466 let multi_workspace_handle =
14467 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14468 cx.run_until_parked();
14469
14470 let workspace_a = multi_workspace_handle
14471 .read_with(cx, |mw, _| mw.workspace().clone())
14472 .unwrap();
14473
14474 let _workspace_b = multi_workspace_handle
14475 .update(cx, |mw, window, cx| {
14476 mw.test_add_workspace(project_b, window, cx)
14477 })
14478 .unwrap();
14479
14480 // Switch to workspace A
14481 multi_workspace_handle
14482 .update(cx, |mw, window, cx| {
14483 let workspace = mw.workspaces()[0].clone();
14484 mw.activate(workspace, window, cx);
14485 })
14486 .unwrap();
14487
14488 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14489
14490 // Add a panel to workspace A's right dock and open the dock
14491 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14492 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14493 workspace.add_panel(panel.clone(), window, cx);
14494 workspace
14495 .right_dock()
14496 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14497 panel
14498 });
14499
14500 // Focus the panel through the workspace (matching existing test pattern)
14501 workspace_a.update_in(cx, |workspace, window, cx| {
14502 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14503 });
14504
14505 // Zoom the panel
14506 panel.update_in(cx, |panel, window, cx| {
14507 panel.set_zoomed(true, window, cx);
14508 });
14509
14510 // Verify the panel is zoomed and the dock is open
14511 workspace_a.update_in(cx, |workspace, window, cx| {
14512 assert!(
14513 workspace.right_dock().read(cx).is_open(),
14514 "dock should be open before switch"
14515 );
14516 assert!(
14517 panel.is_zoomed(window, cx),
14518 "panel should be zoomed before switch"
14519 );
14520 assert!(
14521 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14522 "panel should be focused before switch"
14523 );
14524 });
14525
14526 // Switch to workspace B
14527 multi_workspace_handle
14528 .update(cx, |mw, window, cx| {
14529 let workspace = mw.workspaces()[1].clone();
14530 mw.activate(workspace, window, cx);
14531 })
14532 .unwrap();
14533 cx.run_until_parked();
14534
14535 // Switch back to workspace A
14536 multi_workspace_handle
14537 .update(cx, |mw, window, cx| {
14538 let workspace = mw.workspaces()[0].clone();
14539 mw.activate(workspace, window, cx);
14540 })
14541 .unwrap();
14542 cx.run_until_parked();
14543
14544 // Verify the panel is still zoomed and the dock is still open
14545 workspace_a.update_in(cx, |workspace, window, cx| {
14546 assert!(
14547 workspace.right_dock().read(cx).is_open(),
14548 "dock should still be open after switching back"
14549 );
14550 assert!(
14551 panel.is_zoomed(window, cx),
14552 "panel should still be zoomed after switching back"
14553 );
14554 });
14555 }
14556
14557 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14558 pane.read(cx)
14559 .items()
14560 .flat_map(|item| {
14561 item.project_paths(cx)
14562 .into_iter()
14563 .map(|path| path.path.display(PathStyle::local()).into_owned())
14564 })
14565 .collect()
14566 }
14567
14568 pub fn init_test(cx: &mut TestAppContext) {
14569 cx.update(|cx| {
14570 let settings_store = SettingsStore::test(cx);
14571 cx.set_global(settings_store);
14572 cx.set_global(db::AppDatabase::test_new());
14573 theme_settings::init(theme::LoadThemes::JustBase, cx);
14574 });
14575 }
14576
14577 #[gpui::test]
14578 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14579 use settings::{ThemeName, ThemeSelection};
14580 use theme::SystemAppearance;
14581 use zed_actions::theme::ToggleMode;
14582
14583 init_test(cx);
14584
14585 let fs = FakeFs::new(cx.executor());
14586 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14587
14588 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14589 .await;
14590
14591 // Build a test project and workspace view so the test can invoke
14592 // the workspace action handler the same way the UI would.
14593 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14594 let (workspace, cx) =
14595 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14596
14597 // Seed the settings file with a plain static light theme so the
14598 // first toggle always starts from a known persisted state.
14599 workspace.update_in(cx, |_workspace, _window, cx| {
14600 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14601 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14602 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14603 });
14604 });
14605 cx.executor().advance_clock(Duration::from_millis(200));
14606 cx.run_until_parked();
14607
14608 // Confirm the initial persisted settings contain the static theme
14609 // we just wrote before any toggling happens.
14610 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14611 assert!(settings_text.contains(r#""theme": "One Light""#));
14612
14613 // Toggle once. This should migrate the persisted theme settings
14614 // into light/dark slots and enable system mode.
14615 workspace.update_in(cx, |workspace, window, cx| {
14616 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14617 });
14618 cx.executor().advance_clock(Duration::from_millis(200));
14619 cx.run_until_parked();
14620
14621 // 1. Static -> Dynamic
14622 // this assertion checks theme changed from static to dynamic.
14623 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14624 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14625 assert_eq!(
14626 parsed["theme"],
14627 serde_json::json!({
14628 "mode": "system",
14629 "light": "One Light",
14630 "dark": "One Dark"
14631 })
14632 );
14633
14634 // 2. Toggle again, suppose it will change the mode to light
14635 workspace.update_in(cx, |workspace, window, cx| {
14636 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14637 });
14638 cx.executor().advance_clock(Duration::from_millis(200));
14639 cx.run_until_parked();
14640
14641 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14642 assert!(settings_text.contains(r#""mode": "light""#));
14643 }
14644
14645 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14646 let item = TestProjectItem::new(id, path, cx);
14647 item.update(cx, |item, _| {
14648 item.is_dirty = true;
14649 });
14650 item
14651 }
14652
14653 #[gpui::test]
14654 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14655 cx: &mut gpui::TestAppContext,
14656 ) {
14657 init_test(cx);
14658 let fs = FakeFs::new(cx.executor());
14659
14660 let project = Project::test(fs, [], cx).await;
14661 let (workspace, cx) =
14662 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14663
14664 let panel = workspace.update_in(cx, |workspace, window, cx| {
14665 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14666 workspace.add_panel(panel.clone(), window, cx);
14667 workspace
14668 .right_dock()
14669 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14670 panel
14671 });
14672
14673 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14674 pane.update_in(cx, |pane, window, cx| {
14675 let item = cx.new(TestItem::new);
14676 pane.add_item(Box::new(item), true, true, None, window, cx);
14677 });
14678
14679 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14680 // mirrors the real-world flow and avoids side effects from directly
14681 // focusing the panel while the center pane is active.
14682 workspace.update_in(cx, |workspace, window, cx| {
14683 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14684 });
14685
14686 panel.update_in(cx, |panel, window, cx| {
14687 panel.set_zoomed(true, window, cx);
14688 });
14689
14690 workspace.update_in(cx, |workspace, window, cx| {
14691 assert!(workspace.right_dock().read(cx).is_open());
14692 assert!(panel.is_zoomed(window, cx));
14693 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14694 });
14695
14696 // Simulate a spurious pane::Event::Focus on the center pane while the
14697 // panel still has focus. This mirrors what happens during macOS window
14698 // activation: the center pane fires a focus event even though actual
14699 // focus remains on the dock panel.
14700 pane.update_in(cx, |_, _, cx| {
14701 cx.emit(pane::Event::Focus);
14702 });
14703
14704 // The dock must remain open because the panel had focus at the time the
14705 // event was processed. Before the fix, dock_to_preserve was None for
14706 // panels that don't implement pane(), causing the dock to close.
14707 workspace.update_in(cx, |workspace, window, cx| {
14708 assert!(
14709 workspace.right_dock().read(cx).is_open(),
14710 "Dock should stay open when its zoomed panel (without pane()) still has focus"
14711 );
14712 assert!(panel.is_zoomed(window, cx));
14713 });
14714 }
14715
14716 #[gpui::test]
14717 async fn test_panels_stay_open_after_position_change_and_settings_update(
14718 cx: &mut gpui::TestAppContext,
14719 ) {
14720 init_test(cx);
14721 let fs = FakeFs::new(cx.executor());
14722 let project = Project::test(fs, [], cx).await;
14723 let (workspace, cx) =
14724 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14725
14726 // Add two panels to the left dock and open it.
14727 let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14728 let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14729 let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14730 workspace.add_panel(panel_a.clone(), window, cx);
14731 workspace.add_panel(panel_b.clone(), window, cx);
14732 workspace.left_dock().update(cx, |dock, cx| {
14733 dock.set_open(true, window, cx);
14734 dock.activate_panel(0, window, cx);
14735 });
14736 (panel_a, panel_b)
14737 });
14738
14739 workspace.update_in(cx, |workspace, _, cx| {
14740 assert!(workspace.left_dock().read(cx).is_open());
14741 });
14742
14743 // Simulate a feature flag changing default dock positions: both panels
14744 // move from Left to Right.
14745 workspace.update_in(cx, |_workspace, _window, cx| {
14746 panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14747 panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14748 cx.update_global::<SettingsStore, _>(|_, _| {});
14749 });
14750
14751 // Both panels should now be in the right dock.
14752 workspace.update_in(cx, |workspace, _, cx| {
14753 let right_dock = workspace.right_dock().read(cx);
14754 assert_eq!(right_dock.panels_len(), 2);
14755 });
14756
14757 // Open the right dock and activate panel_b (simulating the user
14758 // opening the panel after it moved).
14759 workspace.update_in(cx, |workspace, window, cx| {
14760 workspace.right_dock().update(cx, |dock, cx| {
14761 dock.set_open(true, window, cx);
14762 dock.activate_panel(1, window, cx);
14763 });
14764 });
14765
14766 // Now trigger another SettingsStore change
14767 workspace.update_in(cx, |_workspace, _window, cx| {
14768 cx.update_global::<SettingsStore, _>(|_, _| {});
14769 });
14770
14771 workspace.update_in(cx, |workspace, _, cx| {
14772 assert!(
14773 workspace.right_dock().read(cx).is_open(),
14774 "Right dock should still be open after a settings change"
14775 );
14776 assert_eq!(
14777 workspace.right_dock().read(cx).panels_len(),
14778 2,
14779 "Both panels should still be in the right dock"
14780 );
14781 });
14782 }
14783}