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;
22mod status_bar;
23pub mod tasks;
24mod theme_preview;
25mod toast_layer;
26mod toolbar;
27pub mod welcome;
28mod workspace_settings;
29
30pub use crate::notifications::NotificationFrame;
31pub use dock::Panel;
32pub use multi_workspace::{
33 CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
34 MultiWorkspaceEvent, NextWorkspace, PreviousWorkspace, ProjectGroupKey, Sidebar, SidebarEvent,
35 SidebarHandle, SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar,
36 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, SerializedMultiWorkspace, SerializedWorkspaceLocation,
88 SessionWorkspace,
89 },
90 read_serialized_multi_workspaces, resolve_worktree_workspaces,
91};
92use postage::stream::Stream;
93use project::{
94 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
95 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, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
152 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::Replace,
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::Replace, 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 _panels_task: Option<Task<Result<()>>>,
1349 sidebar_focus_handle: Option<FocusHandle>,
1350 multi_workspace: Option<WeakEntity<MultiWorkspace>>,
1351}
1352
1353impl EventEmitter<Event> for Workspace {}
1354
1355#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1356pub struct ViewId {
1357 pub creator: CollaboratorId,
1358 pub id: u64,
1359}
1360
1361pub struct FollowerState {
1362 center_pane: Entity<Pane>,
1363 dock_pane: Option<Entity<Pane>>,
1364 active_view_id: Option<ViewId>,
1365 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1366}
1367
1368struct FollowerView {
1369 view: Box<dyn FollowableItemHandle>,
1370 location: Option<proto::PanelId>,
1371}
1372
1373#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1374pub enum OpenMode {
1375 /// Open the workspace in a new window.
1376 NewWindow,
1377 /// Add to the window's multi workspace without activating it (used during deserialization).
1378 Add,
1379 /// Add to the window's multi workspace and activate it.
1380 #[default]
1381 Activate,
1382 /// Replace the currently active workspace, and any of it's linked workspaces
1383 Replace,
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 }
1783 }
1784
1785 pub fn new_local(
1786 abs_paths: Vec<PathBuf>,
1787 app_state: Arc<AppState>,
1788 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1789 env: Option<HashMap<String, String>>,
1790 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1791 open_mode: OpenMode,
1792 cx: &mut App,
1793 ) -> Task<anyhow::Result<OpenResult>> {
1794 let project_handle = Project::local(
1795 app_state.client.clone(),
1796 app_state.node_runtime.clone(),
1797 app_state.user_store.clone(),
1798 app_state.languages.clone(),
1799 app_state.fs.clone(),
1800 env,
1801 Default::default(),
1802 cx,
1803 );
1804
1805 let db = WorkspaceDb::global(cx);
1806 let kvp = db::kvp::KeyValueStore::global(cx);
1807 cx.spawn(async move |cx| {
1808 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1809 for path in abs_paths.into_iter() {
1810 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1811 paths_to_open.push(canonical)
1812 } else {
1813 paths_to_open.push(path)
1814 }
1815 }
1816
1817 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1818
1819 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1820 paths_to_open = paths.ordered_paths().cloned().collect();
1821 if !paths.is_lexicographically_ordered() {
1822 project_handle.update(cx, |project, cx| {
1823 project.set_worktrees_reordered(true, cx);
1824 });
1825 }
1826 }
1827
1828 // Get project paths for all of the abs_paths
1829 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1830 Vec::with_capacity(paths_to_open.len());
1831
1832 for path in paths_to_open.into_iter() {
1833 if let Some((_, project_entry)) = cx
1834 .update(|cx| {
1835 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1836 })
1837 .await
1838 .log_err()
1839 {
1840 project_paths.push((path, Some(project_entry)));
1841 } else {
1842 project_paths.push((path, None));
1843 }
1844 }
1845
1846 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1847 serialized_workspace.id
1848 } else {
1849 db.next_id().await.unwrap_or_else(|_| Default::default())
1850 };
1851
1852 let toolchains = db.toolchains(workspace_id).await?;
1853
1854 for (toolchain, worktree_path, path) in toolchains {
1855 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1856 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1857 this.find_worktree(&worktree_path, cx)
1858 .and_then(|(worktree, rel_path)| {
1859 if rel_path.is_empty() {
1860 Some(worktree.read(cx).id())
1861 } else {
1862 None
1863 }
1864 })
1865 }) else {
1866 // We did not find a worktree with a given path, but that's whatever.
1867 continue;
1868 };
1869 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1870 continue;
1871 }
1872
1873 project_handle
1874 .update(cx, |this, cx| {
1875 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1876 })
1877 .await;
1878 }
1879 if let Some(workspace) = serialized_workspace.as_ref() {
1880 project_handle.update(cx, |this, cx| {
1881 for (scope, toolchains) in &workspace.user_toolchains {
1882 for toolchain in toolchains {
1883 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1884 }
1885 }
1886 });
1887 }
1888
1889 let window_to_replace = match open_mode {
1890 OpenMode::NewWindow => None,
1891 _ => requesting_window,
1892 };
1893
1894 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1895 if let Some(window) = window_to_replace {
1896 let centered_layout = serialized_workspace
1897 .as_ref()
1898 .map(|w| w.centered_layout)
1899 .unwrap_or(false);
1900
1901 let workspace = window.update(cx, |multi_workspace, window, cx| {
1902 let workspace = cx.new(|cx| {
1903 let mut workspace = Workspace::new(
1904 Some(workspace_id),
1905 project_handle.clone(),
1906 app_state.clone(),
1907 window,
1908 cx,
1909 );
1910
1911 workspace.centered_layout = centered_layout;
1912
1913 // Call init callback to add items before window renders
1914 if let Some(init) = init {
1915 init(&mut workspace, window, cx);
1916 }
1917
1918 workspace
1919 });
1920 match open_mode {
1921 OpenMode::Replace => {
1922 multi_workspace.replace(workspace.clone(), &*window, cx);
1923 }
1924 OpenMode::Activate => {
1925 multi_workspace.activate(workspace.clone(), window, cx);
1926 }
1927 OpenMode::Add => {
1928 multi_workspace.add(workspace.clone(), &*window, cx);
1929 }
1930 OpenMode::NewWindow => {
1931 unreachable!()
1932 }
1933 }
1934 workspace
1935 })?;
1936 (window, workspace)
1937 } else {
1938 let window_bounds_override = window_bounds_env_override();
1939
1940 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1941 (Some(WindowBounds::Windowed(bounds)), None)
1942 } else if let Some(workspace) = serialized_workspace.as_ref()
1943 && let Some(display) = workspace.display
1944 && let Some(bounds) = workspace.window_bounds.as_ref()
1945 {
1946 // Reopening an existing workspace - restore its saved bounds
1947 (Some(bounds.0), Some(display))
1948 } else if let Some((display, bounds)) =
1949 persistence::read_default_window_bounds(&kvp)
1950 {
1951 // New or empty workspace - use the last known window bounds
1952 (Some(bounds), Some(display))
1953 } else {
1954 // New window - let GPUI's default_bounds() handle cascading
1955 (None, None)
1956 };
1957
1958 // Use the serialized workspace to construct the new window
1959 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1960 options.window_bounds = window_bounds;
1961 let centered_layout = serialized_workspace
1962 .as_ref()
1963 .map(|w| w.centered_layout)
1964 .unwrap_or(false);
1965 let window = cx.open_window(options, {
1966 let app_state = app_state.clone();
1967 let project_handle = project_handle.clone();
1968 move |window, cx| {
1969 let workspace = cx.new(|cx| {
1970 let mut workspace = Workspace::new(
1971 Some(workspace_id),
1972 project_handle,
1973 app_state,
1974 window,
1975 cx,
1976 );
1977 workspace.centered_layout = centered_layout;
1978
1979 // Call init callback to add items before window renders
1980 if let Some(init) = init {
1981 init(&mut workspace, window, cx);
1982 }
1983
1984 workspace
1985 });
1986 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1987 }
1988 })?;
1989 let workspace =
1990 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1991 multi_workspace.workspace().clone()
1992 })?;
1993 (window, workspace)
1994 };
1995
1996 notify_if_database_failed(window, cx);
1997 // Check if this is an empty workspace (no paths to open)
1998 // An empty workspace is one where project_paths is empty
1999 let is_empty_workspace = project_paths.is_empty();
2000 // Check if serialized workspace has paths before it's moved
2001 let serialized_workspace_has_paths = serialized_workspace
2002 .as_ref()
2003 .map(|ws| !ws.paths.is_empty())
2004 .unwrap_or(false);
2005
2006 let opened_items = window
2007 .update(cx, |_, window, cx| {
2008 workspace.update(cx, |_workspace: &mut Workspace, cx| {
2009 open_items(serialized_workspace, project_paths, window, cx)
2010 })
2011 })?
2012 .await
2013 .unwrap_or_default();
2014
2015 // Restore default dock state for empty workspaces
2016 // Only restore if:
2017 // 1. This is an empty workspace (no paths), AND
2018 // 2. The serialized workspace either doesn't exist or has no paths
2019 if is_empty_workspace && !serialized_workspace_has_paths {
2020 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
2021 window
2022 .update(cx, |_, window, cx| {
2023 workspace.update(cx, |workspace, cx| {
2024 for (dock, serialized_dock) in [
2025 (&workspace.right_dock, &default_docks.right),
2026 (&workspace.left_dock, &default_docks.left),
2027 (&workspace.bottom_dock, &default_docks.bottom),
2028 ] {
2029 dock.update(cx, |dock, cx| {
2030 dock.serialized_dock = Some(serialized_dock.clone());
2031 dock.restore_state(window, cx);
2032 });
2033 }
2034 cx.notify();
2035 });
2036 })
2037 .log_err();
2038 }
2039 }
2040
2041 window
2042 .update(cx, |_, _window, cx| {
2043 workspace.update(cx, |this: &mut Workspace, cx| {
2044 this.update_history(cx);
2045 });
2046 })
2047 .log_err();
2048 Ok(OpenResult {
2049 window,
2050 workspace,
2051 opened_items,
2052 })
2053 })
2054 }
2055
2056 pub fn weak_handle(&self) -> WeakEntity<Self> {
2057 self.weak_self.clone()
2058 }
2059
2060 pub fn left_dock(&self) -> &Entity<Dock> {
2061 &self.left_dock
2062 }
2063
2064 pub fn bottom_dock(&self) -> &Entity<Dock> {
2065 &self.bottom_dock
2066 }
2067
2068 pub fn set_bottom_dock_layout(
2069 &mut self,
2070 layout: BottomDockLayout,
2071 window: &mut Window,
2072 cx: &mut Context<Self>,
2073 ) {
2074 let fs = self.project().read(cx).fs();
2075 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2076 content.workspace.bottom_dock_layout = Some(layout);
2077 });
2078
2079 cx.notify();
2080 self.serialize_workspace(window, cx);
2081 }
2082
2083 pub fn right_dock(&self) -> &Entity<Dock> {
2084 &self.right_dock
2085 }
2086
2087 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2088 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2089 }
2090
2091 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2092 let left_dock = self.left_dock.read(cx);
2093 let left_visible = left_dock.is_open();
2094 let left_active_panel = left_dock
2095 .active_panel()
2096 .map(|panel| panel.persistent_name().to_string());
2097 // `zoomed_position` is kept in sync with individual panel zoom state
2098 // by the dock code in `Dock::new` and `Dock::add_panel`.
2099 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2100
2101 let right_dock = self.right_dock.read(cx);
2102 let right_visible = right_dock.is_open();
2103 let right_active_panel = right_dock
2104 .active_panel()
2105 .map(|panel| panel.persistent_name().to_string());
2106 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2107
2108 let bottom_dock = self.bottom_dock.read(cx);
2109 let bottom_visible = bottom_dock.is_open();
2110 let bottom_active_panel = bottom_dock
2111 .active_panel()
2112 .map(|panel| panel.persistent_name().to_string());
2113 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2114
2115 DockStructure {
2116 left: DockData {
2117 visible: left_visible,
2118 active_panel: left_active_panel,
2119 zoom: left_dock_zoom,
2120 },
2121 right: DockData {
2122 visible: right_visible,
2123 active_panel: right_active_panel,
2124 zoom: right_dock_zoom,
2125 },
2126 bottom: DockData {
2127 visible: bottom_visible,
2128 active_panel: bottom_active_panel,
2129 zoom: bottom_dock_zoom,
2130 },
2131 }
2132 }
2133
2134 pub fn set_dock_structure(
2135 &self,
2136 docks: DockStructure,
2137 window: &mut Window,
2138 cx: &mut Context<Self>,
2139 ) {
2140 for (dock, data) in [
2141 (&self.left_dock, docks.left),
2142 (&self.bottom_dock, docks.bottom),
2143 (&self.right_dock, docks.right),
2144 ] {
2145 dock.update(cx, |dock, cx| {
2146 dock.serialized_dock = Some(data);
2147 dock.restore_state(window, cx);
2148 });
2149 }
2150 }
2151
2152 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2153 self.items(cx)
2154 .filter_map(|item| {
2155 let project_path = item.project_path(cx)?;
2156 self.project.read(cx).absolute_path(&project_path, cx)
2157 })
2158 .collect()
2159 }
2160
2161 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2162 match position {
2163 DockPosition::Left => &self.left_dock,
2164 DockPosition::Bottom => &self.bottom_dock,
2165 DockPosition::Right => &self.right_dock,
2166 }
2167 }
2168
2169 pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
2170 self.all_docks().into_iter().find_map(|dock| {
2171 let dock = dock.read(cx);
2172 dock.has_agent_panel(cx).then_some(dock.position())
2173 })
2174 }
2175
2176 pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
2177 self.all_docks().into_iter().find_map(|dock| {
2178 let dock = dock.read(cx);
2179 let panel = dock.panel::<T>()?;
2180 dock.stored_panel_size_state(&panel)
2181 })
2182 }
2183
2184 pub fn persisted_panel_size_state(
2185 &self,
2186 panel_key: &'static str,
2187 cx: &App,
2188 ) -> Option<dock::PanelSizeState> {
2189 dock::Dock::load_persisted_size_state(self, panel_key, cx)
2190 }
2191
2192 pub fn persist_panel_size_state(
2193 &self,
2194 panel_key: &str,
2195 size_state: dock::PanelSizeState,
2196 cx: &mut App,
2197 ) {
2198 let Some(workspace_id) = self
2199 .database_id()
2200 .map(|id| i64::from(id).to_string())
2201 .or(self.session_id())
2202 else {
2203 return;
2204 };
2205
2206 let kvp = db::kvp::KeyValueStore::global(cx);
2207 let panel_key = panel_key.to_string();
2208 cx.background_spawn(async move {
2209 let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
2210 scope
2211 .write(
2212 format!("{workspace_id}:{panel_key}"),
2213 serde_json::to_string(&size_state)?,
2214 )
2215 .await
2216 })
2217 .detach_and_log_err(cx);
2218 }
2219
2220 pub fn set_panel_size_state<T: Panel>(
2221 &mut self,
2222 size_state: dock::PanelSizeState,
2223 window: &mut Window,
2224 cx: &mut Context<Self>,
2225 ) -> bool {
2226 let Some(panel) = self.panel::<T>(cx) else {
2227 return false;
2228 };
2229
2230 let dock = self.dock_at_position(panel.position(window, cx));
2231 let did_set = dock.update(cx, |dock, cx| {
2232 dock.set_panel_size_state(&panel, size_state, cx)
2233 });
2234
2235 if did_set {
2236 self.persist_panel_size_state(T::panel_key(), size_state, cx);
2237 }
2238
2239 did_set
2240 }
2241
2242 pub fn toggle_dock_panel_flexible_size(
2243 &self,
2244 dock: &Entity<Dock>,
2245 panel: &dyn PanelHandle,
2246 window: &mut Window,
2247 cx: &mut App,
2248 ) {
2249 let position = dock.read(cx).position();
2250 let current_size = self.dock_size(&dock.read(cx), window, cx);
2251 let current_flex =
2252 current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
2253 dock.update(cx, |dock, cx| {
2254 dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
2255 });
2256 }
2257
2258 fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
2259 let panel = dock.active_panel()?;
2260 let size_state = dock
2261 .stored_panel_size_state(panel.as_ref())
2262 .unwrap_or_default();
2263 let position = dock.position();
2264
2265 let use_flex = panel.has_flexible_size(window, cx);
2266
2267 if position.axis() == Axis::Horizontal
2268 && use_flex
2269 && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
2270 {
2271 let workspace_width = self.bounds.size.width;
2272 if workspace_width <= Pixels::ZERO {
2273 return None;
2274 }
2275 let flex = flex.max(0.001);
2276 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2277 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2278 // Both docks are flex items sharing the full workspace width.
2279 let total_flex = flex + 1.0 + opposite_flex;
2280 return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
2281 } else {
2282 // Opposite dock is fixed-width; flex items share (W - fixed).
2283 let opposite_fixed = opposite
2284 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2285 .unwrap_or_default();
2286 let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
2287 return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
2288 }
2289 }
2290
2291 Some(
2292 size_state
2293 .size
2294 .unwrap_or_else(|| panel.default_size(window, cx)),
2295 )
2296 }
2297
2298 pub fn dock_flex_for_size(
2299 &self,
2300 position: DockPosition,
2301 size: Pixels,
2302 window: &Window,
2303 cx: &App,
2304 ) -> Option<f32> {
2305 if position.axis() != Axis::Horizontal {
2306 return None;
2307 }
2308
2309 let workspace_width = self.bounds.size.width;
2310 if workspace_width <= Pixels::ZERO {
2311 return None;
2312 }
2313
2314 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2315 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2316 let size = size.clamp(px(0.), workspace_width - px(1.));
2317 Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
2318 } else {
2319 let opposite_width = opposite
2320 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2321 .unwrap_or_default();
2322 let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
2323 let remaining = (available - size).max(px(1.));
2324 Some((size / remaining).max(0.0))
2325 }
2326 }
2327
2328 fn opposite_dock_panel_and_size_state(
2329 &self,
2330 position: DockPosition,
2331 window: &Window,
2332 cx: &App,
2333 ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
2334 let opposite_position = match position {
2335 DockPosition::Left => DockPosition::Right,
2336 DockPosition::Right => DockPosition::Left,
2337 DockPosition::Bottom => return None,
2338 };
2339
2340 let opposite_dock = self.dock_at_position(opposite_position).read(cx);
2341 let panel = opposite_dock.visible_panel()?;
2342 let mut size_state = opposite_dock
2343 .stored_panel_size_state(panel.as_ref())
2344 .unwrap_or_default();
2345 if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
2346 size_state.flex = self.default_dock_flex(opposite_position);
2347 }
2348 Some((panel.clone(), size_state))
2349 }
2350
2351 pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
2352 if position.axis() != Axis::Horizontal {
2353 return None;
2354 }
2355
2356 let pane = self.last_active_center_pane.clone()?.upgrade()?;
2357 Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
2358 }
2359
2360 pub fn is_edited(&self) -> bool {
2361 self.window_edited
2362 }
2363
2364 pub fn add_panel<T: Panel>(
2365 &mut self,
2366 panel: Entity<T>,
2367 window: &mut Window,
2368 cx: &mut Context<Self>,
2369 ) {
2370 let focus_handle = panel.panel_focus_handle(cx);
2371 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2372 .detach();
2373
2374 let dock_position = panel.position(window, cx);
2375 let dock = self.dock_at_position(dock_position);
2376 let any_panel = panel.to_any();
2377 let persisted_size_state =
2378 self.persisted_panel_size_state(T::panel_key(), cx)
2379 .or_else(|| {
2380 load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
2381 let state = dock::PanelSizeState {
2382 size: Some(size),
2383 flex: None,
2384 };
2385 self.persist_panel_size_state(T::panel_key(), state, cx);
2386 state
2387 })
2388 });
2389
2390 dock.update(cx, |dock, cx| {
2391 let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
2392 if let Some(size_state) = persisted_size_state {
2393 dock.set_panel_size_state(&panel, size_state, cx);
2394 }
2395 index
2396 });
2397
2398 cx.emit(Event::PanelAdded(any_panel));
2399 }
2400
2401 pub fn remove_panel<T: Panel>(
2402 &mut self,
2403 panel: &Entity<T>,
2404 window: &mut Window,
2405 cx: &mut Context<Self>,
2406 ) {
2407 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2408 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2409 }
2410 }
2411
2412 pub fn status_bar(&self) -> &Entity<StatusBar> {
2413 &self.status_bar
2414 }
2415
2416 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2417 self.sidebar_focus_handle = handle;
2418 }
2419
2420 pub fn status_bar_visible(&self, cx: &App) -> bool {
2421 StatusBarSettings::get_global(cx).show
2422 }
2423
2424 pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
2425 self.multi_workspace.as_ref()
2426 }
2427
2428 pub fn set_multi_workspace(
2429 &mut self,
2430 multi_workspace: WeakEntity<MultiWorkspace>,
2431 cx: &mut App,
2432 ) {
2433 self.status_bar.update(cx, |status_bar, cx| {
2434 status_bar.set_multi_workspace(multi_workspace.clone(), cx);
2435 });
2436 self.multi_workspace = Some(multi_workspace);
2437 }
2438
2439 pub fn app_state(&self) -> &Arc<AppState> {
2440 &self.app_state
2441 }
2442
2443 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2444 self._panels_task = Some(task);
2445 }
2446
2447 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2448 self._panels_task.take()
2449 }
2450
2451 pub fn user_store(&self) -> &Entity<UserStore> {
2452 &self.app_state.user_store
2453 }
2454
2455 pub fn project(&self) -> &Entity<Project> {
2456 &self.project
2457 }
2458
2459 pub fn path_style(&self, cx: &App) -> PathStyle {
2460 self.project.read(cx).path_style(cx)
2461 }
2462
2463 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2464 let mut history: HashMap<EntityId, usize> = HashMap::default();
2465
2466 for pane_handle in &self.panes {
2467 let pane = pane_handle.read(cx);
2468
2469 for entry in pane.activation_history() {
2470 history.insert(
2471 entry.entity_id,
2472 history
2473 .get(&entry.entity_id)
2474 .cloned()
2475 .unwrap_or(0)
2476 .max(entry.timestamp),
2477 );
2478 }
2479 }
2480
2481 history
2482 }
2483
2484 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2485 let mut recent_item: Option<Entity<T>> = None;
2486 let mut recent_timestamp = 0;
2487 for pane_handle in &self.panes {
2488 let pane = pane_handle.read(cx);
2489 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2490 pane.items().map(|item| (item.item_id(), item)).collect();
2491 for entry in pane.activation_history() {
2492 if entry.timestamp > recent_timestamp
2493 && let Some(&item) = item_map.get(&entry.entity_id)
2494 && let Some(typed_item) = item.act_as::<T>(cx)
2495 {
2496 recent_timestamp = entry.timestamp;
2497 recent_item = Some(typed_item);
2498 }
2499 }
2500 }
2501 recent_item
2502 }
2503
2504 pub fn recent_navigation_history_iter(
2505 &self,
2506 cx: &App,
2507 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2508 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2509 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2510
2511 for pane in &self.panes {
2512 let pane = pane.read(cx);
2513
2514 pane.nav_history()
2515 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2516 if let Some(fs_path) = &fs_path {
2517 abs_paths_opened
2518 .entry(fs_path.clone())
2519 .or_default()
2520 .insert(project_path.clone());
2521 }
2522 let timestamp = entry.timestamp;
2523 match history.entry(project_path) {
2524 hash_map::Entry::Occupied(mut entry) => {
2525 let (_, old_timestamp) = entry.get();
2526 if ×tamp > old_timestamp {
2527 entry.insert((fs_path, timestamp));
2528 }
2529 }
2530 hash_map::Entry::Vacant(entry) => {
2531 entry.insert((fs_path, timestamp));
2532 }
2533 }
2534 });
2535
2536 if let Some(item) = pane.active_item()
2537 && let Some(project_path) = item.project_path(cx)
2538 {
2539 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2540
2541 if let Some(fs_path) = &fs_path {
2542 abs_paths_opened
2543 .entry(fs_path.clone())
2544 .or_default()
2545 .insert(project_path.clone());
2546 }
2547
2548 history.insert(project_path, (fs_path, std::usize::MAX));
2549 }
2550 }
2551
2552 history
2553 .into_iter()
2554 .sorted_by_key(|(_, (_, order))| *order)
2555 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2556 .rev()
2557 .filter(move |(history_path, abs_path)| {
2558 let latest_project_path_opened = abs_path
2559 .as_ref()
2560 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2561 .and_then(|project_paths| {
2562 project_paths
2563 .iter()
2564 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2565 });
2566
2567 latest_project_path_opened.is_none_or(|path| path == history_path)
2568 })
2569 }
2570
2571 pub fn recent_navigation_history(
2572 &self,
2573 limit: Option<usize>,
2574 cx: &App,
2575 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2576 self.recent_navigation_history_iter(cx)
2577 .take(limit.unwrap_or(usize::MAX))
2578 .collect()
2579 }
2580
2581 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2582 for pane in &self.panes {
2583 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2584 }
2585 }
2586
2587 fn navigate_history(
2588 &mut self,
2589 pane: WeakEntity<Pane>,
2590 mode: NavigationMode,
2591 window: &mut Window,
2592 cx: &mut Context<Workspace>,
2593 ) -> Task<Result<()>> {
2594 self.navigate_history_impl(
2595 pane,
2596 mode,
2597 window,
2598 &mut |history, cx| history.pop(mode, cx),
2599 cx,
2600 )
2601 }
2602
2603 fn navigate_tag_history(
2604 &mut self,
2605 pane: WeakEntity<Pane>,
2606 mode: TagNavigationMode,
2607 window: &mut Window,
2608 cx: &mut Context<Workspace>,
2609 ) -> Task<Result<()>> {
2610 self.navigate_history_impl(
2611 pane,
2612 NavigationMode::Normal,
2613 window,
2614 &mut |history, _cx| history.pop_tag(mode),
2615 cx,
2616 )
2617 }
2618
2619 fn navigate_history_impl(
2620 &mut self,
2621 pane: WeakEntity<Pane>,
2622 mode: NavigationMode,
2623 window: &mut Window,
2624 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2625 cx: &mut Context<Workspace>,
2626 ) -> Task<Result<()>> {
2627 let to_load = if let Some(pane) = pane.upgrade() {
2628 pane.update(cx, |pane, cx| {
2629 window.focus(&pane.focus_handle(cx), cx);
2630 loop {
2631 // Retrieve the weak item handle from the history.
2632 let entry = cb(pane.nav_history_mut(), cx)?;
2633
2634 // If the item is still present in this pane, then activate it.
2635 if let Some(index) = entry
2636 .item
2637 .upgrade()
2638 .and_then(|v| pane.index_for_item(v.as_ref()))
2639 {
2640 let prev_active_item_index = pane.active_item_index();
2641 pane.nav_history_mut().set_mode(mode);
2642 pane.activate_item(index, true, true, window, cx);
2643 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2644
2645 let mut navigated = prev_active_item_index != pane.active_item_index();
2646 if let Some(data) = entry.data {
2647 navigated |= pane.active_item()?.navigate(data, window, cx);
2648 }
2649
2650 if navigated {
2651 break None;
2652 }
2653 } else {
2654 // If the item is no longer present in this pane, then retrieve its
2655 // path info in order to reopen it.
2656 break pane
2657 .nav_history()
2658 .path_for_item(entry.item.id())
2659 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2660 }
2661 }
2662 })
2663 } else {
2664 None
2665 };
2666
2667 if let Some((project_path, abs_path, entry)) = to_load {
2668 // If the item was no longer present, then load it again from its previous path, first try the local path
2669 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2670
2671 cx.spawn_in(window, async move |workspace, cx| {
2672 let open_by_project_path = open_by_project_path.await;
2673 let mut navigated = false;
2674 match open_by_project_path
2675 .with_context(|| format!("Navigating to {project_path:?}"))
2676 {
2677 Ok((project_entry_id, build_item)) => {
2678 let prev_active_item_id = pane.update(cx, |pane, _| {
2679 pane.nav_history_mut().set_mode(mode);
2680 pane.active_item().map(|p| p.item_id())
2681 })?;
2682
2683 pane.update_in(cx, |pane, window, cx| {
2684 let item = pane.open_item(
2685 project_entry_id,
2686 project_path,
2687 true,
2688 entry.is_preview,
2689 true,
2690 None,
2691 window, cx,
2692 build_item,
2693 );
2694 navigated |= Some(item.item_id()) != prev_active_item_id;
2695 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2696 if let Some(data) = entry.data {
2697 navigated |= item.navigate(data, window, cx);
2698 }
2699 })?;
2700 }
2701 Err(open_by_project_path_e) => {
2702 // Fall back to opening by abs path, in case an external file was opened and closed,
2703 // and its worktree is now dropped
2704 if let Some(abs_path) = abs_path {
2705 let prev_active_item_id = pane.update(cx, |pane, _| {
2706 pane.nav_history_mut().set_mode(mode);
2707 pane.active_item().map(|p| p.item_id())
2708 })?;
2709 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2710 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2711 })?;
2712 match open_by_abs_path
2713 .await
2714 .with_context(|| format!("Navigating to {abs_path:?}"))
2715 {
2716 Ok(item) => {
2717 pane.update_in(cx, |pane, window, cx| {
2718 navigated |= Some(item.item_id()) != prev_active_item_id;
2719 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2720 if let Some(data) = entry.data {
2721 navigated |= item.navigate(data, window, cx);
2722 }
2723 })?;
2724 }
2725 Err(open_by_abs_path_e) => {
2726 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2727 }
2728 }
2729 }
2730 }
2731 }
2732
2733 if !navigated {
2734 workspace
2735 .update_in(cx, |workspace, window, cx| {
2736 Self::navigate_history(workspace, pane, mode, window, cx)
2737 })?
2738 .await?;
2739 }
2740
2741 Ok(())
2742 })
2743 } else {
2744 Task::ready(Ok(()))
2745 }
2746 }
2747
2748 pub fn go_back(
2749 &mut self,
2750 pane: WeakEntity<Pane>,
2751 window: &mut Window,
2752 cx: &mut Context<Workspace>,
2753 ) -> Task<Result<()>> {
2754 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2755 }
2756
2757 pub fn go_forward(
2758 &mut self,
2759 pane: WeakEntity<Pane>,
2760 window: &mut Window,
2761 cx: &mut Context<Workspace>,
2762 ) -> Task<Result<()>> {
2763 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2764 }
2765
2766 pub fn reopen_closed_item(
2767 &mut self,
2768 window: &mut Window,
2769 cx: &mut Context<Workspace>,
2770 ) -> Task<Result<()>> {
2771 self.navigate_history(
2772 self.active_pane().downgrade(),
2773 NavigationMode::ReopeningClosedItem,
2774 window,
2775 cx,
2776 )
2777 }
2778
2779 pub fn client(&self) -> &Arc<Client> {
2780 &self.app_state.client
2781 }
2782
2783 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2784 self.titlebar_item = Some(item);
2785 cx.notify();
2786 }
2787
2788 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2789 self.on_prompt_for_new_path = Some(prompt)
2790 }
2791
2792 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2793 self.on_prompt_for_open_path = Some(prompt)
2794 }
2795
2796 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2797 self.terminal_provider = Some(Box::new(provider));
2798 }
2799
2800 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2801 self.debugger_provider = Some(Arc::new(provider));
2802 }
2803
2804 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2805 self.debugger_provider.clone()
2806 }
2807
2808 pub fn prompt_for_open_path(
2809 &mut self,
2810 path_prompt_options: PathPromptOptions,
2811 lister: DirectoryLister,
2812 window: &mut Window,
2813 cx: &mut Context<Self>,
2814 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2815 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2816 let prompt = self.on_prompt_for_open_path.take().unwrap();
2817 let rx = prompt(self, lister, window, cx);
2818 self.on_prompt_for_open_path = Some(prompt);
2819 rx
2820 } else {
2821 let (tx, rx) = oneshot::channel();
2822 let abs_path = cx.prompt_for_paths(path_prompt_options);
2823
2824 cx.spawn_in(window, async move |workspace, cx| {
2825 let Ok(result) = abs_path.await else {
2826 return Ok(());
2827 };
2828
2829 match result {
2830 Ok(result) => {
2831 tx.send(result).ok();
2832 }
2833 Err(err) => {
2834 let rx = workspace.update_in(cx, |workspace, window, cx| {
2835 workspace.show_portal_error(err.to_string(), cx);
2836 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2837 let rx = prompt(workspace, lister, window, cx);
2838 workspace.on_prompt_for_open_path = Some(prompt);
2839 rx
2840 })?;
2841 if let Ok(path) = rx.await {
2842 tx.send(path).ok();
2843 }
2844 }
2845 };
2846 anyhow::Ok(())
2847 })
2848 .detach();
2849
2850 rx
2851 }
2852 }
2853
2854 pub fn prompt_for_new_path(
2855 &mut self,
2856 lister: DirectoryLister,
2857 suggested_name: Option<String>,
2858 window: &mut Window,
2859 cx: &mut Context<Self>,
2860 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2861 if self.project.read(cx).is_via_collab()
2862 || self.project.read(cx).is_via_remote_server()
2863 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2864 {
2865 let prompt = self.on_prompt_for_new_path.take().unwrap();
2866 let rx = prompt(self, lister, suggested_name, window, cx);
2867 self.on_prompt_for_new_path = Some(prompt);
2868 return rx;
2869 }
2870
2871 let (tx, rx) = oneshot::channel();
2872 cx.spawn_in(window, async move |workspace, cx| {
2873 let abs_path = workspace.update(cx, |workspace, cx| {
2874 let relative_to = workspace
2875 .most_recent_active_path(cx)
2876 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2877 .or_else(|| {
2878 let project = workspace.project.read(cx);
2879 project.visible_worktrees(cx).find_map(|worktree| {
2880 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2881 })
2882 })
2883 .or_else(std::env::home_dir)
2884 .unwrap_or_else(|| PathBuf::from(""));
2885 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2886 })?;
2887 let abs_path = match abs_path.await? {
2888 Ok(path) => path,
2889 Err(err) => {
2890 let rx = workspace.update_in(cx, |workspace, window, cx| {
2891 workspace.show_portal_error(err.to_string(), cx);
2892
2893 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2894 let rx = prompt(workspace, lister, suggested_name, window, cx);
2895 workspace.on_prompt_for_new_path = Some(prompt);
2896 rx
2897 })?;
2898 if let Ok(path) = rx.await {
2899 tx.send(path).ok();
2900 }
2901 return anyhow::Ok(());
2902 }
2903 };
2904
2905 tx.send(abs_path.map(|path| vec![path])).ok();
2906 anyhow::Ok(())
2907 })
2908 .detach();
2909
2910 rx
2911 }
2912
2913 pub fn titlebar_item(&self) -> Option<AnyView> {
2914 self.titlebar_item.clone()
2915 }
2916
2917 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2918 /// When set, git-related operations should use this worktree instead of deriving
2919 /// the active worktree from the focused file.
2920 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2921 self.active_worktree_override
2922 }
2923
2924 pub fn set_active_worktree_override(
2925 &mut self,
2926 worktree_id: Option<WorktreeId>,
2927 cx: &mut Context<Self>,
2928 ) {
2929 self.active_worktree_override = worktree_id;
2930 cx.notify();
2931 }
2932
2933 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2934 self.active_worktree_override = None;
2935 cx.notify();
2936 }
2937
2938 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2939 ///
2940 /// If the given workspace has a local project, then it will be passed
2941 /// to the callback. Otherwise, a new empty window will be created.
2942 pub fn with_local_workspace<T, F>(
2943 &mut self,
2944 window: &mut Window,
2945 cx: &mut Context<Self>,
2946 callback: F,
2947 ) -> Task<Result<T>>
2948 where
2949 T: 'static,
2950 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2951 {
2952 if self.project.read(cx).is_local() {
2953 Task::ready(Ok(callback(self, window, cx)))
2954 } else {
2955 let env = self.project.read(cx).cli_environment(cx);
2956 let task = Self::new_local(
2957 Vec::new(),
2958 self.app_state.clone(),
2959 None,
2960 env,
2961 None,
2962 OpenMode::Activate,
2963 cx,
2964 );
2965 cx.spawn_in(window, async move |_vh, cx| {
2966 let OpenResult {
2967 window: multi_workspace_window,
2968 ..
2969 } = task.await?;
2970 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2971 let workspace = multi_workspace.workspace().clone();
2972 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2973 })
2974 })
2975 }
2976 }
2977
2978 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2979 ///
2980 /// If the given workspace has a local project, then it will be passed
2981 /// to the callback. Otherwise, a new empty window will be created.
2982 pub fn with_local_or_wsl_workspace<T, F>(
2983 &mut self,
2984 window: &mut Window,
2985 cx: &mut Context<Self>,
2986 callback: F,
2987 ) -> Task<Result<T>>
2988 where
2989 T: 'static,
2990 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2991 {
2992 let project = self.project.read(cx);
2993 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2994 Task::ready(Ok(callback(self, window, cx)))
2995 } else {
2996 let env = self.project.read(cx).cli_environment(cx);
2997 let task = Self::new_local(
2998 Vec::new(),
2999 self.app_state.clone(),
3000 None,
3001 env,
3002 None,
3003 OpenMode::Activate,
3004 cx,
3005 );
3006 cx.spawn_in(window, async move |_vh, cx| {
3007 let OpenResult {
3008 window: multi_workspace_window,
3009 ..
3010 } = task.await?;
3011 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
3012 let workspace = multi_workspace.workspace().clone();
3013 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3014 })
3015 })
3016 }
3017 }
3018
3019 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3020 self.project.read(cx).worktrees(cx)
3021 }
3022
3023 pub fn visible_worktrees<'a>(
3024 &self,
3025 cx: &'a App,
3026 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3027 self.project.read(cx).visible_worktrees(cx)
3028 }
3029
3030 #[cfg(any(test, feature = "test-support"))]
3031 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
3032 let futures = self
3033 .worktrees(cx)
3034 .filter_map(|worktree| worktree.read(cx).as_local())
3035 .map(|worktree| worktree.scan_complete())
3036 .collect::<Vec<_>>();
3037 async move {
3038 for future in futures {
3039 future.await;
3040 }
3041 }
3042 }
3043
3044 pub fn close_global(cx: &mut App) {
3045 cx.defer(|cx| {
3046 cx.windows().iter().find(|window| {
3047 window
3048 .update(cx, |_, window, _| {
3049 if window.is_window_active() {
3050 //This can only get called when the window's project connection has been lost
3051 //so we don't need to prompt the user for anything and instead just close the window
3052 window.remove_window();
3053 true
3054 } else {
3055 false
3056 }
3057 })
3058 .unwrap_or(false)
3059 });
3060 });
3061 }
3062
3063 pub fn move_focused_panel_to_next_position(
3064 &mut self,
3065 _: &MoveFocusedPanelToNextPosition,
3066 window: &mut Window,
3067 cx: &mut Context<Self>,
3068 ) {
3069 let docks = self.all_docks();
3070 let active_dock = docks
3071 .into_iter()
3072 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
3073
3074 if let Some(dock) = active_dock {
3075 dock.update(cx, |dock, cx| {
3076 let active_panel = dock
3077 .active_panel()
3078 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
3079
3080 if let Some(panel) = active_panel {
3081 panel.move_to_next_position(window, cx);
3082 }
3083 })
3084 }
3085 }
3086
3087 pub fn prepare_to_close(
3088 &mut self,
3089 close_intent: CloseIntent,
3090 window: &mut Window,
3091 cx: &mut Context<Self>,
3092 ) -> Task<Result<bool>> {
3093 let active_call = self.active_global_call();
3094
3095 cx.spawn_in(window, async move |this, cx| {
3096 this.update(cx, |this, _| {
3097 if close_intent == CloseIntent::CloseWindow {
3098 this.removing = true;
3099 }
3100 })?;
3101
3102 let workspace_count = cx.update(|_window, cx| {
3103 cx.windows()
3104 .iter()
3105 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
3106 .count()
3107 })?;
3108
3109 #[cfg(target_os = "macos")]
3110 let save_last_workspace = false;
3111
3112 // On Linux and Windows, closing the last window should restore the last workspace.
3113 #[cfg(not(target_os = "macos"))]
3114 let save_last_workspace = {
3115 let remaining_workspaces = cx.update(|_window, cx| {
3116 cx.windows()
3117 .iter()
3118 .filter_map(|window| window.downcast::<MultiWorkspace>())
3119 .filter_map(|multi_workspace| {
3120 multi_workspace
3121 .update(cx, |multi_workspace, _, cx| {
3122 multi_workspace.workspace().read(cx).removing
3123 })
3124 .ok()
3125 })
3126 .filter(|removing| !removing)
3127 .count()
3128 })?;
3129
3130 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
3131 };
3132
3133 if let Some(active_call) = active_call
3134 && workspace_count == 1
3135 && cx
3136 .update(|_window, cx| active_call.0.is_in_room(cx))
3137 .unwrap_or(false)
3138 {
3139 if close_intent == CloseIntent::CloseWindow {
3140 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
3141 let answer = cx.update(|window, cx| {
3142 window.prompt(
3143 PromptLevel::Warning,
3144 "Do you want to leave the current call?",
3145 None,
3146 &["Close window and hang up", "Cancel"],
3147 cx,
3148 )
3149 })?;
3150
3151 if answer.await.log_err() == Some(1) {
3152 return anyhow::Ok(false);
3153 } else {
3154 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
3155 task.await.log_err();
3156 }
3157 }
3158 }
3159 if close_intent == CloseIntent::ReplaceWindow {
3160 _ = cx.update(|_window, cx| {
3161 let multi_workspace = cx
3162 .windows()
3163 .iter()
3164 .filter_map(|window| window.downcast::<MultiWorkspace>())
3165 .next()
3166 .unwrap();
3167 let project = multi_workspace
3168 .read(cx)?
3169 .workspace()
3170 .read(cx)
3171 .project
3172 .clone();
3173 if project.read(cx).is_shared() {
3174 active_call.0.unshare_project(project, cx)?;
3175 }
3176 Ok::<_, anyhow::Error>(())
3177 });
3178 }
3179 }
3180
3181 let save_result = this
3182 .update_in(cx, |this, window, cx| {
3183 this.save_all_internal(SaveIntent::Close, window, cx)
3184 })?
3185 .await;
3186
3187 // If we're not quitting, but closing, we remove the workspace from
3188 // the current session.
3189 if close_intent != CloseIntent::Quit
3190 && !save_last_workspace
3191 && save_result.as_ref().is_ok_and(|&res| res)
3192 {
3193 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
3194 .await;
3195 }
3196
3197 save_result
3198 })
3199 }
3200
3201 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
3202 self.save_all_internal(
3203 action.save_intent.unwrap_or(SaveIntent::SaveAll),
3204 window,
3205 cx,
3206 )
3207 .detach_and_log_err(cx);
3208 }
3209
3210 fn send_keystrokes(
3211 &mut self,
3212 action: &SendKeystrokes,
3213 window: &mut Window,
3214 cx: &mut Context<Self>,
3215 ) {
3216 let keystrokes: Vec<Keystroke> = action
3217 .0
3218 .split(' ')
3219 .flat_map(|k| Keystroke::parse(k).log_err())
3220 .map(|k| {
3221 cx.keyboard_mapper()
3222 .map_key_equivalent(k, false)
3223 .inner()
3224 .clone()
3225 })
3226 .collect();
3227 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
3228 }
3229
3230 pub fn send_keystrokes_impl(
3231 &mut self,
3232 keystrokes: Vec<Keystroke>,
3233 window: &mut Window,
3234 cx: &mut Context<Self>,
3235 ) -> Shared<Task<()>> {
3236 let mut state = self.dispatching_keystrokes.borrow_mut();
3237 if !state.dispatched.insert(keystrokes.clone()) {
3238 cx.propagate();
3239 return state.task.clone().unwrap();
3240 }
3241
3242 state.queue.extend(keystrokes);
3243
3244 let keystrokes = self.dispatching_keystrokes.clone();
3245 if state.task.is_none() {
3246 state.task = Some(
3247 window
3248 .spawn(cx, async move |cx| {
3249 // limit to 100 keystrokes to avoid infinite recursion.
3250 for _ in 0..100 {
3251 let keystroke = {
3252 let mut state = keystrokes.borrow_mut();
3253 let Some(keystroke) = state.queue.pop_front() else {
3254 state.dispatched.clear();
3255 state.task.take();
3256 return;
3257 };
3258 keystroke
3259 };
3260 cx.update(|window, cx| {
3261 let focused = window.focused(cx);
3262 window.dispatch_keystroke(keystroke.clone(), cx);
3263 if window.focused(cx) != focused {
3264 // dispatch_keystroke may cause the focus to change.
3265 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3266 // And we need that to happen before the next keystroke to keep vim mode happy...
3267 // (Note that the tests always do this implicitly, so you must manually test with something like:
3268 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3269 // )
3270 window.draw(cx).clear();
3271 }
3272 })
3273 .ok();
3274
3275 // Yield between synthetic keystrokes so deferred focus and
3276 // other effects can settle before dispatching the next key.
3277 yield_now().await;
3278 }
3279
3280 *keystrokes.borrow_mut() = Default::default();
3281 log::error!("over 100 keystrokes passed to send_keystrokes");
3282 })
3283 .shared(),
3284 );
3285 }
3286 state.task.clone().unwrap()
3287 }
3288
3289 fn save_all_internal(
3290 &mut self,
3291 mut save_intent: SaveIntent,
3292 window: &mut Window,
3293 cx: &mut Context<Self>,
3294 ) -> Task<Result<bool>> {
3295 if self.project.read(cx).is_disconnected(cx) {
3296 return Task::ready(Ok(true));
3297 }
3298 let dirty_items = self
3299 .panes
3300 .iter()
3301 .flat_map(|pane| {
3302 pane.read(cx).items().filter_map(|item| {
3303 if item.is_dirty(cx) {
3304 item.tab_content_text(0, cx);
3305 Some((pane.downgrade(), item.boxed_clone()))
3306 } else {
3307 None
3308 }
3309 })
3310 })
3311 .collect::<Vec<_>>();
3312
3313 let project = self.project.clone();
3314 cx.spawn_in(window, async move |workspace, cx| {
3315 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3316 let (serialize_tasks, remaining_dirty_items) =
3317 workspace.update_in(cx, |workspace, window, cx| {
3318 let mut remaining_dirty_items = Vec::new();
3319 let mut serialize_tasks = Vec::new();
3320 for (pane, item) in dirty_items {
3321 if let Some(task) = item
3322 .to_serializable_item_handle(cx)
3323 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3324 {
3325 serialize_tasks.push(task);
3326 } else {
3327 remaining_dirty_items.push((pane, item));
3328 }
3329 }
3330 (serialize_tasks, remaining_dirty_items)
3331 })?;
3332
3333 futures::future::try_join_all(serialize_tasks).await?;
3334
3335 if !remaining_dirty_items.is_empty() {
3336 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3337 }
3338
3339 if remaining_dirty_items.len() > 1 {
3340 let answer = workspace.update_in(cx, |_, window, cx| {
3341 let detail = Pane::file_names_for_prompt(
3342 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3343 cx,
3344 );
3345 window.prompt(
3346 PromptLevel::Warning,
3347 "Do you want to save all changes in the following files?",
3348 Some(&detail),
3349 &["Save all", "Discard all", "Cancel"],
3350 cx,
3351 )
3352 })?;
3353 match answer.await.log_err() {
3354 Some(0) => save_intent = SaveIntent::SaveAll,
3355 Some(1) => save_intent = SaveIntent::Skip,
3356 Some(2) => return Ok(false),
3357 _ => {}
3358 }
3359 }
3360
3361 remaining_dirty_items
3362 } else {
3363 dirty_items
3364 };
3365
3366 for (pane, item) in dirty_items {
3367 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3368 (
3369 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3370 item.project_entry_ids(cx),
3371 )
3372 })?;
3373 if (singleton || !project_entry_ids.is_empty())
3374 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3375 {
3376 return Ok(false);
3377 }
3378 }
3379 Ok(true)
3380 })
3381 }
3382
3383 pub fn open_workspace_for_paths(
3384 &mut self,
3385 // replace_current_window: bool,
3386 mut open_mode: OpenMode,
3387 paths: Vec<PathBuf>,
3388 window: &mut Window,
3389 cx: &mut Context<Self>,
3390 ) -> Task<Result<Entity<Workspace>>> {
3391 let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
3392 let is_remote = self.project.read(cx).is_via_collab();
3393 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3394 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3395
3396 let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
3397 if workspace_is_empty {
3398 open_mode = OpenMode::Replace;
3399 }
3400
3401 let app_state = self.app_state.clone();
3402
3403 cx.spawn(async move |_, cx| {
3404 let OpenResult { workspace, .. } = cx
3405 .update(|cx| {
3406 open_paths(
3407 &paths,
3408 app_state,
3409 OpenOptions {
3410 requesting_window,
3411 open_mode,
3412 ..Default::default()
3413 },
3414 cx,
3415 )
3416 })
3417 .await?;
3418 Ok(workspace)
3419 })
3420 }
3421
3422 #[allow(clippy::type_complexity)]
3423 pub fn open_paths(
3424 &mut self,
3425 mut abs_paths: Vec<PathBuf>,
3426 options: OpenOptions,
3427 pane: Option<WeakEntity<Pane>>,
3428 window: &mut Window,
3429 cx: &mut Context<Self>,
3430 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3431 let fs = self.app_state.fs.clone();
3432
3433 let caller_ordered_abs_paths = abs_paths.clone();
3434
3435 // Sort the paths to ensure we add worktrees for parents before their children.
3436 abs_paths.sort_unstable();
3437 cx.spawn_in(window, async move |this, cx| {
3438 let mut tasks = Vec::with_capacity(abs_paths.len());
3439
3440 for abs_path in &abs_paths {
3441 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3442 OpenVisible::All => Some(true),
3443 OpenVisible::None => Some(false),
3444 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3445 Some(Some(metadata)) => Some(!metadata.is_dir),
3446 Some(None) => Some(true),
3447 None => None,
3448 },
3449 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3450 Some(Some(metadata)) => Some(metadata.is_dir),
3451 Some(None) => Some(false),
3452 None => None,
3453 },
3454 };
3455 let project_path = match visible {
3456 Some(visible) => match this
3457 .update(cx, |this, cx| {
3458 Workspace::project_path_for_path(
3459 this.project.clone(),
3460 abs_path,
3461 visible,
3462 cx,
3463 )
3464 })
3465 .log_err()
3466 {
3467 Some(project_path) => project_path.await.log_err(),
3468 None => None,
3469 },
3470 None => None,
3471 };
3472
3473 let this = this.clone();
3474 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3475 let fs = fs.clone();
3476 let pane = pane.clone();
3477 let task = cx.spawn(async move |cx| {
3478 let (_worktree, project_path) = project_path?;
3479 if fs.is_dir(&abs_path).await {
3480 // Opening a directory should not race to update the active entry.
3481 // We'll select/reveal a deterministic final entry after all paths finish opening.
3482 None
3483 } else {
3484 Some(
3485 this.update_in(cx, |this, window, cx| {
3486 this.open_path(
3487 project_path,
3488 pane,
3489 options.focus.unwrap_or(true),
3490 window,
3491 cx,
3492 )
3493 })
3494 .ok()?
3495 .await,
3496 )
3497 }
3498 });
3499 tasks.push(task);
3500 }
3501
3502 let results = futures::future::join_all(tasks).await;
3503
3504 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3505 let mut winner: Option<(PathBuf, bool)> = None;
3506 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3507 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3508 if !metadata.is_dir {
3509 winner = Some((abs_path, false));
3510 break;
3511 }
3512 if winner.is_none() {
3513 winner = Some((abs_path, true));
3514 }
3515 } else if winner.is_none() {
3516 winner = Some((abs_path, false));
3517 }
3518 }
3519
3520 // Compute the winner entry id on the foreground thread and emit once, after all
3521 // paths finish opening. This avoids races between concurrently-opening paths
3522 // (directories in particular) and makes the resulting project panel selection
3523 // deterministic.
3524 if let Some((winner_abs_path, winner_is_dir)) = winner {
3525 'emit_winner: {
3526 let winner_abs_path: Arc<Path> =
3527 SanitizedPath::new(&winner_abs_path).as_path().into();
3528
3529 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3530 OpenVisible::All => true,
3531 OpenVisible::None => false,
3532 OpenVisible::OnlyFiles => !winner_is_dir,
3533 OpenVisible::OnlyDirectories => winner_is_dir,
3534 };
3535
3536 let Some(worktree_task) = this
3537 .update(cx, |workspace, cx| {
3538 workspace.project.update(cx, |project, cx| {
3539 project.find_or_create_worktree(
3540 winner_abs_path.as_ref(),
3541 visible,
3542 cx,
3543 )
3544 })
3545 })
3546 .ok()
3547 else {
3548 break 'emit_winner;
3549 };
3550
3551 let Ok((worktree, _)) = worktree_task.await else {
3552 break 'emit_winner;
3553 };
3554
3555 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3556 let worktree = worktree.read(cx);
3557 let worktree_abs_path = worktree.abs_path();
3558 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3559 worktree.root_entry()
3560 } else {
3561 winner_abs_path
3562 .strip_prefix(worktree_abs_path.as_ref())
3563 .ok()
3564 .and_then(|relative_path| {
3565 let relative_path =
3566 RelPath::new(relative_path, PathStyle::local())
3567 .log_err()?;
3568 worktree.entry_for_path(&relative_path)
3569 })
3570 }?;
3571 Some(entry.id)
3572 }) else {
3573 break 'emit_winner;
3574 };
3575
3576 this.update(cx, |workspace, cx| {
3577 workspace.project.update(cx, |_, cx| {
3578 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3579 });
3580 })
3581 .ok();
3582 }
3583 }
3584
3585 results
3586 })
3587 }
3588
3589 pub fn open_resolved_path(
3590 &mut self,
3591 path: ResolvedPath,
3592 window: &mut Window,
3593 cx: &mut Context<Self>,
3594 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3595 match path {
3596 ResolvedPath::ProjectPath { project_path, .. } => {
3597 self.open_path(project_path, None, true, window, cx)
3598 }
3599 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3600 PathBuf::from(path),
3601 OpenOptions {
3602 visible: Some(OpenVisible::None),
3603 ..Default::default()
3604 },
3605 window,
3606 cx,
3607 ),
3608 }
3609 }
3610
3611 pub fn absolute_path_of_worktree(
3612 &self,
3613 worktree_id: WorktreeId,
3614 cx: &mut Context<Self>,
3615 ) -> Option<PathBuf> {
3616 self.project
3617 .read(cx)
3618 .worktree_for_id(worktree_id, cx)
3619 // TODO: use `abs_path` or `root_dir`
3620 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3621 }
3622
3623 pub fn add_folder_to_project(
3624 &mut self,
3625 _: &AddFolderToProject,
3626 window: &mut Window,
3627 cx: &mut Context<Self>,
3628 ) {
3629 let project = self.project.read(cx);
3630 if project.is_via_collab() {
3631 self.show_error(
3632 &anyhow!("You cannot add folders to someone else's project"),
3633 cx,
3634 );
3635 return;
3636 }
3637 let paths = self.prompt_for_open_path(
3638 PathPromptOptions {
3639 files: false,
3640 directories: true,
3641 multiple: true,
3642 prompt: None,
3643 },
3644 DirectoryLister::Project(self.project.clone()),
3645 window,
3646 cx,
3647 );
3648 cx.spawn_in(window, async move |this, cx| {
3649 if let Some(paths) = paths.await.log_err().flatten() {
3650 let results = this
3651 .update_in(cx, |this, window, cx| {
3652 this.open_paths(
3653 paths,
3654 OpenOptions {
3655 visible: Some(OpenVisible::All),
3656 ..Default::default()
3657 },
3658 None,
3659 window,
3660 cx,
3661 )
3662 })?
3663 .await;
3664 for result in results.into_iter().flatten() {
3665 result.log_err();
3666 }
3667 }
3668 anyhow::Ok(())
3669 })
3670 .detach_and_log_err(cx);
3671 }
3672
3673 pub fn project_path_for_path(
3674 project: Entity<Project>,
3675 abs_path: &Path,
3676 visible: bool,
3677 cx: &mut App,
3678 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3679 let entry = project.update(cx, |project, cx| {
3680 project.find_or_create_worktree(abs_path, visible, cx)
3681 });
3682 cx.spawn(async move |cx| {
3683 let (worktree, path) = entry.await?;
3684 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3685 Ok((worktree, ProjectPath { worktree_id, path }))
3686 })
3687 }
3688
3689 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3690 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3691 }
3692
3693 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3694 self.items_of_type(cx).max_by_key(|item| item.item_id())
3695 }
3696
3697 pub fn items_of_type<'a, T: Item>(
3698 &'a self,
3699 cx: &'a App,
3700 ) -> impl 'a + Iterator<Item = Entity<T>> {
3701 self.panes
3702 .iter()
3703 .flat_map(|pane| pane.read(cx).items_of_type())
3704 }
3705
3706 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3707 self.active_pane().read(cx).active_item()
3708 }
3709
3710 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3711 let item = self.active_item(cx)?;
3712 item.to_any_view().downcast::<I>().ok()
3713 }
3714
3715 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3716 self.active_item(cx).and_then(|item| item.project_path(cx))
3717 }
3718
3719 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3720 self.recent_navigation_history_iter(cx)
3721 .filter_map(|(path, abs_path)| {
3722 let worktree = self
3723 .project
3724 .read(cx)
3725 .worktree_for_id(path.worktree_id, cx)?;
3726 if worktree.read(cx).is_visible() {
3727 abs_path
3728 } else {
3729 None
3730 }
3731 })
3732 .next()
3733 }
3734
3735 pub fn save_active_item(
3736 &mut self,
3737 save_intent: SaveIntent,
3738 window: &mut Window,
3739 cx: &mut App,
3740 ) -> Task<Result<()>> {
3741 let project = self.project.clone();
3742 let pane = self.active_pane();
3743 let item = pane.read(cx).active_item();
3744 let pane = pane.downgrade();
3745
3746 window.spawn(cx, async move |cx| {
3747 if let Some(item) = item {
3748 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3749 .await
3750 .map(|_| ())
3751 } else {
3752 Ok(())
3753 }
3754 })
3755 }
3756
3757 pub fn close_inactive_items_and_panes(
3758 &mut self,
3759 action: &CloseInactiveTabsAndPanes,
3760 window: &mut Window,
3761 cx: &mut Context<Self>,
3762 ) {
3763 if let Some(task) = self.close_all_internal(
3764 true,
3765 action.save_intent.unwrap_or(SaveIntent::Close),
3766 window,
3767 cx,
3768 ) {
3769 task.detach_and_log_err(cx)
3770 }
3771 }
3772
3773 pub fn close_all_items_and_panes(
3774 &mut self,
3775 action: &CloseAllItemsAndPanes,
3776 window: &mut Window,
3777 cx: &mut Context<Self>,
3778 ) {
3779 if let Some(task) = self.close_all_internal(
3780 false,
3781 action.save_intent.unwrap_or(SaveIntent::Close),
3782 window,
3783 cx,
3784 ) {
3785 task.detach_and_log_err(cx)
3786 }
3787 }
3788
3789 /// Closes the active item across all panes.
3790 pub fn close_item_in_all_panes(
3791 &mut self,
3792 action: &CloseItemInAllPanes,
3793 window: &mut Window,
3794 cx: &mut Context<Self>,
3795 ) {
3796 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3797 return;
3798 };
3799
3800 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3801 let close_pinned = action.close_pinned;
3802
3803 if let Some(project_path) = active_item.project_path(cx) {
3804 self.close_items_with_project_path(
3805 &project_path,
3806 save_intent,
3807 close_pinned,
3808 window,
3809 cx,
3810 );
3811 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3812 let item_id = active_item.item_id();
3813 self.active_pane().update(cx, |pane, cx| {
3814 pane.close_item_by_id(item_id, save_intent, window, cx)
3815 .detach_and_log_err(cx);
3816 });
3817 }
3818 }
3819
3820 /// Closes all items with the given project path across all panes.
3821 pub fn close_items_with_project_path(
3822 &mut self,
3823 project_path: &ProjectPath,
3824 save_intent: SaveIntent,
3825 close_pinned: bool,
3826 window: &mut Window,
3827 cx: &mut Context<Self>,
3828 ) {
3829 let panes = self.panes().to_vec();
3830 for pane in panes {
3831 pane.update(cx, |pane, cx| {
3832 pane.close_items_for_project_path(
3833 project_path,
3834 save_intent,
3835 close_pinned,
3836 window,
3837 cx,
3838 )
3839 .detach_and_log_err(cx);
3840 });
3841 }
3842 }
3843
3844 fn close_all_internal(
3845 &mut self,
3846 retain_active_pane: bool,
3847 save_intent: SaveIntent,
3848 window: &mut Window,
3849 cx: &mut Context<Self>,
3850 ) -> Option<Task<Result<()>>> {
3851 let current_pane = self.active_pane();
3852
3853 let mut tasks = Vec::new();
3854
3855 if retain_active_pane {
3856 let current_pane_close = current_pane.update(cx, |pane, cx| {
3857 pane.close_other_items(
3858 &CloseOtherItems {
3859 save_intent: None,
3860 close_pinned: false,
3861 },
3862 None,
3863 window,
3864 cx,
3865 )
3866 });
3867
3868 tasks.push(current_pane_close);
3869 }
3870
3871 for pane in self.panes() {
3872 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3873 continue;
3874 }
3875
3876 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3877 pane.close_all_items(
3878 &CloseAllItems {
3879 save_intent: Some(save_intent),
3880 close_pinned: false,
3881 },
3882 window,
3883 cx,
3884 )
3885 });
3886
3887 tasks.push(close_pane_items)
3888 }
3889
3890 if tasks.is_empty() {
3891 None
3892 } else {
3893 Some(cx.spawn_in(window, async move |_, _| {
3894 for task in tasks {
3895 task.await?
3896 }
3897 Ok(())
3898 }))
3899 }
3900 }
3901
3902 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3903 self.dock_at_position(position).read(cx).is_open()
3904 }
3905
3906 pub fn toggle_dock(
3907 &mut self,
3908 dock_side: DockPosition,
3909 window: &mut Window,
3910 cx: &mut Context<Self>,
3911 ) {
3912 let mut focus_center = false;
3913 let mut reveal_dock = false;
3914
3915 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3916 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3917
3918 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3919 telemetry::event!(
3920 "Panel Button Clicked",
3921 name = panel.persistent_name(),
3922 toggle_state = !was_visible
3923 );
3924 }
3925 if was_visible {
3926 self.save_open_dock_positions(cx);
3927 }
3928
3929 let dock = self.dock_at_position(dock_side);
3930 dock.update(cx, |dock, cx| {
3931 dock.set_open(!was_visible, window, cx);
3932
3933 if dock.active_panel().is_none() {
3934 let Some(panel_ix) = dock
3935 .first_enabled_panel_idx(cx)
3936 .log_with_level(log::Level::Info)
3937 else {
3938 return;
3939 };
3940 dock.activate_panel(panel_ix, window, cx);
3941 }
3942
3943 if let Some(active_panel) = dock.active_panel() {
3944 if was_visible {
3945 if active_panel
3946 .panel_focus_handle(cx)
3947 .contains_focused(window, cx)
3948 {
3949 focus_center = true;
3950 }
3951 } else {
3952 let focus_handle = &active_panel.panel_focus_handle(cx);
3953 window.focus(focus_handle, cx);
3954 reveal_dock = true;
3955 }
3956 }
3957 });
3958
3959 if reveal_dock {
3960 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3961 }
3962
3963 if focus_center {
3964 self.active_pane
3965 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3966 }
3967
3968 cx.notify();
3969 self.serialize_workspace(window, cx);
3970 }
3971
3972 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3973 self.all_docks().into_iter().find(|&dock| {
3974 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3975 })
3976 }
3977
3978 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3979 if let Some(dock) = self.active_dock(window, cx).cloned() {
3980 self.save_open_dock_positions(cx);
3981 dock.update(cx, |dock, cx| {
3982 dock.set_open(false, window, cx);
3983 });
3984 return true;
3985 }
3986 false
3987 }
3988
3989 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3990 self.save_open_dock_positions(cx);
3991 for dock in self.all_docks() {
3992 dock.update(cx, |dock, cx| {
3993 dock.set_open(false, window, cx);
3994 });
3995 }
3996
3997 cx.focus_self(window);
3998 cx.notify();
3999 self.serialize_workspace(window, cx);
4000 }
4001
4002 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
4003 self.all_docks()
4004 .into_iter()
4005 .filter_map(|dock| {
4006 let dock_ref = dock.read(cx);
4007 if dock_ref.is_open() {
4008 Some(dock_ref.position())
4009 } else {
4010 None
4011 }
4012 })
4013 .collect()
4014 }
4015
4016 /// Saves the positions of currently open docks.
4017 ///
4018 /// Updates `last_open_dock_positions` with positions of all currently open
4019 /// docks, to later be restored by the 'Toggle All Docks' action.
4020 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
4021 let open_dock_positions = self.get_open_dock_positions(cx);
4022 if !open_dock_positions.is_empty() {
4023 self.last_open_dock_positions = open_dock_positions;
4024 }
4025 }
4026
4027 /// Toggles all docks between open and closed states.
4028 ///
4029 /// If any docks are open, closes all and remembers their positions. If all
4030 /// docks are closed, restores the last remembered dock configuration.
4031 fn toggle_all_docks(
4032 &mut self,
4033 _: &ToggleAllDocks,
4034 window: &mut Window,
4035 cx: &mut Context<Self>,
4036 ) {
4037 let open_dock_positions = self.get_open_dock_positions(cx);
4038
4039 if !open_dock_positions.is_empty() {
4040 self.close_all_docks(window, cx);
4041 } else if !self.last_open_dock_positions.is_empty() {
4042 self.restore_last_open_docks(window, cx);
4043 }
4044 }
4045
4046 /// Reopens docks from the most recently remembered configuration.
4047 ///
4048 /// Opens all docks whose positions are stored in `last_open_dock_positions`
4049 /// and clears the stored positions.
4050 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4051 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
4052
4053 for position in positions_to_open {
4054 let dock = self.dock_at_position(position);
4055 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
4056 }
4057
4058 cx.focus_self(window);
4059 cx.notify();
4060 self.serialize_workspace(window, cx);
4061 }
4062
4063 /// Transfer focus to the panel of the given type.
4064 pub fn focus_panel<T: Panel>(
4065 &mut self,
4066 window: &mut Window,
4067 cx: &mut Context<Self>,
4068 ) -> Option<Entity<T>> {
4069 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
4070 panel.to_any().downcast().ok()
4071 }
4072
4073 /// Focus the panel of the given type if it isn't already focused. If it is
4074 /// already focused, then transfer focus back to the workspace center.
4075 /// When the `close_panel_on_toggle` setting is enabled, also closes the
4076 /// panel when transferring focus back to the center.
4077 pub fn toggle_panel_focus<T: Panel>(
4078 &mut self,
4079 window: &mut Window,
4080 cx: &mut Context<Self>,
4081 ) -> bool {
4082 let mut did_focus_panel = false;
4083 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
4084 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
4085 did_focus_panel
4086 });
4087
4088 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
4089 self.close_panel::<T>(window, cx);
4090 }
4091
4092 telemetry::event!(
4093 "Panel Button Clicked",
4094 name = T::persistent_name(),
4095 toggle_state = did_focus_panel
4096 );
4097
4098 did_focus_panel
4099 }
4100
4101 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4102 if let Some(item) = self.active_item(cx) {
4103 item.item_focus_handle(cx).focus(window, cx);
4104 } else {
4105 log::error!("Could not find a focus target when switching focus to the center panes",);
4106 }
4107 }
4108
4109 pub fn activate_panel_for_proto_id(
4110 &mut self,
4111 panel_id: PanelId,
4112 window: &mut Window,
4113 cx: &mut Context<Self>,
4114 ) -> Option<Arc<dyn PanelHandle>> {
4115 let mut panel = None;
4116 for dock in self.all_docks() {
4117 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
4118 panel = dock.update(cx, |dock, cx| {
4119 dock.activate_panel(panel_index, window, cx);
4120 dock.set_open(true, window, cx);
4121 dock.active_panel().cloned()
4122 });
4123 break;
4124 }
4125 }
4126
4127 if panel.is_some() {
4128 cx.notify();
4129 self.serialize_workspace(window, cx);
4130 }
4131
4132 panel
4133 }
4134
4135 /// Focus or unfocus the given panel type, depending on the given callback.
4136 fn focus_or_unfocus_panel<T: Panel>(
4137 &mut self,
4138 window: &mut Window,
4139 cx: &mut Context<Self>,
4140 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
4141 ) -> Option<Arc<dyn PanelHandle>> {
4142 let mut result_panel = None;
4143 let mut serialize = false;
4144 for dock in self.all_docks() {
4145 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4146 let mut focus_center = false;
4147 let panel = dock.update(cx, |dock, cx| {
4148 dock.activate_panel(panel_index, window, cx);
4149
4150 let panel = dock.active_panel().cloned();
4151 if let Some(panel) = panel.as_ref() {
4152 if should_focus(&**panel, window, cx) {
4153 dock.set_open(true, window, cx);
4154 panel.panel_focus_handle(cx).focus(window, cx);
4155 } else {
4156 focus_center = true;
4157 }
4158 }
4159 panel
4160 });
4161
4162 if focus_center {
4163 self.active_pane
4164 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4165 }
4166
4167 result_panel = panel;
4168 serialize = true;
4169 break;
4170 }
4171 }
4172
4173 if serialize {
4174 self.serialize_workspace(window, cx);
4175 }
4176
4177 cx.notify();
4178 result_panel
4179 }
4180
4181 /// Open the panel of the given type
4182 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4183 for dock in self.all_docks() {
4184 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4185 dock.update(cx, |dock, cx| {
4186 dock.activate_panel(panel_index, window, cx);
4187 dock.set_open(true, window, cx);
4188 });
4189 }
4190 }
4191 }
4192
4193 /// Open the panel of the given type, dismissing any zoomed items that
4194 /// would obscure it (e.g. a zoomed terminal).
4195 pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4196 let dock_position = self.all_docks().iter().find_map(|dock| {
4197 let dock = dock.read(cx);
4198 dock.panel_index_for_type::<T>().map(|_| dock.position())
4199 });
4200 self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
4201 self.open_panel::<T>(window, cx);
4202 }
4203
4204 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
4205 for dock in self.all_docks().iter() {
4206 dock.update(cx, |dock, cx| {
4207 if dock.panel::<T>().is_some() {
4208 dock.set_open(false, window, cx)
4209 }
4210 })
4211 }
4212 }
4213
4214 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
4215 self.all_docks()
4216 .iter()
4217 .find_map(|dock| dock.read(cx).panel::<T>())
4218 }
4219
4220 fn dismiss_zoomed_items_to_reveal(
4221 &mut self,
4222 dock_to_reveal: Option<DockPosition>,
4223 window: &mut Window,
4224 cx: &mut Context<Self>,
4225 ) {
4226 // If a center pane is zoomed, unzoom it.
4227 for pane in &self.panes {
4228 if pane != &self.active_pane || dock_to_reveal.is_some() {
4229 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4230 }
4231 }
4232
4233 // If another dock is zoomed, hide it.
4234 let mut focus_center = false;
4235 for dock in self.all_docks() {
4236 dock.update(cx, |dock, cx| {
4237 if Some(dock.position()) != dock_to_reveal
4238 && let Some(panel) = dock.active_panel()
4239 && panel.is_zoomed(window, cx)
4240 {
4241 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
4242 dock.set_open(false, window, cx);
4243 }
4244 });
4245 }
4246
4247 if focus_center {
4248 self.active_pane
4249 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4250 }
4251
4252 if self.zoomed_position != dock_to_reveal {
4253 self.zoomed = None;
4254 self.zoomed_position = None;
4255 cx.emit(Event::ZoomChanged);
4256 }
4257
4258 cx.notify();
4259 }
4260
4261 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4262 let pane = cx.new(|cx| {
4263 let mut pane = Pane::new(
4264 self.weak_handle(),
4265 self.project.clone(),
4266 self.pane_history_timestamp.clone(),
4267 None,
4268 NewFile.boxed_clone(),
4269 true,
4270 window,
4271 cx,
4272 );
4273 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4274 pane
4275 });
4276 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4277 .detach();
4278 self.panes.push(pane.clone());
4279
4280 window.focus(&pane.focus_handle(cx), cx);
4281
4282 cx.emit(Event::PaneAdded(pane.clone()));
4283 pane
4284 }
4285
4286 pub fn add_item_to_center(
4287 &mut self,
4288 item: Box<dyn ItemHandle>,
4289 window: &mut Window,
4290 cx: &mut Context<Self>,
4291 ) -> bool {
4292 if let Some(center_pane) = self.last_active_center_pane.clone() {
4293 if let Some(center_pane) = center_pane.upgrade() {
4294 center_pane.update(cx, |pane, cx| {
4295 pane.add_item(item, true, true, None, window, cx)
4296 });
4297 true
4298 } else {
4299 false
4300 }
4301 } else {
4302 false
4303 }
4304 }
4305
4306 pub fn add_item_to_active_pane(
4307 &mut self,
4308 item: Box<dyn ItemHandle>,
4309 destination_index: Option<usize>,
4310 focus_item: bool,
4311 window: &mut Window,
4312 cx: &mut App,
4313 ) {
4314 self.add_item(
4315 self.active_pane.clone(),
4316 item,
4317 destination_index,
4318 false,
4319 focus_item,
4320 window,
4321 cx,
4322 )
4323 }
4324
4325 pub fn add_item(
4326 &mut self,
4327 pane: Entity<Pane>,
4328 item: Box<dyn ItemHandle>,
4329 destination_index: Option<usize>,
4330 activate_pane: bool,
4331 focus_item: bool,
4332 window: &mut Window,
4333 cx: &mut App,
4334 ) {
4335 pane.update(cx, |pane, cx| {
4336 pane.add_item(
4337 item,
4338 activate_pane,
4339 focus_item,
4340 destination_index,
4341 window,
4342 cx,
4343 )
4344 });
4345 }
4346
4347 pub fn split_item(
4348 &mut self,
4349 split_direction: SplitDirection,
4350 item: Box<dyn ItemHandle>,
4351 window: &mut Window,
4352 cx: &mut Context<Self>,
4353 ) {
4354 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4355 self.add_item(new_pane, item, None, true, true, window, cx);
4356 }
4357
4358 pub fn open_abs_path(
4359 &mut self,
4360 abs_path: PathBuf,
4361 options: OpenOptions,
4362 window: &mut Window,
4363 cx: &mut Context<Self>,
4364 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4365 cx.spawn_in(window, async move |workspace, cx| {
4366 let open_paths_task_result = workspace
4367 .update_in(cx, |workspace, window, cx| {
4368 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4369 })
4370 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4371 .await;
4372 anyhow::ensure!(
4373 open_paths_task_result.len() == 1,
4374 "open abs path {abs_path:?} task returned incorrect number of results"
4375 );
4376 match open_paths_task_result
4377 .into_iter()
4378 .next()
4379 .expect("ensured single task result")
4380 {
4381 Some(open_result) => {
4382 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4383 }
4384 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4385 }
4386 })
4387 }
4388
4389 pub fn split_abs_path(
4390 &mut self,
4391 abs_path: PathBuf,
4392 visible: bool,
4393 window: &mut Window,
4394 cx: &mut Context<Self>,
4395 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4396 let project_path_task =
4397 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4398 cx.spawn_in(window, async move |this, cx| {
4399 let (_, path) = project_path_task.await?;
4400 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4401 .await
4402 })
4403 }
4404
4405 pub fn open_path(
4406 &mut self,
4407 path: impl Into<ProjectPath>,
4408 pane: Option<WeakEntity<Pane>>,
4409 focus_item: bool,
4410 window: &mut Window,
4411 cx: &mut App,
4412 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4413 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4414 }
4415
4416 pub fn open_path_preview(
4417 &mut self,
4418 path: impl Into<ProjectPath>,
4419 pane: Option<WeakEntity<Pane>>,
4420 focus_item: bool,
4421 allow_preview: bool,
4422 activate: bool,
4423 window: &mut Window,
4424 cx: &mut App,
4425 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4426 let pane = pane.unwrap_or_else(|| {
4427 self.last_active_center_pane.clone().unwrap_or_else(|| {
4428 self.panes
4429 .first()
4430 .expect("There must be an active pane")
4431 .downgrade()
4432 })
4433 });
4434
4435 let project_path = path.into();
4436 let task = self.load_path(project_path.clone(), window, cx);
4437 window.spawn(cx, async move |cx| {
4438 let (project_entry_id, build_item) = task.await?;
4439
4440 pane.update_in(cx, |pane, window, cx| {
4441 pane.open_item(
4442 project_entry_id,
4443 project_path,
4444 focus_item,
4445 allow_preview,
4446 activate,
4447 None,
4448 window,
4449 cx,
4450 build_item,
4451 )
4452 })
4453 })
4454 }
4455
4456 pub fn split_path(
4457 &mut self,
4458 path: impl Into<ProjectPath>,
4459 window: &mut Window,
4460 cx: &mut Context<Self>,
4461 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4462 self.split_path_preview(path, false, None, window, cx)
4463 }
4464
4465 pub fn split_path_preview(
4466 &mut self,
4467 path: impl Into<ProjectPath>,
4468 allow_preview: bool,
4469 split_direction: Option<SplitDirection>,
4470 window: &mut Window,
4471 cx: &mut Context<Self>,
4472 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4473 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4474 self.panes
4475 .first()
4476 .expect("There must be an active pane")
4477 .downgrade()
4478 });
4479
4480 if let Member::Pane(center_pane) = &self.center.root
4481 && center_pane.read(cx).items_len() == 0
4482 {
4483 return self.open_path(path, Some(pane), true, window, cx);
4484 }
4485
4486 let project_path = path.into();
4487 let task = self.load_path(project_path.clone(), window, cx);
4488 cx.spawn_in(window, async move |this, cx| {
4489 let (project_entry_id, build_item) = task.await?;
4490 this.update_in(cx, move |this, window, cx| -> Option<_> {
4491 let pane = pane.upgrade()?;
4492 let new_pane = this.split_pane(
4493 pane,
4494 split_direction.unwrap_or(SplitDirection::Right),
4495 window,
4496 cx,
4497 );
4498 new_pane.update(cx, |new_pane, cx| {
4499 Some(new_pane.open_item(
4500 project_entry_id,
4501 project_path,
4502 true,
4503 allow_preview,
4504 true,
4505 None,
4506 window,
4507 cx,
4508 build_item,
4509 ))
4510 })
4511 })
4512 .map(|option| option.context("pane was dropped"))?
4513 })
4514 }
4515
4516 fn load_path(
4517 &mut self,
4518 path: ProjectPath,
4519 window: &mut Window,
4520 cx: &mut App,
4521 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4522 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4523 registry.open_path(self.project(), &path, window, cx)
4524 }
4525
4526 pub fn find_project_item<T>(
4527 &self,
4528 pane: &Entity<Pane>,
4529 project_item: &Entity<T::Item>,
4530 cx: &App,
4531 ) -> Option<Entity<T>>
4532 where
4533 T: ProjectItem,
4534 {
4535 use project::ProjectItem as _;
4536 let project_item = project_item.read(cx);
4537 let entry_id = project_item.entry_id(cx);
4538 let project_path = project_item.project_path(cx);
4539
4540 let mut item = None;
4541 if let Some(entry_id) = entry_id {
4542 item = pane.read(cx).item_for_entry(entry_id, cx);
4543 }
4544 if item.is_none()
4545 && let Some(project_path) = project_path
4546 {
4547 item = pane.read(cx).item_for_path(project_path, cx);
4548 }
4549
4550 item.and_then(|item| item.downcast::<T>())
4551 }
4552
4553 pub fn is_project_item_open<T>(
4554 &self,
4555 pane: &Entity<Pane>,
4556 project_item: &Entity<T::Item>,
4557 cx: &App,
4558 ) -> bool
4559 where
4560 T: ProjectItem,
4561 {
4562 self.find_project_item::<T>(pane, project_item, cx)
4563 .is_some()
4564 }
4565
4566 pub fn open_project_item<T>(
4567 &mut self,
4568 pane: Entity<Pane>,
4569 project_item: Entity<T::Item>,
4570 activate_pane: bool,
4571 focus_item: bool,
4572 keep_old_preview: bool,
4573 allow_new_preview: bool,
4574 window: &mut Window,
4575 cx: &mut Context<Self>,
4576 ) -> Entity<T>
4577 where
4578 T: ProjectItem,
4579 {
4580 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4581
4582 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4583 if !keep_old_preview
4584 && let Some(old_id) = old_item_id
4585 && old_id != item.item_id()
4586 {
4587 // switching to a different item, so unpreview old active item
4588 pane.update(cx, |pane, _| {
4589 pane.unpreview_item_if_preview(old_id);
4590 });
4591 }
4592
4593 self.activate_item(&item, activate_pane, focus_item, window, cx);
4594 if !allow_new_preview {
4595 pane.update(cx, |pane, _| {
4596 pane.unpreview_item_if_preview(item.item_id());
4597 });
4598 }
4599 return item;
4600 }
4601
4602 let item = pane.update(cx, |pane, cx| {
4603 cx.new(|cx| {
4604 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4605 })
4606 });
4607 let mut destination_index = None;
4608 pane.update(cx, |pane, cx| {
4609 if !keep_old_preview && let Some(old_id) = old_item_id {
4610 pane.unpreview_item_if_preview(old_id);
4611 }
4612 if allow_new_preview {
4613 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4614 }
4615 });
4616
4617 self.add_item(
4618 pane,
4619 Box::new(item.clone()),
4620 destination_index,
4621 activate_pane,
4622 focus_item,
4623 window,
4624 cx,
4625 );
4626 item
4627 }
4628
4629 pub fn open_shared_screen(
4630 &mut self,
4631 peer_id: PeerId,
4632 window: &mut Window,
4633 cx: &mut Context<Self>,
4634 ) {
4635 if let Some(shared_screen) =
4636 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4637 {
4638 self.active_pane.update(cx, |pane, cx| {
4639 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4640 });
4641 }
4642 }
4643
4644 pub fn activate_item(
4645 &mut self,
4646 item: &dyn ItemHandle,
4647 activate_pane: bool,
4648 focus_item: bool,
4649 window: &mut Window,
4650 cx: &mut App,
4651 ) -> bool {
4652 let result = self.panes.iter().find_map(|pane| {
4653 pane.read(cx)
4654 .index_for_item(item)
4655 .map(|ix| (pane.clone(), ix))
4656 });
4657 if let Some((pane, ix)) = result {
4658 pane.update(cx, |pane, cx| {
4659 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4660 });
4661 true
4662 } else {
4663 false
4664 }
4665 }
4666
4667 fn activate_pane_at_index(
4668 &mut self,
4669 action: &ActivatePane,
4670 window: &mut Window,
4671 cx: &mut Context<Self>,
4672 ) {
4673 let panes = self.center.panes();
4674 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4675 window.focus(&pane.focus_handle(cx), cx);
4676 } else {
4677 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4678 .detach();
4679 }
4680 }
4681
4682 fn move_item_to_pane_at_index(
4683 &mut self,
4684 action: &MoveItemToPane,
4685 window: &mut Window,
4686 cx: &mut Context<Self>,
4687 ) {
4688 let panes = self.center.panes();
4689 let destination = match panes.get(action.destination) {
4690 Some(&destination) => destination.clone(),
4691 None => {
4692 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4693 return;
4694 }
4695 let direction = SplitDirection::Right;
4696 let split_off_pane = self
4697 .find_pane_in_direction(direction, cx)
4698 .unwrap_or_else(|| self.active_pane.clone());
4699 let new_pane = self.add_pane(window, cx);
4700 self.center.split(&split_off_pane, &new_pane, direction, cx);
4701 new_pane
4702 }
4703 };
4704
4705 if action.clone {
4706 if self
4707 .active_pane
4708 .read(cx)
4709 .active_item()
4710 .is_some_and(|item| item.can_split(cx))
4711 {
4712 clone_active_item(
4713 self.database_id(),
4714 &self.active_pane,
4715 &destination,
4716 action.focus,
4717 window,
4718 cx,
4719 );
4720 return;
4721 }
4722 }
4723 move_active_item(
4724 &self.active_pane,
4725 &destination,
4726 action.focus,
4727 true,
4728 window,
4729 cx,
4730 )
4731 }
4732
4733 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4734 let panes = self.center.panes();
4735 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4736 let next_ix = (ix + 1) % panes.len();
4737 let next_pane = panes[next_ix].clone();
4738 window.focus(&next_pane.focus_handle(cx), cx);
4739 }
4740 }
4741
4742 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4743 let panes = self.center.panes();
4744 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4745 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4746 let prev_pane = panes[prev_ix].clone();
4747 window.focus(&prev_pane.focus_handle(cx), cx);
4748 }
4749 }
4750
4751 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4752 let last_pane = self.center.last_pane();
4753 window.focus(&last_pane.focus_handle(cx), cx);
4754 }
4755
4756 pub fn activate_pane_in_direction(
4757 &mut self,
4758 direction: SplitDirection,
4759 window: &mut Window,
4760 cx: &mut App,
4761 ) {
4762 use ActivateInDirectionTarget as Target;
4763 enum Origin {
4764 Sidebar,
4765 LeftDock,
4766 RightDock,
4767 BottomDock,
4768 Center,
4769 }
4770
4771 let origin: Origin = if self
4772 .sidebar_focus_handle
4773 .as_ref()
4774 .is_some_and(|h| h.contains_focused(window, cx))
4775 {
4776 Origin::Sidebar
4777 } else {
4778 [
4779 (&self.left_dock, Origin::LeftDock),
4780 (&self.right_dock, Origin::RightDock),
4781 (&self.bottom_dock, Origin::BottomDock),
4782 ]
4783 .into_iter()
4784 .find_map(|(dock, origin)| {
4785 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4786 Some(origin)
4787 } else {
4788 None
4789 }
4790 })
4791 .unwrap_or(Origin::Center)
4792 };
4793
4794 let get_last_active_pane = || {
4795 let pane = self
4796 .last_active_center_pane
4797 .clone()
4798 .unwrap_or_else(|| {
4799 self.panes
4800 .first()
4801 .expect("There must be an active pane")
4802 .downgrade()
4803 })
4804 .upgrade()?;
4805 (pane.read(cx).items_len() != 0).then_some(pane)
4806 };
4807
4808 let try_dock =
4809 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4810
4811 let sidebar_target = self
4812 .sidebar_focus_handle
4813 .as_ref()
4814 .map(|h| Target::Sidebar(h.clone()));
4815
4816 let target = match (origin, direction) {
4817 // From the sidebar, only Right navigates into the workspace.
4818 (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
4819 .or_else(|| get_last_active_pane().map(Target::Pane))
4820 .or_else(|| try_dock(&self.bottom_dock))
4821 .or_else(|| try_dock(&self.right_dock)),
4822
4823 (Origin::Sidebar, _) => None,
4824
4825 // We're in the center, so we first try to go to a different pane,
4826 // otherwise try to go to a dock.
4827 (Origin::Center, direction) => {
4828 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4829 Some(Target::Pane(pane))
4830 } else {
4831 match direction {
4832 SplitDirection::Up => None,
4833 SplitDirection::Down => try_dock(&self.bottom_dock),
4834 SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
4835 SplitDirection::Right => try_dock(&self.right_dock),
4836 }
4837 }
4838 }
4839
4840 (Origin::LeftDock, SplitDirection::Right) => {
4841 if let Some(last_active_pane) = get_last_active_pane() {
4842 Some(Target::Pane(last_active_pane))
4843 } else {
4844 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4845 }
4846 }
4847
4848 (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
4849
4850 (Origin::LeftDock, SplitDirection::Down)
4851 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4852
4853 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4854 (Origin::BottomDock, SplitDirection::Left) => {
4855 try_dock(&self.left_dock).or(sidebar_target)
4856 }
4857 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4858
4859 (Origin::RightDock, SplitDirection::Left) => {
4860 if let Some(last_active_pane) = get_last_active_pane() {
4861 Some(Target::Pane(last_active_pane))
4862 } else {
4863 try_dock(&self.bottom_dock)
4864 .or_else(|| try_dock(&self.left_dock))
4865 .or(sidebar_target)
4866 }
4867 }
4868
4869 _ => None,
4870 };
4871
4872 match target {
4873 Some(ActivateInDirectionTarget::Pane(pane)) => {
4874 let pane = pane.read(cx);
4875 if let Some(item) = pane.active_item() {
4876 item.item_focus_handle(cx).focus(window, cx);
4877 } else {
4878 log::error!(
4879 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4880 );
4881 }
4882 }
4883 Some(ActivateInDirectionTarget::Dock(dock)) => {
4884 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4885 window.defer(cx, move |window, cx| {
4886 let dock = dock.read(cx);
4887 if let Some(panel) = dock.active_panel() {
4888 panel.panel_focus_handle(cx).focus(window, cx);
4889 } else {
4890 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4891 }
4892 })
4893 }
4894 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4895 focus_handle.focus(window, cx);
4896 }
4897 None => {}
4898 }
4899 }
4900
4901 pub fn move_item_to_pane_in_direction(
4902 &mut self,
4903 action: &MoveItemToPaneInDirection,
4904 window: &mut Window,
4905 cx: &mut Context<Self>,
4906 ) {
4907 let destination = match self.find_pane_in_direction(action.direction, cx) {
4908 Some(destination) => destination,
4909 None => {
4910 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4911 return;
4912 }
4913 let new_pane = self.add_pane(window, cx);
4914 self.center
4915 .split(&self.active_pane, &new_pane, action.direction, cx);
4916 new_pane
4917 }
4918 };
4919
4920 if action.clone {
4921 if self
4922 .active_pane
4923 .read(cx)
4924 .active_item()
4925 .is_some_and(|item| item.can_split(cx))
4926 {
4927 clone_active_item(
4928 self.database_id(),
4929 &self.active_pane,
4930 &destination,
4931 action.focus,
4932 window,
4933 cx,
4934 );
4935 return;
4936 }
4937 }
4938 move_active_item(
4939 &self.active_pane,
4940 &destination,
4941 action.focus,
4942 true,
4943 window,
4944 cx,
4945 );
4946 }
4947
4948 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4949 self.center.bounding_box_for_pane(pane)
4950 }
4951
4952 pub fn find_pane_in_direction(
4953 &mut self,
4954 direction: SplitDirection,
4955 cx: &App,
4956 ) -> Option<Entity<Pane>> {
4957 self.center
4958 .find_pane_in_direction(&self.active_pane, direction, cx)
4959 .cloned()
4960 }
4961
4962 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4963 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4964 self.center.swap(&self.active_pane, &to, cx);
4965 cx.notify();
4966 }
4967 }
4968
4969 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4970 if self
4971 .center
4972 .move_to_border(&self.active_pane, direction, cx)
4973 .unwrap()
4974 {
4975 cx.notify();
4976 }
4977 }
4978
4979 pub fn resize_pane(
4980 &mut self,
4981 axis: gpui::Axis,
4982 amount: Pixels,
4983 window: &mut Window,
4984 cx: &mut Context<Self>,
4985 ) {
4986 let docks = self.all_docks();
4987 let active_dock = docks
4988 .into_iter()
4989 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4990
4991 if let Some(dock_entity) = active_dock {
4992 let dock = dock_entity.read(cx);
4993 let Some(panel_size) = self.dock_size(&dock, window, cx) else {
4994 return;
4995 };
4996 match dock.position() {
4997 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4998 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4999 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
5000 }
5001 } else {
5002 self.center
5003 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
5004 }
5005 cx.notify();
5006 }
5007
5008 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
5009 self.center.reset_pane_sizes(cx);
5010 cx.notify();
5011 }
5012
5013 fn handle_pane_focused(
5014 &mut self,
5015 pane: Entity<Pane>,
5016 window: &mut Window,
5017 cx: &mut Context<Self>,
5018 ) {
5019 // This is explicitly hoisted out of the following check for pane identity as
5020 // terminal panel panes are not registered as a center panes.
5021 self.status_bar.update(cx, |status_bar, cx| {
5022 status_bar.set_active_pane(&pane, window, cx);
5023 });
5024 if self.active_pane != pane {
5025 self.set_active_pane(&pane, window, cx);
5026 }
5027
5028 if self.last_active_center_pane.is_none() {
5029 self.last_active_center_pane = Some(pane.downgrade());
5030 }
5031
5032 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
5033 // This prevents the dock from closing when focus events fire during window activation.
5034 // We also preserve any dock whose active panel itself has focus — this covers
5035 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
5036 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
5037 let dock_read = dock.read(cx);
5038 if let Some(panel) = dock_read.active_panel() {
5039 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
5040 || panel.panel_focus_handle(cx).contains_focused(window, cx)
5041 {
5042 return Some(dock_read.position());
5043 }
5044 }
5045 None
5046 });
5047
5048 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
5049 if pane.read(cx).is_zoomed() {
5050 self.zoomed = Some(pane.downgrade().into());
5051 } else {
5052 self.zoomed = None;
5053 }
5054 self.zoomed_position = None;
5055 cx.emit(Event::ZoomChanged);
5056 self.update_active_view_for_followers(window, cx);
5057 pane.update(cx, |pane, _| {
5058 pane.track_alternate_file_items();
5059 });
5060
5061 cx.notify();
5062 }
5063
5064 fn set_active_pane(
5065 &mut self,
5066 pane: &Entity<Pane>,
5067 window: &mut Window,
5068 cx: &mut Context<Self>,
5069 ) {
5070 self.active_pane = pane.clone();
5071 self.active_item_path_changed(true, window, cx);
5072 self.last_active_center_pane = Some(pane.downgrade());
5073 }
5074
5075 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5076 self.update_active_view_for_followers(window, cx);
5077 }
5078
5079 fn handle_pane_event(
5080 &mut self,
5081 pane: &Entity<Pane>,
5082 event: &pane::Event,
5083 window: &mut Window,
5084 cx: &mut Context<Self>,
5085 ) {
5086 let mut serialize_workspace = true;
5087 match event {
5088 pane::Event::AddItem { item } => {
5089 item.added_to_pane(self, pane.clone(), window, cx);
5090 cx.emit(Event::ItemAdded {
5091 item: item.boxed_clone(),
5092 });
5093 }
5094 pane::Event::Split { direction, mode } => {
5095 match mode {
5096 SplitMode::ClonePane => {
5097 self.split_and_clone(pane.clone(), *direction, window, cx)
5098 .detach();
5099 }
5100 SplitMode::EmptyPane => {
5101 self.split_pane(pane.clone(), *direction, window, cx);
5102 }
5103 SplitMode::MovePane => {
5104 self.split_and_move(pane.clone(), *direction, window, cx);
5105 }
5106 };
5107 }
5108 pane::Event::JoinIntoNext => {
5109 self.join_pane_into_next(pane.clone(), window, cx);
5110 }
5111 pane::Event::JoinAll => {
5112 self.join_all_panes(window, cx);
5113 }
5114 pane::Event::Remove { focus_on_pane } => {
5115 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
5116 }
5117 pane::Event::ActivateItem {
5118 local,
5119 focus_changed,
5120 } => {
5121 window.invalidate_character_coordinates();
5122
5123 pane.update(cx, |pane, _| {
5124 pane.track_alternate_file_items();
5125 });
5126 if *local {
5127 self.unfollow_in_pane(pane, window, cx);
5128 }
5129 serialize_workspace = *focus_changed || pane != self.active_pane();
5130 if pane == self.active_pane() {
5131 self.active_item_path_changed(*focus_changed, window, cx);
5132 self.update_active_view_for_followers(window, cx);
5133 } else if *local {
5134 self.set_active_pane(pane, window, cx);
5135 }
5136 }
5137 pane::Event::UserSavedItem { item, save_intent } => {
5138 cx.emit(Event::UserSavedItem {
5139 pane: pane.downgrade(),
5140 item: item.boxed_clone(),
5141 save_intent: *save_intent,
5142 });
5143 serialize_workspace = false;
5144 }
5145 pane::Event::ChangeItemTitle => {
5146 if *pane == self.active_pane {
5147 self.active_item_path_changed(false, window, cx);
5148 }
5149 serialize_workspace = false;
5150 }
5151 pane::Event::RemovedItem { item } => {
5152 cx.emit(Event::ActiveItemChanged);
5153 self.update_window_edited(window, cx);
5154 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
5155 && entry.get().entity_id() == pane.entity_id()
5156 {
5157 entry.remove();
5158 }
5159 cx.emit(Event::ItemRemoved {
5160 item_id: item.item_id(),
5161 });
5162 }
5163 pane::Event::Focus => {
5164 window.invalidate_character_coordinates();
5165 self.handle_pane_focused(pane.clone(), window, cx);
5166 }
5167 pane::Event::ZoomIn => {
5168 if *pane == self.active_pane {
5169 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
5170 if pane.read(cx).has_focus(window, cx) {
5171 self.zoomed = Some(pane.downgrade().into());
5172 self.zoomed_position = None;
5173 cx.emit(Event::ZoomChanged);
5174 }
5175 cx.notify();
5176 }
5177 }
5178 pane::Event::ZoomOut => {
5179 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
5180 if self.zoomed_position.is_none() {
5181 self.zoomed = None;
5182 cx.emit(Event::ZoomChanged);
5183 }
5184 cx.notify();
5185 }
5186 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
5187 }
5188
5189 if serialize_workspace {
5190 self.serialize_workspace(window, cx);
5191 }
5192 }
5193
5194 pub fn unfollow_in_pane(
5195 &mut self,
5196 pane: &Entity<Pane>,
5197 window: &mut Window,
5198 cx: &mut Context<Workspace>,
5199 ) -> Option<CollaboratorId> {
5200 let leader_id = self.leader_for_pane(pane)?;
5201 self.unfollow(leader_id, window, cx);
5202 Some(leader_id)
5203 }
5204
5205 pub fn split_pane(
5206 &mut self,
5207 pane_to_split: Entity<Pane>,
5208 split_direction: SplitDirection,
5209 window: &mut Window,
5210 cx: &mut Context<Self>,
5211 ) -> Entity<Pane> {
5212 let new_pane = self.add_pane(window, cx);
5213 self.center
5214 .split(&pane_to_split, &new_pane, split_direction, cx);
5215 cx.notify();
5216 new_pane
5217 }
5218
5219 pub fn split_and_move(
5220 &mut self,
5221 pane: Entity<Pane>,
5222 direction: SplitDirection,
5223 window: &mut Window,
5224 cx: &mut Context<Self>,
5225 ) {
5226 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
5227 return;
5228 };
5229 let new_pane = self.add_pane(window, cx);
5230 new_pane.update(cx, |pane, cx| {
5231 pane.add_item(item, true, true, None, window, cx)
5232 });
5233 self.center.split(&pane, &new_pane, direction, cx);
5234 cx.notify();
5235 }
5236
5237 pub fn split_and_clone(
5238 &mut self,
5239 pane: Entity<Pane>,
5240 direction: SplitDirection,
5241 window: &mut Window,
5242 cx: &mut Context<Self>,
5243 ) -> Task<Option<Entity<Pane>>> {
5244 let Some(item) = pane.read(cx).active_item() else {
5245 return Task::ready(None);
5246 };
5247 if !item.can_split(cx) {
5248 return Task::ready(None);
5249 }
5250 let task = item.clone_on_split(self.database_id(), window, cx);
5251 cx.spawn_in(window, async move |this, cx| {
5252 if let Some(clone) = task.await {
5253 this.update_in(cx, |this, window, cx| {
5254 let new_pane = this.add_pane(window, cx);
5255 let nav_history = pane.read(cx).fork_nav_history();
5256 new_pane.update(cx, |pane, cx| {
5257 pane.set_nav_history(nav_history, cx);
5258 pane.add_item(clone, true, true, None, window, cx)
5259 });
5260 this.center.split(&pane, &new_pane, direction, cx);
5261 cx.notify();
5262 new_pane
5263 })
5264 .ok()
5265 } else {
5266 None
5267 }
5268 })
5269 }
5270
5271 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5272 let active_item = self.active_pane.read(cx).active_item();
5273 for pane in &self.panes {
5274 join_pane_into_active(&self.active_pane, pane, window, cx);
5275 }
5276 if let Some(active_item) = active_item {
5277 self.activate_item(active_item.as_ref(), true, true, window, cx);
5278 }
5279 cx.notify();
5280 }
5281
5282 pub fn join_pane_into_next(
5283 &mut self,
5284 pane: Entity<Pane>,
5285 window: &mut Window,
5286 cx: &mut Context<Self>,
5287 ) {
5288 let next_pane = self
5289 .find_pane_in_direction(SplitDirection::Right, cx)
5290 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5291 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5292 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5293 let Some(next_pane) = next_pane else {
5294 return;
5295 };
5296 move_all_items(&pane, &next_pane, window, cx);
5297 cx.notify();
5298 }
5299
5300 fn remove_pane(
5301 &mut self,
5302 pane: Entity<Pane>,
5303 focus_on: Option<Entity<Pane>>,
5304 window: &mut Window,
5305 cx: &mut Context<Self>,
5306 ) {
5307 if self.center.remove(&pane, cx).unwrap() {
5308 self.force_remove_pane(&pane, &focus_on, window, cx);
5309 self.unfollow_in_pane(&pane, window, cx);
5310 self.last_leaders_by_pane.remove(&pane.downgrade());
5311 for removed_item in pane.read(cx).items() {
5312 self.panes_by_item.remove(&removed_item.item_id());
5313 }
5314
5315 cx.notify();
5316 } else {
5317 self.active_item_path_changed(true, window, cx);
5318 }
5319 cx.emit(Event::PaneRemoved);
5320 }
5321
5322 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5323 &mut self.panes
5324 }
5325
5326 pub fn panes(&self) -> &[Entity<Pane>] {
5327 &self.panes
5328 }
5329
5330 pub fn active_pane(&self) -> &Entity<Pane> {
5331 &self.active_pane
5332 }
5333
5334 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5335 for dock in self.all_docks() {
5336 if dock.focus_handle(cx).contains_focused(window, cx)
5337 && let Some(pane) = dock
5338 .read(cx)
5339 .active_panel()
5340 .and_then(|panel| panel.pane(cx))
5341 {
5342 return pane;
5343 }
5344 }
5345 self.active_pane().clone()
5346 }
5347
5348 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5349 self.find_pane_in_direction(SplitDirection::Right, cx)
5350 .unwrap_or_else(|| {
5351 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5352 })
5353 }
5354
5355 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5356 self.pane_for_item_id(handle.item_id())
5357 }
5358
5359 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5360 let weak_pane = self.panes_by_item.get(&item_id)?;
5361 weak_pane.upgrade()
5362 }
5363
5364 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5365 self.panes
5366 .iter()
5367 .find(|pane| pane.entity_id() == entity_id)
5368 .cloned()
5369 }
5370
5371 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5372 self.follower_states.retain(|leader_id, state| {
5373 if *leader_id == CollaboratorId::PeerId(peer_id) {
5374 for item in state.items_by_leader_view_id.values() {
5375 item.view.set_leader_id(None, window, cx);
5376 }
5377 false
5378 } else {
5379 true
5380 }
5381 });
5382 cx.notify();
5383 }
5384
5385 pub fn start_following(
5386 &mut self,
5387 leader_id: impl Into<CollaboratorId>,
5388 window: &mut Window,
5389 cx: &mut Context<Self>,
5390 ) -> Option<Task<Result<()>>> {
5391 let leader_id = leader_id.into();
5392 let pane = self.active_pane().clone();
5393
5394 self.last_leaders_by_pane
5395 .insert(pane.downgrade(), leader_id);
5396 self.unfollow(leader_id, window, cx);
5397 self.unfollow_in_pane(&pane, window, cx);
5398 self.follower_states.insert(
5399 leader_id,
5400 FollowerState {
5401 center_pane: pane.clone(),
5402 dock_pane: None,
5403 active_view_id: None,
5404 items_by_leader_view_id: Default::default(),
5405 },
5406 );
5407 cx.notify();
5408
5409 match leader_id {
5410 CollaboratorId::PeerId(leader_peer_id) => {
5411 let room_id = self.active_call()?.room_id(cx)?;
5412 let project_id = self.project.read(cx).remote_id();
5413 let request = self.app_state.client.request(proto::Follow {
5414 room_id,
5415 project_id,
5416 leader_id: Some(leader_peer_id),
5417 });
5418
5419 Some(cx.spawn_in(window, async move |this, cx| {
5420 let response = request.await?;
5421 this.update(cx, |this, _| {
5422 let state = this
5423 .follower_states
5424 .get_mut(&leader_id)
5425 .context("following interrupted")?;
5426 state.active_view_id = response
5427 .active_view
5428 .as_ref()
5429 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5430 anyhow::Ok(())
5431 })??;
5432 if let Some(view) = response.active_view {
5433 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5434 }
5435 this.update_in(cx, |this, window, cx| {
5436 this.leader_updated(leader_id, window, cx)
5437 })?;
5438 Ok(())
5439 }))
5440 }
5441 CollaboratorId::Agent => {
5442 self.leader_updated(leader_id, window, cx)?;
5443 Some(Task::ready(Ok(())))
5444 }
5445 }
5446 }
5447
5448 pub fn follow_next_collaborator(
5449 &mut self,
5450 _: &FollowNextCollaborator,
5451 window: &mut Window,
5452 cx: &mut Context<Self>,
5453 ) {
5454 let collaborators = self.project.read(cx).collaborators();
5455 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5456 let mut collaborators = collaborators.keys().copied();
5457 for peer_id in collaborators.by_ref() {
5458 if CollaboratorId::PeerId(peer_id) == leader_id {
5459 break;
5460 }
5461 }
5462 collaborators.next().map(CollaboratorId::PeerId)
5463 } else if let Some(last_leader_id) =
5464 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5465 {
5466 match last_leader_id {
5467 CollaboratorId::PeerId(peer_id) => {
5468 if collaborators.contains_key(peer_id) {
5469 Some(*last_leader_id)
5470 } else {
5471 None
5472 }
5473 }
5474 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5475 }
5476 } else {
5477 None
5478 };
5479
5480 let pane = self.active_pane.clone();
5481 let Some(leader_id) = next_leader_id.or_else(|| {
5482 Some(CollaboratorId::PeerId(
5483 collaborators.keys().copied().next()?,
5484 ))
5485 }) else {
5486 return;
5487 };
5488 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5489 return;
5490 }
5491 if let Some(task) = self.start_following(leader_id, window, cx) {
5492 task.detach_and_log_err(cx)
5493 }
5494 }
5495
5496 pub fn follow(
5497 &mut self,
5498 leader_id: impl Into<CollaboratorId>,
5499 window: &mut Window,
5500 cx: &mut Context<Self>,
5501 ) {
5502 let leader_id = leader_id.into();
5503
5504 if let CollaboratorId::PeerId(peer_id) = leader_id {
5505 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5506 return;
5507 };
5508 let Some(remote_participant) =
5509 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5510 else {
5511 return;
5512 };
5513
5514 let project = self.project.read(cx);
5515
5516 let other_project_id = match remote_participant.location {
5517 ParticipantLocation::External => None,
5518 ParticipantLocation::UnsharedProject => None,
5519 ParticipantLocation::SharedProject { project_id } => {
5520 if Some(project_id) == project.remote_id() {
5521 None
5522 } else {
5523 Some(project_id)
5524 }
5525 }
5526 };
5527
5528 // if they are active in another project, follow there.
5529 if let Some(project_id) = other_project_id {
5530 let app_state = self.app_state.clone();
5531 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5532 .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
5533 Some(format!("{error:#}"))
5534 });
5535 }
5536 }
5537
5538 // if you're already following, find the right pane and focus it.
5539 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5540 window.focus(&follower_state.pane().focus_handle(cx), cx);
5541
5542 return;
5543 }
5544
5545 // Otherwise, follow.
5546 if let Some(task) = self.start_following(leader_id, window, cx) {
5547 task.detach_and_log_err(cx)
5548 }
5549 }
5550
5551 pub fn unfollow(
5552 &mut self,
5553 leader_id: impl Into<CollaboratorId>,
5554 window: &mut Window,
5555 cx: &mut Context<Self>,
5556 ) -> Option<()> {
5557 cx.notify();
5558
5559 let leader_id = leader_id.into();
5560 let state = self.follower_states.remove(&leader_id)?;
5561 for (_, item) in state.items_by_leader_view_id {
5562 item.view.set_leader_id(None, window, cx);
5563 }
5564
5565 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5566 let project_id = self.project.read(cx).remote_id();
5567 let room_id = self.active_call()?.room_id(cx)?;
5568 self.app_state
5569 .client
5570 .send(proto::Unfollow {
5571 room_id,
5572 project_id,
5573 leader_id: Some(leader_peer_id),
5574 })
5575 .log_err();
5576 }
5577
5578 Some(())
5579 }
5580
5581 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5582 self.follower_states.contains_key(&id.into())
5583 }
5584
5585 fn active_item_path_changed(
5586 &mut self,
5587 focus_changed: bool,
5588 window: &mut Window,
5589 cx: &mut Context<Self>,
5590 ) {
5591 cx.emit(Event::ActiveItemChanged);
5592 let active_entry = self.active_project_path(cx);
5593 self.project.update(cx, |project, cx| {
5594 project.set_active_path(active_entry.clone(), cx)
5595 });
5596
5597 if focus_changed && let Some(project_path) = &active_entry {
5598 let git_store_entity = self.project.read(cx).git_store().clone();
5599 git_store_entity.update(cx, |git_store, cx| {
5600 git_store.set_active_repo_for_path(project_path, cx);
5601 });
5602 }
5603
5604 self.update_window_title(window, cx);
5605 }
5606
5607 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5608 let project = self.project().read(cx);
5609 let mut title = String::new();
5610
5611 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5612 let name = {
5613 let settings_location = SettingsLocation {
5614 worktree_id: worktree.read(cx).id(),
5615 path: RelPath::empty(),
5616 };
5617
5618 let settings = WorktreeSettings::get(Some(settings_location), cx);
5619 match &settings.project_name {
5620 Some(name) => name.as_str(),
5621 None => worktree.read(cx).root_name_str(),
5622 }
5623 };
5624 if i > 0 {
5625 title.push_str(", ");
5626 }
5627 title.push_str(name);
5628 }
5629
5630 if title.is_empty() {
5631 title = "empty project".to_string();
5632 }
5633
5634 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5635 let filename = path.path.file_name().or_else(|| {
5636 Some(
5637 project
5638 .worktree_for_id(path.worktree_id, cx)?
5639 .read(cx)
5640 .root_name_str(),
5641 )
5642 });
5643
5644 if let Some(filename) = filename {
5645 title.push_str(" — ");
5646 title.push_str(filename.as_ref());
5647 }
5648 }
5649
5650 if project.is_via_collab() {
5651 title.push_str(" ↙");
5652 } else if project.is_shared() {
5653 title.push_str(" ↗");
5654 }
5655
5656 if let Some(last_title) = self.last_window_title.as_ref()
5657 && &title == last_title
5658 {
5659 return;
5660 }
5661 window.set_window_title(&title);
5662 SystemWindowTabController::update_tab_title(
5663 cx,
5664 window.window_handle().window_id(),
5665 SharedString::from(&title),
5666 );
5667 self.last_window_title = Some(title);
5668 }
5669
5670 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5671 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5672 if is_edited != self.window_edited {
5673 self.window_edited = is_edited;
5674 window.set_window_edited(self.window_edited)
5675 }
5676 }
5677
5678 fn update_item_dirty_state(
5679 &mut self,
5680 item: &dyn ItemHandle,
5681 window: &mut Window,
5682 cx: &mut App,
5683 ) {
5684 let is_dirty = item.is_dirty(cx);
5685 let item_id = item.item_id();
5686 let was_dirty = self.dirty_items.contains_key(&item_id);
5687 if is_dirty == was_dirty {
5688 return;
5689 }
5690 if was_dirty {
5691 self.dirty_items.remove(&item_id);
5692 self.update_window_edited(window, cx);
5693 return;
5694 }
5695
5696 let workspace = self.weak_handle();
5697 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5698 return;
5699 };
5700 let on_release_callback = Box::new(move |cx: &mut App| {
5701 window_handle
5702 .update(cx, |_, window, cx| {
5703 workspace
5704 .update(cx, |workspace, cx| {
5705 workspace.dirty_items.remove(&item_id);
5706 workspace.update_window_edited(window, cx)
5707 })
5708 .ok();
5709 })
5710 .ok();
5711 });
5712
5713 let s = item.on_release(cx, on_release_callback);
5714 self.dirty_items.insert(item_id, s);
5715 self.update_window_edited(window, cx);
5716 }
5717
5718 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5719 if self.notifications.is_empty() {
5720 None
5721 } else {
5722 Some(
5723 div()
5724 .absolute()
5725 .right_3()
5726 .bottom_3()
5727 .w_112()
5728 .h_full()
5729 .flex()
5730 .flex_col()
5731 .justify_end()
5732 .gap_2()
5733 .children(
5734 self.notifications
5735 .iter()
5736 .map(|(_, notification)| notification.clone().into_any()),
5737 ),
5738 )
5739 }
5740 }
5741
5742 // RPC handlers
5743
5744 fn active_view_for_follower(
5745 &self,
5746 follower_project_id: Option<u64>,
5747 window: &mut Window,
5748 cx: &mut Context<Self>,
5749 ) -> Option<proto::View> {
5750 let (item, panel_id) = self.active_item_for_followers(window, cx);
5751 let item = item?;
5752 let leader_id = self
5753 .pane_for(&*item)
5754 .and_then(|pane| self.leader_for_pane(&pane));
5755 let leader_peer_id = match leader_id {
5756 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5757 Some(CollaboratorId::Agent) | None => None,
5758 };
5759
5760 let item_handle = item.to_followable_item_handle(cx)?;
5761 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5762 let variant = item_handle.to_state_proto(window, cx)?;
5763
5764 if item_handle.is_project_item(window, cx)
5765 && (follower_project_id.is_none()
5766 || follower_project_id != self.project.read(cx).remote_id())
5767 {
5768 return None;
5769 }
5770
5771 Some(proto::View {
5772 id: id.to_proto(),
5773 leader_id: leader_peer_id,
5774 variant: Some(variant),
5775 panel_id: panel_id.map(|id| id as i32),
5776 })
5777 }
5778
5779 fn handle_follow(
5780 &mut self,
5781 follower_project_id: Option<u64>,
5782 window: &mut Window,
5783 cx: &mut Context<Self>,
5784 ) -> proto::FollowResponse {
5785 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5786
5787 cx.notify();
5788 proto::FollowResponse {
5789 views: active_view.iter().cloned().collect(),
5790 active_view,
5791 }
5792 }
5793
5794 fn handle_update_followers(
5795 &mut self,
5796 leader_id: PeerId,
5797 message: proto::UpdateFollowers,
5798 _window: &mut Window,
5799 _cx: &mut Context<Self>,
5800 ) {
5801 self.leader_updates_tx
5802 .unbounded_send((leader_id, message))
5803 .ok();
5804 }
5805
5806 async fn process_leader_update(
5807 this: &WeakEntity<Self>,
5808 leader_id: PeerId,
5809 update: proto::UpdateFollowers,
5810 cx: &mut AsyncWindowContext,
5811 ) -> Result<()> {
5812 match update.variant.context("invalid update")? {
5813 proto::update_followers::Variant::CreateView(view) => {
5814 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5815 let should_add_view = this.update(cx, |this, _| {
5816 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5817 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5818 } else {
5819 anyhow::Ok(false)
5820 }
5821 })??;
5822
5823 if should_add_view {
5824 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5825 }
5826 }
5827 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5828 let should_add_view = this.update(cx, |this, _| {
5829 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5830 state.active_view_id = update_active_view
5831 .view
5832 .as_ref()
5833 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5834
5835 if state.active_view_id.is_some_and(|view_id| {
5836 !state.items_by_leader_view_id.contains_key(&view_id)
5837 }) {
5838 anyhow::Ok(true)
5839 } else {
5840 anyhow::Ok(false)
5841 }
5842 } else {
5843 anyhow::Ok(false)
5844 }
5845 })??;
5846
5847 if should_add_view && let Some(view) = update_active_view.view {
5848 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5849 }
5850 }
5851 proto::update_followers::Variant::UpdateView(update_view) => {
5852 let variant = update_view.variant.context("missing update view variant")?;
5853 let id = update_view.id.context("missing update view id")?;
5854 let mut tasks = Vec::new();
5855 this.update_in(cx, |this, window, cx| {
5856 let project = this.project.clone();
5857 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5858 let view_id = ViewId::from_proto(id.clone())?;
5859 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5860 tasks.push(item.view.apply_update_proto(
5861 &project,
5862 variant.clone(),
5863 window,
5864 cx,
5865 ));
5866 }
5867 }
5868 anyhow::Ok(())
5869 })??;
5870 try_join_all(tasks).await.log_err();
5871 }
5872 }
5873 this.update_in(cx, |this, window, cx| {
5874 this.leader_updated(leader_id, window, cx)
5875 })?;
5876 Ok(())
5877 }
5878
5879 async fn add_view_from_leader(
5880 this: WeakEntity<Self>,
5881 leader_id: PeerId,
5882 view: &proto::View,
5883 cx: &mut AsyncWindowContext,
5884 ) -> Result<()> {
5885 let this = this.upgrade().context("workspace dropped")?;
5886
5887 let Some(id) = view.id.clone() else {
5888 anyhow::bail!("no id for view");
5889 };
5890 let id = ViewId::from_proto(id)?;
5891 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5892
5893 let pane = this.update(cx, |this, _cx| {
5894 let state = this
5895 .follower_states
5896 .get(&leader_id.into())
5897 .context("stopped following")?;
5898 anyhow::Ok(state.pane().clone())
5899 })?;
5900 let existing_item = pane.update_in(cx, |pane, window, cx| {
5901 let client = this.read(cx).client().clone();
5902 pane.items().find_map(|item| {
5903 let item = item.to_followable_item_handle(cx)?;
5904 if item.remote_id(&client, window, cx) == Some(id) {
5905 Some(item)
5906 } else {
5907 None
5908 }
5909 })
5910 })?;
5911 let item = if let Some(existing_item) = existing_item {
5912 existing_item
5913 } else {
5914 let variant = view.variant.clone();
5915 anyhow::ensure!(variant.is_some(), "missing view variant");
5916
5917 let task = cx.update(|window, cx| {
5918 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5919 })?;
5920
5921 let Some(task) = task else {
5922 anyhow::bail!(
5923 "failed to construct view from leader (maybe from a different version of zed?)"
5924 );
5925 };
5926
5927 let mut new_item = task.await?;
5928 pane.update_in(cx, |pane, window, cx| {
5929 let mut item_to_remove = None;
5930 for (ix, item) in pane.items().enumerate() {
5931 if let Some(item) = item.to_followable_item_handle(cx) {
5932 match new_item.dedup(item.as_ref(), window, cx) {
5933 Some(item::Dedup::KeepExisting) => {
5934 new_item =
5935 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5936 break;
5937 }
5938 Some(item::Dedup::ReplaceExisting) => {
5939 item_to_remove = Some((ix, item.item_id()));
5940 break;
5941 }
5942 None => {}
5943 }
5944 }
5945 }
5946
5947 if let Some((ix, id)) = item_to_remove {
5948 pane.remove_item(id, false, false, window, cx);
5949 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5950 }
5951 })?;
5952
5953 new_item
5954 };
5955
5956 this.update_in(cx, |this, window, cx| {
5957 let state = this.follower_states.get_mut(&leader_id.into())?;
5958 item.set_leader_id(Some(leader_id.into()), window, cx);
5959 state.items_by_leader_view_id.insert(
5960 id,
5961 FollowerView {
5962 view: item,
5963 location: panel_id,
5964 },
5965 );
5966
5967 Some(())
5968 })
5969 .context("no follower state")?;
5970
5971 Ok(())
5972 }
5973
5974 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5975 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5976 return;
5977 };
5978
5979 if let Some(agent_location) = self.project.read(cx).agent_location() {
5980 let buffer_entity_id = agent_location.buffer.entity_id();
5981 let view_id = ViewId {
5982 creator: CollaboratorId::Agent,
5983 id: buffer_entity_id.as_u64(),
5984 };
5985 follower_state.active_view_id = Some(view_id);
5986
5987 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5988 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5989 hash_map::Entry::Vacant(entry) => {
5990 let existing_view =
5991 follower_state
5992 .center_pane
5993 .read(cx)
5994 .items()
5995 .find_map(|item| {
5996 let item = item.to_followable_item_handle(cx)?;
5997 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5998 && item.project_item_model_ids(cx).as_slice()
5999 == [buffer_entity_id]
6000 {
6001 Some(item)
6002 } else {
6003 None
6004 }
6005 });
6006 let view = existing_view.or_else(|| {
6007 agent_location.buffer.upgrade().and_then(|buffer| {
6008 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
6009 registry.build_item(buffer, self.project.clone(), None, window, cx)
6010 })?
6011 .to_followable_item_handle(cx)
6012 })
6013 });
6014
6015 view.map(|view| {
6016 entry.insert(FollowerView {
6017 view,
6018 location: None,
6019 })
6020 })
6021 }
6022 };
6023
6024 if let Some(item) = item {
6025 item.view
6026 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
6027 item.view
6028 .update_agent_location(agent_location.position, window, cx);
6029 }
6030 } else {
6031 follower_state.active_view_id = None;
6032 }
6033
6034 self.leader_updated(CollaboratorId::Agent, window, cx);
6035 }
6036
6037 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
6038 let mut is_project_item = true;
6039 let mut update = proto::UpdateActiveView::default();
6040 if window.is_window_active() {
6041 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
6042
6043 if let Some(item) = active_item
6044 && item.item_focus_handle(cx).contains_focused(window, cx)
6045 {
6046 let leader_id = self
6047 .pane_for(&*item)
6048 .and_then(|pane| self.leader_for_pane(&pane));
6049 let leader_peer_id = match leader_id {
6050 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
6051 Some(CollaboratorId::Agent) | None => None,
6052 };
6053
6054 if let Some(item) = item.to_followable_item_handle(cx) {
6055 let id = item
6056 .remote_id(&self.app_state.client, window, cx)
6057 .map(|id| id.to_proto());
6058
6059 if let Some(id) = id
6060 && let Some(variant) = item.to_state_proto(window, cx)
6061 {
6062 let view = Some(proto::View {
6063 id,
6064 leader_id: leader_peer_id,
6065 variant: Some(variant),
6066 panel_id: panel_id.map(|id| id as i32),
6067 });
6068
6069 is_project_item = item.is_project_item(window, cx);
6070 update = proto::UpdateActiveView { view };
6071 };
6072 }
6073 }
6074 }
6075
6076 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
6077 if active_view_id != self.last_active_view_id.as_ref() {
6078 self.last_active_view_id = active_view_id.cloned();
6079 self.update_followers(
6080 is_project_item,
6081 proto::update_followers::Variant::UpdateActiveView(update),
6082 window,
6083 cx,
6084 );
6085 }
6086 }
6087
6088 fn active_item_for_followers(
6089 &self,
6090 window: &mut Window,
6091 cx: &mut App,
6092 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
6093 let mut active_item = None;
6094 let mut panel_id = None;
6095 for dock in self.all_docks() {
6096 if dock.focus_handle(cx).contains_focused(window, cx)
6097 && let Some(panel) = dock.read(cx).active_panel()
6098 && let Some(pane) = panel.pane(cx)
6099 && let Some(item) = pane.read(cx).active_item()
6100 {
6101 active_item = Some(item);
6102 panel_id = panel.remote_id();
6103 break;
6104 }
6105 }
6106
6107 if active_item.is_none() {
6108 active_item = self.active_pane().read(cx).active_item();
6109 }
6110 (active_item, panel_id)
6111 }
6112
6113 fn update_followers(
6114 &self,
6115 project_only: bool,
6116 update: proto::update_followers::Variant,
6117 _: &mut Window,
6118 cx: &mut App,
6119 ) -> Option<()> {
6120 // If this update only applies to for followers in the current project,
6121 // then skip it unless this project is shared. If it applies to all
6122 // followers, regardless of project, then set `project_id` to none,
6123 // indicating that it goes to all followers.
6124 let project_id = if project_only {
6125 Some(self.project.read(cx).remote_id()?)
6126 } else {
6127 None
6128 };
6129 self.app_state().workspace_store.update(cx, |store, cx| {
6130 store.update_followers(project_id, update, cx)
6131 })
6132 }
6133
6134 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
6135 self.follower_states.iter().find_map(|(leader_id, state)| {
6136 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
6137 Some(*leader_id)
6138 } else {
6139 None
6140 }
6141 })
6142 }
6143
6144 fn leader_updated(
6145 &mut self,
6146 leader_id: impl Into<CollaboratorId>,
6147 window: &mut Window,
6148 cx: &mut Context<Self>,
6149 ) -> Option<Box<dyn ItemHandle>> {
6150 cx.notify();
6151
6152 let leader_id = leader_id.into();
6153 let (panel_id, item) = match leader_id {
6154 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
6155 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
6156 };
6157
6158 let state = self.follower_states.get(&leader_id)?;
6159 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
6160 let pane;
6161 if let Some(panel_id) = panel_id {
6162 pane = self
6163 .activate_panel_for_proto_id(panel_id, window, cx)?
6164 .pane(cx)?;
6165 let state = self.follower_states.get_mut(&leader_id)?;
6166 state.dock_pane = Some(pane.clone());
6167 } else {
6168 pane = state.center_pane.clone();
6169 let state = self.follower_states.get_mut(&leader_id)?;
6170 if let Some(dock_pane) = state.dock_pane.take() {
6171 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
6172 }
6173 }
6174
6175 pane.update(cx, |pane, cx| {
6176 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
6177 if let Some(index) = pane.index_for_item(item.as_ref()) {
6178 pane.activate_item(index, false, false, window, cx);
6179 } else {
6180 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
6181 }
6182
6183 if focus_active_item {
6184 pane.focus_active_item(window, cx)
6185 }
6186 });
6187
6188 Some(item)
6189 }
6190
6191 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
6192 let state = self.follower_states.get(&CollaboratorId::Agent)?;
6193 let active_view_id = state.active_view_id?;
6194 Some(
6195 state
6196 .items_by_leader_view_id
6197 .get(&active_view_id)?
6198 .view
6199 .boxed_clone(),
6200 )
6201 }
6202
6203 fn active_item_for_peer(
6204 &self,
6205 peer_id: PeerId,
6206 window: &mut Window,
6207 cx: &mut Context<Self>,
6208 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
6209 let call = self.active_call()?;
6210 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
6211 let leader_in_this_app;
6212 let leader_in_this_project;
6213 match participant.location {
6214 ParticipantLocation::SharedProject { project_id } => {
6215 leader_in_this_app = true;
6216 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
6217 }
6218 ParticipantLocation::UnsharedProject => {
6219 leader_in_this_app = true;
6220 leader_in_this_project = false;
6221 }
6222 ParticipantLocation::External => {
6223 leader_in_this_app = false;
6224 leader_in_this_project = false;
6225 }
6226 };
6227 let state = self.follower_states.get(&peer_id.into())?;
6228 let mut item_to_activate = None;
6229 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
6230 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
6231 && (leader_in_this_project || !item.view.is_project_item(window, cx))
6232 {
6233 item_to_activate = Some((item.location, item.view.boxed_clone()));
6234 }
6235 } else if let Some(shared_screen) =
6236 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
6237 {
6238 item_to_activate = Some((None, Box::new(shared_screen)));
6239 }
6240 item_to_activate
6241 }
6242
6243 fn shared_screen_for_peer(
6244 &self,
6245 peer_id: PeerId,
6246 pane: &Entity<Pane>,
6247 window: &mut Window,
6248 cx: &mut App,
6249 ) -> Option<Entity<SharedScreen>> {
6250 self.active_call()?
6251 .create_shared_screen(peer_id, pane, window, cx)
6252 }
6253
6254 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6255 if window.is_window_active() {
6256 self.update_active_view_for_followers(window, cx);
6257
6258 if let Some(database_id) = self.database_id {
6259 let db = WorkspaceDb::global(cx);
6260 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6261 .detach();
6262 }
6263 } else {
6264 for pane in &self.panes {
6265 pane.update(cx, |pane, cx| {
6266 if let Some(item) = pane.active_item() {
6267 item.workspace_deactivated(window, cx);
6268 }
6269 for item in pane.items() {
6270 if matches!(
6271 item.workspace_settings(cx).autosave,
6272 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6273 ) {
6274 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6275 .detach_and_log_err(cx);
6276 }
6277 }
6278 });
6279 }
6280 }
6281 }
6282
6283 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6284 self.active_call.as_ref().map(|(call, _)| &*call.0)
6285 }
6286
6287 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6288 self.active_call.as_ref().map(|(call, _)| call.clone())
6289 }
6290
6291 fn on_active_call_event(
6292 &mut self,
6293 event: &ActiveCallEvent,
6294 window: &mut Window,
6295 cx: &mut Context<Self>,
6296 ) {
6297 match event {
6298 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6299 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6300 self.leader_updated(participant_id, window, cx);
6301 }
6302 }
6303 }
6304
6305 pub fn database_id(&self) -> Option<WorkspaceId> {
6306 self.database_id
6307 }
6308
6309 #[cfg(any(test, feature = "test-support"))]
6310 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6311 self.database_id = Some(id);
6312 }
6313
6314 pub fn session_id(&self) -> Option<String> {
6315 self.session_id.clone()
6316 }
6317
6318 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6319 let Some(display) = window.display(cx) else {
6320 return Task::ready(());
6321 };
6322 let Ok(display_uuid) = display.uuid() else {
6323 return Task::ready(());
6324 };
6325
6326 let window_bounds = window.inner_window_bounds();
6327 let database_id = self.database_id;
6328 let has_paths = !self.root_paths(cx).is_empty();
6329 let db = WorkspaceDb::global(cx);
6330 let kvp = db::kvp::KeyValueStore::global(cx);
6331
6332 cx.background_executor().spawn(async move {
6333 if !has_paths {
6334 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6335 .await
6336 .log_err();
6337 }
6338 if let Some(database_id) = database_id {
6339 db.set_window_open_status(
6340 database_id,
6341 SerializedWindowBounds(window_bounds),
6342 display_uuid,
6343 )
6344 .await
6345 .log_err();
6346 } else {
6347 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6348 .await
6349 .log_err();
6350 }
6351 })
6352 }
6353
6354 /// Bypass the 200ms serialization throttle and write workspace state to
6355 /// the DB immediately. Returns a task the caller can await to ensure the
6356 /// write completes. Used by the quit handler so the most recent state
6357 /// isn't lost to a pending throttle timer when the process exits.
6358 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6359 self._schedule_serialize_workspace.take();
6360 self._serialize_workspace_task.take();
6361 self.bounds_save_task_queued.take();
6362
6363 let bounds_task = self.save_window_bounds(window, cx);
6364 let serialize_task = self.serialize_workspace_internal(window, cx);
6365 cx.spawn(async move |_| {
6366 bounds_task.await;
6367 serialize_task.await;
6368 })
6369 }
6370
6371 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6372 let project = self.project().read(cx);
6373 project
6374 .visible_worktrees(cx)
6375 .map(|worktree| worktree.read(cx).abs_path())
6376 .collect::<Vec<_>>()
6377 }
6378
6379 pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
6380 let project = self.project().read(cx);
6381 let repositories = project.repositories(cx);
6382 let paths = project
6383 .visible_worktrees(cx)
6384 .map(|worktree| {
6385 let worktree = worktree.read(cx);
6386 let main_worktree_path = repositories.values().find_map(|repo| {
6387 let repo = repo.read(cx);
6388 if repo.work_directory_abs_path == worktree.abs_path() {
6389 Some(repo.original_repo_abs_path.clone())
6390 } else {
6391 None
6392 }
6393 });
6394 main_worktree_path.unwrap_or_else(|| worktree.abs_path())
6395 })
6396 .collect::<Vec<_>>();
6397 ProjectGroupKey {
6398 host: project.remote_connection_options(cx),
6399 main_worktree_paths: PathList::new(&paths),
6400 }
6401 }
6402
6403 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6404 match member {
6405 Member::Axis(PaneAxis { members, .. }) => {
6406 for child in members.iter() {
6407 self.remove_panes(child.clone(), window, cx)
6408 }
6409 }
6410 Member::Pane(pane) => {
6411 self.force_remove_pane(&pane, &None, window, cx);
6412 }
6413 }
6414 }
6415
6416 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6417 self.session_id.take();
6418 self.serialize_workspace_internal(window, cx)
6419 }
6420
6421 fn force_remove_pane(
6422 &mut self,
6423 pane: &Entity<Pane>,
6424 focus_on: &Option<Entity<Pane>>,
6425 window: &mut Window,
6426 cx: &mut Context<Workspace>,
6427 ) {
6428 self.panes.retain(|p| p != pane);
6429 if let Some(focus_on) = focus_on {
6430 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6431 } else if self.active_pane() == pane {
6432 self.panes
6433 .last()
6434 .unwrap()
6435 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6436 }
6437 if self.last_active_center_pane == Some(pane.downgrade()) {
6438 self.last_active_center_pane = None;
6439 }
6440 cx.notify();
6441 }
6442
6443 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6444 if self._schedule_serialize_workspace.is_none() {
6445 self._schedule_serialize_workspace =
6446 Some(cx.spawn_in(window, async move |this, cx| {
6447 cx.background_executor()
6448 .timer(SERIALIZATION_THROTTLE_TIME)
6449 .await;
6450 this.update_in(cx, |this, window, cx| {
6451 this._serialize_workspace_task =
6452 Some(this.serialize_workspace_internal(window, cx));
6453 this._schedule_serialize_workspace.take();
6454 })
6455 .log_err();
6456 }));
6457 }
6458 }
6459
6460 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6461 let Some(database_id) = self.database_id() else {
6462 return Task::ready(());
6463 };
6464
6465 fn serialize_pane_handle(
6466 pane_handle: &Entity<Pane>,
6467 window: &mut Window,
6468 cx: &mut App,
6469 ) -> SerializedPane {
6470 let (items, active, pinned_count) = {
6471 let pane = pane_handle.read(cx);
6472 let active_item_id = pane.active_item().map(|item| item.item_id());
6473 (
6474 pane.items()
6475 .filter_map(|handle| {
6476 let handle = handle.to_serializable_item_handle(cx)?;
6477
6478 Some(SerializedItem {
6479 kind: Arc::from(handle.serialized_item_kind()),
6480 item_id: handle.item_id().as_u64(),
6481 active: Some(handle.item_id()) == active_item_id,
6482 preview: pane.is_active_preview_item(handle.item_id()),
6483 })
6484 })
6485 .collect::<Vec<_>>(),
6486 pane.has_focus(window, cx),
6487 pane.pinned_count(),
6488 )
6489 };
6490
6491 SerializedPane::new(items, active, pinned_count)
6492 }
6493
6494 fn build_serialized_pane_group(
6495 pane_group: &Member,
6496 window: &mut Window,
6497 cx: &mut App,
6498 ) -> SerializedPaneGroup {
6499 match pane_group {
6500 Member::Axis(PaneAxis {
6501 axis,
6502 members,
6503 flexes,
6504 bounding_boxes: _,
6505 }) => SerializedPaneGroup::Group {
6506 axis: SerializedAxis(*axis),
6507 children: members
6508 .iter()
6509 .map(|member| build_serialized_pane_group(member, window, cx))
6510 .collect::<Vec<_>>(),
6511 flexes: Some(flexes.lock().clone()),
6512 },
6513 Member::Pane(pane_handle) => {
6514 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6515 }
6516 }
6517 }
6518
6519 fn build_serialized_docks(
6520 this: &Workspace,
6521 window: &mut Window,
6522 cx: &mut App,
6523 ) -> DockStructure {
6524 this.capture_dock_state(window, cx)
6525 }
6526
6527 match self.workspace_location(cx) {
6528 WorkspaceLocation::Location(location, paths) => {
6529 let breakpoints = self.project.update(cx, |project, cx| {
6530 project
6531 .breakpoint_store()
6532 .read(cx)
6533 .all_source_breakpoints(cx)
6534 });
6535 let user_toolchains = self
6536 .project
6537 .read(cx)
6538 .user_toolchains(cx)
6539 .unwrap_or_default();
6540
6541 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6542 let docks = build_serialized_docks(self, window, cx);
6543 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6544
6545 let serialized_workspace = SerializedWorkspace {
6546 id: database_id,
6547 location,
6548 paths,
6549 center_group,
6550 window_bounds,
6551 display: Default::default(),
6552 docks,
6553 centered_layout: self.centered_layout,
6554 session_id: self.session_id.clone(),
6555 breakpoints,
6556 window_id: Some(window.window_handle().window_id().as_u64()),
6557 user_toolchains,
6558 };
6559
6560 let db = WorkspaceDb::global(cx);
6561 window.spawn(cx, async move |_| {
6562 db.save_workspace(serialized_workspace).await;
6563 })
6564 }
6565 WorkspaceLocation::DetachFromSession => {
6566 let window_bounds = SerializedWindowBounds(window.window_bounds());
6567 let display = window.display(cx).and_then(|d| d.uuid().ok());
6568 // Save dock state for empty local workspaces
6569 let docks = build_serialized_docks(self, window, cx);
6570 let db = WorkspaceDb::global(cx);
6571 let kvp = db::kvp::KeyValueStore::global(cx);
6572 window.spawn(cx, async move |_| {
6573 db.set_window_open_status(
6574 database_id,
6575 window_bounds,
6576 display.unwrap_or_default(),
6577 )
6578 .await
6579 .log_err();
6580 db.set_session_id(database_id, None).await.log_err();
6581 persistence::write_default_dock_state(&kvp, docks)
6582 .await
6583 .log_err();
6584 })
6585 }
6586 WorkspaceLocation::None => {
6587 // Save dock state for empty non-local workspaces
6588 let docks = build_serialized_docks(self, window, cx);
6589 let kvp = db::kvp::KeyValueStore::global(cx);
6590 window.spawn(cx, async move |_| {
6591 persistence::write_default_dock_state(&kvp, docks)
6592 .await
6593 .log_err();
6594 })
6595 }
6596 }
6597 }
6598
6599 fn has_any_items_open(&self, cx: &App) -> bool {
6600 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6601 }
6602
6603 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6604 let paths = PathList::new(&self.root_paths(cx));
6605 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6606 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6607 } else if self.project.read(cx).is_local() {
6608 if !paths.is_empty() || self.has_any_items_open(cx) {
6609 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6610 } else {
6611 WorkspaceLocation::DetachFromSession
6612 }
6613 } else {
6614 WorkspaceLocation::None
6615 }
6616 }
6617
6618 fn update_history(&self, cx: &mut App) {
6619 let Some(id) = self.database_id() else {
6620 return;
6621 };
6622 if !self.project.read(cx).is_local() {
6623 return;
6624 }
6625 if let Some(manager) = HistoryManager::global(cx) {
6626 let paths = PathList::new(&self.root_paths(cx));
6627 manager.update(cx, |this, cx| {
6628 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6629 });
6630 }
6631 }
6632
6633 async fn serialize_items(
6634 this: &WeakEntity<Self>,
6635 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6636 cx: &mut AsyncWindowContext,
6637 ) -> Result<()> {
6638 const CHUNK_SIZE: usize = 200;
6639
6640 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6641
6642 while let Some(items_received) = serializable_items.next().await {
6643 let unique_items =
6644 items_received
6645 .into_iter()
6646 .fold(HashMap::default(), |mut acc, item| {
6647 acc.entry(item.item_id()).or_insert(item);
6648 acc
6649 });
6650
6651 // We use into_iter() here so that the references to the items are moved into
6652 // the tasks and not kept alive while we're sleeping.
6653 for (_, item) in unique_items.into_iter() {
6654 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6655 item.serialize(workspace, false, window, cx)
6656 }) {
6657 cx.background_spawn(async move { task.await.log_err() })
6658 .detach();
6659 }
6660 }
6661
6662 cx.background_executor()
6663 .timer(SERIALIZATION_THROTTLE_TIME)
6664 .await;
6665 }
6666
6667 Ok(())
6668 }
6669
6670 pub(crate) fn enqueue_item_serialization(
6671 &mut self,
6672 item: Box<dyn SerializableItemHandle>,
6673 ) -> Result<()> {
6674 self.serializable_items_tx
6675 .unbounded_send(item)
6676 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6677 }
6678
6679 pub(crate) fn load_workspace(
6680 serialized_workspace: SerializedWorkspace,
6681 paths_to_open: Vec<Option<ProjectPath>>,
6682 window: &mut Window,
6683 cx: &mut Context<Workspace>,
6684 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6685 cx.spawn_in(window, async move |workspace, cx| {
6686 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6687
6688 let mut center_group = None;
6689 let mut center_items = None;
6690
6691 // Traverse the splits tree and add to things
6692 if let Some((group, active_pane, items)) = serialized_workspace
6693 .center_group
6694 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6695 .await
6696 {
6697 center_items = Some(items);
6698 center_group = Some((group, active_pane))
6699 }
6700
6701 let mut items_by_project_path = HashMap::default();
6702 let mut item_ids_by_kind = HashMap::default();
6703 let mut all_deserialized_items = Vec::default();
6704 cx.update(|_, cx| {
6705 for item in center_items.unwrap_or_default().into_iter().flatten() {
6706 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6707 item_ids_by_kind
6708 .entry(serializable_item_handle.serialized_item_kind())
6709 .or_insert(Vec::new())
6710 .push(item.item_id().as_u64() as ItemId);
6711 }
6712
6713 if let Some(project_path) = item.project_path(cx) {
6714 items_by_project_path.insert(project_path, item.clone());
6715 }
6716 all_deserialized_items.push(item);
6717 }
6718 })?;
6719
6720 let opened_items = paths_to_open
6721 .into_iter()
6722 .map(|path_to_open| {
6723 path_to_open
6724 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6725 })
6726 .collect::<Vec<_>>();
6727
6728 // Remove old panes from workspace panes list
6729 workspace.update_in(cx, |workspace, window, cx| {
6730 if let Some((center_group, active_pane)) = center_group {
6731 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6732
6733 // Swap workspace center group
6734 workspace.center = PaneGroup::with_root(center_group);
6735 workspace.center.set_is_center(true);
6736 workspace.center.mark_positions(cx);
6737
6738 if let Some(active_pane) = active_pane {
6739 workspace.set_active_pane(&active_pane, window, cx);
6740 cx.focus_self(window);
6741 } else {
6742 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6743 }
6744 }
6745
6746 let docks = serialized_workspace.docks;
6747
6748 for (dock, serialized_dock) in [
6749 (&mut workspace.right_dock, docks.right),
6750 (&mut workspace.left_dock, docks.left),
6751 (&mut workspace.bottom_dock, docks.bottom),
6752 ]
6753 .iter_mut()
6754 {
6755 dock.update(cx, |dock, cx| {
6756 dock.serialized_dock = Some(serialized_dock.clone());
6757 dock.restore_state(window, cx);
6758 });
6759 }
6760
6761 cx.notify();
6762 })?;
6763
6764 let _ = project
6765 .update(cx, |project, cx| {
6766 project
6767 .breakpoint_store()
6768 .update(cx, |breakpoint_store, cx| {
6769 breakpoint_store
6770 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6771 })
6772 })
6773 .await;
6774
6775 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6776 // after loading the items, we might have different items and in order to avoid
6777 // the database filling up, we delete items that haven't been loaded now.
6778 //
6779 // The items that have been loaded, have been saved after they've been added to the workspace.
6780 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6781 item_ids_by_kind
6782 .into_iter()
6783 .map(|(item_kind, loaded_items)| {
6784 SerializableItemRegistry::cleanup(
6785 item_kind,
6786 serialized_workspace.id,
6787 loaded_items,
6788 window,
6789 cx,
6790 )
6791 .log_err()
6792 })
6793 .collect::<Vec<_>>()
6794 })?;
6795
6796 futures::future::join_all(clean_up_tasks).await;
6797
6798 workspace
6799 .update_in(cx, |workspace, window, cx| {
6800 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6801 workspace.serialize_workspace_internal(window, cx).detach();
6802
6803 // Ensure that we mark the window as edited if we did load dirty items
6804 workspace.update_window_edited(window, cx);
6805 })
6806 .ok();
6807
6808 Ok(opened_items)
6809 })
6810 }
6811
6812 pub fn key_context(&self, cx: &App) -> KeyContext {
6813 let mut context = KeyContext::new_with_defaults();
6814 context.add("Workspace");
6815 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6816 if let Some(status) = self
6817 .debugger_provider
6818 .as_ref()
6819 .and_then(|provider| provider.active_thread_state(cx))
6820 {
6821 match status {
6822 ThreadStatus::Running | ThreadStatus::Stepping => {
6823 context.add("debugger_running");
6824 }
6825 ThreadStatus::Stopped => context.add("debugger_stopped"),
6826 ThreadStatus::Exited | ThreadStatus::Ended => {}
6827 }
6828 }
6829
6830 if self.left_dock.read(cx).is_open() {
6831 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6832 context.set("left_dock", active_panel.panel_key());
6833 }
6834 }
6835
6836 if self.right_dock.read(cx).is_open() {
6837 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6838 context.set("right_dock", active_panel.panel_key());
6839 }
6840 }
6841
6842 if self.bottom_dock.read(cx).is_open() {
6843 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6844 context.set("bottom_dock", active_panel.panel_key());
6845 }
6846 }
6847
6848 context
6849 }
6850
6851 /// Multiworkspace uses this to add workspace action handling to itself
6852 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6853 self.add_workspace_actions_listeners(div, window, cx)
6854 .on_action(cx.listener(
6855 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6856 for action in &action_sequence.0 {
6857 window.dispatch_action(action.boxed_clone(), cx);
6858 }
6859 },
6860 ))
6861 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6862 .on_action(cx.listener(Self::close_all_items_and_panes))
6863 .on_action(cx.listener(Self::close_item_in_all_panes))
6864 .on_action(cx.listener(Self::save_all))
6865 .on_action(cx.listener(Self::send_keystrokes))
6866 .on_action(cx.listener(Self::add_folder_to_project))
6867 .on_action(cx.listener(Self::follow_next_collaborator))
6868 .on_action(cx.listener(Self::activate_pane_at_index))
6869 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6870 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6871 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6872 .on_action(cx.listener(Self::toggle_theme_mode))
6873 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6874 let pane = workspace.active_pane().clone();
6875 workspace.unfollow_in_pane(&pane, window, cx);
6876 }))
6877 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6878 workspace
6879 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6880 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6881 }))
6882 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6883 workspace
6884 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6885 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6886 }))
6887 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6888 workspace
6889 .save_active_item(SaveIntent::SaveAs, window, cx)
6890 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6891 }))
6892 .on_action(
6893 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6894 workspace.activate_previous_pane(window, cx)
6895 }),
6896 )
6897 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6898 workspace.activate_next_pane(window, cx)
6899 }))
6900 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6901 workspace.activate_last_pane(window, cx)
6902 }))
6903 .on_action(
6904 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6905 workspace.activate_next_window(cx)
6906 }),
6907 )
6908 .on_action(
6909 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6910 workspace.activate_previous_window(cx)
6911 }),
6912 )
6913 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6914 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6915 }))
6916 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6917 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6918 }))
6919 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6920 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6921 }))
6922 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6923 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6924 }))
6925 .on_action(cx.listener(
6926 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6927 workspace.move_item_to_pane_in_direction(action, window, cx)
6928 },
6929 ))
6930 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6931 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6932 }))
6933 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6934 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6935 }))
6936 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6937 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6938 }))
6939 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6940 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6941 }))
6942 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6943 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6944 SplitDirection::Down,
6945 SplitDirection::Up,
6946 SplitDirection::Right,
6947 SplitDirection::Left,
6948 ];
6949 for dir in DIRECTION_PRIORITY {
6950 if workspace.find_pane_in_direction(dir, cx).is_some() {
6951 workspace.swap_pane_in_direction(dir, cx);
6952 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6953 break;
6954 }
6955 }
6956 }))
6957 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6958 workspace.move_pane_to_border(SplitDirection::Left, cx)
6959 }))
6960 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6961 workspace.move_pane_to_border(SplitDirection::Right, cx)
6962 }))
6963 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6964 workspace.move_pane_to_border(SplitDirection::Up, cx)
6965 }))
6966 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6967 workspace.move_pane_to_border(SplitDirection::Down, cx)
6968 }))
6969 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6970 this.toggle_dock(DockPosition::Left, window, cx);
6971 }))
6972 .on_action(cx.listener(
6973 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6974 workspace.toggle_dock(DockPosition::Right, window, cx);
6975 },
6976 ))
6977 .on_action(cx.listener(
6978 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6979 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6980 },
6981 ))
6982 .on_action(cx.listener(
6983 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6984 if !workspace.close_active_dock(window, cx) {
6985 cx.propagate();
6986 }
6987 },
6988 ))
6989 .on_action(
6990 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6991 workspace.close_all_docks(window, cx);
6992 }),
6993 )
6994 .on_action(cx.listener(Self::toggle_all_docks))
6995 .on_action(cx.listener(
6996 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6997 workspace.clear_all_notifications(cx);
6998 },
6999 ))
7000 .on_action(cx.listener(
7001 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
7002 workspace.clear_navigation_history(window, cx);
7003 },
7004 ))
7005 .on_action(cx.listener(
7006 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
7007 if let Some((notification_id, _)) = workspace.notifications.pop() {
7008 workspace.suppress_notification(¬ification_id, cx);
7009 }
7010 },
7011 ))
7012 .on_action(cx.listener(
7013 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
7014 workspace.show_worktree_trust_security_modal(true, window, cx);
7015 },
7016 ))
7017 .on_action(
7018 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
7019 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
7020 trusted_worktrees.update(cx, |trusted_worktrees, _| {
7021 trusted_worktrees.clear_trusted_paths()
7022 });
7023 let db = WorkspaceDb::global(cx);
7024 cx.spawn(async move |_, cx| {
7025 if db.clear_trusted_worktrees().await.log_err().is_some() {
7026 cx.update(|cx| reload(cx));
7027 }
7028 })
7029 .detach();
7030 }
7031 }),
7032 )
7033 .on_action(cx.listener(
7034 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
7035 workspace.reopen_closed_item(window, cx).detach();
7036 },
7037 ))
7038 .on_action(cx.listener(
7039 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
7040 for dock in workspace.all_docks() {
7041 if dock.focus_handle(cx).contains_focused(window, cx) {
7042 let panel = dock.read(cx).active_panel().cloned();
7043 if let Some(panel) = panel {
7044 dock.update(cx, |dock, cx| {
7045 dock.set_panel_size_state(
7046 panel.as_ref(),
7047 dock::PanelSizeState::default(),
7048 cx,
7049 );
7050 });
7051 }
7052 return;
7053 }
7054 }
7055 },
7056 ))
7057 .on_action(cx.listener(
7058 |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
7059 for dock in workspace.all_docks() {
7060 let panel = dock.read(cx).visible_panel().cloned();
7061 if let Some(panel) = panel {
7062 dock.update(cx, |dock, cx| {
7063 dock.set_panel_size_state(
7064 panel.as_ref(),
7065 dock::PanelSizeState::default(),
7066 cx,
7067 );
7068 });
7069 }
7070 }
7071 },
7072 ))
7073 .on_action(cx.listener(
7074 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
7075 adjust_active_dock_size_by_px(
7076 px_with_ui_font_fallback(act.px, cx),
7077 workspace,
7078 window,
7079 cx,
7080 );
7081 },
7082 ))
7083 .on_action(cx.listener(
7084 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
7085 adjust_active_dock_size_by_px(
7086 px_with_ui_font_fallback(act.px, cx) * -1.,
7087 workspace,
7088 window,
7089 cx,
7090 );
7091 },
7092 ))
7093 .on_action(cx.listener(
7094 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
7095 adjust_open_docks_size_by_px(
7096 px_with_ui_font_fallback(act.px, cx),
7097 workspace,
7098 window,
7099 cx,
7100 );
7101 },
7102 ))
7103 .on_action(cx.listener(
7104 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
7105 adjust_open_docks_size_by_px(
7106 px_with_ui_font_fallback(act.px, cx) * -1.,
7107 workspace,
7108 window,
7109 cx,
7110 );
7111 },
7112 ))
7113 .on_action(cx.listener(Workspace::toggle_centered_layout))
7114 .on_action(cx.listener(
7115 |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
7116 if let Some(active_dock) = workspace.active_dock(window, cx) {
7117 let dock = active_dock.read(cx);
7118 if let Some(active_panel) = dock.active_panel() {
7119 if active_panel.pane(cx).is_none() {
7120 let mut recent_pane: Option<Entity<Pane>> = None;
7121 let mut recent_timestamp = 0;
7122 for pane_handle in workspace.panes() {
7123 let pane = pane_handle.read(cx);
7124 for entry in pane.activation_history() {
7125 if entry.timestamp > recent_timestamp {
7126 recent_timestamp = entry.timestamp;
7127 recent_pane = Some(pane_handle.clone());
7128 }
7129 }
7130 }
7131
7132 if let Some(pane) = recent_pane {
7133 let wrap_around = action.wrap_around;
7134 pane.update(cx, |pane, cx| {
7135 let current_index = pane.active_item_index();
7136 let items_len = pane.items_len();
7137 if items_len > 0 {
7138 let next_index = if current_index + 1 < items_len {
7139 current_index + 1
7140 } else if wrap_around {
7141 0
7142 } else {
7143 return;
7144 };
7145 pane.activate_item(
7146 next_index, false, false, window, cx,
7147 );
7148 }
7149 });
7150 return;
7151 }
7152 }
7153 }
7154 }
7155 cx.propagate();
7156 },
7157 ))
7158 .on_action(cx.listener(
7159 |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
7160 if let Some(active_dock) = workspace.active_dock(window, cx) {
7161 let dock = active_dock.read(cx);
7162 if let Some(active_panel) = dock.active_panel() {
7163 if active_panel.pane(cx).is_none() {
7164 let mut recent_pane: Option<Entity<Pane>> = None;
7165 let mut recent_timestamp = 0;
7166 for pane_handle in workspace.panes() {
7167 let pane = pane_handle.read(cx);
7168 for entry in pane.activation_history() {
7169 if entry.timestamp > recent_timestamp {
7170 recent_timestamp = entry.timestamp;
7171 recent_pane = Some(pane_handle.clone());
7172 }
7173 }
7174 }
7175
7176 if let Some(pane) = recent_pane {
7177 let wrap_around = action.wrap_around;
7178 pane.update(cx, |pane, cx| {
7179 let current_index = pane.active_item_index();
7180 let items_len = pane.items_len();
7181 if items_len > 0 {
7182 let prev_index = if current_index > 0 {
7183 current_index - 1
7184 } else if wrap_around {
7185 items_len.saturating_sub(1)
7186 } else {
7187 return;
7188 };
7189 pane.activate_item(
7190 prev_index, false, false, window, cx,
7191 );
7192 }
7193 });
7194 return;
7195 }
7196 }
7197 }
7198 }
7199 cx.propagate();
7200 },
7201 ))
7202 .on_action(cx.listener(
7203 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
7204 if let Some(active_dock) = workspace.active_dock(window, cx) {
7205 let dock = active_dock.read(cx);
7206 if let Some(active_panel) = dock.active_panel() {
7207 if active_panel.pane(cx).is_none() {
7208 let active_pane = workspace.active_pane().clone();
7209 active_pane.update(cx, |pane, cx| {
7210 pane.close_active_item(action, window, cx)
7211 .detach_and_log_err(cx);
7212 });
7213 return;
7214 }
7215 }
7216 }
7217 cx.propagate();
7218 },
7219 ))
7220 .on_action(
7221 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
7222 let pane = workspace.active_pane().clone();
7223 if let Some(item) = pane.read(cx).active_item() {
7224 item.toggle_read_only(window, cx);
7225 }
7226 }),
7227 )
7228 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
7229 workspace.focus_center_pane(window, cx);
7230 }))
7231 .on_action(cx.listener(Workspace::cancel))
7232 }
7233
7234 #[cfg(any(test, feature = "test-support"))]
7235 pub fn set_random_database_id(&mut self) {
7236 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
7237 }
7238
7239 #[cfg(any(test, feature = "test-support"))]
7240 pub(crate) fn test_new(
7241 project: Entity<Project>,
7242 window: &mut Window,
7243 cx: &mut Context<Self>,
7244 ) -> Self {
7245 use node_runtime::NodeRuntime;
7246 use session::Session;
7247
7248 let client = project.read(cx).client();
7249 let user_store = project.read(cx).user_store();
7250 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
7251 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
7252 window.activate_window();
7253 let app_state = Arc::new(AppState {
7254 languages: project.read(cx).languages().clone(),
7255 workspace_store,
7256 client,
7257 user_store,
7258 fs: project.read(cx).fs().clone(),
7259 build_window_options: |_, _| Default::default(),
7260 node_runtime: NodeRuntime::unavailable(),
7261 session,
7262 });
7263 let workspace = Self::new(Default::default(), project, app_state, window, cx);
7264 workspace
7265 .active_pane
7266 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
7267 workspace
7268 }
7269
7270 pub fn register_action<A: Action>(
7271 &mut self,
7272 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
7273 ) -> &mut Self {
7274 let callback = Arc::new(callback);
7275
7276 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
7277 let callback = callback.clone();
7278 div.on_action(cx.listener(move |workspace, event, window, cx| {
7279 (callback)(workspace, event, window, cx)
7280 }))
7281 }));
7282 self
7283 }
7284 pub fn register_action_renderer(
7285 &mut self,
7286 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
7287 ) -> &mut Self {
7288 self.workspace_actions.push(Box::new(callback));
7289 self
7290 }
7291
7292 fn add_workspace_actions_listeners(
7293 &self,
7294 mut div: Div,
7295 window: &mut Window,
7296 cx: &mut Context<Self>,
7297 ) -> Div {
7298 for action in self.workspace_actions.iter() {
7299 div = (action)(div, self, window, cx)
7300 }
7301 div
7302 }
7303
7304 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7305 self.modal_layer.read(cx).has_active_modal()
7306 }
7307
7308 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7309 self.modal_layer
7310 .read(cx)
7311 .is_active_modal_command_palette(cx)
7312 }
7313
7314 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7315 self.modal_layer.read(cx).active_modal()
7316 }
7317
7318 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7319 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7320 /// If no modal is active, the new modal will be shown.
7321 ///
7322 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7323 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7324 /// will not be shown.
7325 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7326 where
7327 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7328 {
7329 self.modal_layer.update(cx, |modal_layer, cx| {
7330 modal_layer.toggle_modal(window, cx, build)
7331 })
7332 }
7333
7334 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7335 self.modal_layer
7336 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7337 }
7338
7339 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7340 self.toast_layer
7341 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7342 }
7343
7344 pub fn toggle_centered_layout(
7345 &mut self,
7346 _: &ToggleCenteredLayout,
7347 _: &mut Window,
7348 cx: &mut Context<Self>,
7349 ) {
7350 self.centered_layout = !self.centered_layout;
7351 if let Some(database_id) = self.database_id() {
7352 let db = WorkspaceDb::global(cx);
7353 let centered_layout = self.centered_layout;
7354 cx.background_spawn(async move {
7355 db.set_centered_layout(database_id, centered_layout).await
7356 })
7357 .detach_and_log_err(cx);
7358 }
7359 cx.notify();
7360 }
7361
7362 fn adjust_padding(padding: Option<f32>) -> f32 {
7363 padding
7364 .unwrap_or(CenteredPaddingSettings::default().0)
7365 .clamp(
7366 CenteredPaddingSettings::MIN_PADDING,
7367 CenteredPaddingSettings::MAX_PADDING,
7368 )
7369 }
7370
7371 fn render_dock(
7372 &self,
7373 position: DockPosition,
7374 dock: &Entity<Dock>,
7375 window: &mut Window,
7376 cx: &mut App,
7377 ) -> Option<Div> {
7378 if self.zoomed_position == Some(position) {
7379 return None;
7380 }
7381
7382 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7383 let pane = panel.pane(cx)?;
7384 let follower_states = &self.follower_states;
7385 leader_border_for_pane(follower_states, &pane, window, cx)
7386 });
7387
7388 let mut container = div()
7389 .flex()
7390 .overflow_hidden()
7391 .flex_none()
7392 .child(dock.clone())
7393 .children(leader_border);
7394
7395 // Apply sizing only when the dock is open. When closed the dock is still
7396 // included in the element tree so its focus handle remains mounted — without
7397 // this, toggle_panel_focus cannot focus the panel when the dock is closed.
7398 let dock = dock.read(cx);
7399 if let Some(panel) = dock.visible_panel() {
7400 let size_state = dock.stored_panel_size_state(panel.as_ref());
7401 if position.axis() == Axis::Horizontal {
7402 let use_flexible = panel.has_flexible_size(window, cx);
7403 let flex_grow = if use_flexible {
7404 size_state
7405 .and_then(|state| state.flex)
7406 .or_else(|| self.default_dock_flex(position))
7407 } else {
7408 None
7409 };
7410 if let Some(grow) = flex_grow {
7411 let grow = grow.max(0.001);
7412 let style = container.style();
7413 style.flex_grow = Some(grow);
7414 style.flex_shrink = Some(1.0);
7415 style.flex_basis = Some(relative(0.).into());
7416 } else {
7417 let size = size_state
7418 .and_then(|state| state.size)
7419 .unwrap_or_else(|| panel.default_size(window, cx));
7420 container = container.w(size);
7421 }
7422 } else {
7423 let size = size_state
7424 .and_then(|state| state.size)
7425 .unwrap_or_else(|| panel.default_size(window, cx));
7426 container = container.h(size);
7427 }
7428 }
7429
7430 Some(container)
7431 }
7432
7433 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7434 window
7435 .root::<MultiWorkspace>()
7436 .flatten()
7437 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7438 }
7439
7440 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7441 self.zoomed.as_ref()
7442 }
7443
7444 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7445 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7446 return;
7447 };
7448 let windows = cx.windows();
7449 let next_window =
7450 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7451 || {
7452 windows
7453 .iter()
7454 .cycle()
7455 .skip_while(|window| window.window_id() != current_window_id)
7456 .nth(1)
7457 },
7458 );
7459
7460 if let Some(window) = next_window {
7461 window
7462 .update(cx, |_, window, _| window.activate_window())
7463 .ok();
7464 }
7465 }
7466
7467 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7468 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7469 return;
7470 };
7471 let windows = cx.windows();
7472 let prev_window =
7473 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7474 || {
7475 windows
7476 .iter()
7477 .rev()
7478 .cycle()
7479 .skip_while(|window| window.window_id() != current_window_id)
7480 .nth(1)
7481 },
7482 );
7483
7484 if let Some(window) = prev_window {
7485 window
7486 .update(cx, |_, window, _| window.activate_window())
7487 .ok();
7488 }
7489 }
7490
7491 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7492 if cx.stop_active_drag(window) {
7493 } else if let Some((notification_id, _)) = self.notifications.pop() {
7494 dismiss_app_notification(¬ification_id, cx);
7495 } else {
7496 cx.propagate();
7497 }
7498 }
7499
7500 fn resize_dock(
7501 &mut self,
7502 dock_pos: DockPosition,
7503 new_size: Pixels,
7504 window: &mut Window,
7505 cx: &mut Context<Self>,
7506 ) {
7507 match dock_pos {
7508 DockPosition::Left => self.resize_left_dock(new_size, window, cx),
7509 DockPosition::Right => self.resize_right_dock(new_size, window, cx),
7510 DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
7511 }
7512 }
7513
7514 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7515 let workspace_width = self.bounds.size.width;
7516 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7517
7518 self.right_dock.read_with(cx, |right_dock, cx| {
7519 let right_dock_size = right_dock
7520 .stored_active_panel_size(window, cx)
7521 .unwrap_or(Pixels::ZERO);
7522 if right_dock_size + size > workspace_width {
7523 size = workspace_width - right_dock_size
7524 }
7525 });
7526
7527 let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
7528 self.left_dock.update(cx, |left_dock, cx| {
7529 if WorkspaceSettings::get_global(cx)
7530 .resize_all_panels_in_dock
7531 .contains(&DockPosition::Left)
7532 {
7533 left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7534 } else {
7535 left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7536 }
7537 });
7538 }
7539
7540 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7541 let workspace_width = self.bounds.size.width;
7542 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7543 self.left_dock.read_with(cx, |left_dock, cx| {
7544 let left_dock_size = left_dock
7545 .stored_active_panel_size(window, cx)
7546 .unwrap_or(Pixels::ZERO);
7547 if left_dock_size + size > workspace_width {
7548 size = workspace_width - left_dock_size
7549 }
7550 });
7551 let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
7552 self.right_dock.update(cx, |right_dock, cx| {
7553 if WorkspaceSettings::get_global(cx)
7554 .resize_all_panels_in_dock
7555 .contains(&DockPosition::Right)
7556 {
7557 right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7558 } else {
7559 right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7560 }
7561 });
7562 }
7563
7564 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7565 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7566 self.bottom_dock.update(cx, |bottom_dock, cx| {
7567 if WorkspaceSettings::get_global(cx)
7568 .resize_all_panels_in_dock
7569 .contains(&DockPosition::Bottom)
7570 {
7571 bottom_dock.resize_all_panels(Some(size), None, window, cx);
7572 } else {
7573 bottom_dock.resize_active_panel(Some(size), None, window, cx);
7574 }
7575 });
7576 }
7577
7578 fn toggle_edit_predictions_all_files(
7579 &mut self,
7580 _: &ToggleEditPrediction,
7581 _window: &mut Window,
7582 cx: &mut Context<Self>,
7583 ) {
7584 let fs = self.project().read(cx).fs().clone();
7585 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7586 update_settings_file(fs, cx, move |file, _| {
7587 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7588 });
7589 }
7590
7591 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7592 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7593 let next_mode = match current_mode {
7594 Some(theme_settings::ThemeAppearanceMode::Light) => {
7595 theme_settings::ThemeAppearanceMode::Dark
7596 }
7597 Some(theme_settings::ThemeAppearanceMode::Dark) => {
7598 theme_settings::ThemeAppearanceMode::Light
7599 }
7600 Some(theme_settings::ThemeAppearanceMode::System) | None => {
7601 match cx.theme().appearance() {
7602 theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
7603 theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
7604 }
7605 }
7606 };
7607
7608 let fs = self.project().read(cx).fs().clone();
7609 settings::update_settings_file(fs, cx, move |settings, _cx| {
7610 theme_settings::set_mode(settings, next_mode);
7611 });
7612 }
7613
7614 pub fn show_worktree_trust_security_modal(
7615 &mut self,
7616 toggle: bool,
7617 window: &mut Window,
7618 cx: &mut Context<Self>,
7619 ) {
7620 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7621 if toggle {
7622 security_modal.update(cx, |security_modal, cx| {
7623 security_modal.dismiss(cx);
7624 })
7625 } else {
7626 security_modal.update(cx, |security_modal, cx| {
7627 security_modal.refresh_restricted_paths(cx);
7628 });
7629 }
7630 } else {
7631 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7632 .map(|trusted_worktrees| {
7633 trusted_worktrees
7634 .read(cx)
7635 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7636 })
7637 .unwrap_or(false);
7638 if has_restricted_worktrees {
7639 let project = self.project().read(cx);
7640 let remote_host = project
7641 .remote_connection_options(cx)
7642 .map(RemoteHostLocation::from);
7643 let worktree_store = project.worktree_store().downgrade();
7644 self.toggle_modal(window, cx, |_, cx| {
7645 SecurityModal::new(worktree_store, remote_host, cx)
7646 });
7647 }
7648 }
7649 }
7650}
7651
7652pub trait AnyActiveCall {
7653 fn entity(&self) -> AnyEntity;
7654 fn is_in_room(&self, _: &App) -> bool;
7655 fn room_id(&self, _: &App) -> Option<u64>;
7656 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7657 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7658 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7659 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7660 fn is_sharing_project(&self, _: &App) -> bool;
7661 fn has_remote_participants(&self, _: &App) -> bool;
7662 fn local_participant_is_guest(&self, _: &App) -> bool;
7663 fn client(&self, _: &App) -> Arc<Client>;
7664 fn share_on_join(&self, _: &App) -> bool;
7665 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7666 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7667 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7668 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7669 fn join_project(
7670 &self,
7671 _: u64,
7672 _: Arc<LanguageRegistry>,
7673 _: Arc<dyn Fs>,
7674 _: &mut App,
7675 ) -> Task<Result<Entity<Project>>>;
7676 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7677 fn subscribe(
7678 &self,
7679 _: &mut Window,
7680 _: &mut Context<Workspace>,
7681 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7682 ) -> Subscription;
7683 fn create_shared_screen(
7684 &self,
7685 _: PeerId,
7686 _: &Entity<Pane>,
7687 _: &mut Window,
7688 _: &mut App,
7689 ) -> Option<Entity<SharedScreen>>;
7690}
7691
7692#[derive(Clone)]
7693pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7694impl Global for GlobalAnyActiveCall {}
7695
7696impl GlobalAnyActiveCall {
7697 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7698 cx.try_global()
7699 }
7700
7701 pub(crate) fn global(cx: &App) -> &Self {
7702 cx.global()
7703 }
7704}
7705
7706pub fn merge_conflict_notification_id() -> NotificationId {
7707 struct MergeConflictNotification;
7708 NotificationId::unique::<MergeConflictNotification>()
7709}
7710
7711/// Workspace-local view of a remote participant's location.
7712#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7713pub enum ParticipantLocation {
7714 SharedProject { project_id: u64 },
7715 UnsharedProject,
7716 External,
7717}
7718
7719impl ParticipantLocation {
7720 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7721 match location
7722 .and_then(|l| l.variant)
7723 .context("participant location was not provided")?
7724 {
7725 proto::participant_location::Variant::SharedProject(project) => {
7726 Ok(Self::SharedProject {
7727 project_id: project.id,
7728 })
7729 }
7730 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7731 proto::participant_location::Variant::External(_) => Ok(Self::External),
7732 }
7733 }
7734}
7735/// Workspace-local view of a remote collaborator's state.
7736/// This is the subset of `call::RemoteParticipant` that workspace needs.
7737#[derive(Clone)]
7738pub struct RemoteCollaborator {
7739 pub user: Arc<User>,
7740 pub peer_id: PeerId,
7741 pub location: ParticipantLocation,
7742 pub participant_index: ParticipantIndex,
7743}
7744
7745pub enum ActiveCallEvent {
7746 ParticipantLocationChanged { participant_id: PeerId },
7747 RemoteVideoTracksChanged { participant_id: PeerId },
7748}
7749
7750fn leader_border_for_pane(
7751 follower_states: &HashMap<CollaboratorId, FollowerState>,
7752 pane: &Entity<Pane>,
7753 _: &Window,
7754 cx: &App,
7755) -> Option<Div> {
7756 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7757 if state.pane() == pane {
7758 Some((*leader_id, state))
7759 } else {
7760 None
7761 }
7762 })?;
7763
7764 let mut leader_color = match leader_id {
7765 CollaboratorId::PeerId(leader_peer_id) => {
7766 let leader = GlobalAnyActiveCall::try_global(cx)?
7767 .0
7768 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7769
7770 cx.theme()
7771 .players()
7772 .color_for_participant(leader.participant_index.0)
7773 .cursor
7774 }
7775 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7776 };
7777 leader_color.fade_out(0.3);
7778 Some(
7779 div()
7780 .absolute()
7781 .size_full()
7782 .left_0()
7783 .top_0()
7784 .border_2()
7785 .border_color(leader_color),
7786 )
7787}
7788
7789fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7790 ZED_WINDOW_POSITION
7791 .zip(*ZED_WINDOW_SIZE)
7792 .map(|(position, size)| Bounds {
7793 origin: position,
7794 size,
7795 })
7796}
7797
7798fn open_items(
7799 serialized_workspace: Option<SerializedWorkspace>,
7800 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7801 window: &mut Window,
7802 cx: &mut Context<Workspace>,
7803) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7804 let restored_items = serialized_workspace.map(|serialized_workspace| {
7805 Workspace::load_workspace(
7806 serialized_workspace,
7807 project_paths_to_open
7808 .iter()
7809 .map(|(_, project_path)| project_path)
7810 .cloned()
7811 .collect(),
7812 window,
7813 cx,
7814 )
7815 });
7816
7817 cx.spawn_in(window, async move |workspace, cx| {
7818 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7819
7820 if let Some(restored_items) = restored_items {
7821 let restored_items = restored_items.await?;
7822
7823 let restored_project_paths = restored_items
7824 .iter()
7825 .filter_map(|item| {
7826 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7827 .ok()
7828 .flatten()
7829 })
7830 .collect::<HashSet<_>>();
7831
7832 for restored_item in restored_items {
7833 opened_items.push(restored_item.map(Ok));
7834 }
7835
7836 project_paths_to_open
7837 .iter_mut()
7838 .for_each(|(_, project_path)| {
7839 if let Some(project_path_to_open) = project_path
7840 && restored_project_paths.contains(project_path_to_open)
7841 {
7842 *project_path = None;
7843 }
7844 });
7845 } else {
7846 for _ in 0..project_paths_to_open.len() {
7847 opened_items.push(None);
7848 }
7849 }
7850 assert!(opened_items.len() == project_paths_to_open.len());
7851
7852 let tasks =
7853 project_paths_to_open
7854 .into_iter()
7855 .enumerate()
7856 .map(|(ix, (abs_path, project_path))| {
7857 let workspace = workspace.clone();
7858 cx.spawn(async move |cx| {
7859 let file_project_path = project_path?;
7860 let abs_path_task = workspace.update(cx, |workspace, cx| {
7861 workspace.project().update(cx, |project, cx| {
7862 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7863 })
7864 });
7865
7866 // We only want to open file paths here. If one of the items
7867 // here is a directory, it was already opened further above
7868 // with a `find_or_create_worktree`.
7869 if let Ok(task) = abs_path_task
7870 && task.await.is_none_or(|p| p.is_file())
7871 {
7872 return Some((
7873 ix,
7874 workspace
7875 .update_in(cx, |workspace, window, cx| {
7876 workspace.open_path(
7877 file_project_path,
7878 None,
7879 true,
7880 window,
7881 cx,
7882 )
7883 })
7884 .log_err()?
7885 .await,
7886 ));
7887 }
7888 None
7889 })
7890 });
7891
7892 let tasks = tasks.collect::<Vec<_>>();
7893
7894 let tasks = futures::future::join_all(tasks);
7895 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7896 opened_items[ix] = Some(path_open_result);
7897 }
7898
7899 Ok(opened_items)
7900 })
7901}
7902
7903#[derive(Clone)]
7904enum ActivateInDirectionTarget {
7905 Pane(Entity<Pane>),
7906 Dock(Entity<Dock>),
7907 Sidebar(FocusHandle),
7908}
7909
7910fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7911 window
7912 .update(cx, |multi_workspace, _, cx| {
7913 let workspace = multi_workspace.workspace().clone();
7914 workspace.update(cx, |workspace, cx| {
7915 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7916 struct DatabaseFailedNotification;
7917
7918 workspace.show_notification(
7919 NotificationId::unique::<DatabaseFailedNotification>(),
7920 cx,
7921 |cx| {
7922 cx.new(|cx| {
7923 MessageNotification::new("Failed to load the database file.", cx)
7924 .primary_message("File an Issue")
7925 .primary_icon(IconName::Plus)
7926 .primary_on_click(|window, cx| {
7927 window.dispatch_action(Box::new(FileBugReport), cx)
7928 })
7929 })
7930 },
7931 );
7932 }
7933 });
7934 })
7935 .log_err();
7936}
7937
7938fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7939 if val == 0 {
7940 ThemeSettings::get_global(cx).ui_font_size(cx)
7941 } else {
7942 px(val as f32)
7943 }
7944}
7945
7946fn adjust_active_dock_size_by_px(
7947 px: Pixels,
7948 workspace: &mut Workspace,
7949 window: &mut Window,
7950 cx: &mut Context<Workspace>,
7951) {
7952 let Some(active_dock) = workspace
7953 .all_docks()
7954 .into_iter()
7955 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7956 else {
7957 return;
7958 };
7959 let dock = active_dock.read(cx);
7960 let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
7961 return;
7962 };
7963 workspace.resize_dock(dock.position(), panel_size + px, window, cx);
7964}
7965
7966fn adjust_open_docks_size_by_px(
7967 px: Pixels,
7968 workspace: &mut Workspace,
7969 window: &mut Window,
7970 cx: &mut Context<Workspace>,
7971) {
7972 let docks = workspace
7973 .all_docks()
7974 .into_iter()
7975 .filter_map(|dock_entity| {
7976 let dock = dock_entity.read(cx);
7977 if dock.is_open() {
7978 let dock_pos = dock.position();
7979 let panel_size = workspace.dock_size(&dock, window, cx)?;
7980 Some((dock_pos, panel_size + px))
7981 } else {
7982 None
7983 }
7984 })
7985 .collect::<Vec<_>>();
7986
7987 for (position, new_size) in docks {
7988 workspace.resize_dock(position, new_size, window, cx);
7989 }
7990}
7991
7992impl Focusable for Workspace {
7993 fn focus_handle(&self, cx: &App) -> FocusHandle {
7994 self.active_pane.focus_handle(cx)
7995 }
7996}
7997
7998#[derive(Clone)]
7999struct DraggedDock(DockPosition);
8000
8001impl Render for DraggedDock {
8002 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8003 gpui::Empty
8004 }
8005}
8006
8007impl Render for Workspace {
8008 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8009 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
8010 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
8011 log::info!("Rendered first frame");
8012 }
8013
8014 let centered_layout = self.centered_layout
8015 && self.center.panes().len() == 1
8016 && self.active_item(cx).is_some();
8017 let render_padding = |size| {
8018 (size > 0.0).then(|| {
8019 div()
8020 .h_full()
8021 .w(relative(size))
8022 .bg(cx.theme().colors().editor_background)
8023 .border_color(cx.theme().colors().pane_group_border)
8024 })
8025 };
8026 let paddings = if centered_layout {
8027 let settings = WorkspaceSettings::get_global(cx).centered_layout;
8028 (
8029 render_padding(Self::adjust_padding(
8030 settings.left_padding.map(|padding| padding.0),
8031 )),
8032 render_padding(Self::adjust_padding(
8033 settings.right_padding.map(|padding| padding.0),
8034 )),
8035 )
8036 } else {
8037 (None, None)
8038 };
8039 let ui_font = theme_settings::setup_ui_font(window, cx);
8040
8041 let theme = cx.theme().clone();
8042 let colors = theme.colors();
8043 let notification_entities = self
8044 .notifications
8045 .iter()
8046 .map(|(_, notification)| notification.entity_id())
8047 .collect::<Vec<_>>();
8048 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
8049
8050 div()
8051 .relative()
8052 .size_full()
8053 .flex()
8054 .flex_col()
8055 .font(ui_font)
8056 .gap_0()
8057 .justify_start()
8058 .items_start()
8059 .text_color(colors.text)
8060 .overflow_hidden()
8061 .children(self.titlebar_item.clone())
8062 .on_modifiers_changed(move |_, _, cx| {
8063 for &id in ¬ification_entities {
8064 cx.notify(id);
8065 }
8066 })
8067 .child(
8068 div()
8069 .size_full()
8070 .relative()
8071 .flex_1()
8072 .flex()
8073 .flex_col()
8074 .child(
8075 div()
8076 .id("workspace")
8077 .bg(colors.background)
8078 .relative()
8079 .flex_1()
8080 .w_full()
8081 .flex()
8082 .flex_col()
8083 .overflow_hidden()
8084 .border_t_1()
8085 .border_b_1()
8086 .border_color(colors.border)
8087 .child({
8088 let this = cx.entity();
8089 canvas(
8090 move |bounds, window, cx| {
8091 this.update(cx, |this, cx| {
8092 let bounds_changed = this.bounds != bounds;
8093 this.bounds = bounds;
8094
8095 if bounds_changed {
8096 this.left_dock.update(cx, |dock, cx| {
8097 dock.clamp_panel_size(
8098 bounds.size.width,
8099 window,
8100 cx,
8101 )
8102 });
8103
8104 this.right_dock.update(cx, |dock, cx| {
8105 dock.clamp_panel_size(
8106 bounds.size.width,
8107 window,
8108 cx,
8109 )
8110 });
8111
8112 this.bottom_dock.update(cx, |dock, cx| {
8113 dock.clamp_panel_size(
8114 bounds.size.height,
8115 window,
8116 cx,
8117 )
8118 });
8119 }
8120 })
8121 },
8122 |_, _, _, _| {},
8123 )
8124 .absolute()
8125 .size_full()
8126 })
8127 .when(self.zoomed.is_none(), |this| {
8128 this.on_drag_move(cx.listener(
8129 move |workspace,
8130 e: &DragMoveEvent<DraggedDock>,
8131 window,
8132 cx| {
8133 if workspace.previous_dock_drag_coordinates
8134 != Some(e.event.position)
8135 {
8136 workspace.previous_dock_drag_coordinates =
8137 Some(e.event.position);
8138
8139 match e.drag(cx).0 {
8140 DockPosition::Left => {
8141 workspace.resize_left_dock(
8142 e.event.position.x
8143 - workspace.bounds.left(),
8144 window,
8145 cx,
8146 );
8147 }
8148 DockPosition::Right => {
8149 workspace.resize_right_dock(
8150 workspace.bounds.right()
8151 - e.event.position.x,
8152 window,
8153 cx,
8154 );
8155 }
8156 DockPosition::Bottom => {
8157 workspace.resize_bottom_dock(
8158 workspace.bounds.bottom()
8159 - e.event.position.y,
8160 window,
8161 cx,
8162 );
8163 }
8164 };
8165 workspace.serialize_workspace(window, cx);
8166 }
8167 },
8168 ))
8169
8170 })
8171 .child({
8172 match bottom_dock_layout {
8173 BottomDockLayout::Full => div()
8174 .flex()
8175 .flex_col()
8176 .h_full()
8177 .child(
8178 div()
8179 .flex()
8180 .flex_row()
8181 .flex_1()
8182 .overflow_hidden()
8183 .children(self.render_dock(
8184 DockPosition::Left,
8185 &self.left_dock,
8186 window,
8187 cx,
8188 ))
8189
8190 .child(
8191 div()
8192 .flex()
8193 .flex_col()
8194 .flex_1()
8195 .overflow_hidden()
8196 .child(
8197 h_flex()
8198 .flex_1()
8199 .when_some(
8200 paddings.0,
8201 |this, p| {
8202 this.child(
8203 p.border_r_1(),
8204 )
8205 },
8206 )
8207 .child(self.center.render(
8208 self.zoomed.as_ref(),
8209 &PaneRenderContext {
8210 follower_states:
8211 &self.follower_states,
8212 active_call: self.active_call(),
8213 active_pane: &self.active_pane,
8214 app_state: &self.app_state,
8215 project: &self.project,
8216 workspace: &self.weak_self,
8217 },
8218 window,
8219 cx,
8220 ))
8221 .when_some(
8222 paddings.1,
8223 |this, p| {
8224 this.child(
8225 p.border_l_1(),
8226 )
8227 },
8228 ),
8229 ),
8230 )
8231
8232 .children(self.render_dock(
8233 DockPosition::Right,
8234 &self.right_dock,
8235 window,
8236 cx,
8237 )),
8238 )
8239 .child(div().w_full().children(self.render_dock(
8240 DockPosition::Bottom,
8241 &self.bottom_dock,
8242 window,
8243 cx
8244 ))),
8245
8246 BottomDockLayout::LeftAligned => div()
8247 .flex()
8248 .flex_row()
8249 .h_full()
8250 .child(
8251 div()
8252 .flex()
8253 .flex_col()
8254 .flex_1()
8255 .h_full()
8256 .child(
8257 div()
8258 .flex()
8259 .flex_row()
8260 .flex_1()
8261 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
8262
8263 .child(
8264 div()
8265 .flex()
8266 .flex_col()
8267 .flex_1()
8268 .overflow_hidden()
8269 .child(
8270 h_flex()
8271 .flex_1()
8272 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8273 .child(self.center.render(
8274 self.zoomed.as_ref(),
8275 &PaneRenderContext {
8276 follower_states:
8277 &self.follower_states,
8278 active_call: self.active_call(),
8279 active_pane: &self.active_pane,
8280 app_state: &self.app_state,
8281 project: &self.project,
8282 workspace: &self.weak_self,
8283 },
8284 window,
8285 cx,
8286 ))
8287 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8288 )
8289 )
8290
8291 )
8292 .child(
8293 div()
8294 .w_full()
8295 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8296 ),
8297 )
8298 .children(self.render_dock(
8299 DockPosition::Right,
8300 &self.right_dock,
8301 window,
8302 cx,
8303 )),
8304 BottomDockLayout::RightAligned => div()
8305 .flex()
8306 .flex_row()
8307 .h_full()
8308 .children(self.render_dock(
8309 DockPosition::Left,
8310 &self.left_dock,
8311 window,
8312 cx,
8313 ))
8314
8315 .child(
8316 div()
8317 .flex()
8318 .flex_col()
8319 .flex_1()
8320 .h_full()
8321 .child(
8322 div()
8323 .flex()
8324 .flex_row()
8325 .flex_1()
8326 .child(
8327 div()
8328 .flex()
8329 .flex_col()
8330 .flex_1()
8331 .overflow_hidden()
8332 .child(
8333 h_flex()
8334 .flex_1()
8335 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8336 .child(self.center.render(
8337 self.zoomed.as_ref(),
8338 &PaneRenderContext {
8339 follower_states:
8340 &self.follower_states,
8341 active_call: self.active_call(),
8342 active_pane: &self.active_pane,
8343 app_state: &self.app_state,
8344 project: &self.project,
8345 workspace: &self.weak_self,
8346 },
8347 window,
8348 cx,
8349 ))
8350 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8351 )
8352 )
8353
8354 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8355 )
8356 .child(
8357 div()
8358 .w_full()
8359 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8360 ),
8361 ),
8362 BottomDockLayout::Contained => div()
8363 .flex()
8364 .flex_row()
8365 .h_full()
8366 .children(self.render_dock(
8367 DockPosition::Left,
8368 &self.left_dock,
8369 window,
8370 cx,
8371 ))
8372
8373 .child(
8374 div()
8375 .flex()
8376 .flex_col()
8377 .flex_1()
8378 .overflow_hidden()
8379 .child(
8380 h_flex()
8381 .flex_1()
8382 .when_some(paddings.0, |this, p| {
8383 this.child(p.border_r_1())
8384 })
8385 .child(self.center.render(
8386 self.zoomed.as_ref(),
8387 &PaneRenderContext {
8388 follower_states:
8389 &self.follower_states,
8390 active_call: self.active_call(),
8391 active_pane: &self.active_pane,
8392 app_state: &self.app_state,
8393 project: &self.project,
8394 workspace: &self.weak_self,
8395 },
8396 window,
8397 cx,
8398 ))
8399 .when_some(paddings.1, |this, p| {
8400 this.child(p.border_l_1())
8401 }),
8402 )
8403 .children(self.render_dock(
8404 DockPosition::Bottom,
8405 &self.bottom_dock,
8406 window,
8407 cx,
8408 )),
8409 )
8410
8411 .children(self.render_dock(
8412 DockPosition::Right,
8413 &self.right_dock,
8414 window,
8415 cx,
8416 )),
8417 }
8418 })
8419 .children(self.zoomed.as_ref().and_then(|view| {
8420 let zoomed_view = view.upgrade()?;
8421 let div = div()
8422 .occlude()
8423 .absolute()
8424 .overflow_hidden()
8425 .border_color(colors.border)
8426 .bg(colors.background)
8427 .child(zoomed_view)
8428 .inset_0()
8429 .shadow_lg();
8430
8431 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8432 return Some(div);
8433 }
8434
8435 Some(match self.zoomed_position {
8436 Some(DockPosition::Left) => div.right_2().border_r_1(),
8437 Some(DockPosition::Right) => div.left_2().border_l_1(),
8438 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8439 None => {
8440 div.top_2().bottom_2().left_2().right_2().border_1()
8441 }
8442 })
8443 }))
8444 .children(self.render_notifications(window, cx)),
8445 )
8446 .when(self.status_bar_visible(cx), |parent| {
8447 parent.child(self.status_bar.clone())
8448 })
8449 .child(self.toast_layer.clone()),
8450 )
8451 }
8452}
8453
8454impl WorkspaceStore {
8455 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8456 Self {
8457 workspaces: Default::default(),
8458 _subscriptions: vec![
8459 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8460 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8461 ],
8462 client,
8463 }
8464 }
8465
8466 pub fn update_followers(
8467 &self,
8468 project_id: Option<u64>,
8469 update: proto::update_followers::Variant,
8470 cx: &App,
8471 ) -> Option<()> {
8472 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8473 let room_id = active_call.0.room_id(cx)?;
8474 self.client
8475 .send(proto::UpdateFollowers {
8476 room_id,
8477 project_id,
8478 variant: Some(update),
8479 })
8480 .log_err()
8481 }
8482
8483 pub async fn handle_follow(
8484 this: Entity<Self>,
8485 envelope: TypedEnvelope<proto::Follow>,
8486 mut cx: AsyncApp,
8487 ) -> Result<proto::FollowResponse> {
8488 this.update(&mut cx, |this, cx| {
8489 let follower = Follower {
8490 project_id: envelope.payload.project_id,
8491 peer_id: envelope.original_sender_id()?,
8492 };
8493
8494 let mut response = proto::FollowResponse::default();
8495
8496 this.workspaces.retain(|(window_handle, weak_workspace)| {
8497 let Some(workspace) = weak_workspace.upgrade() else {
8498 return false;
8499 };
8500 window_handle
8501 .update(cx, |_, window, cx| {
8502 workspace.update(cx, |workspace, cx| {
8503 let handler_response =
8504 workspace.handle_follow(follower.project_id, window, cx);
8505 if let Some(active_view) = handler_response.active_view
8506 && workspace.project.read(cx).remote_id() == follower.project_id
8507 {
8508 response.active_view = Some(active_view)
8509 }
8510 });
8511 })
8512 .is_ok()
8513 });
8514
8515 Ok(response)
8516 })
8517 }
8518
8519 async fn handle_update_followers(
8520 this: Entity<Self>,
8521 envelope: TypedEnvelope<proto::UpdateFollowers>,
8522 mut cx: AsyncApp,
8523 ) -> Result<()> {
8524 let leader_id = envelope.original_sender_id()?;
8525 let update = envelope.payload;
8526
8527 this.update(&mut cx, |this, cx| {
8528 this.workspaces.retain(|(window_handle, weak_workspace)| {
8529 let Some(workspace) = weak_workspace.upgrade() else {
8530 return false;
8531 };
8532 window_handle
8533 .update(cx, |_, window, cx| {
8534 workspace.update(cx, |workspace, cx| {
8535 let project_id = workspace.project.read(cx).remote_id();
8536 if update.project_id != project_id && update.project_id.is_some() {
8537 return;
8538 }
8539 workspace.handle_update_followers(
8540 leader_id,
8541 update.clone(),
8542 window,
8543 cx,
8544 );
8545 });
8546 })
8547 .is_ok()
8548 });
8549 Ok(())
8550 })
8551 }
8552
8553 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8554 self.workspaces.iter().map(|(_, weak)| weak)
8555 }
8556
8557 pub fn workspaces_with_windows(
8558 &self,
8559 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8560 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8561 }
8562}
8563
8564impl ViewId {
8565 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8566 Ok(Self {
8567 creator: message
8568 .creator
8569 .map(CollaboratorId::PeerId)
8570 .context("creator is missing")?,
8571 id: message.id,
8572 })
8573 }
8574
8575 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8576 if let CollaboratorId::PeerId(peer_id) = self.creator {
8577 Some(proto::ViewId {
8578 creator: Some(peer_id),
8579 id: self.id,
8580 })
8581 } else {
8582 None
8583 }
8584 }
8585}
8586
8587impl FollowerState {
8588 fn pane(&self) -> &Entity<Pane> {
8589 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8590 }
8591}
8592
8593pub trait WorkspaceHandle {
8594 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8595}
8596
8597impl WorkspaceHandle for Entity<Workspace> {
8598 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8599 self.read(cx)
8600 .worktrees(cx)
8601 .flat_map(|worktree| {
8602 let worktree_id = worktree.read(cx).id();
8603 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8604 worktree_id,
8605 path: f.path.clone(),
8606 })
8607 })
8608 .collect::<Vec<_>>()
8609 }
8610}
8611
8612pub async fn last_opened_workspace_location(
8613 db: &WorkspaceDb,
8614 fs: &dyn fs::Fs,
8615) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8616 db.last_workspace(fs)
8617 .await
8618 .log_err()
8619 .flatten()
8620 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8621}
8622
8623pub async fn last_session_workspace_locations(
8624 db: &WorkspaceDb,
8625 last_session_id: &str,
8626 last_session_window_stack: Option<Vec<WindowId>>,
8627 fs: &dyn fs::Fs,
8628) -> Option<Vec<SessionWorkspace>> {
8629 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8630 .await
8631 .log_err()
8632}
8633
8634pub struct MultiWorkspaceRestoreResult {
8635 pub window_handle: WindowHandle<MultiWorkspace>,
8636 pub errors: Vec<anyhow::Error>,
8637}
8638
8639pub async fn restore_multiworkspace(
8640 multi_workspace: SerializedMultiWorkspace,
8641 app_state: Arc<AppState>,
8642 cx: &mut AsyncApp,
8643) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8644 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
8645 let mut group_iter = workspaces.into_iter();
8646 let first = group_iter
8647 .next()
8648 .context("window group must not be empty")?;
8649
8650 let window_handle = if first.paths.is_empty() {
8651 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8652 .await?
8653 } else {
8654 let OpenResult { window, .. } = cx
8655 .update(|cx| {
8656 Workspace::new_local(
8657 first.paths.paths().to_vec(),
8658 app_state.clone(),
8659 None,
8660 None,
8661 None,
8662 OpenMode::Activate,
8663 cx,
8664 )
8665 })
8666 .await?;
8667 window
8668 };
8669
8670 let mut errors = Vec::new();
8671
8672 for session_workspace in group_iter {
8673 let error = if session_workspace.paths.is_empty() {
8674 cx.update(|cx| {
8675 open_workspace_by_id(
8676 session_workspace.workspace_id,
8677 app_state.clone(),
8678 Some(window_handle),
8679 cx,
8680 )
8681 })
8682 .await
8683 .err()
8684 } else {
8685 cx.update(|cx| {
8686 Workspace::new_local(
8687 session_workspace.paths.paths().to_vec(),
8688 app_state.clone(),
8689 Some(window_handle),
8690 None,
8691 None,
8692 OpenMode::Add,
8693 cx,
8694 )
8695 })
8696 .await
8697 .err()
8698 };
8699
8700 if let Some(error) = error {
8701 errors.push(error);
8702 }
8703 }
8704
8705 if let Some(target_id) = state.active_workspace_id {
8706 window_handle
8707 .update(cx, |multi_workspace, window, cx| {
8708 let target_index = multi_workspace
8709 .workspaces()
8710 .iter()
8711 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8712 let index = target_index.unwrap_or(0);
8713 if let Some(workspace) = multi_workspace.workspaces().get(index).cloned() {
8714 multi_workspace.activate(workspace, window, cx);
8715 }
8716 })
8717 .ok();
8718 } else {
8719 window_handle
8720 .update(cx, |multi_workspace, window, cx| {
8721 if let Some(workspace) = multi_workspace.workspaces().first().cloned() {
8722 multi_workspace.activate(workspace, window, cx);
8723 }
8724 })
8725 .ok();
8726 }
8727
8728 if state.sidebar_open {
8729 window_handle
8730 .update(cx, |multi_workspace, _, cx| {
8731 multi_workspace.open_sidebar(cx);
8732 })
8733 .ok();
8734 }
8735
8736 if let Some(sidebar_state) = &state.sidebar_state {
8737 let sidebar_state = sidebar_state.clone();
8738 window_handle
8739 .update(cx, |multi_workspace, window, cx| {
8740 if let Some(sidebar) = multi_workspace.sidebar() {
8741 sidebar.restore_serialized_state(&sidebar_state, window, cx);
8742 }
8743 multi_workspace.serialize(cx);
8744 })
8745 .ok();
8746 }
8747
8748 window_handle
8749 .update(cx, |_, window, _cx| {
8750 window.activate_window();
8751 })
8752 .ok();
8753
8754 Ok(MultiWorkspaceRestoreResult {
8755 window_handle,
8756 errors,
8757 })
8758}
8759
8760actions!(
8761 collab,
8762 [
8763 /// Opens the channel notes for the current call.
8764 ///
8765 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8766 /// channel in the collab panel.
8767 ///
8768 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8769 /// can be copied via "Copy link to section" in the context menu of the channel notes
8770 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8771 OpenChannelNotes,
8772 /// Mutes your microphone.
8773 Mute,
8774 /// Deafens yourself (mute both microphone and speakers).
8775 Deafen,
8776 /// Leaves the current call.
8777 LeaveCall,
8778 /// Shares the current project with collaborators.
8779 ShareProject,
8780 /// Shares your screen with collaborators.
8781 ScreenShare,
8782 /// Copies the current room name and session id for debugging purposes.
8783 CopyRoomId,
8784 ]
8785);
8786
8787/// Opens the channel notes for a specific channel by its ID.
8788#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8789#[action(namespace = collab)]
8790#[serde(deny_unknown_fields)]
8791pub struct OpenChannelNotesById {
8792 pub channel_id: u64,
8793}
8794
8795actions!(
8796 zed,
8797 [
8798 /// Opens the Zed log file.
8799 OpenLog,
8800 /// Reveals the Zed log file in the system file manager.
8801 RevealLogInFileManager
8802 ]
8803);
8804
8805async fn join_channel_internal(
8806 channel_id: ChannelId,
8807 app_state: &Arc<AppState>,
8808 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8809 requesting_workspace: Option<WeakEntity<Workspace>>,
8810 active_call: &dyn AnyActiveCall,
8811 cx: &mut AsyncApp,
8812) -> Result<bool> {
8813 let (should_prompt, already_in_channel) = cx.update(|cx| {
8814 if !active_call.is_in_room(cx) {
8815 return (false, false);
8816 }
8817
8818 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8819 let should_prompt = active_call.is_sharing_project(cx)
8820 && active_call.has_remote_participants(cx)
8821 && !already_in_channel;
8822 (should_prompt, already_in_channel)
8823 });
8824
8825 if already_in_channel {
8826 let task = cx.update(|cx| {
8827 if let Some((project, host)) = active_call.most_active_project(cx) {
8828 Some(join_in_room_project(project, host, app_state.clone(), cx))
8829 } else {
8830 None
8831 }
8832 });
8833 if let Some(task) = task {
8834 task.await?;
8835 }
8836 return anyhow::Ok(true);
8837 }
8838
8839 if should_prompt {
8840 if let Some(multi_workspace) = requesting_window {
8841 let answer = multi_workspace
8842 .update(cx, |_, window, cx| {
8843 window.prompt(
8844 PromptLevel::Warning,
8845 "Do you want to switch channels?",
8846 Some("Leaving this call will unshare your current project."),
8847 &["Yes, Join Channel", "Cancel"],
8848 cx,
8849 )
8850 })?
8851 .await;
8852
8853 if answer == Ok(1) {
8854 return Ok(false);
8855 }
8856 } else {
8857 return Ok(false);
8858 }
8859 }
8860
8861 let client = cx.update(|cx| active_call.client(cx));
8862
8863 let mut client_status = client.status();
8864
8865 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8866 'outer: loop {
8867 let Some(status) = client_status.recv().await else {
8868 anyhow::bail!("error connecting");
8869 };
8870
8871 match status {
8872 Status::Connecting
8873 | Status::Authenticating
8874 | Status::Authenticated
8875 | Status::Reconnecting
8876 | Status::Reauthenticating
8877 | Status::Reauthenticated => continue,
8878 Status::Connected { .. } => break 'outer,
8879 Status::SignedOut | Status::AuthenticationError => {
8880 return Err(ErrorCode::SignedOut.into());
8881 }
8882 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8883 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8884 return Err(ErrorCode::Disconnected.into());
8885 }
8886 }
8887 }
8888
8889 let joined = cx
8890 .update(|cx| active_call.join_channel(channel_id, cx))
8891 .await?;
8892
8893 if !joined {
8894 return anyhow::Ok(true);
8895 }
8896
8897 cx.update(|cx| active_call.room_update_completed(cx)).await;
8898
8899 let task = cx.update(|cx| {
8900 if let Some((project, host)) = active_call.most_active_project(cx) {
8901 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8902 }
8903
8904 // If you are the first to join a channel, see if you should share your project.
8905 if !active_call.has_remote_participants(cx)
8906 && !active_call.local_participant_is_guest(cx)
8907 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8908 {
8909 let project = workspace.update(cx, |workspace, cx| {
8910 let project = workspace.project.read(cx);
8911
8912 if !active_call.share_on_join(cx) {
8913 return None;
8914 }
8915
8916 if (project.is_local() || project.is_via_remote_server())
8917 && project.visible_worktrees(cx).any(|tree| {
8918 tree.read(cx)
8919 .root_entry()
8920 .is_some_and(|entry| entry.is_dir())
8921 })
8922 {
8923 Some(workspace.project.clone())
8924 } else {
8925 None
8926 }
8927 });
8928 if let Some(project) = project {
8929 let share_task = active_call.share_project(project, cx);
8930 return Some(cx.spawn(async move |_cx| -> Result<()> {
8931 share_task.await?;
8932 Ok(())
8933 }));
8934 }
8935 }
8936
8937 None
8938 });
8939 if let Some(task) = task {
8940 task.await?;
8941 return anyhow::Ok(true);
8942 }
8943 anyhow::Ok(false)
8944}
8945
8946pub fn join_channel(
8947 channel_id: ChannelId,
8948 app_state: Arc<AppState>,
8949 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8950 requesting_workspace: Option<WeakEntity<Workspace>>,
8951 cx: &mut App,
8952) -> Task<Result<()>> {
8953 let active_call = GlobalAnyActiveCall::global(cx).clone();
8954 cx.spawn(async move |cx| {
8955 let result = join_channel_internal(
8956 channel_id,
8957 &app_state,
8958 requesting_window,
8959 requesting_workspace,
8960 &*active_call.0,
8961 cx,
8962 )
8963 .await;
8964
8965 // join channel succeeded, and opened a window
8966 if matches!(result, Ok(true)) {
8967 return anyhow::Ok(());
8968 }
8969
8970 // find an existing workspace to focus and show call controls
8971 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8972 if active_window.is_none() {
8973 // no open workspaces, make one to show the error in (blergh)
8974 let OpenResult {
8975 window: window_handle,
8976 ..
8977 } = cx
8978 .update(|cx| {
8979 Workspace::new_local(
8980 vec![],
8981 app_state.clone(),
8982 requesting_window,
8983 None,
8984 None,
8985 OpenMode::Activate,
8986 cx,
8987 )
8988 })
8989 .await?;
8990
8991 window_handle
8992 .update(cx, |_, window, _cx| {
8993 window.activate_window();
8994 })
8995 .ok();
8996
8997 if result.is_ok() {
8998 cx.update(|cx| {
8999 cx.dispatch_action(&OpenChannelNotes);
9000 });
9001 }
9002
9003 active_window = Some(window_handle);
9004 }
9005
9006 if let Err(err) = result {
9007 log::error!("failed to join channel: {}", err);
9008 if let Some(active_window) = active_window {
9009 active_window
9010 .update(cx, |_, window, cx| {
9011 let detail: SharedString = match err.error_code() {
9012 ErrorCode::SignedOut => "Please sign in to continue.".into(),
9013 ErrorCode::UpgradeRequired => concat!(
9014 "Your are running an unsupported version of Zed. ",
9015 "Please update to continue."
9016 )
9017 .into(),
9018 ErrorCode::NoSuchChannel => concat!(
9019 "No matching channel was found. ",
9020 "Please check the link and try again."
9021 )
9022 .into(),
9023 ErrorCode::Forbidden => concat!(
9024 "This channel is private, and you do not have access. ",
9025 "Please ask someone to add you and try again."
9026 )
9027 .into(),
9028 ErrorCode::Disconnected => {
9029 "Please check your internet connection and try again.".into()
9030 }
9031 _ => format!("{}\n\nPlease try again.", err).into(),
9032 };
9033 window.prompt(
9034 PromptLevel::Critical,
9035 "Failed to join channel",
9036 Some(&detail),
9037 &["Ok"],
9038 cx,
9039 )
9040 })?
9041 .await
9042 .ok();
9043 }
9044 }
9045
9046 // return ok, we showed the error to the user.
9047 anyhow::Ok(())
9048 })
9049}
9050
9051pub async fn get_any_active_multi_workspace(
9052 app_state: Arc<AppState>,
9053 mut cx: AsyncApp,
9054) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
9055 // find an existing workspace to focus and show call controls
9056 let active_window = activate_any_workspace_window(&mut cx);
9057 if active_window.is_none() {
9058 cx.update(|cx| {
9059 Workspace::new_local(
9060 vec![],
9061 app_state.clone(),
9062 None,
9063 None,
9064 None,
9065 OpenMode::Activate,
9066 cx,
9067 )
9068 })
9069 .await?;
9070 }
9071 activate_any_workspace_window(&mut cx).context("could not open zed")
9072}
9073
9074fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
9075 cx.update(|cx| {
9076 if let Some(workspace_window) = cx
9077 .active_window()
9078 .and_then(|window| window.downcast::<MultiWorkspace>())
9079 {
9080 return Some(workspace_window);
9081 }
9082
9083 for window in cx.windows() {
9084 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
9085 workspace_window
9086 .update(cx, |_, window, _| window.activate_window())
9087 .ok();
9088 return Some(workspace_window);
9089 }
9090 }
9091 None
9092 })
9093}
9094
9095pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
9096 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
9097}
9098
9099pub fn workspace_windows_for_location(
9100 serialized_location: &SerializedWorkspaceLocation,
9101 cx: &App,
9102) -> Vec<WindowHandle<MultiWorkspace>> {
9103 cx.windows()
9104 .into_iter()
9105 .filter_map(|window| window.downcast::<MultiWorkspace>())
9106 .filter(|multi_workspace| {
9107 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
9108 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
9109 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
9110 }
9111 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
9112 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
9113 a.distro_name == b.distro_name
9114 }
9115 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
9116 a.container_id == b.container_id
9117 }
9118 #[cfg(any(test, feature = "test-support"))]
9119 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
9120 a.id == b.id
9121 }
9122 _ => false,
9123 };
9124
9125 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
9126 multi_workspace.workspaces().iter().any(|workspace| {
9127 match workspace.read(cx).workspace_location(cx) {
9128 WorkspaceLocation::Location(location, _) => {
9129 match (&location, serialized_location) {
9130 (
9131 SerializedWorkspaceLocation::Local,
9132 SerializedWorkspaceLocation::Local,
9133 ) => true,
9134 (
9135 SerializedWorkspaceLocation::Remote(a),
9136 SerializedWorkspaceLocation::Remote(b),
9137 ) => same_host(a, b),
9138 _ => false,
9139 }
9140 }
9141 _ => false,
9142 }
9143 })
9144 })
9145 })
9146 .collect()
9147}
9148
9149pub async fn find_existing_workspace(
9150 abs_paths: &[PathBuf],
9151 open_options: &OpenOptions,
9152 location: &SerializedWorkspaceLocation,
9153 cx: &mut AsyncApp,
9154) -> (
9155 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
9156 OpenVisible,
9157) {
9158 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
9159 let mut open_visible = OpenVisible::All;
9160 let mut best_match = None;
9161
9162 if open_options.open_new_workspace != Some(true) {
9163 cx.update(|cx| {
9164 for window in workspace_windows_for_location(location, cx) {
9165 if let Ok(multi_workspace) = window.read(cx) {
9166 for workspace in multi_workspace.workspaces() {
9167 let project = workspace.read(cx).project.read(cx);
9168 let m = project.visibility_for_paths(
9169 abs_paths,
9170 open_options.open_new_workspace == None,
9171 cx,
9172 );
9173 if m > best_match {
9174 existing = Some((window, workspace.clone()));
9175 best_match = m;
9176 } else if best_match.is_none()
9177 && open_options.open_new_workspace == Some(false)
9178 {
9179 existing = Some((window, workspace.clone()))
9180 }
9181 }
9182 }
9183 }
9184 });
9185
9186 let all_paths_are_files = existing
9187 .as_ref()
9188 .and_then(|(_, target_workspace)| {
9189 cx.update(|cx| {
9190 let workspace = target_workspace.read(cx);
9191 let project = workspace.project.read(cx);
9192 let path_style = workspace.path_style(cx);
9193 Some(!abs_paths.iter().any(|path| {
9194 let path = util::paths::SanitizedPath::new(path);
9195 project.worktrees(cx).any(|worktree| {
9196 let worktree = worktree.read(cx);
9197 let abs_path = worktree.abs_path();
9198 path_style
9199 .strip_prefix(path.as_ref(), abs_path.as_ref())
9200 .and_then(|rel| worktree.entry_for_path(&rel))
9201 .is_some_and(|e| e.is_dir())
9202 })
9203 }))
9204 })
9205 })
9206 .unwrap_or(false);
9207
9208 if open_options.open_new_workspace.is_none()
9209 && existing.is_some()
9210 && open_options.wait
9211 && all_paths_are_files
9212 {
9213 cx.update(|cx| {
9214 let windows = workspace_windows_for_location(location, cx);
9215 let window = cx
9216 .active_window()
9217 .and_then(|window| window.downcast::<MultiWorkspace>())
9218 .filter(|window| windows.contains(window))
9219 .or_else(|| windows.into_iter().next());
9220 if let Some(window) = window {
9221 if let Ok(multi_workspace) = window.read(cx) {
9222 let active_workspace = multi_workspace.workspace().clone();
9223 existing = Some((window, active_workspace));
9224 open_visible = OpenVisible::None;
9225 }
9226 }
9227 });
9228 }
9229 }
9230 (existing, open_visible)
9231}
9232
9233#[derive(Default, Clone)]
9234pub struct OpenOptions {
9235 pub visible: Option<OpenVisible>,
9236 pub focus: Option<bool>,
9237 pub open_new_workspace: Option<bool>,
9238 pub wait: bool,
9239 pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
9240 pub open_mode: OpenMode,
9241 pub env: Option<HashMap<String, String>>,
9242}
9243
9244/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
9245/// or [`Workspace::open_workspace_for_paths`].
9246pub struct OpenResult {
9247 pub window: WindowHandle<MultiWorkspace>,
9248 pub workspace: Entity<Workspace>,
9249 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
9250}
9251
9252/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
9253pub fn open_workspace_by_id(
9254 workspace_id: WorkspaceId,
9255 app_state: Arc<AppState>,
9256 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9257 cx: &mut App,
9258) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
9259 let project_handle = Project::local(
9260 app_state.client.clone(),
9261 app_state.node_runtime.clone(),
9262 app_state.user_store.clone(),
9263 app_state.languages.clone(),
9264 app_state.fs.clone(),
9265 None,
9266 project::LocalProjectFlags {
9267 init_worktree_trust: true,
9268 ..project::LocalProjectFlags::default()
9269 },
9270 cx,
9271 );
9272
9273 let db = WorkspaceDb::global(cx);
9274 let kvp = db::kvp::KeyValueStore::global(cx);
9275 cx.spawn(async move |cx| {
9276 let serialized_workspace = db
9277 .workspace_for_id(workspace_id)
9278 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
9279
9280 let centered_layout = serialized_workspace.centered_layout;
9281
9282 let (window, workspace) = if let Some(window) = requesting_window {
9283 let workspace = window.update(cx, |multi_workspace, window, cx| {
9284 let workspace = cx.new(|cx| {
9285 let mut workspace = Workspace::new(
9286 Some(workspace_id),
9287 project_handle.clone(),
9288 app_state.clone(),
9289 window,
9290 cx,
9291 );
9292 workspace.centered_layout = centered_layout;
9293 workspace
9294 });
9295 multi_workspace.add(workspace.clone(), &*window, cx);
9296 workspace
9297 })?;
9298 (window, workspace)
9299 } else {
9300 let window_bounds_override = window_bounds_env_override();
9301
9302 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
9303 (Some(WindowBounds::Windowed(bounds)), None)
9304 } else if let Some(display) = serialized_workspace.display
9305 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
9306 {
9307 (Some(bounds.0), Some(display))
9308 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
9309 (Some(bounds), Some(display))
9310 } else {
9311 (None, None)
9312 };
9313
9314 let options = cx.update(|cx| {
9315 let mut options = (app_state.build_window_options)(display, cx);
9316 options.window_bounds = window_bounds;
9317 options
9318 });
9319
9320 let window = cx.open_window(options, {
9321 let app_state = app_state.clone();
9322 let project_handle = project_handle.clone();
9323 move |window, cx| {
9324 let workspace = cx.new(|cx| {
9325 let mut workspace = Workspace::new(
9326 Some(workspace_id),
9327 project_handle,
9328 app_state,
9329 window,
9330 cx,
9331 );
9332 workspace.centered_layout = centered_layout;
9333 workspace
9334 });
9335 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9336 }
9337 })?;
9338
9339 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9340 multi_workspace.workspace().clone()
9341 })?;
9342
9343 (window, workspace)
9344 };
9345
9346 notify_if_database_failed(window, cx);
9347
9348 // Restore items from the serialized workspace
9349 window
9350 .update(cx, |_, window, cx| {
9351 workspace.update(cx, |_workspace, cx| {
9352 open_items(Some(serialized_workspace), vec![], window, cx)
9353 })
9354 })?
9355 .await?;
9356
9357 window.update(cx, |_, window, cx| {
9358 workspace.update(cx, |workspace, cx| {
9359 workspace.serialize_workspace(window, cx);
9360 });
9361 })?;
9362
9363 Ok(window)
9364 })
9365}
9366
9367#[allow(clippy::type_complexity)]
9368pub fn open_paths(
9369 abs_paths: &[PathBuf],
9370 app_state: Arc<AppState>,
9371 open_options: OpenOptions,
9372 cx: &mut App,
9373) -> Task<anyhow::Result<OpenResult>> {
9374 let abs_paths = abs_paths.to_vec();
9375 #[cfg(target_os = "windows")]
9376 let wsl_path = abs_paths
9377 .iter()
9378 .find_map(|p| util::paths::WslPath::from_path(p));
9379
9380 cx.spawn(async move |cx| {
9381 let (mut existing, mut open_visible) = find_existing_workspace(
9382 &abs_paths,
9383 &open_options,
9384 &SerializedWorkspaceLocation::Local,
9385 cx,
9386 )
9387 .await;
9388
9389 // Fallback: if no workspace contains the paths and all paths are files,
9390 // prefer an existing local workspace window (active window first).
9391 if open_options.open_new_workspace.is_none() && existing.is_none() {
9392 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9393 let all_metadatas = futures::future::join_all(all_paths)
9394 .await
9395 .into_iter()
9396 .filter_map(|result| result.ok().flatten())
9397 .collect::<Vec<_>>();
9398
9399 if all_metadatas.iter().all(|file| !file.is_dir) {
9400 cx.update(|cx| {
9401 let windows = workspace_windows_for_location(
9402 &SerializedWorkspaceLocation::Local,
9403 cx,
9404 );
9405 let window = cx
9406 .active_window()
9407 .and_then(|window| window.downcast::<MultiWorkspace>())
9408 .filter(|window| windows.contains(window))
9409 .or_else(|| windows.into_iter().next());
9410 if let Some(window) = window {
9411 if let Ok(multi_workspace) = window.read(cx) {
9412 let active_workspace = multi_workspace.workspace().clone();
9413 existing = Some((window, active_workspace));
9414 open_visible = OpenVisible::None;
9415 }
9416 }
9417 });
9418 }
9419 }
9420
9421 let result = if let Some((existing, target_workspace)) = existing {
9422 let open_task = existing
9423 .update(cx, |multi_workspace, window, cx| {
9424 window.activate_window();
9425 multi_workspace.activate(target_workspace.clone(), window, cx);
9426 target_workspace.update(cx, |workspace, cx| {
9427 workspace.open_paths(
9428 abs_paths,
9429 OpenOptions {
9430 visible: Some(open_visible),
9431 ..Default::default()
9432 },
9433 None,
9434 window,
9435 cx,
9436 )
9437 })
9438 })?
9439 .await;
9440
9441 _ = existing.update(cx, |multi_workspace, _, cx| {
9442 let workspace = multi_workspace.workspace().clone();
9443 workspace.update(cx, |workspace, cx| {
9444 for item in open_task.iter().flatten() {
9445 if let Err(e) = item {
9446 workspace.show_error(&e, cx);
9447 }
9448 }
9449 });
9450 });
9451
9452 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9453 } else {
9454 let result = cx
9455 .update(move |cx| {
9456 Workspace::new_local(
9457 abs_paths,
9458 app_state.clone(),
9459 open_options.requesting_window,
9460 open_options.env,
9461 None,
9462 open_options.open_mode,
9463 cx,
9464 )
9465 })
9466 .await;
9467
9468 if let Ok(ref result) = result {
9469 result.window
9470 .update(cx, |_, window, _cx| {
9471 window.activate_window();
9472 })
9473 .log_err();
9474 }
9475
9476 result
9477 };
9478
9479 #[cfg(target_os = "windows")]
9480 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9481 && let Ok(ref result) = result
9482 {
9483 result.window
9484 .update(cx, move |multi_workspace, _window, cx| {
9485 struct OpenInWsl;
9486 let workspace = multi_workspace.workspace().clone();
9487 workspace.update(cx, |workspace, cx| {
9488 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9489 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9490 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9491 cx.new(move |cx| {
9492 MessageNotification::new(msg, cx)
9493 .primary_message("Open in WSL")
9494 .primary_icon(IconName::FolderOpen)
9495 .primary_on_click(move |window, cx| {
9496 window.dispatch_action(Box::new(remote::OpenWslPath {
9497 distro: remote::WslConnectionOptions {
9498 distro_name: distro.clone(),
9499 user: None,
9500 },
9501 paths: vec![path.clone().into()],
9502 }), cx)
9503 })
9504 })
9505 });
9506 });
9507 })
9508 .unwrap();
9509 };
9510 result
9511 })
9512}
9513
9514pub fn open_new(
9515 open_options: OpenOptions,
9516 app_state: Arc<AppState>,
9517 cx: &mut App,
9518 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9519) -> Task<anyhow::Result<()>> {
9520 let addition = open_options.open_mode;
9521 let task = Workspace::new_local(
9522 Vec::new(),
9523 app_state,
9524 open_options.requesting_window,
9525 open_options.env,
9526 Some(Box::new(init)),
9527 addition,
9528 cx,
9529 );
9530 cx.spawn(async move |cx| {
9531 let OpenResult { window, .. } = task.await?;
9532 window
9533 .update(cx, |_, window, _cx| {
9534 window.activate_window();
9535 })
9536 .ok();
9537 Ok(())
9538 })
9539}
9540
9541pub fn create_and_open_local_file(
9542 path: &'static Path,
9543 window: &mut Window,
9544 cx: &mut Context<Workspace>,
9545 default_content: impl 'static + Send + FnOnce() -> Rope,
9546) -> Task<Result<Box<dyn ItemHandle>>> {
9547 cx.spawn_in(window, async move |workspace, cx| {
9548 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9549 if !fs.is_file(path).await {
9550 fs.create_file(path, Default::default()).await?;
9551 fs.save(path, &default_content(), Default::default())
9552 .await?;
9553 }
9554
9555 workspace
9556 .update_in(cx, |workspace, window, cx| {
9557 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9558 let path = workspace
9559 .project
9560 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9561 cx.spawn_in(window, async move |workspace, cx| {
9562 let path = path.await?;
9563
9564 let path = fs.canonicalize(&path).await.unwrap_or(path);
9565
9566 let mut items = workspace
9567 .update_in(cx, |workspace, window, cx| {
9568 workspace.open_paths(
9569 vec![path.to_path_buf()],
9570 OpenOptions {
9571 visible: Some(OpenVisible::None),
9572 ..Default::default()
9573 },
9574 None,
9575 window,
9576 cx,
9577 )
9578 })?
9579 .await;
9580 let item = items.pop().flatten();
9581 item.with_context(|| format!("path {path:?} is not a file"))?
9582 })
9583 })
9584 })?
9585 .await?
9586 .await
9587 })
9588}
9589
9590pub fn open_remote_project_with_new_connection(
9591 window: WindowHandle<MultiWorkspace>,
9592 remote_connection: Arc<dyn RemoteConnection>,
9593 cancel_rx: oneshot::Receiver<()>,
9594 delegate: Arc<dyn RemoteClientDelegate>,
9595 app_state: Arc<AppState>,
9596 paths: Vec<PathBuf>,
9597 cx: &mut App,
9598) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9599 cx.spawn(async move |cx| {
9600 let (workspace_id, serialized_workspace) =
9601 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9602 .await?;
9603
9604 let session = match cx
9605 .update(|cx| {
9606 remote::RemoteClient::new(
9607 ConnectionIdentifier::Workspace(workspace_id.0),
9608 remote_connection,
9609 cancel_rx,
9610 delegate,
9611 cx,
9612 )
9613 })
9614 .await?
9615 {
9616 Some(result) => result,
9617 None => return Ok(Vec::new()),
9618 };
9619
9620 let project = cx.update(|cx| {
9621 project::Project::remote(
9622 session,
9623 app_state.client.clone(),
9624 app_state.node_runtime.clone(),
9625 app_state.user_store.clone(),
9626 app_state.languages.clone(),
9627 app_state.fs.clone(),
9628 true,
9629 cx,
9630 )
9631 });
9632
9633 open_remote_project_inner(
9634 project,
9635 paths,
9636 workspace_id,
9637 serialized_workspace,
9638 app_state,
9639 window,
9640 cx,
9641 )
9642 .await
9643 })
9644}
9645
9646pub fn open_remote_project_with_existing_connection(
9647 connection_options: RemoteConnectionOptions,
9648 project: Entity<Project>,
9649 paths: Vec<PathBuf>,
9650 app_state: Arc<AppState>,
9651 window: WindowHandle<MultiWorkspace>,
9652 cx: &mut AsyncApp,
9653) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9654 cx.spawn(async move |cx| {
9655 let (workspace_id, serialized_workspace) =
9656 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9657
9658 open_remote_project_inner(
9659 project,
9660 paths,
9661 workspace_id,
9662 serialized_workspace,
9663 app_state,
9664 window,
9665 cx,
9666 )
9667 .await
9668 })
9669}
9670
9671async fn open_remote_project_inner(
9672 project: Entity<Project>,
9673 paths: Vec<PathBuf>,
9674 workspace_id: WorkspaceId,
9675 serialized_workspace: Option<SerializedWorkspace>,
9676 app_state: Arc<AppState>,
9677 window: WindowHandle<MultiWorkspace>,
9678 cx: &mut AsyncApp,
9679) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9680 let db = cx.update(|cx| WorkspaceDb::global(cx));
9681 let toolchains = db.toolchains(workspace_id).await?;
9682 for (toolchain, worktree_path, path) in toolchains {
9683 project
9684 .update(cx, |this, cx| {
9685 let Some(worktree_id) =
9686 this.find_worktree(&worktree_path, cx)
9687 .and_then(|(worktree, rel_path)| {
9688 if rel_path.is_empty() {
9689 Some(worktree.read(cx).id())
9690 } else {
9691 None
9692 }
9693 })
9694 else {
9695 return Task::ready(None);
9696 };
9697
9698 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9699 })
9700 .await;
9701 }
9702 let mut project_paths_to_open = vec![];
9703 let mut project_path_errors = vec![];
9704
9705 for path in paths {
9706 let result = cx
9707 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9708 .await;
9709 match result {
9710 Ok((_, project_path)) => {
9711 project_paths_to_open.push((path.clone(), Some(project_path)));
9712 }
9713 Err(error) => {
9714 project_path_errors.push(error);
9715 }
9716 };
9717 }
9718
9719 if project_paths_to_open.is_empty() {
9720 return Err(project_path_errors.pop().context("no paths given")?);
9721 }
9722
9723 let workspace = window.update(cx, |multi_workspace, window, cx| {
9724 telemetry::event!("SSH Project Opened");
9725
9726 let new_workspace = cx.new(|cx| {
9727 let mut workspace =
9728 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9729 workspace.update_history(cx);
9730
9731 if let Some(ref serialized) = serialized_workspace {
9732 workspace.centered_layout = serialized.centered_layout;
9733 }
9734
9735 workspace
9736 });
9737
9738 multi_workspace.activate(new_workspace.clone(), window, cx);
9739 new_workspace
9740 })?;
9741
9742 let items = window
9743 .update(cx, |_, window, cx| {
9744 window.activate_window();
9745 workspace.update(cx, |_workspace, cx| {
9746 open_items(serialized_workspace, project_paths_to_open, window, cx)
9747 })
9748 })?
9749 .await?;
9750
9751 workspace.update(cx, |workspace, cx| {
9752 for error in project_path_errors {
9753 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9754 if let Some(path) = error.error_tag("path") {
9755 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9756 }
9757 } else {
9758 workspace.show_error(&error, cx)
9759 }
9760 }
9761 });
9762
9763 Ok(items.into_iter().map(|item| item?.ok()).collect())
9764}
9765
9766fn deserialize_remote_project(
9767 connection_options: RemoteConnectionOptions,
9768 paths: Vec<PathBuf>,
9769 cx: &AsyncApp,
9770) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9771 let db = cx.update(|cx| WorkspaceDb::global(cx));
9772 cx.background_spawn(async move {
9773 let remote_connection_id = db
9774 .get_or_create_remote_connection(connection_options)
9775 .await?;
9776
9777 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9778
9779 let workspace_id = if let Some(workspace_id) =
9780 serialized_workspace.as_ref().map(|workspace| workspace.id)
9781 {
9782 workspace_id
9783 } else {
9784 db.next_id().await?
9785 };
9786
9787 Ok((workspace_id, serialized_workspace))
9788 })
9789}
9790
9791pub fn join_in_room_project(
9792 project_id: u64,
9793 follow_user_id: u64,
9794 app_state: Arc<AppState>,
9795 cx: &mut App,
9796) -> Task<Result<()>> {
9797 let windows = cx.windows();
9798 cx.spawn(async move |cx| {
9799 let existing_window_and_workspace: Option<(
9800 WindowHandle<MultiWorkspace>,
9801 Entity<Workspace>,
9802 )> = windows.into_iter().find_map(|window_handle| {
9803 window_handle
9804 .downcast::<MultiWorkspace>()
9805 .and_then(|window_handle| {
9806 window_handle
9807 .update(cx, |multi_workspace, _window, cx| {
9808 for workspace in multi_workspace.workspaces() {
9809 if workspace.read(cx).project().read(cx).remote_id()
9810 == Some(project_id)
9811 {
9812 return Some((window_handle, workspace.clone()));
9813 }
9814 }
9815 None
9816 })
9817 .unwrap_or(None)
9818 })
9819 });
9820
9821 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9822 existing_window_and_workspace
9823 {
9824 existing_window
9825 .update(cx, |multi_workspace, window, cx| {
9826 multi_workspace.activate(target_workspace, window, cx);
9827 })
9828 .ok();
9829 existing_window
9830 } else {
9831 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9832 let project = cx
9833 .update(|cx| {
9834 active_call.0.join_project(
9835 project_id,
9836 app_state.languages.clone(),
9837 app_state.fs.clone(),
9838 cx,
9839 )
9840 })
9841 .await?;
9842
9843 let window_bounds_override = window_bounds_env_override();
9844 cx.update(|cx| {
9845 let mut options = (app_state.build_window_options)(None, cx);
9846 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9847 cx.open_window(options, |window, cx| {
9848 let workspace = cx.new(|cx| {
9849 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9850 });
9851 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9852 })
9853 })?
9854 };
9855
9856 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9857 cx.activate(true);
9858 window.activate_window();
9859
9860 // We set the active workspace above, so this is the correct workspace.
9861 let workspace = multi_workspace.workspace().clone();
9862 workspace.update(cx, |workspace, cx| {
9863 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9864 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9865 .or_else(|| {
9866 // If we couldn't follow the given user, follow the host instead.
9867 let collaborator = workspace
9868 .project()
9869 .read(cx)
9870 .collaborators()
9871 .values()
9872 .find(|collaborator| collaborator.is_host)?;
9873 Some(collaborator.peer_id)
9874 });
9875
9876 if let Some(follow_peer_id) = follow_peer_id {
9877 workspace.follow(follow_peer_id, window, cx);
9878 }
9879 });
9880 })?;
9881
9882 anyhow::Ok(())
9883 })
9884}
9885
9886pub fn reload(cx: &mut App) {
9887 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9888 let mut workspace_windows = cx
9889 .windows()
9890 .into_iter()
9891 .filter_map(|window| window.downcast::<MultiWorkspace>())
9892 .collect::<Vec<_>>();
9893
9894 // If multiple windows have unsaved changes, and need a save prompt,
9895 // prompt in the active window before switching to a different window.
9896 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9897
9898 let mut prompt = None;
9899 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9900 prompt = window
9901 .update(cx, |_, window, cx| {
9902 window.prompt(
9903 PromptLevel::Info,
9904 "Are you sure you want to restart?",
9905 None,
9906 &["Restart", "Cancel"],
9907 cx,
9908 )
9909 })
9910 .ok();
9911 }
9912
9913 cx.spawn(async move |cx| {
9914 if let Some(prompt) = prompt {
9915 let answer = prompt.await?;
9916 if answer != 0 {
9917 return anyhow::Ok(());
9918 }
9919 }
9920
9921 // If the user cancels any save prompt, then keep the app open.
9922 for window in workspace_windows {
9923 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9924 let workspace = multi_workspace.workspace().clone();
9925 workspace.update(cx, |workspace, cx| {
9926 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9927 })
9928 }) && !should_close.await?
9929 {
9930 return anyhow::Ok(());
9931 }
9932 }
9933 cx.update(|cx| cx.restart());
9934 anyhow::Ok(())
9935 })
9936 .detach_and_log_err(cx);
9937}
9938
9939fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9940 let mut parts = value.split(',');
9941 let x: usize = parts.next()?.parse().ok()?;
9942 let y: usize = parts.next()?.parse().ok()?;
9943 Some(point(px(x as f32), px(y as f32)))
9944}
9945
9946fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9947 let mut parts = value.split(',');
9948 let width: usize = parts.next()?.parse().ok()?;
9949 let height: usize = parts.next()?.parse().ok()?;
9950 Some(size(px(width as f32), px(height as f32)))
9951}
9952
9953/// Add client-side decorations (rounded corners, shadows, resize handling) when
9954/// appropriate.
9955///
9956/// The `border_radius_tiling` parameter allows overriding which corners get
9957/// rounded, independently of the actual window tiling state. This is used
9958/// specifically for the workspace switcher sidebar: when the sidebar is open,
9959/// we want square corners on the left (so the sidebar appears flush with the
9960/// window edge) but we still need the shadow padding for proper visual
9961/// appearance. Unlike actual window tiling, this only affects border radius -
9962/// not padding or shadows.
9963pub fn client_side_decorations(
9964 element: impl IntoElement,
9965 window: &mut Window,
9966 cx: &mut App,
9967 border_radius_tiling: Tiling,
9968) -> Stateful<Div> {
9969 const BORDER_SIZE: Pixels = px(1.0);
9970 let decorations = window.window_decorations();
9971 let tiling = match decorations {
9972 Decorations::Server => Tiling::default(),
9973 Decorations::Client { tiling } => tiling,
9974 };
9975
9976 match decorations {
9977 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9978 Decorations::Server => window.set_client_inset(px(0.0)),
9979 }
9980
9981 struct GlobalResizeEdge(ResizeEdge);
9982 impl Global for GlobalResizeEdge {}
9983
9984 div()
9985 .id("window-backdrop")
9986 .bg(transparent_black())
9987 .map(|div| match decorations {
9988 Decorations::Server => div,
9989 Decorations::Client { .. } => div
9990 .when(
9991 !(tiling.top
9992 || tiling.right
9993 || border_radius_tiling.top
9994 || border_radius_tiling.right),
9995 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9996 )
9997 .when(
9998 !(tiling.top
9999 || tiling.left
10000 || border_radius_tiling.top
10001 || border_radius_tiling.left),
10002 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10003 )
10004 .when(
10005 !(tiling.bottom
10006 || tiling.right
10007 || border_radius_tiling.bottom
10008 || border_radius_tiling.right),
10009 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10010 )
10011 .when(
10012 !(tiling.bottom
10013 || tiling.left
10014 || border_radius_tiling.bottom
10015 || border_radius_tiling.left),
10016 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10017 )
10018 .when(!tiling.top, |div| {
10019 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10020 })
10021 .when(!tiling.bottom, |div| {
10022 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10023 })
10024 .when(!tiling.left, |div| {
10025 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10026 })
10027 .when(!tiling.right, |div| {
10028 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10029 })
10030 .on_mouse_move(move |e, window, cx| {
10031 let size = window.window_bounds().get_bounds().size;
10032 let pos = e.position;
10033
10034 let new_edge =
10035 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10036
10037 let edge = cx.try_global::<GlobalResizeEdge>();
10038 if new_edge != edge.map(|edge| edge.0) {
10039 window
10040 .window_handle()
10041 .update(cx, |workspace, _, cx| {
10042 cx.notify(workspace.entity_id());
10043 })
10044 .ok();
10045 }
10046 })
10047 .on_mouse_down(MouseButton::Left, move |e, window, _| {
10048 let size = window.window_bounds().get_bounds().size;
10049 let pos = e.position;
10050
10051 let edge = match resize_edge(
10052 pos,
10053 theme::CLIENT_SIDE_DECORATION_SHADOW,
10054 size,
10055 tiling,
10056 ) {
10057 Some(value) => value,
10058 None => return,
10059 };
10060
10061 window.start_window_resize(edge);
10062 }),
10063 })
10064 .size_full()
10065 .child(
10066 div()
10067 .cursor(CursorStyle::Arrow)
10068 .map(|div| match decorations {
10069 Decorations::Server => div,
10070 Decorations::Client { .. } => div
10071 .border_color(cx.theme().colors().border)
10072 .when(
10073 !(tiling.top
10074 || tiling.right
10075 || border_radius_tiling.top
10076 || border_radius_tiling.right),
10077 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10078 )
10079 .when(
10080 !(tiling.top
10081 || tiling.left
10082 || border_radius_tiling.top
10083 || border_radius_tiling.left),
10084 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10085 )
10086 .when(
10087 !(tiling.bottom
10088 || tiling.right
10089 || border_radius_tiling.bottom
10090 || border_radius_tiling.right),
10091 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10092 )
10093 .when(
10094 !(tiling.bottom
10095 || tiling.left
10096 || border_radius_tiling.bottom
10097 || border_radius_tiling.left),
10098 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10099 )
10100 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10101 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10102 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10103 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10104 .when(!tiling.is_tiled(), |div| {
10105 div.shadow(vec![gpui::BoxShadow {
10106 color: Hsla {
10107 h: 0.,
10108 s: 0.,
10109 l: 0.,
10110 a: 0.4,
10111 },
10112 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10113 spread_radius: px(0.),
10114 offset: point(px(0.0), px(0.0)),
10115 }])
10116 }),
10117 })
10118 .on_mouse_move(|_e, _, cx| {
10119 cx.stop_propagation();
10120 })
10121 .size_full()
10122 .child(element),
10123 )
10124 .map(|div| match decorations {
10125 Decorations::Server => div,
10126 Decorations::Client { tiling, .. } => div.child(
10127 canvas(
10128 |_bounds, window, _| {
10129 window.insert_hitbox(
10130 Bounds::new(
10131 point(px(0.0), px(0.0)),
10132 window.window_bounds().get_bounds().size,
10133 ),
10134 HitboxBehavior::Normal,
10135 )
10136 },
10137 move |_bounds, hitbox, window, cx| {
10138 let mouse = window.mouse_position();
10139 let size = window.window_bounds().get_bounds().size;
10140 let Some(edge) =
10141 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10142 else {
10143 return;
10144 };
10145 cx.set_global(GlobalResizeEdge(edge));
10146 window.set_cursor_style(
10147 match edge {
10148 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10149 ResizeEdge::Left | ResizeEdge::Right => {
10150 CursorStyle::ResizeLeftRight
10151 }
10152 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10153 CursorStyle::ResizeUpLeftDownRight
10154 }
10155 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10156 CursorStyle::ResizeUpRightDownLeft
10157 }
10158 },
10159 &hitbox,
10160 );
10161 },
10162 )
10163 .size_full()
10164 .absolute(),
10165 ),
10166 })
10167}
10168
10169fn resize_edge(
10170 pos: Point<Pixels>,
10171 shadow_size: Pixels,
10172 window_size: Size<Pixels>,
10173 tiling: Tiling,
10174) -> Option<ResizeEdge> {
10175 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10176 if bounds.contains(&pos) {
10177 return None;
10178 }
10179
10180 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10181 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10182 if !tiling.top && top_left_bounds.contains(&pos) {
10183 return Some(ResizeEdge::TopLeft);
10184 }
10185
10186 let top_right_bounds = Bounds::new(
10187 Point::new(window_size.width - corner_size.width, px(0.)),
10188 corner_size,
10189 );
10190 if !tiling.top && top_right_bounds.contains(&pos) {
10191 return Some(ResizeEdge::TopRight);
10192 }
10193
10194 let bottom_left_bounds = Bounds::new(
10195 Point::new(px(0.), window_size.height - corner_size.height),
10196 corner_size,
10197 );
10198 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10199 return Some(ResizeEdge::BottomLeft);
10200 }
10201
10202 let bottom_right_bounds = Bounds::new(
10203 Point::new(
10204 window_size.width - corner_size.width,
10205 window_size.height - corner_size.height,
10206 ),
10207 corner_size,
10208 );
10209 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10210 return Some(ResizeEdge::BottomRight);
10211 }
10212
10213 if !tiling.top && pos.y < shadow_size {
10214 Some(ResizeEdge::Top)
10215 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10216 Some(ResizeEdge::Bottom)
10217 } else if !tiling.left && pos.x < shadow_size {
10218 Some(ResizeEdge::Left)
10219 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10220 Some(ResizeEdge::Right)
10221 } else {
10222 None
10223 }
10224}
10225
10226fn join_pane_into_active(
10227 active_pane: &Entity<Pane>,
10228 pane: &Entity<Pane>,
10229 window: &mut Window,
10230 cx: &mut App,
10231) {
10232 if pane == active_pane {
10233 } else if pane.read(cx).items_len() == 0 {
10234 pane.update(cx, |_, cx| {
10235 cx.emit(pane::Event::Remove {
10236 focus_on_pane: None,
10237 });
10238 })
10239 } else {
10240 move_all_items(pane, active_pane, window, cx);
10241 }
10242}
10243
10244fn move_all_items(
10245 from_pane: &Entity<Pane>,
10246 to_pane: &Entity<Pane>,
10247 window: &mut Window,
10248 cx: &mut App,
10249) {
10250 let destination_is_different = from_pane != to_pane;
10251 let mut moved_items = 0;
10252 for (item_ix, item_handle) in from_pane
10253 .read(cx)
10254 .items()
10255 .enumerate()
10256 .map(|(ix, item)| (ix, item.clone()))
10257 .collect::<Vec<_>>()
10258 {
10259 let ix = item_ix - moved_items;
10260 if destination_is_different {
10261 // Close item from previous pane
10262 from_pane.update(cx, |source, cx| {
10263 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10264 });
10265 moved_items += 1;
10266 }
10267
10268 // This automatically removes duplicate items in the pane
10269 to_pane.update(cx, |destination, cx| {
10270 destination.add_item(item_handle, true, true, None, window, cx);
10271 window.focus(&destination.focus_handle(cx), cx)
10272 });
10273 }
10274}
10275
10276pub fn move_item(
10277 source: &Entity<Pane>,
10278 destination: &Entity<Pane>,
10279 item_id_to_move: EntityId,
10280 destination_index: usize,
10281 activate: bool,
10282 window: &mut Window,
10283 cx: &mut App,
10284) {
10285 let Some((item_ix, item_handle)) = source
10286 .read(cx)
10287 .items()
10288 .enumerate()
10289 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10290 .map(|(ix, item)| (ix, item.clone()))
10291 else {
10292 // Tab was closed during drag
10293 return;
10294 };
10295
10296 if source != destination {
10297 // Close item from previous pane
10298 source.update(cx, |source, cx| {
10299 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10300 });
10301 }
10302
10303 // This automatically removes duplicate items in the pane
10304 destination.update(cx, |destination, cx| {
10305 destination.add_item_inner(
10306 item_handle,
10307 activate,
10308 activate,
10309 activate,
10310 Some(destination_index),
10311 window,
10312 cx,
10313 );
10314 if activate {
10315 window.focus(&destination.focus_handle(cx), cx)
10316 }
10317 });
10318}
10319
10320pub fn move_active_item(
10321 source: &Entity<Pane>,
10322 destination: &Entity<Pane>,
10323 focus_destination: bool,
10324 close_if_empty: bool,
10325 window: &mut Window,
10326 cx: &mut App,
10327) {
10328 if source == destination {
10329 return;
10330 }
10331 let Some(active_item) = source.read(cx).active_item() else {
10332 return;
10333 };
10334 source.update(cx, |source_pane, cx| {
10335 let item_id = active_item.item_id();
10336 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10337 destination.update(cx, |target_pane, cx| {
10338 target_pane.add_item(
10339 active_item,
10340 focus_destination,
10341 focus_destination,
10342 Some(target_pane.items_len()),
10343 window,
10344 cx,
10345 );
10346 });
10347 });
10348}
10349
10350pub fn clone_active_item(
10351 workspace_id: Option<WorkspaceId>,
10352 source: &Entity<Pane>,
10353 destination: &Entity<Pane>,
10354 focus_destination: bool,
10355 window: &mut Window,
10356 cx: &mut App,
10357) {
10358 if source == destination {
10359 return;
10360 }
10361 let Some(active_item) = source.read(cx).active_item() else {
10362 return;
10363 };
10364 if !active_item.can_split(cx) {
10365 return;
10366 }
10367 let destination = destination.downgrade();
10368 let task = active_item.clone_on_split(workspace_id, window, cx);
10369 window
10370 .spawn(cx, async move |cx| {
10371 let Some(clone) = task.await else {
10372 return;
10373 };
10374 destination
10375 .update_in(cx, |target_pane, window, cx| {
10376 target_pane.add_item(
10377 clone,
10378 focus_destination,
10379 focus_destination,
10380 Some(target_pane.items_len()),
10381 window,
10382 cx,
10383 );
10384 })
10385 .log_err();
10386 })
10387 .detach();
10388}
10389
10390#[derive(Debug)]
10391pub struct WorkspacePosition {
10392 pub window_bounds: Option<WindowBounds>,
10393 pub display: Option<Uuid>,
10394 pub centered_layout: bool,
10395}
10396
10397pub fn remote_workspace_position_from_db(
10398 connection_options: RemoteConnectionOptions,
10399 paths_to_open: &[PathBuf],
10400 cx: &App,
10401) -> Task<Result<WorkspacePosition>> {
10402 let paths = paths_to_open.to_vec();
10403 let db = WorkspaceDb::global(cx);
10404 let kvp = db::kvp::KeyValueStore::global(cx);
10405
10406 cx.background_spawn(async move {
10407 let remote_connection_id = db
10408 .get_or_create_remote_connection(connection_options)
10409 .await
10410 .context("fetching serialized ssh project")?;
10411 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10412
10413 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10414 (Some(WindowBounds::Windowed(bounds)), None)
10415 } else {
10416 let restorable_bounds = serialized_workspace
10417 .as_ref()
10418 .and_then(|workspace| {
10419 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10420 })
10421 .or_else(|| persistence::read_default_window_bounds(&kvp));
10422
10423 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10424 (Some(serialized_bounds), Some(serialized_display))
10425 } else {
10426 (None, None)
10427 }
10428 };
10429
10430 let centered_layout = serialized_workspace
10431 .as_ref()
10432 .map(|w| w.centered_layout)
10433 .unwrap_or(false);
10434
10435 Ok(WorkspacePosition {
10436 window_bounds,
10437 display,
10438 centered_layout,
10439 })
10440 })
10441}
10442
10443pub fn with_active_or_new_workspace(
10444 cx: &mut App,
10445 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10446) {
10447 match cx
10448 .active_window()
10449 .and_then(|w| w.downcast::<MultiWorkspace>())
10450 {
10451 Some(multi_workspace) => {
10452 cx.defer(move |cx| {
10453 multi_workspace
10454 .update(cx, |multi_workspace, window, cx| {
10455 let workspace = multi_workspace.workspace().clone();
10456 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10457 })
10458 .log_err();
10459 });
10460 }
10461 None => {
10462 let app_state = AppState::global(cx);
10463 open_new(
10464 OpenOptions::default(),
10465 app_state,
10466 cx,
10467 move |workspace, window, cx| f(workspace, window, cx),
10468 )
10469 .detach_and_log_err(cx);
10470 }
10471 }
10472}
10473
10474/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10475/// key. This migration path only runs once per panel per workspace.
10476fn load_legacy_panel_size(
10477 panel_key: &str,
10478 dock_position: DockPosition,
10479 workspace: &Workspace,
10480 cx: &mut App,
10481) -> Option<Pixels> {
10482 #[derive(Deserialize)]
10483 struct LegacyPanelState {
10484 #[serde(default)]
10485 width: Option<Pixels>,
10486 #[serde(default)]
10487 height: Option<Pixels>,
10488 }
10489
10490 let workspace_id = workspace
10491 .database_id()
10492 .map(|id| i64::from(id).to_string())
10493 .or_else(|| workspace.session_id())?;
10494
10495 let legacy_key = match panel_key {
10496 "ProjectPanel" => {
10497 format!("{}-{:?}", "ProjectPanel", workspace_id)
10498 }
10499 "OutlinePanel" => {
10500 format!("{}-{:?}", "OutlinePanel", workspace_id)
10501 }
10502 "GitPanel" => {
10503 format!("{}-{:?}", "GitPanel", workspace_id)
10504 }
10505 "TerminalPanel" => {
10506 format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10507 }
10508 _ => return None,
10509 };
10510
10511 let kvp = db::kvp::KeyValueStore::global(cx);
10512 let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10513 let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10514 let size = match dock_position {
10515 DockPosition::Bottom => state.height,
10516 DockPosition::Left | DockPosition::Right => state.width,
10517 }?;
10518
10519 cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10520 .detach_and_log_err(cx);
10521
10522 Some(size)
10523}
10524
10525#[cfg(test)]
10526mod tests {
10527 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10528
10529 use super::*;
10530 use crate::{
10531 dock::{PanelEvent, test::TestPanel},
10532 item::{
10533 ItemBufferKind, ItemEvent,
10534 test::{TestItem, TestProjectItem},
10535 },
10536 };
10537 use fs::FakeFs;
10538 use gpui::{
10539 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10540 UpdateGlobal, VisualTestContext, px,
10541 };
10542 use project::{Project, ProjectEntryId};
10543 use serde_json::json;
10544 use settings::SettingsStore;
10545 use util::path;
10546 use util::rel_path::rel_path;
10547
10548 #[gpui::test]
10549 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10550 init_test(cx);
10551
10552 let fs = FakeFs::new(cx.executor());
10553 let project = Project::test(fs, [], cx).await;
10554 let (workspace, cx) =
10555 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10556
10557 // Adding an item with no ambiguity renders the tab without detail.
10558 let item1 = cx.new(|cx| {
10559 let mut item = TestItem::new(cx);
10560 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10561 item
10562 });
10563 workspace.update_in(cx, |workspace, window, cx| {
10564 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10565 });
10566 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10567
10568 // Adding an item that creates ambiguity increases the level of detail on
10569 // both tabs.
10570 let item2 = cx.new_window_entity(|_window, cx| {
10571 let mut item = TestItem::new(cx);
10572 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10573 item
10574 });
10575 workspace.update_in(cx, |workspace, window, cx| {
10576 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10577 });
10578 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10579 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10580
10581 // Adding an item that creates ambiguity increases the level of detail only
10582 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10583 // we stop at the highest detail available.
10584 let item3 = cx.new(|cx| {
10585 let mut item = TestItem::new(cx);
10586 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10587 item
10588 });
10589 workspace.update_in(cx, |workspace, window, cx| {
10590 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10591 });
10592 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10593 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10594 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10595 }
10596
10597 #[gpui::test]
10598 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10599 init_test(cx);
10600
10601 let fs = FakeFs::new(cx.executor());
10602 fs.insert_tree(
10603 "/root1",
10604 json!({
10605 "one.txt": "",
10606 "two.txt": "",
10607 }),
10608 )
10609 .await;
10610 fs.insert_tree(
10611 "/root2",
10612 json!({
10613 "three.txt": "",
10614 }),
10615 )
10616 .await;
10617
10618 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10619 let (workspace, cx) =
10620 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10621 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10622 let worktree_id = project.update(cx, |project, cx| {
10623 project.worktrees(cx).next().unwrap().read(cx).id()
10624 });
10625
10626 let item1 = cx.new(|cx| {
10627 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10628 });
10629 let item2 = cx.new(|cx| {
10630 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10631 });
10632
10633 // Add an item to an empty pane
10634 workspace.update_in(cx, |workspace, window, cx| {
10635 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10636 });
10637 project.update(cx, |project, cx| {
10638 assert_eq!(
10639 project.active_entry(),
10640 project
10641 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10642 .map(|e| e.id)
10643 );
10644 });
10645 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10646
10647 // Add a second item to a non-empty pane
10648 workspace.update_in(cx, |workspace, window, cx| {
10649 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10650 });
10651 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10652 project.update(cx, |project, cx| {
10653 assert_eq!(
10654 project.active_entry(),
10655 project
10656 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10657 .map(|e| e.id)
10658 );
10659 });
10660
10661 // Close the active item
10662 pane.update_in(cx, |pane, window, cx| {
10663 pane.close_active_item(&Default::default(), window, cx)
10664 })
10665 .await
10666 .unwrap();
10667 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10668 project.update(cx, |project, cx| {
10669 assert_eq!(
10670 project.active_entry(),
10671 project
10672 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10673 .map(|e| e.id)
10674 );
10675 });
10676
10677 // Add a project folder
10678 project
10679 .update(cx, |project, cx| {
10680 project.find_or_create_worktree("root2", true, cx)
10681 })
10682 .await
10683 .unwrap();
10684 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10685
10686 // Remove a project folder
10687 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10688 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10689 }
10690
10691 #[gpui::test]
10692 async fn test_close_window(cx: &mut TestAppContext) {
10693 init_test(cx);
10694
10695 let fs = FakeFs::new(cx.executor());
10696 fs.insert_tree("/root", json!({ "one": "" })).await;
10697
10698 let project = Project::test(fs, ["root".as_ref()], cx).await;
10699 let (workspace, cx) =
10700 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10701
10702 // When there are no dirty items, there's nothing to do.
10703 let item1 = cx.new(TestItem::new);
10704 workspace.update_in(cx, |w, window, cx| {
10705 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10706 });
10707 let task = workspace.update_in(cx, |w, window, cx| {
10708 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10709 });
10710 assert!(task.await.unwrap());
10711
10712 // When there are dirty untitled items, prompt to save each one. If the user
10713 // cancels any prompt, then abort.
10714 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10715 let item3 = cx.new(|cx| {
10716 TestItem::new(cx)
10717 .with_dirty(true)
10718 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10719 });
10720 workspace.update_in(cx, |w, window, cx| {
10721 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10722 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10723 });
10724 let task = workspace.update_in(cx, |w, window, cx| {
10725 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10726 });
10727 cx.executor().run_until_parked();
10728 cx.simulate_prompt_answer("Cancel"); // cancel save all
10729 cx.executor().run_until_parked();
10730 assert!(!cx.has_pending_prompt());
10731 assert!(!task.await.unwrap());
10732 }
10733
10734 #[gpui::test]
10735 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10736 init_test(cx);
10737
10738 let fs = FakeFs::new(cx.executor());
10739 fs.insert_tree("/root", json!({ "one": "" })).await;
10740
10741 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10742 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10743 let multi_workspace_handle =
10744 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10745 cx.run_until_parked();
10746
10747 let workspace_a = multi_workspace_handle
10748 .read_with(cx, |mw, _| mw.workspace().clone())
10749 .unwrap();
10750
10751 let workspace_b = multi_workspace_handle
10752 .update(cx, |mw, window, cx| {
10753 mw.test_add_workspace(project_b, window, cx)
10754 })
10755 .unwrap();
10756
10757 // Activate workspace A
10758 multi_workspace_handle
10759 .update(cx, |mw, window, cx| {
10760 let workspace = mw.workspaces()[0].clone();
10761 mw.activate(workspace, window, cx);
10762 })
10763 .unwrap();
10764
10765 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10766
10767 // Workspace A has a clean item
10768 let item_a = cx.new(TestItem::new);
10769 workspace_a.update_in(cx, |w, window, cx| {
10770 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10771 });
10772
10773 // Workspace B has a dirty item
10774 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10775 workspace_b.update_in(cx, |w, window, cx| {
10776 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10777 });
10778
10779 // Verify workspace A is active
10780 multi_workspace_handle
10781 .read_with(cx, |mw, _| {
10782 assert_eq!(mw.active_workspace_index(), 0);
10783 })
10784 .unwrap();
10785
10786 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10787 multi_workspace_handle
10788 .update(cx, |mw, window, cx| {
10789 mw.close_window(&CloseWindow, window, cx);
10790 })
10791 .unwrap();
10792 cx.run_until_parked();
10793
10794 // Workspace B should now be active since it has dirty items that need attention
10795 multi_workspace_handle
10796 .read_with(cx, |mw, _| {
10797 assert_eq!(
10798 mw.active_workspace_index(),
10799 1,
10800 "workspace B should be activated when it prompts"
10801 );
10802 })
10803 .unwrap();
10804
10805 // User cancels the save prompt from workspace B
10806 cx.simulate_prompt_answer("Cancel");
10807 cx.run_until_parked();
10808
10809 // Window should still exist because workspace B's close was cancelled
10810 assert!(
10811 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10812 "window should still exist after cancelling one workspace's close"
10813 );
10814 }
10815
10816 #[gpui::test]
10817 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10818 init_test(cx);
10819
10820 // Register TestItem as a serializable item
10821 cx.update(|cx| {
10822 register_serializable_item::<TestItem>(cx);
10823 });
10824
10825 let fs = FakeFs::new(cx.executor());
10826 fs.insert_tree("/root", json!({ "one": "" })).await;
10827
10828 let project = Project::test(fs, ["root".as_ref()], cx).await;
10829 let (workspace, cx) =
10830 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10831
10832 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10833 let item1 = cx.new(|cx| {
10834 TestItem::new(cx)
10835 .with_dirty(true)
10836 .with_serialize(|| Some(Task::ready(Ok(()))))
10837 });
10838 let item2 = cx.new(|cx| {
10839 TestItem::new(cx)
10840 .with_dirty(true)
10841 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10842 .with_serialize(|| Some(Task::ready(Ok(()))))
10843 });
10844 workspace.update_in(cx, |w, window, cx| {
10845 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10846 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10847 });
10848 let task = workspace.update_in(cx, |w, window, cx| {
10849 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10850 });
10851 assert!(task.await.unwrap());
10852 }
10853
10854 #[gpui::test]
10855 async fn test_close_pane_items(cx: &mut TestAppContext) {
10856 init_test(cx);
10857
10858 let fs = FakeFs::new(cx.executor());
10859
10860 let project = Project::test(fs, None, cx).await;
10861 let (workspace, cx) =
10862 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10863
10864 let item1 = cx.new(|cx| {
10865 TestItem::new(cx)
10866 .with_dirty(true)
10867 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10868 });
10869 let item2 = cx.new(|cx| {
10870 TestItem::new(cx)
10871 .with_dirty(true)
10872 .with_conflict(true)
10873 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10874 });
10875 let item3 = cx.new(|cx| {
10876 TestItem::new(cx)
10877 .with_dirty(true)
10878 .with_conflict(true)
10879 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10880 });
10881 let item4 = cx.new(|cx| {
10882 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10883 let project_item = TestProjectItem::new_untitled(cx);
10884 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10885 project_item
10886 }])
10887 });
10888 let pane = workspace.update_in(cx, |workspace, window, cx| {
10889 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10890 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10891 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10892 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10893 workspace.active_pane().clone()
10894 });
10895
10896 let close_items = pane.update_in(cx, |pane, window, cx| {
10897 pane.activate_item(1, true, true, window, cx);
10898 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10899 let item1_id = item1.item_id();
10900 let item3_id = item3.item_id();
10901 let item4_id = item4.item_id();
10902 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10903 [item1_id, item3_id, item4_id].contains(&id)
10904 })
10905 });
10906 cx.executor().run_until_parked();
10907
10908 assert!(cx.has_pending_prompt());
10909 cx.simulate_prompt_answer("Save all");
10910
10911 cx.executor().run_until_parked();
10912
10913 // Item 1 is saved. There's a prompt to save item 3.
10914 pane.update(cx, |pane, cx| {
10915 assert_eq!(item1.read(cx).save_count, 1);
10916 assert_eq!(item1.read(cx).save_as_count, 0);
10917 assert_eq!(item1.read(cx).reload_count, 0);
10918 assert_eq!(pane.items_len(), 3);
10919 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10920 });
10921 assert!(cx.has_pending_prompt());
10922
10923 // Cancel saving item 3.
10924 cx.simulate_prompt_answer("Discard");
10925 cx.executor().run_until_parked();
10926
10927 // Item 3 is reloaded. There's a prompt to save item 4.
10928 pane.update(cx, |pane, cx| {
10929 assert_eq!(item3.read(cx).save_count, 0);
10930 assert_eq!(item3.read(cx).save_as_count, 0);
10931 assert_eq!(item3.read(cx).reload_count, 1);
10932 assert_eq!(pane.items_len(), 2);
10933 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10934 });
10935
10936 // There's a prompt for a path for item 4.
10937 cx.simulate_new_path_selection(|_| Some(Default::default()));
10938 close_items.await.unwrap();
10939
10940 // The requested items are closed.
10941 pane.update(cx, |pane, cx| {
10942 assert_eq!(item4.read(cx).save_count, 0);
10943 assert_eq!(item4.read(cx).save_as_count, 1);
10944 assert_eq!(item4.read(cx).reload_count, 0);
10945 assert_eq!(pane.items_len(), 1);
10946 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10947 });
10948 }
10949
10950 #[gpui::test]
10951 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10952 init_test(cx);
10953
10954 let fs = FakeFs::new(cx.executor());
10955 let project = Project::test(fs, [], cx).await;
10956 let (workspace, cx) =
10957 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10958
10959 // Create several workspace items with single project entries, and two
10960 // workspace items with multiple project entries.
10961 let single_entry_items = (0..=4)
10962 .map(|project_entry_id| {
10963 cx.new(|cx| {
10964 TestItem::new(cx)
10965 .with_dirty(true)
10966 .with_project_items(&[dirty_project_item(
10967 project_entry_id,
10968 &format!("{project_entry_id}.txt"),
10969 cx,
10970 )])
10971 })
10972 })
10973 .collect::<Vec<_>>();
10974 let item_2_3 = cx.new(|cx| {
10975 TestItem::new(cx)
10976 .with_dirty(true)
10977 .with_buffer_kind(ItemBufferKind::Multibuffer)
10978 .with_project_items(&[
10979 single_entry_items[2].read(cx).project_items[0].clone(),
10980 single_entry_items[3].read(cx).project_items[0].clone(),
10981 ])
10982 });
10983 let item_3_4 = cx.new(|cx| {
10984 TestItem::new(cx)
10985 .with_dirty(true)
10986 .with_buffer_kind(ItemBufferKind::Multibuffer)
10987 .with_project_items(&[
10988 single_entry_items[3].read(cx).project_items[0].clone(),
10989 single_entry_items[4].read(cx).project_items[0].clone(),
10990 ])
10991 });
10992
10993 // Create two panes that contain the following project entries:
10994 // left pane:
10995 // multi-entry items: (2, 3)
10996 // single-entry items: 0, 2, 3, 4
10997 // right pane:
10998 // single-entry items: 4, 1
10999 // multi-entry items: (3, 4)
11000 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11001 let left_pane = workspace.active_pane().clone();
11002 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11003 workspace.add_item_to_active_pane(
11004 single_entry_items[0].boxed_clone(),
11005 None,
11006 true,
11007 window,
11008 cx,
11009 );
11010 workspace.add_item_to_active_pane(
11011 single_entry_items[2].boxed_clone(),
11012 None,
11013 true,
11014 window,
11015 cx,
11016 );
11017 workspace.add_item_to_active_pane(
11018 single_entry_items[3].boxed_clone(),
11019 None,
11020 true,
11021 window,
11022 cx,
11023 );
11024 workspace.add_item_to_active_pane(
11025 single_entry_items[4].boxed_clone(),
11026 None,
11027 true,
11028 window,
11029 cx,
11030 );
11031
11032 let right_pane =
11033 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11034
11035 let boxed_clone = single_entry_items[1].boxed_clone();
11036 let right_pane = window.spawn(cx, async move |cx| {
11037 right_pane.await.inspect(|right_pane| {
11038 right_pane
11039 .update_in(cx, |pane, window, cx| {
11040 pane.add_item(boxed_clone, true, true, None, window, cx);
11041 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11042 })
11043 .unwrap();
11044 })
11045 });
11046
11047 (left_pane, right_pane)
11048 });
11049 let right_pane = right_pane.await.unwrap();
11050 cx.focus(&right_pane);
11051
11052 let close = right_pane.update_in(cx, |pane, window, cx| {
11053 pane.close_all_items(&CloseAllItems::default(), window, cx)
11054 .unwrap()
11055 });
11056 cx.executor().run_until_parked();
11057
11058 let msg = cx.pending_prompt().unwrap().0;
11059 assert!(msg.contains("1.txt"));
11060 assert!(!msg.contains("2.txt"));
11061 assert!(!msg.contains("3.txt"));
11062 assert!(!msg.contains("4.txt"));
11063
11064 // With best-effort close, cancelling item 1 keeps it open but items 4
11065 // and (3,4) still close since their entries exist in left pane.
11066 cx.simulate_prompt_answer("Cancel");
11067 close.await;
11068
11069 right_pane.read_with(cx, |pane, _| {
11070 assert_eq!(pane.items_len(), 1);
11071 });
11072
11073 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11074 left_pane
11075 .update_in(cx, |left_pane, window, cx| {
11076 left_pane.close_item_by_id(
11077 single_entry_items[3].entity_id(),
11078 SaveIntent::Skip,
11079 window,
11080 cx,
11081 )
11082 })
11083 .await
11084 .unwrap();
11085
11086 let close = left_pane.update_in(cx, |pane, window, cx| {
11087 pane.close_all_items(&CloseAllItems::default(), window, cx)
11088 .unwrap()
11089 });
11090 cx.executor().run_until_parked();
11091
11092 let details = cx.pending_prompt().unwrap().1;
11093 assert!(details.contains("0.txt"));
11094 assert!(details.contains("3.txt"));
11095 assert!(details.contains("4.txt"));
11096 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11097 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11098 // assert!(!details.contains("2.txt"));
11099
11100 cx.simulate_prompt_answer("Save all");
11101 cx.executor().run_until_parked();
11102 close.await;
11103
11104 left_pane.read_with(cx, |pane, _| {
11105 assert_eq!(pane.items_len(), 0);
11106 });
11107 }
11108
11109 #[gpui::test]
11110 async fn test_autosave(cx: &mut gpui::TestAppContext) {
11111 init_test(cx);
11112
11113 let fs = FakeFs::new(cx.executor());
11114 let project = Project::test(fs, [], cx).await;
11115 let (workspace, cx) =
11116 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11117 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11118
11119 let item = cx.new(|cx| {
11120 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11121 });
11122 let item_id = item.entity_id();
11123 workspace.update_in(cx, |workspace, window, cx| {
11124 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11125 });
11126
11127 // Autosave on window change.
11128 item.update(cx, |item, cx| {
11129 SettingsStore::update_global(cx, |settings, cx| {
11130 settings.update_user_settings(cx, |settings| {
11131 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11132 })
11133 });
11134 item.is_dirty = true;
11135 });
11136
11137 // Deactivating the window saves the file.
11138 cx.deactivate_window();
11139 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11140
11141 // Re-activating the window doesn't save the file.
11142 cx.update(|window, _| window.activate_window());
11143 cx.executor().run_until_parked();
11144 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11145
11146 // Autosave on focus change.
11147 item.update_in(cx, |item, window, cx| {
11148 cx.focus_self(window);
11149 SettingsStore::update_global(cx, |settings, cx| {
11150 settings.update_user_settings(cx, |settings| {
11151 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11152 })
11153 });
11154 item.is_dirty = true;
11155 });
11156 // Blurring the item saves the file.
11157 item.update_in(cx, |_, window, _| window.blur());
11158 cx.executor().run_until_parked();
11159 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11160
11161 // Deactivating the window still saves the file.
11162 item.update_in(cx, |item, window, cx| {
11163 cx.focus_self(window);
11164 item.is_dirty = true;
11165 });
11166 cx.deactivate_window();
11167 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11168
11169 // Autosave after delay.
11170 item.update(cx, |item, cx| {
11171 SettingsStore::update_global(cx, |settings, cx| {
11172 settings.update_user_settings(cx, |settings| {
11173 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11174 milliseconds: 500.into(),
11175 });
11176 })
11177 });
11178 item.is_dirty = true;
11179 cx.emit(ItemEvent::Edit);
11180 });
11181
11182 // Delay hasn't fully expired, so the file is still dirty and unsaved.
11183 cx.executor().advance_clock(Duration::from_millis(250));
11184 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11185
11186 // After delay expires, the file is saved.
11187 cx.executor().advance_clock(Duration::from_millis(250));
11188 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11189
11190 // Autosave after delay, should save earlier than delay if tab is closed
11191 item.update(cx, |item, cx| {
11192 item.is_dirty = true;
11193 cx.emit(ItemEvent::Edit);
11194 });
11195 cx.executor().advance_clock(Duration::from_millis(250));
11196 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11197
11198 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11199 pane.update_in(cx, |pane, window, cx| {
11200 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11201 })
11202 .await
11203 .unwrap();
11204 assert!(!cx.has_pending_prompt());
11205 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11206
11207 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11208 workspace.update_in(cx, |workspace, window, cx| {
11209 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11210 });
11211 item.update_in(cx, |item, _window, cx| {
11212 item.is_dirty = true;
11213 for project_item in &mut item.project_items {
11214 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11215 }
11216 });
11217 cx.run_until_parked();
11218 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11219
11220 // Autosave on focus change, ensuring closing the tab counts as such.
11221 item.update(cx, |item, cx| {
11222 SettingsStore::update_global(cx, |settings, cx| {
11223 settings.update_user_settings(cx, |settings| {
11224 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11225 })
11226 });
11227 item.is_dirty = true;
11228 for project_item in &mut item.project_items {
11229 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11230 }
11231 });
11232
11233 pane.update_in(cx, |pane, window, cx| {
11234 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11235 })
11236 .await
11237 .unwrap();
11238 assert!(!cx.has_pending_prompt());
11239 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11240
11241 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11242 workspace.update_in(cx, |workspace, window, cx| {
11243 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11244 });
11245 item.update_in(cx, |item, window, cx| {
11246 item.project_items[0].update(cx, |item, _| {
11247 item.entry_id = None;
11248 });
11249 item.is_dirty = true;
11250 window.blur();
11251 });
11252 cx.run_until_parked();
11253 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11254
11255 // Ensure autosave is prevented for deleted files also when closing the buffer.
11256 let _close_items = pane.update_in(cx, |pane, window, cx| {
11257 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11258 });
11259 cx.run_until_parked();
11260 assert!(cx.has_pending_prompt());
11261 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11262 }
11263
11264 #[gpui::test]
11265 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11266 init_test(cx);
11267
11268 let fs = FakeFs::new(cx.executor());
11269 let project = Project::test(fs, [], cx).await;
11270 let (workspace, cx) =
11271 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11272
11273 // Create a multibuffer-like item with two child focus handles,
11274 // simulating individual buffer editors within a multibuffer.
11275 let item = cx.new(|cx| {
11276 TestItem::new(cx)
11277 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11278 .with_child_focus_handles(2, cx)
11279 });
11280 workspace.update_in(cx, |workspace, window, cx| {
11281 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11282 });
11283
11284 // Set autosave to OnFocusChange and focus the first child handle,
11285 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11286 item.update_in(cx, |item, window, cx| {
11287 SettingsStore::update_global(cx, |settings, cx| {
11288 settings.update_user_settings(cx, |settings| {
11289 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11290 })
11291 });
11292 item.is_dirty = true;
11293 window.focus(&item.child_focus_handles[0], cx);
11294 });
11295 cx.executor().run_until_parked();
11296 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11297
11298 // Moving focus from one child to another within the same item should
11299 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11300 item.update_in(cx, |item, window, cx| {
11301 window.focus(&item.child_focus_handles[1], cx);
11302 });
11303 cx.executor().run_until_parked();
11304 item.read_with(cx, |item, _| {
11305 assert_eq!(
11306 item.save_count, 0,
11307 "Switching focus between children within the same item should not autosave"
11308 );
11309 });
11310
11311 // Blurring the item saves the file. This is the core regression scenario:
11312 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11313 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11314 // the leaf is always a child focus handle, so `on_blur` never detected
11315 // focus leaving the item.
11316 item.update_in(cx, |_, window, _| window.blur());
11317 cx.executor().run_until_parked();
11318 item.read_with(cx, |item, _| {
11319 assert_eq!(
11320 item.save_count, 1,
11321 "Blurring should trigger autosave when focus was on a child of the item"
11322 );
11323 });
11324
11325 // Deactivating the window should also trigger autosave when a child of
11326 // the multibuffer item currently owns focus.
11327 item.update_in(cx, |item, window, cx| {
11328 item.is_dirty = true;
11329 window.focus(&item.child_focus_handles[0], cx);
11330 });
11331 cx.executor().run_until_parked();
11332 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11333
11334 cx.deactivate_window();
11335 item.read_with(cx, |item, _| {
11336 assert_eq!(
11337 item.save_count, 2,
11338 "Deactivating window should trigger autosave when focus was on a child"
11339 );
11340 });
11341 }
11342
11343 #[gpui::test]
11344 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11345 init_test(cx);
11346
11347 let fs = FakeFs::new(cx.executor());
11348
11349 let project = Project::test(fs, [], cx).await;
11350 let (workspace, cx) =
11351 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11352
11353 let item = cx.new(|cx| {
11354 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11355 });
11356 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11357 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11358 let toolbar_notify_count = Rc::new(RefCell::new(0));
11359
11360 workspace.update_in(cx, |workspace, window, cx| {
11361 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11362 let toolbar_notification_count = toolbar_notify_count.clone();
11363 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11364 *toolbar_notification_count.borrow_mut() += 1
11365 })
11366 .detach();
11367 });
11368
11369 pane.read_with(cx, |pane, _| {
11370 assert!(!pane.can_navigate_backward());
11371 assert!(!pane.can_navigate_forward());
11372 });
11373
11374 item.update_in(cx, |item, _, cx| {
11375 item.set_state("one".to_string(), cx);
11376 });
11377
11378 // Toolbar must be notified to re-render the navigation buttons
11379 assert_eq!(*toolbar_notify_count.borrow(), 1);
11380
11381 pane.read_with(cx, |pane, _| {
11382 assert!(pane.can_navigate_backward());
11383 assert!(!pane.can_navigate_forward());
11384 });
11385
11386 workspace
11387 .update_in(cx, |workspace, window, cx| {
11388 workspace.go_back(pane.downgrade(), window, cx)
11389 })
11390 .await
11391 .unwrap();
11392
11393 assert_eq!(*toolbar_notify_count.borrow(), 2);
11394 pane.read_with(cx, |pane, _| {
11395 assert!(!pane.can_navigate_backward());
11396 assert!(pane.can_navigate_forward());
11397 });
11398 }
11399
11400 /// Tests that the navigation history deduplicates entries for the same item.
11401 ///
11402 /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11403 /// the navigation history deduplicates by keeping only the most recent visit to each item,
11404 /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11405 /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11406 /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11407 ///
11408 /// This behavior prevents the navigation history from growing unnecessarily large and provides
11409 /// a better user experience by eliminating redundant navigation steps when jumping between files.
11410 #[gpui::test]
11411 async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11412 init_test(cx);
11413
11414 let fs = FakeFs::new(cx.executor());
11415 let project = Project::test(fs, [], cx).await;
11416 let (workspace, cx) =
11417 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11418
11419 let item_a = cx.new(|cx| {
11420 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11421 });
11422 let item_b = cx.new(|cx| {
11423 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11424 });
11425 let item_c = cx.new(|cx| {
11426 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11427 });
11428
11429 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11430
11431 workspace.update_in(cx, |workspace, window, cx| {
11432 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11433 workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11434 workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11435 });
11436
11437 workspace.update_in(cx, |workspace, window, cx| {
11438 workspace.activate_item(&item_a, false, false, window, cx);
11439 });
11440 cx.run_until_parked();
11441
11442 workspace.update_in(cx, |workspace, window, cx| {
11443 workspace.activate_item(&item_b, false, false, window, cx);
11444 });
11445 cx.run_until_parked();
11446
11447 workspace.update_in(cx, |workspace, window, cx| {
11448 workspace.activate_item(&item_a, false, false, window, cx);
11449 });
11450 cx.run_until_parked();
11451
11452 workspace.update_in(cx, |workspace, window, cx| {
11453 workspace.activate_item(&item_b, false, false, window, cx);
11454 });
11455 cx.run_until_parked();
11456
11457 workspace.update_in(cx, |workspace, window, cx| {
11458 workspace.activate_item(&item_a, false, false, window, cx);
11459 });
11460 cx.run_until_parked();
11461
11462 workspace.update_in(cx, |workspace, window, cx| {
11463 workspace.activate_item(&item_b, false, false, window, cx);
11464 });
11465 cx.run_until_parked();
11466
11467 workspace.update_in(cx, |workspace, window, cx| {
11468 workspace.activate_item(&item_c, false, false, window, cx);
11469 });
11470 cx.run_until_parked();
11471
11472 let backward_count = pane.read_with(cx, |pane, cx| {
11473 let mut count = 0;
11474 pane.nav_history().for_each_entry(cx, &mut |_, _| {
11475 count += 1;
11476 });
11477 count
11478 });
11479 assert!(
11480 backward_count <= 4,
11481 "Should have at most 4 entries, got {}",
11482 backward_count
11483 );
11484
11485 workspace
11486 .update_in(cx, |workspace, window, cx| {
11487 workspace.go_back(pane.downgrade(), window, cx)
11488 })
11489 .await
11490 .unwrap();
11491
11492 let active_item = workspace.read_with(cx, |workspace, cx| {
11493 workspace.active_item(cx).unwrap().item_id()
11494 });
11495 assert_eq!(
11496 active_item,
11497 item_b.entity_id(),
11498 "After first go_back, should be at item B"
11499 );
11500
11501 workspace
11502 .update_in(cx, |workspace, window, cx| {
11503 workspace.go_back(pane.downgrade(), window, cx)
11504 })
11505 .await
11506 .unwrap();
11507
11508 let active_item = workspace.read_with(cx, |workspace, cx| {
11509 workspace.active_item(cx).unwrap().item_id()
11510 });
11511 assert_eq!(
11512 active_item,
11513 item_a.entity_id(),
11514 "After second go_back, should be at item A"
11515 );
11516
11517 pane.read_with(cx, |pane, _| {
11518 assert!(pane.can_navigate_forward(), "Should be able to go forward");
11519 });
11520 }
11521
11522 #[gpui::test]
11523 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11524 init_test(cx);
11525 let fs = FakeFs::new(cx.executor());
11526 let project = Project::test(fs, [], cx).await;
11527 let (multi_workspace, cx) =
11528 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11529 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11530
11531 workspace.update_in(cx, |workspace, window, cx| {
11532 let first_item = cx.new(|cx| {
11533 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11534 });
11535 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11536 workspace.split_pane(
11537 workspace.active_pane().clone(),
11538 SplitDirection::Right,
11539 window,
11540 cx,
11541 );
11542 workspace.split_pane(
11543 workspace.active_pane().clone(),
11544 SplitDirection::Right,
11545 window,
11546 cx,
11547 );
11548 });
11549
11550 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11551 let panes = workspace.center.panes();
11552 assert!(panes.len() >= 2);
11553 (
11554 panes.first().expect("at least one pane").entity_id(),
11555 panes.last().expect("at least one pane").entity_id(),
11556 )
11557 });
11558
11559 workspace.update_in(cx, |workspace, window, cx| {
11560 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11561 });
11562 workspace.update(cx, |workspace, _| {
11563 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11564 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11565 });
11566
11567 cx.dispatch_action(ActivateLastPane);
11568
11569 workspace.update(cx, |workspace, _| {
11570 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11571 });
11572 }
11573
11574 #[gpui::test]
11575 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11576 init_test(cx);
11577 let fs = FakeFs::new(cx.executor());
11578
11579 let project = Project::test(fs, [], cx).await;
11580 let (workspace, cx) =
11581 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11582
11583 let panel = workspace.update_in(cx, |workspace, window, cx| {
11584 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11585 workspace.add_panel(panel.clone(), window, cx);
11586
11587 workspace
11588 .right_dock()
11589 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11590
11591 panel
11592 });
11593
11594 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11595 pane.update_in(cx, |pane, window, cx| {
11596 let item = cx.new(TestItem::new);
11597 pane.add_item(Box::new(item), true, true, None, window, cx);
11598 });
11599
11600 // Transfer focus from center to panel
11601 workspace.update_in(cx, |workspace, window, cx| {
11602 workspace.toggle_panel_focus::<TestPanel>(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 from panel to center
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 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11621 });
11622
11623 // Close the dock
11624 workspace.update_in(cx, |workspace, window, cx| {
11625 workspace.toggle_dock(DockPosition::Right, window, cx);
11626 });
11627
11628 workspace.update_in(cx, |workspace, window, cx| {
11629 assert!(!workspace.right_dock().read(cx).is_open());
11630 assert!(!panel.is_zoomed(window, cx));
11631 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11632 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11633 });
11634
11635 // Open the dock
11636 workspace.update_in(cx, |workspace, window, cx| {
11637 workspace.toggle_dock(DockPosition::Right, window, cx);
11638 });
11639
11640 workspace.update_in(cx, |workspace, window, cx| {
11641 assert!(workspace.right_dock().read(cx).is_open());
11642 assert!(!panel.is_zoomed(window, cx));
11643 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11644 });
11645
11646 // Focus and zoom panel
11647 panel.update_in(cx, |panel, window, cx| {
11648 cx.focus_self(window);
11649 panel.set_zoomed(true, window, cx)
11650 });
11651
11652 workspace.update_in(cx, |workspace, window, cx| {
11653 assert!(workspace.right_dock().read(cx).is_open());
11654 assert!(panel.is_zoomed(window, cx));
11655 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11656 });
11657
11658 // Transfer focus to the center closes the dock
11659 workspace.update_in(cx, |workspace, window, cx| {
11660 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11661 });
11662
11663 workspace.update_in(cx, |workspace, window, cx| {
11664 assert!(!workspace.right_dock().read(cx).is_open());
11665 assert!(panel.is_zoomed(window, cx));
11666 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11667 });
11668
11669 // Transferring focus back to the panel keeps it zoomed
11670 workspace.update_in(cx, |workspace, window, cx| {
11671 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11672 });
11673
11674 workspace.update_in(cx, |workspace, window, cx| {
11675 assert!(workspace.right_dock().read(cx).is_open());
11676 assert!(panel.is_zoomed(window, cx));
11677 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11678 });
11679
11680 // Close the dock while it is zoomed
11681 workspace.update_in(cx, |workspace, window, cx| {
11682 workspace.toggle_dock(DockPosition::Right, window, cx)
11683 });
11684
11685 workspace.update_in(cx, |workspace, window, cx| {
11686 assert!(!workspace.right_dock().read(cx).is_open());
11687 assert!(panel.is_zoomed(window, cx));
11688 assert!(workspace.zoomed.is_none());
11689 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11690 });
11691
11692 // Opening the dock, when it's zoomed, retains focus
11693 workspace.update_in(cx, |workspace, window, cx| {
11694 workspace.toggle_dock(DockPosition::Right, window, cx)
11695 });
11696
11697 workspace.update_in(cx, |workspace, window, cx| {
11698 assert!(workspace.right_dock().read(cx).is_open());
11699 assert!(panel.is_zoomed(window, cx));
11700 assert!(workspace.zoomed.is_some());
11701 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11702 });
11703
11704 // Unzoom and close the panel, zoom the active pane.
11705 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11706 workspace.update_in(cx, |workspace, window, cx| {
11707 workspace.toggle_dock(DockPosition::Right, window, cx)
11708 });
11709 pane.update_in(cx, |pane, window, cx| {
11710 pane.toggle_zoom(&Default::default(), window, cx)
11711 });
11712
11713 // Opening a dock unzooms the pane.
11714 workspace.update_in(cx, |workspace, window, cx| {
11715 workspace.toggle_dock(DockPosition::Right, window, cx)
11716 });
11717 workspace.update_in(cx, |workspace, window, cx| {
11718 let pane = pane.read(cx);
11719 assert!(!pane.is_zoomed());
11720 assert!(!pane.focus_handle(cx).is_focused(window));
11721 assert!(workspace.right_dock().read(cx).is_open());
11722 assert!(workspace.zoomed.is_none());
11723 });
11724 }
11725
11726 #[gpui::test]
11727 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11728 init_test(cx);
11729 let fs = FakeFs::new(cx.executor());
11730
11731 let project = Project::test(fs, [], cx).await;
11732 let (workspace, cx) =
11733 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11734
11735 let panel = workspace.update_in(cx, |workspace, window, cx| {
11736 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11737 workspace.add_panel(panel.clone(), window, cx);
11738 panel
11739 });
11740
11741 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11742 pane.update_in(cx, |pane, window, cx| {
11743 let item = cx.new(TestItem::new);
11744 pane.add_item(Box::new(item), true, true, None, window, cx);
11745 });
11746
11747 // Enable close_panel_on_toggle
11748 cx.update_global(|store: &mut SettingsStore, cx| {
11749 store.update_user_settings(cx, |settings| {
11750 settings.workspace.close_panel_on_toggle = Some(true);
11751 });
11752 });
11753
11754 // Panel starts closed. Toggling should open and focus it.
11755 workspace.update_in(cx, |workspace, window, cx| {
11756 assert!(!workspace.right_dock().read(cx).is_open());
11757 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11758 });
11759
11760 workspace.update_in(cx, |workspace, window, cx| {
11761 assert!(
11762 workspace.right_dock().read(cx).is_open(),
11763 "Dock should be open after toggling from center"
11764 );
11765 assert!(
11766 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11767 "Panel should be focused after toggling from center"
11768 );
11769 });
11770
11771 // Panel is open and focused. Toggling should close the panel and
11772 // return focus to the center.
11773 workspace.update_in(cx, |workspace, window, cx| {
11774 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11775 });
11776
11777 workspace.update_in(cx, |workspace, window, cx| {
11778 assert!(
11779 !workspace.right_dock().read(cx).is_open(),
11780 "Dock should be closed after toggling from focused panel"
11781 );
11782 assert!(
11783 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11784 "Panel should not be focused after toggling from focused panel"
11785 );
11786 });
11787
11788 // Open the dock and focus something else so the panel is open but not
11789 // focused. Toggling should focus the panel (not close it).
11790 workspace.update_in(cx, |workspace, window, cx| {
11791 workspace
11792 .right_dock()
11793 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11794 window.focus(&pane.read(cx).focus_handle(cx), cx);
11795 });
11796
11797 workspace.update_in(cx, |workspace, window, cx| {
11798 assert!(workspace.right_dock().read(cx).is_open());
11799 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11800 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11801 });
11802
11803 workspace.update_in(cx, |workspace, window, cx| {
11804 assert!(
11805 workspace.right_dock().read(cx).is_open(),
11806 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11807 );
11808 assert!(
11809 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11810 "Panel should be focused after toggling an open-but-unfocused panel"
11811 );
11812 });
11813
11814 // Now disable the setting and verify the original behavior: toggling
11815 // from a focused panel moves focus to center but leaves the dock open.
11816 cx.update_global(|store: &mut SettingsStore, cx| {
11817 store.update_user_settings(cx, |settings| {
11818 settings.workspace.close_panel_on_toggle = Some(false);
11819 });
11820 });
11821
11822 workspace.update_in(cx, |workspace, window, cx| {
11823 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11824 });
11825
11826 workspace.update_in(cx, |workspace, window, cx| {
11827 assert!(
11828 workspace.right_dock().read(cx).is_open(),
11829 "Dock should remain open when setting is disabled"
11830 );
11831 assert!(
11832 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11833 "Panel should not be focused after toggling with setting disabled"
11834 );
11835 });
11836 }
11837
11838 #[gpui::test]
11839 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11840 init_test(cx);
11841 let fs = FakeFs::new(cx.executor());
11842
11843 let project = Project::test(fs, [], cx).await;
11844 let (workspace, cx) =
11845 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11846
11847 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11848 workspace.active_pane().clone()
11849 });
11850
11851 // Add an item to the pane so it can be zoomed
11852 workspace.update_in(cx, |workspace, window, cx| {
11853 let item = cx.new(TestItem::new);
11854 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11855 });
11856
11857 // Initially not zoomed
11858 workspace.update_in(cx, |workspace, _window, cx| {
11859 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11860 assert!(
11861 workspace.zoomed.is_none(),
11862 "Workspace should track no zoomed pane"
11863 );
11864 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11865 });
11866
11867 // Zoom In
11868 pane.update_in(cx, |pane, window, cx| {
11869 pane.zoom_in(&crate::ZoomIn, window, cx);
11870 });
11871
11872 workspace.update_in(cx, |workspace, window, cx| {
11873 assert!(
11874 pane.read(cx).is_zoomed(),
11875 "Pane should be zoomed after ZoomIn"
11876 );
11877 assert!(
11878 workspace.zoomed.is_some(),
11879 "Workspace should track the zoomed pane"
11880 );
11881 assert!(
11882 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11883 "ZoomIn should focus the pane"
11884 );
11885 });
11886
11887 // Zoom In again is a no-op
11888 pane.update_in(cx, |pane, window, cx| {
11889 pane.zoom_in(&crate::ZoomIn, window, cx);
11890 });
11891
11892 workspace.update_in(cx, |workspace, window, cx| {
11893 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11894 assert!(
11895 workspace.zoomed.is_some(),
11896 "Workspace still tracks zoomed pane"
11897 );
11898 assert!(
11899 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11900 "Pane remains focused after repeated ZoomIn"
11901 );
11902 });
11903
11904 // Zoom Out
11905 pane.update_in(cx, |pane, window, cx| {
11906 pane.zoom_out(&crate::ZoomOut, window, cx);
11907 });
11908
11909 workspace.update_in(cx, |workspace, _window, cx| {
11910 assert!(
11911 !pane.read(cx).is_zoomed(),
11912 "Pane should unzoom after ZoomOut"
11913 );
11914 assert!(
11915 workspace.zoomed.is_none(),
11916 "Workspace clears zoom tracking after ZoomOut"
11917 );
11918 });
11919
11920 // Zoom Out again is a no-op
11921 pane.update_in(cx, |pane, window, cx| {
11922 pane.zoom_out(&crate::ZoomOut, window, cx);
11923 });
11924
11925 workspace.update_in(cx, |workspace, _window, cx| {
11926 assert!(
11927 !pane.read(cx).is_zoomed(),
11928 "Second ZoomOut keeps pane unzoomed"
11929 );
11930 assert!(
11931 workspace.zoomed.is_none(),
11932 "Workspace remains without zoomed pane"
11933 );
11934 });
11935 }
11936
11937 #[gpui::test]
11938 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11939 init_test(cx);
11940 let fs = FakeFs::new(cx.executor());
11941
11942 let project = Project::test(fs, [], cx).await;
11943 let (workspace, cx) =
11944 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11945 workspace.update_in(cx, |workspace, window, cx| {
11946 // Open two docks
11947 let left_dock = workspace.dock_at_position(DockPosition::Left);
11948 let right_dock = workspace.dock_at_position(DockPosition::Right);
11949
11950 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11951 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11952
11953 assert!(left_dock.read(cx).is_open());
11954 assert!(right_dock.read(cx).is_open());
11955 });
11956
11957 workspace.update_in(cx, |workspace, window, cx| {
11958 // Toggle all docks - should close both
11959 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11960
11961 let left_dock = workspace.dock_at_position(DockPosition::Left);
11962 let right_dock = workspace.dock_at_position(DockPosition::Right);
11963 assert!(!left_dock.read(cx).is_open());
11964 assert!(!right_dock.read(cx).is_open());
11965 });
11966
11967 workspace.update_in(cx, |workspace, window, cx| {
11968 // Toggle again - should reopen both
11969 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11970
11971 let left_dock = workspace.dock_at_position(DockPosition::Left);
11972 let right_dock = workspace.dock_at_position(DockPosition::Right);
11973 assert!(left_dock.read(cx).is_open());
11974 assert!(right_dock.read(cx).is_open());
11975 });
11976 }
11977
11978 #[gpui::test]
11979 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11980 init_test(cx);
11981 let fs = FakeFs::new(cx.executor());
11982
11983 let project = Project::test(fs, [], cx).await;
11984 let (workspace, cx) =
11985 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11986 workspace.update_in(cx, |workspace, window, cx| {
11987 // Open two docks
11988 let left_dock = workspace.dock_at_position(DockPosition::Left);
11989 let right_dock = workspace.dock_at_position(DockPosition::Right);
11990
11991 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11992 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11993
11994 assert!(left_dock.read(cx).is_open());
11995 assert!(right_dock.read(cx).is_open());
11996 });
11997
11998 workspace.update_in(cx, |workspace, window, cx| {
11999 // Close them manually
12000 workspace.toggle_dock(DockPosition::Left, window, cx);
12001 workspace.toggle_dock(DockPosition::Right, window, cx);
12002
12003 let left_dock = workspace.dock_at_position(DockPosition::Left);
12004 let right_dock = workspace.dock_at_position(DockPosition::Right);
12005 assert!(!left_dock.read(cx).is_open());
12006 assert!(!right_dock.read(cx).is_open());
12007 });
12008
12009 workspace.update_in(cx, |workspace, window, cx| {
12010 // Toggle all docks - only last closed (right dock) should reopen
12011 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12012
12013 let left_dock = workspace.dock_at_position(DockPosition::Left);
12014 let right_dock = workspace.dock_at_position(DockPosition::Right);
12015 assert!(!left_dock.read(cx).is_open());
12016 assert!(right_dock.read(cx).is_open());
12017 });
12018 }
12019
12020 #[gpui::test]
12021 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12022 init_test(cx);
12023 let fs = FakeFs::new(cx.executor());
12024 let project = Project::test(fs, [], cx).await;
12025 let (multi_workspace, cx) =
12026 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12027 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12028
12029 // Open two docks (left and right) with one panel each
12030 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12031 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12032 workspace.add_panel(left_panel.clone(), window, cx);
12033
12034 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12035 workspace.add_panel(right_panel.clone(), window, cx);
12036
12037 workspace.toggle_dock(DockPosition::Left, window, cx);
12038 workspace.toggle_dock(DockPosition::Right, window, cx);
12039
12040 // Verify initial state
12041 assert!(
12042 workspace.left_dock().read(cx).is_open(),
12043 "Left dock should be open"
12044 );
12045 assert_eq!(
12046 workspace
12047 .left_dock()
12048 .read(cx)
12049 .visible_panel()
12050 .unwrap()
12051 .panel_id(),
12052 left_panel.panel_id(),
12053 "Left panel should be visible in left dock"
12054 );
12055 assert!(
12056 workspace.right_dock().read(cx).is_open(),
12057 "Right dock should be open"
12058 );
12059 assert_eq!(
12060 workspace
12061 .right_dock()
12062 .read(cx)
12063 .visible_panel()
12064 .unwrap()
12065 .panel_id(),
12066 right_panel.panel_id(),
12067 "Right panel should be visible in right dock"
12068 );
12069 assert!(
12070 !workspace.bottom_dock().read(cx).is_open(),
12071 "Bottom dock should be closed"
12072 );
12073
12074 (left_panel, right_panel)
12075 });
12076
12077 // Focus the left panel and move it to the next position (bottom dock)
12078 workspace.update_in(cx, |workspace, window, cx| {
12079 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12080 assert!(
12081 left_panel.read(cx).focus_handle(cx).is_focused(window),
12082 "Left panel should be focused"
12083 );
12084 });
12085
12086 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12087
12088 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12089 workspace.update(cx, |workspace, cx| {
12090 assert!(
12091 !workspace.left_dock().read(cx).is_open(),
12092 "Left dock should be closed"
12093 );
12094 assert!(
12095 workspace.bottom_dock().read(cx).is_open(),
12096 "Bottom dock should now be open"
12097 );
12098 assert_eq!(
12099 left_panel.read(cx).position,
12100 DockPosition::Bottom,
12101 "Left panel should now be in the bottom dock"
12102 );
12103 assert_eq!(
12104 workspace
12105 .bottom_dock()
12106 .read(cx)
12107 .visible_panel()
12108 .unwrap()
12109 .panel_id(),
12110 left_panel.panel_id(),
12111 "Left panel should be the visible panel in the bottom dock"
12112 );
12113 });
12114
12115 // Toggle all docks off
12116 workspace.update_in(cx, |workspace, window, cx| {
12117 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12118 assert!(
12119 !workspace.left_dock().read(cx).is_open(),
12120 "Left dock should be closed"
12121 );
12122 assert!(
12123 !workspace.right_dock().read(cx).is_open(),
12124 "Right dock should be closed"
12125 );
12126 assert!(
12127 !workspace.bottom_dock().read(cx).is_open(),
12128 "Bottom dock should be closed"
12129 );
12130 });
12131
12132 // Toggle all docks back on and verify positions are restored
12133 workspace.update_in(cx, |workspace, window, cx| {
12134 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12135 assert!(
12136 !workspace.left_dock().read(cx).is_open(),
12137 "Left dock should remain closed"
12138 );
12139 assert!(
12140 workspace.right_dock().read(cx).is_open(),
12141 "Right dock should remain open"
12142 );
12143 assert!(
12144 workspace.bottom_dock().read(cx).is_open(),
12145 "Bottom dock should remain open"
12146 );
12147 assert_eq!(
12148 left_panel.read(cx).position,
12149 DockPosition::Bottom,
12150 "Left panel should remain in the bottom dock"
12151 );
12152 assert_eq!(
12153 right_panel.read(cx).position,
12154 DockPosition::Right,
12155 "Right panel should remain in the right dock"
12156 );
12157 assert_eq!(
12158 workspace
12159 .bottom_dock()
12160 .read(cx)
12161 .visible_panel()
12162 .unwrap()
12163 .panel_id(),
12164 left_panel.panel_id(),
12165 "Left panel should be the visible panel in the right dock"
12166 );
12167 });
12168 }
12169
12170 #[gpui::test]
12171 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12172 init_test(cx);
12173
12174 let fs = FakeFs::new(cx.executor());
12175
12176 let project = Project::test(fs, None, cx).await;
12177 let (workspace, cx) =
12178 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12179
12180 // Let's arrange the panes like this:
12181 //
12182 // +-----------------------+
12183 // | top |
12184 // +------+--------+-------+
12185 // | left | center | right |
12186 // +------+--------+-------+
12187 // | bottom |
12188 // +-----------------------+
12189
12190 let top_item = cx.new(|cx| {
12191 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12192 });
12193 let bottom_item = cx.new(|cx| {
12194 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12195 });
12196 let left_item = cx.new(|cx| {
12197 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12198 });
12199 let right_item = cx.new(|cx| {
12200 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12201 });
12202 let center_item = cx.new(|cx| {
12203 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12204 });
12205
12206 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12207 let top_pane_id = workspace.active_pane().entity_id();
12208 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12209 workspace.split_pane(
12210 workspace.active_pane().clone(),
12211 SplitDirection::Down,
12212 window,
12213 cx,
12214 );
12215 top_pane_id
12216 });
12217 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12218 let bottom_pane_id = workspace.active_pane().entity_id();
12219 workspace.add_item_to_active_pane(
12220 Box::new(bottom_item.clone()),
12221 None,
12222 false,
12223 window,
12224 cx,
12225 );
12226 workspace.split_pane(
12227 workspace.active_pane().clone(),
12228 SplitDirection::Up,
12229 window,
12230 cx,
12231 );
12232 bottom_pane_id
12233 });
12234 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12235 let left_pane_id = workspace.active_pane().entity_id();
12236 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12237 workspace.split_pane(
12238 workspace.active_pane().clone(),
12239 SplitDirection::Right,
12240 window,
12241 cx,
12242 );
12243 left_pane_id
12244 });
12245 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12246 let right_pane_id = workspace.active_pane().entity_id();
12247 workspace.add_item_to_active_pane(
12248 Box::new(right_item.clone()),
12249 None,
12250 false,
12251 window,
12252 cx,
12253 );
12254 workspace.split_pane(
12255 workspace.active_pane().clone(),
12256 SplitDirection::Left,
12257 window,
12258 cx,
12259 );
12260 right_pane_id
12261 });
12262 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12263 let center_pane_id = workspace.active_pane().entity_id();
12264 workspace.add_item_to_active_pane(
12265 Box::new(center_item.clone()),
12266 None,
12267 false,
12268 window,
12269 cx,
12270 );
12271 center_pane_id
12272 });
12273 cx.executor().run_until_parked();
12274
12275 workspace.update_in(cx, |workspace, window, cx| {
12276 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12277
12278 // Join into next from center pane into right
12279 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12280 });
12281
12282 workspace.update_in(cx, |workspace, window, cx| {
12283 let active_pane = workspace.active_pane();
12284 assert_eq!(right_pane_id, active_pane.entity_id());
12285 assert_eq!(2, active_pane.read(cx).items_len());
12286 let item_ids_in_pane =
12287 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12288 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12289 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12290
12291 // Join into next from right pane into bottom
12292 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12293 });
12294
12295 workspace.update_in(cx, |workspace, window, cx| {
12296 let active_pane = workspace.active_pane();
12297 assert_eq!(bottom_pane_id, active_pane.entity_id());
12298 assert_eq!(3, active_pane.read(cx).items_len());
12299 let item_ids_in_pane =
12300 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12301 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12302 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12303 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12304
12305 // Join into next from bottom pane into left
12306 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12307 });
12308
12309 workspace.update_in(cx, |workspace, window, cx| {
12310 let active_pane = workspace.active_pane();
12311 assert_eq!(left_pane_id, active_pane.entity_id());
12312 assert_eq!(4, active_pane.read(cx).items_len());
12313 let item_ids_in_pane =
12314 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12315 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12316 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12317 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12318 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12319
12320 // Join into next from left pane into top
12321 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12322 });
12323
12324 workspace.update_in(cx, |workspace, window, cx| {
12325 let active_pane = workspace.active_pane();
12326 assert_eq!(top_pane_id, active_pane.entity_id());
12327 assert_eq!(5, active_pane.read(cx).items_len());
12328 let item_ids_in_pane =
12329 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12330 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12331 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12332 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12333 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12334 assert!(item_ids_in_pane.contains(&top_item.item_id()));
12335
12336 // Single pane left: no-op
12337 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12338 });
12339
12340 workspace.update(cx, |workspace, _cx| {
12341 let active_pane = workspace.active_pane();
12342 assert_eq!(top_pane_id, active_pane.entity_id());
12343 });
12344 }
12345
12346 fn add_an_item_to_active_pane(
12347 cx: &mut VisualTestContext,
12348 workspace: &Entity<Workspace>,
12349 item_id: u64,
12350 ) -> Entity<TestItem> {
12351 let item = cx.new(|cx| {
12352 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12353 item_id,
12354 "item{item_id}.txt",
12355 cx,
12356 )])
12357 });
12358 workspace.update_in(cx, |workspace, window, cx| {
12359 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12360 });
12361 item
12362 }
12363
12364 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12365 workspace.update_in(cx, |workspace, window, cx| {
12366 workspace.split_pane(
12367 workspace.active_pane().clone(),
12368 SplitDirection::Right,
12369 window,
12370 cx,
12371 )
12372 })
12373 }
12374
12375 #[gpui::test]
12376 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12377 init_test(cx);
12378 let fs = FakeFs::new(cx.executor());
12379 let project = Project::test(fs, None, cx).await;
12380 let (workspace, cx) =
12381 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12382
12383 add_an_item_to_active_pane(cx, &workspace, 1);
12384 split_pane(cx, &workspace);
12385 add_an_item_to_active_pane(cx, &workspace, 2);
12386 split_pane(cx, &workspace); // empty pane
12387 split_pane(cx, &workspace);
12388 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12389
12390 cx.executor().run_until_parked();
12391
12392 workspace.update(cx, |workspace, cx| {
12393 let num_panes = workspace.panes().len();
12394 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12395 let active_item = workspace
12396 .active_pane()
12397 .read(cx)
12398 .active_item()
12399 .expect("item is in focus");
12400
12401 assert_eq!(num_panes, 4);
12402 assert_eq!(num_items_in_current_pane, 1);
12403 assert_eq!(active_item.item_id(), last_item.item_id());
12404 });
12405
12406 workspace.update_in(cx, |workspace, window, cx| {
12407 workspace.join_all_panes(window, cx);
12408 });
12409
12410 workspace.update(cx, |workspace, cx| {
12411 let num_panes = workspace.panes().len();
12412 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12413 let active_item = workspace
12414 .active_pane()
12415 .read(cx)
12416 .active_item()
12417 .expect("item is in focus");
12418
12419 assert_eq!(num_panes, 1);
12420 assert_eq!(num_items_in_current_pane, 3);
12421 assert_eq!(active_item.item_id(), last_item.item_id());
12422 });
12423 }
12424
12425 #[gpui::test]
12426 async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12427 init_test(cx);
12428 let fs = FakeFs::new(cx.executor());
12429
12430 let project = Project::test(fs, [], cx).await;
12431 let (multi_workspace, cx) =
12432 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12433 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12434
12435 workspace.update(cx, |workspace, _cx| {
12436 workspace.bounds.size.width = px(800.);
12437 });
12438
12439 workspace.update_in(cx, |workspace, window, cx| {
12440 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12441 workspace.add_panel(panel, window, cx);
12442 workspace.toggle_dock(DockPosition::Right, window, cx);
12443 });
12444
12445 let (panel, resized_width, ratio_basis_width) =
12446 workspace.update_in(cx, |workspace, window, cx| {
12447 let item = cx.new(|cx| {
12448 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12449 });
12450 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12451
12452 let dock = workspace.right_dock().read(cx);
12453 let workspace_width = workspace.bounds.size.width;
12454 let initial_width = workspace
12455 .dock_size(&dock, window, cx)
12456 .expect("flexible dock should have an initial width");
12457
12458 assert_eq!(initial_width, workspace_width / 2.);
12459
12460 workspace.resize_right_dock(px(300.), window, cx);
12461
12462 let dock = workspace.right_dock().read(cx);
12463 let resized_width = workspace
12464 .dock_size(&dock, window, cx)
12465 .expect("flexible dock should keep its resized width");
12466
12467 assert_eq!(resized_width, px(300.));
12468
12469 let panel = workspace
12470 .right_dock()
12471 .read(cx)
12472 .visible_panel()
12473 .expect("flexible dock should have a visible panel")
12474 .panel_id();
12475
12476 (panel, resized_width, workspace_width)
12477 });
12478
12479 workspace.update_in(cx, |workspace, window, cx| {
12480 workspace.toggle_dock(DockPosition::Right, window, cx);
12481 workspace.toggle_dock(DockPosition::Right, window, cx);
12482
12483 let dock = workspace.right_dock().read(cx);
12484 let reopened_width = workspace
12485 .dock_size(&dock, window, cx)
12486 .expect("flexible dock should restore when reopened");
12487
12488 assert_eq!(reopened_width, resized_width);
12489
12490 let right_dock = workspace.right_dock().read(cx);
12491 let flexible_panel = right_dock
12492 .visible_panel()
12493 .expect("flexible dock should still have a visible panel");
12494 assert_eq!(flexible_panel.panel_id(), panel);
12495 assert_eq!(
12496 right_dock
12497 .stored_panel_size_state(flexible_panel.as_ref())
12498 .and_then(|size_state| size_state.flex),
12499 Some(
12500 resized_width.to_f64() as f32
12501 / (workspace.bounds.size.width - resized_width).to_f64() as f32
12502 )
12503 );
12504 });
12505
12506 workspace.update_in(cx, |workspace, window, cx| {
12507 workspace.split_pane(
12508 workspace.active_pane().clone(),
12509 SplitDirection::Right,
12510 window,
12511 cx,
12512 );
12513
12514 let dock = workspace.right_dock().read(cx);
12515 let split_width = workspace
12516 .dock_size(&dock, window, cx)
12517 .expect("flexible dock should keep its user-resized proportion");
12518
12519 assert_eq!(split_width, px(300.));
12520
12521 workspace.bounds.size.width = px(1600.);
12522
12523 let dock = workspace.right_dock().read(cx);
12524 let resized_window_width = workspace
12525 .dock_size(&dock, window, cx)
12526 .expect("flexible dock should preserve proportional size on window resize");
12527
12528 assert_eq!(
12529 resized_window_width,
12530 workspace.bounds.size.width
12531 * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12532 );
12533 });
12534 }
12535
12536 #[gpui::test]
12537 async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12538 init_test(cx);
12539 let fs = FakeFs::new(cx.executor());
12540
12541 // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12542 {
12543 let project = Project::test(fs.clone(), [], cx).await;
12544 let (multi_workspace, cx) =
12545 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12546 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12547
12548 workspace.update(cx, |workspace, _cx| {
12549 workspace.set_random_database_id();
12550 workspace.bounds.size.width = px(800.);
12551 });
12552
12553 let panel = workspace.update_in(cx, |workspace, window, cx| {
12554 let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12555 workspace.add_panel(panel.clone(), window, cx);
12556 workspace.toggle_dock(DockPosition::Left, window, cx);
12557 panel
12558 });
12559
12560 workspace.update_in(cx, |workspace, window, cx| {
12561 workspace.resize_left_dock(px(350.), window, cx);
12562 });
12563
12564 cx.run_until_parked();
12565
12566 let persisted = workspace.read_with(cx, |workspace, cx| {
12567 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12568 });
12569 assert_eq!(
12570 persisted.and_then(|s| s.size),
12571 Some(px(350.)),
12572 "fixed-width panel size should be persisted to KVP"
12573 );
12574
12575 // Remove the panel and re-add a fresh instance with the same key.
12576 // The new instance should have its size state restored from KVP.
12577 workspace.update_in(cx, |workspace, window, cx| {
12578 workspace.remove_panel(&panel, window, cx);
12579 });
12580
12581 workspace.update_in(cx, |workspace, window, cx| {
12582 let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12583 workspace.add_panel(new_panel, window, cx);
12584
12585 let left_dock = workspace.left_dock().read(cx);
12586 let size_state = left_dock
12587 .panel::<TestPanel>()
12588 .and_then(|p| left_dock.stored_panel_size_state(&p));
12589 assert_eq!(
12590 size_state.and_then(|s| s.size),
12591 Some(px(350.)),
12592 "re-added fixed-width panel should restore persisted size from KVP"
12593 );
12594 });
12595 }
12596
12597 // Flexible panel: both pixel size and ratio are persisted and restored.
12598 {
12599 let project = Project::test(fs.clone(), [], cx).await;
12600 let (multi_workspace, cx) =
12601 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12602 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12603
12604 workspace.update(cx, |workspace, _cx| {
12605 workspace.set_random_database_id();
12606 workspace.bounds.size.width = px(800.);
12607 });
12608
12609 let panel = workspace.update_in(cx, |workspace, window, cx| {
12610 let item = cx.new(|cx| {
12611 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12612 });
12613 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12614
12615 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12616 workspace.add_panel(panel.clone(), window, cx);
12617 workspace.toggle_dock(DockPosition::Right, window, cx);
12618 panel
12619 });
12620
12621 workspace.update_in(cx, |workspace, window, cx| {
12622 workspace.resize_right_dock(px(300.), window, cx);
12623 });
12624
12625 cx.run_until_parked();
12626
12627 let persisted = workspace
12628 .read_with(cx, |workspace, cx| {
12629 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12630 })
12631 .expect("flexible panel state should be persisted to KVP");
12632 assert_eq!(
12633 persisted.size, None,
12634 "flexible panel should not persist a redundant pixel size"
12635 );
12636 let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12637
12638 // Remove the panel and re-add: both size and ratio should be restored.
12639 workspace.update_in(cx, |workspace, window, cx| {
12640 workspace.remove_panel(&panel, window, cx);
12641 });
12642
12643 workspace.update_in(cx, |workspace, window, cx| {
12644 let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12645 workspace.add_panel(new_panel, window, cx);
12646
12647 let right_dock = workspace.right_dock().read(cx);
12648 let size_state = right_dock
12649 .panel::<TestPanel>()
12650 .and_then(|p| right_dock.stored_panel_size_state(&p))
12651 .expect("re-added flexible panel should have restored size state from KVP");
12652 assert_eq!(
12653 size_state.size, None,
12654 "re-added flexible panel should not have a persisted pixel size"
12655 );
12656 assert_eq!(
12657 size_state.flex,
12658 Some(original_ratio),
12659 "re-added flexible panel should restore persisted flex"
12660 );
12661 });
12662 }
12663 }
12664
12665 #[gpui::test]
12666 async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12667 init_test(cx);
12668 let fs = FakeFs::new(cx.executor());
12669
12670 let project = Project::test(fs, [], cx).await;
12671 let (multi_workspace, cx) =
12672 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12673 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12674
12675 workspace.update(cx, |workspace, _cx| {
12676 workspace.bounds.size.width = px(900.);
12677 });
12678
12679 // Step 1: Add a tab to the center pane then open a flexible panel in the left
12680 // dock. With one full-width center pane the default ratio is 0.5, so the panel
12681 // and the center pane each take half the workspace width.
12682 workspace.update_in(cx, |workspace, window, cx| {
12683 let item = cx.new(|cx| {
12684 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12685 });
12686 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12687
12688 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12689 workspace.add_panel(panel, window, cx);
12690 workspace.toggle_dock(DockPosition::Left, window, cx);
12691
12692 let left_dock = workspace.left_dock().read(cx);
12693 let left_width = workspace
12694 .dock_size(&left_dock, window, cx)
12695 .expect("left dock should have an active panel");
12696
12697 assert_eq!(
12698 left_width,
12699 workspace.bounds.size.width / 2.,
12700 "flexible left panel should split evenly with the center pane"
12701 );
12702 });
12703
12704 // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12705 // change horizontal width fractions, so the flexible panel stays at the same
12706 // width as each half of the split.
12707 workspace.update_in(cx, |workspace, window, cx| {
12708 workspace.split_pane(
12709 workspace.active_pane().clone(),
12710 SplitDirection::Down,
12711 window,
12712 cx,
12713 );
12714
12715 let left_dock = workspace.left_dock().read(cx);
12716 let left_width = workspace
12717 .dock_size(&left_dock, window, cx)
12718 .expect("left dock should still have an active panel after vertical split");
12719
12720 assert_eq!(
12721 left_width,
12722 workspace.bounds.size.width / 2.,
12723 "flexible left panel width should match each vertically-split pane"
12724 );
12725 });
12726
12727 // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12728 // size reduces the available width, so the flexible left panel and the center
12729 // panes all shrink proportionally to accommodate it.
12730 workspace.update_in(cx, |workspace, window, cx| {
12731 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12732 workspace.add_panel(panel, window, cx);
12733 workspace.toggle_dock(DockPosition::Right, window, cx);
12734
12735 let right_dock = workspace.right_dock().read(cx);
12736 let right_width = workspace
12737 .dock_size(&right_dock, window, cx)
12738 .expect("right dock should have an active panel");
12739
12740 let left_dock = workspace.left_dock().read(cx);
12741 let left_width = workspace
12742 .dock_size(&left_dock, window, cx)
12743 .expect("left dock should still have an active panel");
12744
12745 let available_width = workspace.bounds.size.width - right_width;
12746 assert_eq!(
12747 left_width,
12748 available_width / 2.,
12749 "flexible left panel should shrink proportionally as the right dock takes space"
12750 );
12751 });
12752
12753 // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12754 // flex sizing and the workspace width is divided among left-flex, center
12755 // (implicit flex 1.0), and right-flex.
12756 workspace.update_in(cx, |workspace, window, cx| {
12757 let right_dock = workspace.right_dock().clone();
12758 let right_panel = right_dock
12759 .read(cx)
12760 .visible_panel()
12761 .expect("right dock should have a visible panel")
12762 .clone();
12763 workspace.toggle_dock_panel_flexible_size(
12764 &right_dock,
12765 right_panel.as_ref(),
12766 window,
12767 cx,
12768 );
12769
12770 let right_dock = right_dock.read(cx);
12771 let right_panel = right_dock
12772 .visible_panel()
12773 .expect("right dock should still have a visible panel");
12774 assert!(
12775 right_panel.has_flexible_size(window, cx),
12776 "right panel should now be flexible"
12777 );
12778
12779 let right_size_state = right_dock
12780 .stored_panel_size_state(right_panel.as_ref())
12781 .expect("right panel should have a stored size state after toggling");
12782 let right_flex = right_size_state
12783 .flex
12784 .expect("right panel should have a flex value after toggling");
12785
12786 let left_dock = workspace.left_dock().read(cx);
12787 let left_width = workspace
12788 .dock_size(&left_dock, window, cx)
12789 .expect("left dock should still have an active panel");
12790 let right_width = workspace
12791 .dock_size(&right_dock, window, cx)
12792 .expect("right dock should still have an active panel");
12793
12794 let left_flex = workspace
12795 .default_dock_flex(DockPosition::Left)
12796 .expect("left dock should have a default flex");
12797
12798 let total_flex = left_flex + 1.0 + right_flex;
12799 let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12800 let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12801 assert_eq!(
12802 left_width, expected_left,
12803 "flexible left panel should share workspace width via flex ratios"
12804 );
12805 assert_eq!(
12806 right_width, expected_right,
12807 "flexible right panel should share workspace width via flex ratios"
12808 );
12809 });
12810 }
12811
12812 struct TestModal(FocusHandle);
12813
12814 impl TestModal {
12815 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12816 Self(cx.focus_handle())
12817 }
12818 }
12819
12820 impl EventEmitter<DismissEvent> for TestModal {}
12821
12822 impl Focusable for TestModal {
12823 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12824 self.0.clone()
12825 }
12826 }
12827
12828 impl ModalView for TestModal {}
12829
12830 impl Render for TestModal {
12831 fn render(
12832 &mut self,
12833 _window: &mut Window,
12834 _cx: &mut Context<TestModal>,
12835 ) -> impl IntoElement {
12836 div().track_focus(&self.0)
12837 }
12838 }
12839
12840 #[gpui::test]
12841 async fn test_panels(cx: &mut gpui::TestAppContext) {
12842 init_test(cx);
12843 let fs = FakeFs::new(cx.executor());
12844
12845 let project = Project::test(fs, [], cx).await;
12846 let (multi_workspace, cx) =
12847 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12848 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12849
12850 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12851 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12852 workspace.add_panel(panel_1.clone(), window, cx);
12853 workspace.toggle_dock(DockPosition::Left, window, cx);
12854 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12855 workspace.add_panel(panel_2.clone(), window, cx);
12856 workspace.toggle_dock(DockPosition::Right, window, cx);
12857
12858 let left_dock = workspace.left_dock();
12859 assert_eq!(
12860 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12861 panel_1.panel_id()
12862 );
12863 assert_eq!(
12864 workspace.dock_size(&left_dock.read(cx), window, cx),
12865 Some(px(300.))
12866 );
12867
12868 workspace.resize_left_dock(px(1337.), window, cx);
12869 assert_eq!(
12870 workspace
12871 .right_dock()
12872 .read(cx)
12873 .visible_panel()
12874 .unwrap()
12875 .panel_id(),
12876 panel_2.panel_id(),
12877 );
12878
12879 (panel_1, panel_2)
12880 });
12881
12882 // Move panel_1 to the right
12883 panel_1.update_in(cx, |panel_1, window, cx| {
12884 panel_1.set_position(DockPosition::Right, window, cx)
12885 });
12886
12887 workspace.update_in(cx, |workspace, window, cx| {
12888 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12889 // Since it was the only panel on the left, the left dock should now be closed.
12890 assert!(!workspace.left_dock().read(cx).is_open());
12891 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12892 let right_dock = workspace.right_dock();
12893 assert_eq!(
12894 right_dock.read(cx).visible_panel().unwrap().panel_id(),
12895 panel_1.panel_id()
12896 );
12897 assert_eq!(
12898 right_dock
12899 .read(cx)
12900 .active_panel_size()
12901 .unwrap()
12902 .size
12903 .unwrap(),
12904 px(1337.)
12905 );
12906
12907 // Now we move panel_2 to the left
12908 panel_2.set_position(DockPosition::Left, window, cx);
12909 });
12910
12911 workspace.update(cx, |workspace, cx| {
12912 // Since panel_2 was not visible on the right, we don't open the left dock.
12913 assert!(!workspace.left_dock().read(cx).is_open());
12914 // And the right dock is unaffected in its displaying of panel_1
12915 assert!(workspace.right_dock().read(cx).is_open());
12916 assert_eq!(
12917 workspace
12918 .right_dock()
12919 .read(cx)
12920 .visible_panel()
12921 .unwrap()
12922 .panel_id(),
12923 panel_1.panel_id(),
12924 );
12925 });
12926
12927 // Move panel_1 back to the left
12928 panel_1.update_in(cx, |panel_1, window, cx| {
12929 panel_1.set_position(DockPosition::Left, window, cx)
12930 });
12931
12932 workspace.update_in(cx, |workspace, window, cx| {
12933 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12934 let left_dock = workspace.left_dock();
12935 assert!(left_dock.read(cx).is_open());
12936 assert_eq!(
12937 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12938 panel_1.panel_id()
12939 );
12940 assert_eq!(
12941 workspace.dock_size(&left_dock.read(cx), window, cx),
12942 Some(px(1337.))
12943 );
12944 // And the right dock should be closed as it no longer has any panels.
12945 assert!(!workspace.right_dock().read(cx).is_open());
12946
12947 // Now we move panel_1 to the bottom
12948 panel_1.set_position(DockPosition::Bottom, window, cx);
12949 });
12950
12951 workspace.update_in(cx, |workspace, window, cx| {
12952 // Since panel_1 was visible on the left, we close the left dock.
12953 assert!(!workspace.left_dock().read(cx).is_open());
12954 // The bottom dock is sized based on the panel's default size,
12955 // since the panel orientation changed from vertical to horizontal.
12956 let bottom_dock = workspace.bottom_dock();
12957 assert_eq!(
12958 workspace.dock_size(&bottom_dock.read(cx), window, cx),
12959 Some(px(300.))
12960 );
12961 // Close bottom dock and move panel_1 back to the left.
12962 bottom_dock.update(cx, |bottom_dock, cx| {
12963 bottom_dock.set_open(false, window, cx)
12964 });
12965 panel_1.set_position(DockPosition::Left, window, cx);
12966 });
12967
12968 // Emit activated event on panel 1
12969 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12970
12971 // Now the left dock is open and panel_1 is active and focused.
12972 workspace.update_in(cx, |workspace, window, cx| {
12973 let left_dock = workspace.left_dock();
12974 assert!(left_dock.read(cx).is_open());
12975 assert_eq!(
12976 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12977 panel_1.panel_id(),
12978 );
12979 assert!(panel_1.focus_handle(cx).is_focused(window));
12980 });
12981
12982 // Emit closed event on panel 2, which is not active
12983 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12984
12985 // Wo don't close the left dock, because panel_2 wasn't the active panel
12986 workspace.update(cx, |workspace, cx| {
12987 let left_dock = workspace.left_dock();
12988 assert!(left_dock.read(cx).is_open());
12989 assert_eq!(
12990 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12991 panel_1.panel_id(),
12992 );
12993 });
12994
12995 // Emitting a ZoomIn event shows the panel as zoomed.
12996 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12997 workspace.read_with(cx, |workspace, _| {
12998 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12999 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13000 });
13001
13002 // Move panel to another dock while it is zoomed
13003 panel_1.update_in(cx, |panel, window, cx| {
13004 panel.set_position(DockPosition::Right, window, cx)
13005 });
13006 workspace.read_with(cx, |workspace, _| {
13007 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13008
13009 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13010 });
13011
13012 // This is a helper for getting a:
13013 // - valid focus on an element,
13014 // - that isn't a part of the panes and panels system of the Workspace,
13015 // - and doesn't trigger the 'on_focus_lost' API.
13016 let focus_other_view = {
13017 let workspace = workspace.clone();
13018 move |cx: &mut VisualTestContext| {
13019 workspace.update_in(cx, |workspace, window, cx| {
13020 if workspace.active_modal::<TestModal>(cx).is_some() {
13021 workspace.toggle_modal(window, cx, TestModal::new);
13022 workspace.toggle_modal(window, cx, TestModal::new);
13023 } else {
13024 workspace.toggle_modal(window, cx, TestModal::new);
13025 }
13026 })
13027 }
13028 };
13029
13030 // If focus is transferred to another view that's not a panel or another pane, we still show
13031 // the panel as zoomed.
13032 focus_other_view(cx);
13033 workspace.read_with(cx, |workspace, _| {
13034 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13035 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13036 });
13037
13038 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13039 workspace.update_in(cx, |_workspace, window, cx| {
13040 cx.focus_self(window);
13041 });
13042 workspace.read_with(cx, |workspace, _| {
13043 assert_eq!(workspace.zoomed, None);
13044 assert_eq!(workspace.zoomed_position, None);
13045 });
13046
13047 // If focus is transferred again to another view that's not a panel or a pane, we won't
13048 // show the panel as zoomed because it wasn't zoomed before.
13049 focus_other_view(cx);
13050 workspace.read_with(cx, |workspace, _| {
13051 assert_eq!(workspace.zoomed, None);
13052 assert_eq!(workspace.zoomed_position, None);
13053 });
13054
13055 // When the panel is activated, it is zoomed again.
13056 cx.dispatch_action(ToggleRightDock);
13057 workspace.read_with(cx, |workspace, _| {
13058 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13059 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13060 });
13061
13062 // Emitting a ZoomOut event unzooms the panel.
13063 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13064 workspace.read_with(cx, |workspace, _| {
13065 assert_eq!(workspace.zoomed, None);
13066 assert_eq!(workspace.zoomed_position, None);
13067 });
13068
13069 // Emit closed event on panel 1, which is active
13070 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13071
13072 // Now the left dock is closed, because panel_1 was the active panel
13073 workspace.update(cx, |workspace, cx| {
13074 let right_dock = workspace.right_dock();
13075 assert!(!right_dock.read(cx).is_open());
13076 });
13077 }
13078
13079 #[gpui::test]
13080 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13081 init_test(cx);
13082
13083 let fs = FakeFs::new(cx.background_executor.clone());
13084 let project = Project::test(fs, [], cx).await;
13085 let (workspace, cx) =
13086 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13087 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13088
13089 let dirty_regular_buffer = cx.new(|cx| {
13090 TestItem::new(cx)
13091 .with_dirty(true)
13092 .with_label("1.txt")
13093 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13094 });
13095 let dirty_regular_buffer_2 = cx.new(|cx| {
13096 TestItem::new(cx)
13097 .with_dirty(true)
13098 .with_label("2.txt")
13099 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13100 });
13101 let dirty_multi_buffer_with_both = cx.new(|cx| {
13102 TestItem::new(cx)
13103 .with_dirty(true)
13104 .with_buffer_kind(ItemBufferKind::Multibuffer)
13105 .with_label("Fake Project Search")
13106 .with_project_items(&[
13107 dirty_regular_buffer.read(cx).project_items[0].clone(),
13108 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13109 ])
13110 });
13111 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13112 workspace.update_in(cx, |workspace, window, cx| {
13113 workspace.add_item(
13114 pane.clone(),
13115 Box::new(dirty_regular_buffer.clone()),
13116 None,
13117 false,
13118 false,
13119 window,
13120 cx,
13121 );
13122 workspace.add_item(
13123 pane.clone(),
13124 Box::new(dirty_regular_buffer_2.clone()),
13125 None,
13126 false,
13127 false,
13128 window,
13129 cx,
13130 );
13131 workspace.add_item(
13132 pane.clone(),
13133 Box::new(dirty_multi_buffer_with_both.clone()),
13134 None,
13135 false,
13136 false,
13137 window,
13138 cx,
13139 );
13140 });
13141
13142 pane.update_in(cx, |pane, window, cx| {
13143 pane.activate_item(2, true, true, window, cx);
13144 assert_eq!(
13145 pane.active_item().unwrap().item_id(),
13146 multi_buffer_with_both_files_id,
13147 "Should select the multi buffer in the pane"
13148 );
13149 });
13150 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13151 pane.close_other_items(
13152 &CloseOtherItems {
13153 save_intent: Some(SaveIntent::Save),
13154 close_pinned: true,
13155 },
13156 None,
13157 window,
13158 cx,
13159 )
13160 });
13161 cx.background_executor.run_until_parked();
13162 assert!(!cx.has_pending_prompt());
13163 close_all_but_multi_buffer_task
13164 .await
13165 .expect("Closing all buffers but the multi buffer failed");
13166 pane.update(cx, |pane, cx| {
13167 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13168 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13169 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13170 assert_eq!(pane.items_len(), 1);
13171 assert_eq!(
13172 pane.active_item().unwrap().item_id(),
13173 multi_buffer_with_both_files_id,
13174 "Should have only the multi buffer left in the pane"
13175 );
13176 assert!(
13177 dirty_multi_buffer_with_both.read(cx).is_dirty,
13178 "The multi buffer containing the unsaved buffer should still be dirty"
13179 );
13180 });
13181
13182 dirty_regular_buffer.update(cx, |buffer, cx| {
13183 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13184 });
13185
13186 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13187 pane.close_active_item(
13188 &CloseActiveItem {
13189 save_intent: Some(SaveIntent::Close),
13190 close_pinned: false,
13191 },
13192 window,
13193 cx,
13194 )
13195 });
13196 cx.background_executor.run_until_parked();
13197 assert!(
13198 cx.has_pending_prompt(),
13199 "Dirty multi buffer should prompt a save dialog"
13200 );
13201 cx.simulate_prompt_answer("Save");
13202 cx.background_executor.run_until_parked();
13203 close_multi_buffer_task
13204 .await
13205 .expect("Closing the multi buffer failed");
13206 pane.update(cx, |pane, cx| {
13207 assert_eq!(
13208 dirty_multi_buffer_with_both.read(cx).save_count,
13209 1,
13210 "Multi buffer item should get be saved"
13211 );
13212 // Test impl does not save inner items, so we do not assert them
13213 assert_eq!(
13214 pane.items_len(),
13215 0,
13216 "No more items should be left in the pane"
13217 );
13218 assert!(pane.active_item().is_none());
13219 });
13220 }
13221
13222 #[gpui::test]
13223 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13224 cx: &mut TestAppContext,
13225 ) {
13226 init_test(cx);
13227
13228 let fs = FakeFs::new(cx.background_executor.clone());
13229 let project = Project::test(fs, [], cx).await;
13230 let (workspace, cx) =
13231 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13232 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13233
13234 let dirty_regular_buffer = cx.new(|cx| {
13235 TestItem::new(cx)
13236 .with_dirty(true)
13237 .with_label("1.txt")
13238 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13239 });
13240 let dirty_regular_buffer_2 = cx.new(|cx| {
13241 TestItem::new(cx)
13242 .with_dirty(true)
13243 .with_label("2.txt")
13244 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13245 });
13246 let clear_regular_buffer = cx.new(|cx| {
13247 TestItem::new(cx)
13248 .with_label("3.txt")
13249 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13250 });
13251
13252 let dirty_multi_buffer_with_both = cx.new(|cx| {
13253 TestItem::new(cx)
13254 .with_dirty(true)
13255 .with_buffer_kind(ItemBufferKind::Multibuffer)
13256 .with_label("Fake Project Search")
13257 .with_project_items(&[
13258 dirty_regular_buffer.read(cx).project_items[0].clone(),
13259 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13260 clear_regular_buffer.read(cx).project_items[0].clone(),
13261 ])
13262 });
13263 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13264 workspace.update_in(cx, |workspace, window, cx| {
13265 workspace.add_item(
13266 pane.clone(),
13267 Box::new(dirty_regular_buffer.clone()),
13268 None,
13269 false,
13270 false,
13271 window,
13272 cx,
13273 );
13274 workspace.add_item(
13275 pane.clone(),
13276 Box::new(dirty_multi_buffer_with_both.clone()),
13277 None,
13278 false,
13279 false,
13280 window,
13281 cx,
13282 );
13283 });
13284
13285 pane.update_in(cx, |pane, window, cx| {
13286 pane.activate_item(1, true, true, window, cx);
13287 assert_eq!(
13288 pane.active_item().unwrap().item_id(),
13289 multi_buffer_with_both_files_id,
13290 "Should select the multi buffer in the pane"
13291 );
13292 });
13293 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13294 pane.close_active_item(
13295 &CloseActiveItem {
13296 save_intent: None,
13297 close_pinned: false,
13298 },
13299 window,
13300 cx,
13301 )
13302 });
13303 cx.background_executor.run_until_parked();
13304 assert!(
13305 cx.has_pending_prompt(),
13306 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13307 );
13308 }
13309
13310 /// Tests that when `close_on_file_delete` is enabled, files are automatically
13311 /// closed when they are deleted from disk.
13312 #[gpui::test]
13313 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13314 init_test(cx);
13315
13316 // Enable the close_on_disk_deletion setting
13317 cx.update_global(|store: &mut SettingsStore, cx| {
13318 store.update_user_settings(cx, |settings| {
13319 settings.workspace.close_on_file_delete = Some(true);
13320 });
13321 });
13322
13323 let fs = FakeFs::new(cx.background_executor.clone());
13324 let project = Project::test(fs, [], cx).await;
13325 let (workspace, cx) =
13326 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13327 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13328
13329 // Create a test item that simulates a file
13330 let item = cx.new(|cx| {
13331 TestItem::new(cx)
13332 .with_label("test.txt")
13333 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13334 });
13335
13336 // Add item to workspace
13337 workspace.update_in(cx, |workspace, window, cx| {
13338 workspace.add_item(
13339 pane.clone(),
13340 Box::new(item.clone()),
13341 None,
13342 false,
13343 false,
13344 window,
13345 cx,
13346 );
13347 });
13348
13349 // Verify the item is in the pane
13350 pane.read_with(cx, |pane, _| {
13351 assert_eq!(pane.items().count(), 1);
13352 });
13353
13354 // Simulate file deletion by setting the item's deleted state
13355 item.update(cx, |item, _| {
13356 item.set_has_deleted_file(true);
13357 });
13358
13359 // Emit UpdateTab event to trigger the close behavior
13360 cx.run_until_parked();
13361 item.update(cx, |_, cx| {
13362 cx.emit(ItemEvent::UpdateTab);
13363 });
13364
13365 // Allow the close operation to complete
13366 cx.run_until_parked();
13367
13368 // Verify the item was automatically closed
13369 pane.read_with(cx, |pane, _| {
13370 assert_eq!(
13371 pane.items().count(),
13372 0,
13373 "Item should be automatically closed when file is deleted"
13374 );
13375 });
13376 }
13377
13378 /// Tests that when `close_on_file_delete` is disabled (default), files remain
13379 /// open with a strikethrough when they are deleted from disk.
13380 #[gpui::test]
13381 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13382 init_test(cx);
13383
13384 // Ensure close_on_disk_deletion is disabled (default)
13385 cx.update_global(|store: &mut SettingsStore, cx| {
13386 store.update_user_settings(cx, |settings| {
13387 settings.workspace.close_on_file_delete = Some(false);
13388 });
13389 });
13390
13391 let fs = FakeFs::new(cx.background_executor.clone());
13392 let project = Project::test(fs, [], cx).await;
13393 let (workspace, cx) =
13394 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13395 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13396
13397 // Create a test item that simulates a file
13398 let item = cx.new(|cx| {
13399 TestItem::new(cx)
13400 .with_label("test.txt")
13401 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13402 });
13403
13404 // Add item to workspace
13405 workspace.update_in(cx, |workspace, window, cx| {
13406 workspace.add_item(
13407 pane.clone(),
13408 Box::new(item.clone()),
13409 None,
13410 false,
13411 false,
13412 window,
13413 cx,
13414 );
13415 });
13416
13417 // Verify the item is in the pane
13418 pane.read_with(cx, |pane, _| {
13419 assert_eq!(pane.items().count(), 1);
13420 });
13421
13422 // Simulate file deletion
13423 item.update(cx, |item, _| {
13424 item.set_has_deleted_file(true);
13425 });
13426
13427 // Emit UpdateTab event
13428 cx.run_until_parked();
13429 item.update(cx, |_, cx| {
13430 cx.emit(ItemEvent::UpdateTab);
13431 });
13432
13433 // Allow any potential close operation to complete
13434 cx.run_until_parked();
13435
13436 // Verify the item remains open (with strikethrough)
13437 pane.read_with(cx, |pane, _| {
13438 assert_eq!(
13439 pane.items().count(),
13440 1,
13441 "Item should remain open when close_on_disk_deletion is disabled"
13442 );
13443 });
13444
13445 // Verify the item shows as deleted
13446 item.read_with(cx, |item, _| {
13447 assert!(
13448 item.has_deleted_file,
13449 "Item should be marked as having deleted file"
13450 );
13451 });
13452 }
13453
13454 /// Tests that dirty files are not automatically closed when deleted from disk,
13455 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13456 /// unsaved changes without being prompted.
13457 #[gpui::test]
13458 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13459 init_test(cx);
13460
13461 // Enable the close_on_file_delete setting
13462 cx.update_global(|store: &mut SettingsStore, cx| {
13463 store.update_user_settings(cx, |settings| {
13464 settings.workspace.close_on_file_delete = Some(true);
13465 });
13466 });
13467
13468 let fs = FakeFs::new(cx.background_executor.clone());
13469 let project = Project::test(fs, [], cx).await;
13470 let (workspace, cx) =
13471 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13472 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13473
13474 // Create a dirty test item
13475 let item = cx.new(|cx| {
13476 TestItem::new(cx)
13477 .with_dirty(true)
13478 .with_label("test.txt")
13479 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13480 });
13481
13482 // Add item to workspace
13483 workspace.update_in(cx, |workspace, window, cx| {
13484 workspace.add_item(
13485 pane.clone(),
13486 Box::new(item.clone()),
13487 None,
13488 false,
13489 false,
13490 window,
13491 cx,
13492 );
13493 });
13494
13495 // Simulate file deletion
13496 item.update(cx, |item, _| {
13497 item.set_has_deleted_file(true);
13498 });
13499
13500 // Emit UpdateTab event to trigger the close behavior
13501 cx.run_until_parked();
13502 item.update(cx, |_, cx| {
13503 cx.emit(ItemEvent::UpdateTab);
13504 });
13505
13506 // Allow any potential close operation to complete
13507 cx.run_until_parked();
13508
13509 // Verify the item remains open (dirty files are not auto-closed)
13510 pane.read_with(cx, |pane, _| {
13511 assert_eq!(
13512 pane.items().count(),
13513 1,
13514 "Dirty items should not be automatically closed even when file is deleted"
13515 );
13516 });
13517
13518 // Verify the item is marked as deleted and still dirty
13519 item.read_with(cx, |item, _| {
13520 assert!(
13521 item.has_deleted_file,
13522 "Item should be marked as having deleted file"
13523 );
13524 assert!(item.is_dirty, "Item should still be dirty");
13525 });
13526 }
13527
13528 /// Tests that navigation history is cleaned up when files are auto-closed
13529 /// due to deletion from disk.
13530 #[gpui::test]
13531 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13532 init_test(cx);
13533
13534 // Enable the close_on_file_delete setting
13535 cx.update_global(|store: &mut SettingsStore, cx| {
13536 store.update_user_settings(cx, |settings| {
13537 settings.workspace.close_on_file_delete = Some(true);
13538 });
13539 });
13540
13541 let fs = FakeFs::new(cx.background_executor.clone());
13542 let project = Project::test(fs, [], cx).await;
13543 let (workspace, cx) =
13544 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13545 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13546
13547 // Create test items
13548 let item1 = cx.new(|cx| {
13549 TestItem::new(cx)
13550 .with_label("test1.txt")
13551 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13552 });
13553 let item1_id = item1.item_id();
13554
13555 let item2 = cx.new(|cx| {
13556 TestItem::new(cx)
13557 .with_label("test2.txt")
13558 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13559 });
13560
13561 // Add items to workspace
13562 workspace.update_in(cx, |workspace, window, cx| {
13563 workspace.add_item(
13564 pane.clone(),
13565 Box::new(item1.clone()),
13566 None,
13567 false,
13568 false,
13569 window,
13570 cx,
13571 );
13572 workspace.add_item(
13573 pane.clone(),
13574 Box::new(item2.clone()),
13575 None,
13576 false,
13577 false,
13578 window,
13579 cx,
13580 );
13581 });
13582
13583 // Activate item1 to ensure it gets navigation entries
13584 pane.update_in(cx, |pane, window, cx| {
13585 pane.activate_item(0, true, true, window, cx);
13586 });
13587
13588 // Switch to item2 and back to create navigation history
13589 pane.update_in(cx, |pane, window, cx| {
13590 pane.activate_item(1, true, true, window, cx);
13591 });
13592 cx.run_until_parked();
13593
13594 pane.update_in(cx, |pane, window, cx| {
13595 pane.activate_item(0, true, true, window, cx);
13596 });
13597 cx.run_until_parked();
13598
13599 // Simulate file deletion for item1
13600 item1.update(cx, |item, _| {
13601 item.set_has_deleted_file(true);
13602 });
13603
13604 // Emit UpdateTab event to trigger the close behavior
13605 item1.update(cx, |_, cx| {
13606 cx.emit(ItemEvent::UpdateTab);
13607 });
13608 cx.run_until_parked();
13609
13610 // Verify item1 was closed
13611 pane.read_with(cx, |pane, _| {
13612 assert_eq!(
13613 pane.items().count(),
13614 1,
13615 "Should have 1 item remaining after auto-close"
13616 );
13617 });
13618
13619 // Check navigation history after close
13620 let has_item = pane.read_with(cx, |pane, cx| {
13621 let mut has_item = false;
13622 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13623 if entry.item.id() == item1_id {
13624 has_item = true;
13625 }
13626 });
13627 has_item
13628 });
13629
13630 assert!(
13631 !has_item,
13632 "Navigation history should not contain closed item entries"
13633 );
13634 }
13635
13636 #[gpui::test]
13637 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13638 cx: &mut TestAppContext,
13639 ) {
13640 init_test(cx);
13641
13642 let fs = FakeFs::new(cx.background_executor.clone());
13643 let project = Project::test(fs, [], cx).await;
13644 let (workspace, cx) =
13645 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13646 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13647
13648 let dirty_regular_buffer = cx.new(|cx| {
13649 TestItem::new(cx)
13650 .with_dirty(true)
13651 .with_label("1.txt")
13652 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13653 });
13654 let dirty_regular_buffer_2 = cx.new(|cx| {
13655 TestItem::new(cx)
13656 .with_dirty(true)
13657 .with_label("2.txt")
13658 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13659 });
13660 let clear_regular_buffer = cx.new(|cx| {
13661 TestItem::new(cx)
13662 .with_label("3.txt")
13663 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13664 });
13665
13666 let dirty_multi_buffer = cx.new(|cx| {
13667 TestItem::new(cx)
13668 .with_dirty(true)
13669 .with_buffer_kind(ItemBufferKind::Multibuffer)
13670 .with_label("Fake Project Search")
13671 .with_project_items(&[
13672 dirty_regular_buffer.read(cx).project_items[0].clone(),
13673 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13674 clear_regular_buffer.read(cx).project_items[0].clone(),
13675 ])
13676 });
13677 workspace.update_in(cx, |workspace, window, cx| {
13678 workspace.add_item(
13679 pane.clone(),
13680 Box::new(dirty_regular_buffer.clone()),
13681 None,
13682 false,
13683 false,
13684 window,
13685 cx,
13686 );
13687 workspace.add_item(
13688 pane.clone(),
13689 Box::new(dirty_regular_buffer_2.clone()),
13690 None,
13691 false,
13692 false,
13693 window,
13694 cx,
13695 );
13696 workspace.add_item(
13697 pane.clone(),
13698 Box::new(dirty_multi_buffer.clone()),
13699 None,
13700 false,
13701 false,
13702 window,
13703 cx,
13704 );
13705 });
13706
13707 pane.update_in(cx, |pane, window, cx| {
13708 pane.activate_item(2, true, true, window, cx);
13709 assert_eq!(
13710 pane.active_item().unwrap().item_id(),
13711 dirty_multi_buffer.item_id(),
13712 "Should select the multi buffer in the pane"
13713 );
13714 });
13715 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13716 pane.close_active_item(
13717 &CloseActiveItem {
13718 save_intent: None,
13719 close_pinned: false,
13720 },
13721 window,
13722 cx,
13723 )
13724 });
13725 cx.background_executor.run_until_parked();
13726 assert!(
13727 !cx.has_pending_prompt(),
13728 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13729 );
13730 close_multi_buffer_task
13731 .await
13732 .expect("Closing multi buffer failed");
13733 pane.update(cx, |pane, cx| {
13734 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13735 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13736 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13737 assert_eq!(
13738 pane.items()
13739 .map(|item| item.item_id())
13740 .sorted()
13741 .collect::<Vec<_>>(),
13742 vec![
13743 dirty_regular_buffer.item_id(),
13744 dirty_regular_buffer_2.item_id(),
13745 ],
13746 "Should have no multi buffer left in the pane"
13747 );
13748 assert!(dirty_regular_buffer.read(cx).is_dirty);
13749 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13750 });
13751 }
13752
13753 #[gpui::test]
13754 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13755 init_test(cx);
13756 let fs = FakeFs::new(cx.executor());
13757 let project = Project::test(fs, [], cx).await;
13758 let (multi_workspace, cx) =
13759 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13760 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13761
13762 // Add a new panel to the right dock, opening the dock and setting the
13763 // focus to the new panel.
13764 let panel = workspace.update_in(cx, |workspace, window, cx| {
13765 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13766 workspace.add_panel(panel.clone(), window, cx);
13767
13768 workspace
13769 .right_dock()
13770 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13771
13772 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13773
13774 panel
13775 });
13776
13777 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13778 // panel to the next valid position which, in this case, is the left
13779 // dock.
13780 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13781 workspace.update(cx, |workspace, cx| {
13782 assert!(workspace.left_dock().read(cx).is_open());
13783 assert_eq!(panel.read(cx).position, DockPosition::Left);
13784 });
13785
13786 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13787 // panel to the next valid position which, in this case, is the bottom
13788 // dock.
13789 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13790 workspace.update(cx, |workspace, cx| {
13791 assert!(workspace.bottom_dock().read(cx).is_open());
13792 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13793 });
13794
13795 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13796 // around moving the panel to its initial position, the right dock.
13797 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13798 workspace.update(cx, |workspace, cx| {
13799 assert!(workspace.right_dock().read(cx).is_open());
13800 assert_eq!(panel.read(cx).position, DockPosition::Right);
13801 });
13802
13803 // Remove focus from the panel, ensuring that, if the panel is not
13804 // focused, the `MoveFocusedPanelToNextPosition` action does not update
13805 // the panel's position, so the panel is still in the right dock.
13806 workspace.update_in(cx, |workspace, window, cx| {
13807 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13808 });
13809
13810 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13811 workspace.update(cx, |workspace, cx| {
13812 assert!(workspace.right_dock().read(cx).is_open());
13813 assert_eq!(panel.read(cx).position, DockPosition::Right);
13814 });
13815 }
13816
13817 #[gpui::test]
13818 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13819 init_test(cx);
13820
13821 let fs = FakeFs::new(cx.executor());
13822 let project = Project::test(fs, [], cx).await;
13823 let (workspace, cx) =
13824 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13825
13826 let item_1 = cx.new(|cx| {
13827 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13828 });
13829 workspace.update_in(cx, |workspace, window, cx| {
13830 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13831 workspace.move_item_to_pane_in_direction(
13832 &MoveItemToPaneInDirection {
13833 direction: SplitDirection::Right,
13834 focus: true,
13835 clone: false,
13836 },
13837 window,
13838 cx,
13839 );
13840 workspace.move_item_to_pane_at_index(
13841 &MoveItemToPane {
13842 destination: 3,
13843 focus: true,
13844 clone: false,
13845 },
13846 window,
13847 cx,
13848 );
13849
13850 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13851 assert_eq!(
13852 pane_items_paths(&workspace.active_pane, cx),
13853 vec!["first.txt".to_string()],
13854 "Single item was not moved anywhere"
13855 );
13856 });
13857
13858 let item_2 = cx.new(|cx| {
13859 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13860 });
13861 workspace.update_in(cx, |workspace, window, cx| {
13862 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13863 assert_eq!(
13864 pane_items_paths(&workspace.panes[0], cx),
13865 vec!["first.txt".to_string(), "second.txt".to_string()],
13866 );
13867 workspace.move_item_to_pane_in_direction(
13868 &MoveItemToPaneInDirection {
13869 direction: SplitDirection::Right,
13870 focus: true,
13871 clone: false,
13872 },
13873 window,
13874 cx,
13875 );
13876
13877 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13878 assert_eq!(
13879 pane_items_paths(&workspace.panes[0], cx),
13880 vec!["first.txt".to_string()],
13881 "After moving, one item should be left in the original pane"
13882 );
13883 assert_eq!(
13884 pane_items_paths(&workspace.panes[1], cx),
13885 vec!["second.txt".to_string()],
13886 "New item should have been moved to the new pane"
13887 );
13888 });
13889
13890 let item_3 = cx.new(|cx| {
13891 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13892 });
13893 workspace.update_in(cx, |workspace, window, cx| {
13894 let original_pane = workspace.panes[0].clone();
13895 workspace.set_active_pane(&original_pane, window, cx);
13896 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13897 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13898 assert_eq!(
13899 pane_items_paths(&workspace.active_pane, cx),
13900 vec!["first.txt".to_string(), "third.txt".to_string()],
13901 "New pane should be ready to move one item out"
13902 );
13903
13904 workspace.move_item_to_pane_at_index(
13905 &MoveItemToPane {
13906 destination: 3,
13907 focus: true,
13908 clone: false,
13909 },
13910 window,
13911 cx,
13912 );
13913 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13914 assert_eq!(
13915 pane_items_paths(&workspace.active_pane, cx),
13916 vec!["first.txt".to_string()],
13917 "After moving, one item should be left in the original pane"
13918 );
13919 assert_eq!(
13920 pane_items_paths(&workspace.panes[1], cx),
13921 vec!["second.txt".to_string()],
13922 "Previously created pane should be unchanged"
13923 );
13924 assert_eq!(
13925 pane_items_paths(&workspace.panes[2], cx),
13926 vec!["third.txt".to_string()],
13927 "New item should have been moved to the new pane"
13928 );
13929 });
13930 }
13931
13932 #[gpui::test]
13933 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13934 init_test(cx);
13935
13936 let fs = FakeFs::new(cx.executor());
13937 let project = Project::test(fs, [], cx).await;
13938 let (workspace, cx) =
13939 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13940
13941 let item_1 = cx.new(|cx| {
13942 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13943 });
13944 workspace.update_in(cx, |workspace, window, cx| {
13945 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13946 workspace.move_item_to_pane_in_direction(
13947 &MoveItemToPaneInDirection {
13948 direction: SplitDirection::Right,
13949 focus: true,
13950 clone: true,
13951 },
13952 window,
13953 cx,
13954 );
13955 });
13956 cx.run_until_parked();
13957 workspace.update_in(cx, |workspace, window, cx| {
13958 workspace.move_item_to_pane_at_index(
13959 &MoveItemToPane {
13960 destination: 3,
13961 focus: true,
13962 clone: true,
13963 },
13964 window,
13965 cx,
13966 );
13967 });
13968 cx.run_until_parked();
13969
13970 workspace.update(cx, |workspace, cx| {
13971 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13972 for pane in workspace.panes() {
13973 assert_eq!(
13974 pane_items_paths(pane, cx),
13975 vec!["first.txt".to_string()],
13976 "Single item exists in all panes"
13977 );
13978 }
13979 });
13980
13981 // verify that the active pane has been updated after waiting for the
13982 // pane focus event to fire and resolve
13983 workspace.read_with(cx, |workspace, _app| {
13984 assert_eq!(
13985 workspace.active_pane(),
13986 &workspace.panes[2],
13987 "The third pane should be the active one: {:?}",
13988 workspace.panes
13989 );
13990 })
13991 }
13992
13993 #[gpui::test]
13994 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13995 init_test(cx);
13996
13997 let fs = FakeFs::new(cx.executor());
13998 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13999
14000 let project = Project::test(fs, ["root".as_ref()], cx).await;
14001 let (workspace, cx) =
14002 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14003
14004 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14005 // Add item to pane A with project path
14006 let item_a = cx.new(|cx| {
14007 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14008 });
14009 workspace.update_in(cx, |workspace, window, cx| {
14010 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14011 });
14012
14013 // Split to create pane B
14014 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14015 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14016 });
14017
14018 // Add item with SAME project path to pane B, and pin it
14019 let item_b = cx.new(|cx| {
14020 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14021 });
14022 pane_b.update_in(cx, |pane, window, cx| {
14023 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14024 pane.set_pinned_count(1);
14025 });
14026
14027 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14028 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14029
14030 // close_pinned: false should only close the unpinned copy
14031 workspace.update_in(cx, |workspace, window, cx| {
14032 workspace.close_item_in_all_panes(
14033 &CloseItemInAllPanes {
14034 save_intent: Some(SaveIntent::Close),
14035 close_pinned: false,
14036 },
14037 window,
14038 cx,
14039 )
14040 });
14041 cx.executor().run_until_parked();
14042
14043 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14044 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14045 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14046 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14047
14048 // Split again, seeing as closing the previous item also closed its
14049 // pane, so only pane remains, which does not allow us to properly test
14050 // that both items close when `close_pinned: true`.
14051 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14052 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14053 });
14054
14055 // Add an item with the same project path to pane C so that
14056 // close_item_in_all_panes can determine what to close across all panes
14057 // (it reads the active item from the active pane, and split_pane
14058 // creates an empty pane).
14059 let item_c = cx.new(|cx| {
14060 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14061 });
14062 pane_c.update_in(cx, |pane, window, cx| {
14063 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14064 });
14065
14066 // close_pinned: true should close the pinned copy too
14067 workspace.update_in(cx, |workspace, window, cx| {
14068 let panes_count = workspace.panes().len();
14069 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14070
14071 workspace.close_item_in_all_panes(
14072 &CloseItemInAllPanes {
14073 save_intent: Some(SaveIntent::Close),
14074 close_pinned: true,
14075 },
14076 window,
14077 cx,
14078 )
14079 });
14080 cx.executor().run_until_parked();
14081
14082 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14083 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14084 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14085 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14086 }
14087
14088 mod register_project_item_tests {
14089
14090 use super::*;
14091
14092 // View
14093 struct TestPngItemView {
14094 focus_handle: FocusHandle,
14095 }
14096 // Model
14097 struct TestPngItem {}
14098
14099 impl project::ProjectItem for TestPngItem {
14100 fn try_open(
14101 _project: &Entity<Project>,
14102 path: &ProjectPath,
14103 cx: &mut App,
14104 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14105 if path.path.extension().unwrap() == "png" {
14106 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14107 } else {
14108 None
14109 }
14110 }
14111
14112 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14113 None
14114 }
14115
14116 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14117 None
14118 }
14119
14120 fn is_dirty(&self) -> bool {
14121 false
14122 }
14123 }
14124
14125 impl Item for TestPngItemView {
14126 type Event = ();
14127 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14128 "".into()
14129 }
14130 }
14131 impl EventEmitter<()> for TestPngItemView {}
14132 impl Focusable for TestPngItemView {
14133 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14134 self.focus_handle.clone()
14135 }
14136 }
14137
14138 impl Render for TestPngItemView {
14139 fn render(
14140 &mut self,
14141 _window: &mut Window,
14142 _cx: &mut Context<Self>,
14143 ) -> impl IntoElement {
14144 Empty
14145 }
14146 }
14147
14148 impl ProjectItem for TestPngItemView {
14149 type Item = TestPngItem;
14150
14151 fn for_project_item(
14152 _project: Entity<Project>,
14153 _pane: Option<&Pane>,
14154 _item: Entity<Self::Item>,
14155 _: &mut Window,
14156 cx: &mut Context<Self>,
14157 ) -> Self
14158 where
14159 Self: Sized,
14160 {
14161 Self {
14162 focus_handle: cx.focus_handle(),
14163 }
14164 }
14165 }
14166
14167 // View
14168 struct TestIpynbItemView {
14169 focus_handle: FocusHandle,
14170 }
14171 // Model
14172 struct TestIpynbItem {}
14173
14174 impl project::ProjectItem for TestIpynbItem {
14175 fn try_open(
14176 _project: &Entity<Project>,
14177 path: &ProjectPath,
14178 cx: &mut App,
14179 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14180 if path.path.extension().unwrap() == "ipynb" {
14181 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14182 } else {
14183 None
14184 }
14185 }
14186
14187 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14188 None
14189 }
14190
14191 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14192 None
14193 }
14194
14195 fn is_dirty(&self) -> bool {
14196 false
14197 }
14198 }
14199
14200 impl Item for TestIpynbItemView {
14201 type Event = ();
14202 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14203 "".into()
14204 }
14205 }
14206 impl EventEmitter<()> for TestIpynbItemView {}
14207 impl Focusable for TestIpynbItemView {
14208 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14209 self.focus_handle.clone()
14210 }
14211 }
14212
14213 impl Render for TestIpynbItemView {
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 TestIpynbItemView {
14224 type Item = TestIpynbItem;
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 struct TestAlternatePngItemView {
14243 focus_handle: FocusHandle,
14244 }
14245
14246 impl Item for TestAlternatePngItemView {
14247 type Event = ();
14248 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14249 "".into()
14250 }
14251 }
14252
14253 impl EventEmitter<()> for TestAlternatePngItemView {}
14254 impl Focusable for TestAlternatePngItemView {
14255 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14256 self.focus_handle.clone()
14257 }
14258 }
14259
14260 impl Render for TestAlternatePngItemView {
14261 fn render(
14262 &mut self,
14263 _window: &mut Window,
14264 _cx: &mut Context<Self>,
14265 ) -> impl IntoElement {
14266 Empty
14267 }
14268 }
14269
14270 impl ProjectItem for TestAlternatePngItemView {
14271 type Item = TestPngItem;
14272
14273 fn for_project_item(
14274 _project: Entity<Project>,
14275 _pane: Option<&Pane>,
14276 _item: Entity<Self::Item>,
14277 _: &mut Window,
14278 cx: &mut Context<Self>,
14279 ) -> Self
14280 where
14281 Self: Sized,
14282 {
14283 Self {
14284 focus_handle: cx.focus_handle(),
14285 }
14286 }
14287 }
14288
14289 #[gpui::test]
14290 async fn test_register_project_item(cx: &mut TestAppContext) {
14291 init_test(cx);
14292
14293 cx.update(|cx| {
14294 register_project_item::<TestPngItemView>(cx);
14295 register_project_item::<TestIpynbItemView>(cx);
14296 });
14297
14298 let fs = FakeFs::new(cx.executor());
14299 fs.insert_tree(
14300 "/root1",
14301 json!({
14302 "one.png": "BINARYDATAHERE",
14303 "two.ipynb": "{ totally a notebook }",
14304 "three.txt": "editing text, sure why not?"
14305 }),
14306 )
14307 .await;
14308
14309 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14310 let (workspace, cx) =
14311 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14312
14313 let worktree_id = project.update(cx, |project, cx| {
14314 project.worktrees(cx).next().unwrap().read(cx).id()
14315 });
14316
14317 let handle = workspace
14318 .update_in(cx, |workspace, window, cx| {
14319 let project_path = (worktree_id, rel_path("one.png"));
14320 workspace.open_path(project_path, None, true, window, cx)
14321 })
14322 .await
14323 .unwrap();
14324
14325 // Now we can check if the handle we got back errored or not
14326 assert_eq!(
14327 handle.to_any_view().entity_type(),
14328 TypeId::of::<TestPngItemView>()
14329 );
14330
14331 let handle = workspace
14332 .update_in(cx, |workspace, window, cx| {
14333 let project_path = (worktree_id, rel_path("two.ipynb"));
14334 workspace.open_path(project_path, None, true, window, cx)
14335 })
14336 .await
14337 .unwrap();
14338
14339 assert_eq!(
14340 handle.to_any_view().entity_type(),
14341 TypeId::of::<TestIpynbItemView>()
14342 );
14343
14344 let handle = workspace
14345 .update_in(cx, |workspace, window, cx| {
14346 let project_path = (worktree_id, rel_path("three.txt"));
14347 workspace.open_path(project_path, None, true, window, cx)
14348 })
14349 .await;
14350 assert!(handle.is_err());
14351 }
14352
14353 #[gpui::test]
14354 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14355 init_test(cx);
14356
14357 cx.update(|cx| {
14358 register_project_item::<TestPngItemView>(cx);
14359 register_project_item::<TestAlternatePngItemView>(cx);
14360 });
14361
14362 let fs = FakeFs::new(cx.executor());
14363 fs.insert_tree(
14364 "/root1",
14365 json!({
14366 "one.png": "BINARYDATAHERE",
14367 "two.ipynb": "{ totally a notebook }",
14368 "three.txt": "editing text, sure why not?"
14369 }),
14370 )
14371 .await;
14372 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14373 let (workspace, cx) =
14374 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14375 let worktree_id = project.update(cx, |project, cx| {
14376 project.worktrees(cx).next().unwrap().read(cx).id()
14377 });
14378
14379 let handle = workspace
14380 .update_in(cx, |workspace, window, cx| {
14381 let project_path = (worktree_id, rel_path("one.png"));
14382 workspace.open_path(project_path, None, true, window, cx)
14383 })
14384 .await
14385 .unwrap();
14386
14387 // This _must_ be the second item registered
14388 assert_eq!(
14389 handle.to_any_view().entity_type(),
14390 TypeId::of::<TestAlternatePngItemView>()
14391 );
14392
14393 let handle = workspace
14394 .update_in(cx, |workspace, window, cx| {
14395 let project_path = (worktree_id, rel_path("three.txt"));
14396 workspace.open_path(project_path, None, true, window, cx)
14397 })
14398 .await;
14399 assert!(handle.is_err());
14400 }
14401 }
14402
14403 #[gpui::test]
14404 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14405 init_test(cx);
14406
14407 let fs = FakeFs::new(cx.executor());
14408 let project = Project::test(fs, [], cx).await;
14409 let (workspace, _cx) =
14410 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14411
14412 // Test with status bar shown (default)
14413 workspace.read_with(cx, |workspace, cx| {
14414 let visible = workspace.status_bar_visible(cx);
14415 assert!(visible, "Status bar should be visible by default");
14416 });
14417
14418 // Test with status bar hidden
14419 cx.update_global(|store: &mut SettingsStore, cx| {
14420 store.update_user_settings(cx, |settings| {
14421 settings.status_bar.get_or_insert_default().show = Some(false);
14422 });
14423 });
14424
14425 workspace.read_with(cx, |workspace, cx| {
14426 let visible = workspace.status_bar_visible(cx);
14427 assert!(!visible, "Status bar should be hidden when show is false");
14428 });
14429
14430 // Test with status bar shown explicitly
14431 cx.update_global(|store: &mut SettingsStore, cx| {
14432 store.update_user_settings(cx, |settings| {
14433 settings.status_bar.get_or_insert_default().show = Some(true);
14434 });
14435 });
14436
14437 workspace.read_with(cx, |workspace, cx| {
14438 let visible = workspace.status_bar_visible(cx);
14439 assert!(visible, "Status bar should be visible when show is true");
14440 });
14441 }
14442
14443 #[gpui::test]
14444 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14445 init_test(cx);
14446
14447 let fs = FakeFs::new(cx.executor());
14448 let project = Project::test(fs, [], cx).await;
14449 let (multi_workspace, cx) =
14450 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14451 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14452 let panel = workspace.update_in(cx, |workspace, window, cx| {
14453 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14454 workspace.add_panel(panel.clone(), window, cx);
14455
14456 workspace
14457 .right_dock()
14458 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14459
14460 panel
14461 });
14462
14463 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14464 let item_a = cx.new(TestItem::new);
14465 let item_b = cx.new(TestItem::new);
14466 let item_a_id = item_a.entity_id();
14467 let item_b_id = item_b.entity_id();
14468
14469 pane.update_in(cx, |pane, window, cx| {
14470 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14471 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14472 });
14473
14474 pane.read_with(cx, |pane, _| {
14475 assert_eq!(pane.items_len(), 2);
14476 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14477 });
14478
14479 workspace.update_in(cx, |workspace, window, cx| {
14480 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14481 });
14482
14483 workspace.update_in(cx, |_, window, cx| {
14484 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14485 });
14486
14487 // Assert that the `pane::CloseActiveItem` action is handled at the
14488 // workspace level when one of the dock panels is focused and, in that
14489 // case, the center pane's active item is closed but the focus is not
14490 // moved.
14491 cx.dispatch_action(pane::CloseActiveItem::default());
14492 cx.run_until_parked();
14493
14494 pane.read_with(cx, |pane, _| {
14495 assert_eq!(pane.items_len(), 1);
14496 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14497 });
14498
14499 workspace.update_in(cx, |workspace, window, cx| {
14500 assert!(workspace.right_dock().read(cx).is_open());
14501 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14502 });
14503 }
14504
14505 #[gpui::test]
14506 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14507 init_test(cx);
14508 let fs = FakeFs::new(cx.executor());
14509
14510 let project_a = Project::test(fs.clone(), [], cx).await;
14511 let project_b = Project::test(fs, [], cx).await;
14512
14513 let multi_workspace_handle =
14514 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14515 cx.run_until_parked();
14516
14517 let workspace_a = multi_workspace_handle
14518 .read_with(cx, |mw, _| mw.workspace().clone())
14519 .unwrap();
14520
14521 let _workspace_b = multi_workspace_handle
14522 .update(cx, |mw, window, cx| {
14523 mw.test_add_workspace(project_b, window, cx)
14524 })
14525 .unwrap();
14526
14527 // Switch to workspace A
14528 multi_workspace_handle
14529 .update(cx, |mw, window, cx| {
14530 let workspace = mw.workspaces()[0].clone();
14531 mw.activate(workspace, window, cx);
14532 })
14533 .unwrap();
14534
14535 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14536
14537 // Add a panel to workspace A's right dock and open the dock
14538 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14539 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14540 workspace.add_panel(panel.clone(), window, cx);
14541 workspace
14542 .right_dock()
14543 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14544 panel
14545 });
14546
14547 // Focus the panel through the workspace (matching existing test pattern)
14548 workspace_a.update_in(cx, |workspace, window, cx| {
14549 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14550 });
14551
14552 // Zoom the panel
14553 panel.update_in(cx, |panel, window, cx| {
14554 panel.set_zoomed(true, window, cx);
14555 });
14556
14557 // Verify the panel is zoomed and the dock is open
14558 workspace_a.update_in(cx, |workspace, window, cx| {
14559 assert!(
14560 workspace.right_dock().read(cx).is_open(),
14561 "dock should be open before switch"
14562 );
14563 assert!(
14564 panel.is_zoomed(window, cx),
14565 "panel should be zoomed before switch"
14566 );
14567 assert!(
14568 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14569 "panel should be focused before switch"
14570 );
14571 });
14572
14573 // Switch to workspace B
14574 multi_workspace_handle
14575 .update(cx, |mw, window, cx| {
14576 let workspace = mw.workspaces()[1].clone();
14577 mw.activate(workspace, window, cx);
14578 })
14579 .unwrap();
14580 cx.run_until_parked();
14581
14582 // Switch back to workspace A
14583 multi_workspace_handle
14584 .update(cx, |mw, window, cx| {
14585 let workspace = mw.workspaces()[0].clone();
14586 mw.activate(workspace, window, cx);
14587 })
14588 .unwrap();
14589 cx.run_until_parked();
14590
14591 // Verify the panel is still zoomed and the dock is still open
14592 workspace_a.update_in(cx, |workspace, window, cx| {
14593 assert!(
14594 workspace.right_dock().read(cx).is_open(),
14595 "dock should still be open after switching back"
14596 );
14597 assert!(
14598 panel.is_zoomed(window, cx),
14599 "panel should still be zoomed after switching back"
14600 );
14601 });
14602 }
14603
14604 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14605 pane.read(cx)
14606 .items()
14607 .flat_map(|item| {
14608 item.project_paths(cx)
14609 .into_iter()
14610 .map(|path| path.path.display(PathStyle::local()).into_owned())
14611 })
14612 .collect()
14613 }
14614
14615 pub fn init_test(cx: &mut TestAppContext) {
14616 cx.update(|cx| {
14617 let settings_store = SettingsStore::test(cx);
14618 cx.set_global(settings_store);
14619 cx.set_global(db::AppDatabase::test_new());
14620 theme_settings::init(theme::LoadThemes::JustBase, cx);
14621 });
14622 }
14623
14624 #[gpui::test]
14625 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14626 use settings::{ThemeName, ThemeSelection};
14627 use theme::SystemAppearance;
14628 use zed_actions::theme::ToggleMode;
14629
14630 init_test(cx);
14631
14632 let fs = FakeFs::new(cx.executor());
14633 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14634
14635 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14636 .await;
14637
14638 // Build a test project and workspace view so the test can invoke
14639 // the workspace action handler the same way the UI would.
14640 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14641 let (workspace, cx) =
14642 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14643
14644 // Seed the settings file with a plain static light theme so the
14645 // first toggle always starts from a known persisted state.
14646 workspace.update_in(cx, |_workspace, _window, cx| {
14647 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14648 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14649 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14650 });
14651 });
14652 cx.executor().advance_clock(Duration::from_millis(200));
14653 cx.run_until_parked();
14654
14655 // Confirm the initial persisted settings contain the static theme
14656 // we just wrote before any toggling happens.
14657 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14658 assert!(settings_text.contains(r#""theme": "One Light""#));
14659
14660 // Toggle once. This should migrate the persisted theme settings
14661 // into light/dark slots and enable system mode.
14662 workspace.update_in(cx, |workspace, window, cx| {
14663 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14664 });
14665 cx.executor().advance_clock(Duration::from_millis(200));
14666 cx.run_until_parked();
14667
14668 // 1. Static -> Dynamic
14669 // this assertion checks theme changed from static to dynamic.
14670 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14671 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14672 assert_eq!(
14673 parsed["theme"],
14674 serde_json::json!({
14675 "mode": "system",
14676 "light": "One Light",
14677 "dark": "One Dark"
14678 })
14679 );
14680
14681 // 2. Toggle again, suppose it will change the mode to light
14682 workspace.update_in(cx, |workspace, window, cx| {
14683 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14684 });
14685 cx.executor().advance_clock(Duration::from_millis(200));
14686 cx.run_until_parked();
14687
14688 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14689 assert!(settings_text.contains(r#""mode": "light""#));
14690 }
14691
14692 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14693 let item = TestProjectItem::new(id, path, cx);
14694 item.update(cx, |item, _| {
14695 item.is_dirty = true;
14696 });
14697 item
14698 }
14699
14700 #[gpui::test]
14701 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14702 cx: &mut gpui::TestAppContext,
14703 ) {
14704 init_test(cx);
14705 let fs = FakeFs::new(cx.executor());
14706
14707 let project = Project::test(fs, [], cx).await;
14708 let (workspace, cx) =
14709 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14710
14711 let panel = workspace.update_in(cx, |workspace, window, cx| {
14712 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14713 workspace.add_panel(panel.clone(), window, cx);
14714 workspace
14715 .right_dock()
14716 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14717 panel
14718 });
14719
14720 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14721 pane.update_in(cx, |pane, window, cx| {
14722 let item = cx.new(TestItem::new);
14723 pane.add_item(Box::new(item), true, true, None, window, cx);
14724 });
14725
14726 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14727 // mirrors the real-world flow and avoids side effects from directly
14728 // focusing the panel while the center pane is active.
14729 workspace.update_in(cx, |workspace, window, cx| {
14730 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14731 });
14732
14733 panel.update_in(cx, |panel, window, cx| {
14734 panel.set_zoomed(true, window, cx);
14735 });
14736
14737 workspace.update_in(cx, |workspace, window, cx| {
14738 assert!(workspace.right_dock().read(cx).is_open());
14739 assert!(panel.is_zoomed(window, cx));
14740 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14741 });
14742
14743 // Simulate a spurious pane::Event::Focus on the center pane while the
14744 // panel still has focus. This mirrors what happens during macOS window
14745 // activation: the center pane fires a focus event even though actual
14746 // focus remains on the dock panel.
14747 pane.update_in(cx, |_, _, cx| {
14748 cx.emit(pane::Event::Focus);
14749 });
14750
14751 // The dock must remain open because the panel had focus at the time the
14752 // event was processed. Before the fix, dock_to_preserve was None for
14753 // panels that don't implement pane(), causing the dock to close.
14754 workspace.update_in(cx, |workspace, window, cx| {
14755 assert!(
14756 workspace.right_dock().read(cx).is_open(),
14757 "Dock should stay open when its zoomed panel (without pane()) still has focus"
14758 );
14759 assert!(panel.is_zoomed(window, cx));
14760 });
14761 }
14762
14763 #[gpui::test]
14764 async fn test_panels_stay_open_after_position_change_and_settings_update(
14765 cx: &mut gpui::TestAppContext,
14766 ) {
14767 init_test(cx);
14768 let fs = FakeFs::new(cx.executor());
14769 let project = Project::test(fs, [], cx).await;
14770 let (workspace, cx) =
14771 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14772
14773 // Add two panels to the left dock and open it.
14774 let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14775 let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14776 let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14777 workspace.add_panel(panel_a.clone(), window, cx);
14778 workspace.add_panel(panel_b.clone(), window, cx);
14779 workspace.left_dock().update(cx, |dock, cx| {
14780 dock.set_open(true, window, cx);
14781 dock.activate_panel(0, window, cx);
14782 });
14783 (panel_a, panel_b)
14784 });
14785
14786 workspace.update_in(cx, |workspace, _, cx| {
14787 assert!(workspace.left_dock().read(cx).is_open());
14788 });
14789
14790 // Simulate a feature flag changing default dock positions: both panels
14791 // move from Left to Right.
14792 workspace.update_in(cx, |_workspace, _window, cx| {
14793 panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14794 panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14795 cx.update_global::<SettingsStore, _>(|_, _| {});
14796 });
14797
14798 // Both panels should now be in the right dock.
14799 workspace.update_in(cx, |workspace, _, cx| {
14800 let right_dock = workspace.right_dock().read(cx);
14801 assert_eq!(right_dock.panels_len(), 2);
14802 });
14803
14804 // Open the right dock and activate panel_b (simulating the user
14805 // opening the panel after it moved).
14806 workspace.update_in(cx, |workspace, window, cx| {
14807 workspace.right_dock().update(cx, |dock, cx| {
14808 dock.set_open(true, window, cx);
14809 dock.activate_panel(1, window, cx);
14810 });
14811 });
14812
14813 // Now trigger another SettingsStore change
14814 workspace.update_in(cx, |_workspace, _window, cx| {
14815 cx.update_global::<SettingsStore, _>(|_, _| {});
14816 });
14817
14818 workspace.update_in(cx, |workspace, _, cx| {
14819 assert!(
14820 workspace.right_dock().read(cx).is_open(),
14821 "Right dock should still be open after a settings change"
14822 );
14823 assert_eq!(
14824 workspace.right_dock().read(cx).panels_len(),
14825 2,
14826 "Both panels should still be in the right dock"
14827 );
14828 });
14829 }
14830}