1pub mod active_file_name;
2pub mod dock;
3pub mod history_manager;
4pub mod invalid_item_view;
5pub mod item;
6mod modal_layer;
7mod multi_workspace;
8#[cfg(test)]
9mod multi_workspace_tests;
10pub mod notifications;
11pub mod pane;
12pub mod pane_group;
13pub mod path_list {
14 pub use util::path_list::{PathList, SerializedPathList};
15}
16mod persistence;
17pub mod searchable;
18mod security_modal;
19pub mod shared_screen;
20use db::smol::future::yield_now;
21pub use shared_screen::SharedScreen;
22pub mod focus_follows_mouse;
23mod status_bar;
24pub mod tasks;
25mod theme_preview;
26mod toast_layer;
27mod toolbar;
28pub mod welcome;
29mod workspace_settings;
30
31pub use crate::notifications::NotificationFrame;
32pub use dock::Panel;
33pub use multi_workspace::{
34 CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
35 MultiWorkspaceEvent, NextWorkspace, PreviousWorkspace, Sidebar, SidebarEvent, SidebarHandle,
36 SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar, sidebar_side_context_menu,
37};
38pub use path_list::{PathList, SerializedPathList};
39pub use toast_layer::{ToastAction, ToastLayer, ToastView};
40
41use anyhow::{Context as _, Result, anyhow};
42use client::{
43 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
44 proto::{self, ErrorCode, PanelId, PeerId},
45};
46use collections::{HashMap, HashSet, hash_map};
47use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
48use fs::Fs;
49use futures::{
50 Future, FutureExt, StreamExt,
51 channel::{
52 mpsc::{self, UnboundedReceiver, UnboundedSender},
53 oneshot,
54 },
55 future::{Shared, try_join_all},
56};
57use gpui::{
58 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
59 Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
60 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
61 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
62 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
63 WindowOptions, actions, canvas, point, relative, size, transparent_black,
64};
65pub use history_manager::*;
66pub use item::{
67 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
68 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
69};
70use itertools::Itertools;
71use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
72pub use modal_layer::*;
73use node_runtime::NodeRuntime;
74use notifications::{
75 DetachAndPromptErr, Notifications, dismiss_app_notification,
76 simple_message_notification::MessageNotification,
77};
78pub use pane::*;
79pub use pane_group::{
80 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
81 SplitDirection,
82};
83use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
84pub use persistence::{
85 WorkspaceDb, delete_unloaded_items,
86 model::{
87 DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
88 SessionWorkspace,
89 },
90 read_serialized_multi_workspaces, resolve_worktree_workspaces,
91};
92use postage::stream::Stream;
93use project::{
94 DirectoryLister, Project, ProjectEntryId, ProjectGroupKey, ProjectPath, ResolvedPath, Worktree,
95 WorktreeId, WorktreeSettings,
96 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
97 project_settings::ProjectSettings,
98 toolchain_store::ToolchainStoreEvent,
99 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
100};
101use remote::{
102 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
103 remote_client::ConnectionIdentifier,
104};
105use schemars::JsonSchema;
106use serde::Deserialize;
107use session::AppSession;
108use settings::{
109 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
110};
111
112use sqlez::{
113 bindable::{Bind, Column, StaticColumnCount},
114 statement::Statement,
115};
116use status_bar::StatusBar;
117pub use status_bar::StatusItemView;
118use std::{
119 any::TypeId,
120 borrow::Cow,
121 cell::RefCell,
122 cmp,
123 collections::VecDeque,
124 env,
125 hash::Hash,
126 path::{Path, PathBuf},
127 process::ExitStatus,
128 rc::Rc,
129 sync::{
130 Arc, LazyLock,
131 atomic::{AtomicBool, AtomicUsize},
132 },
133 time::Duration,
134};
135use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
136use theme::{ActiveTheme, SystemAppearance};
137use theme_settings::ThemeSettings;
138pub use toolbar::{
139 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
140};
141pub use ui;
142use ui::{Window, prelude::*};
143use util::{
144 ResultExt, TryFutureExt,
145 paths::{PathStyle, SanitizedPath},
146 rel_path::RelPath,
147 serde::default_true,
148};
149use uuid::Uuid;
150pub use workspace_settings::{
151 AutosaveSetting, BottomDockLayout, FocusFollowsMouse, RestoreOnStartupBehavior,
152 StatusBarSettings, TabBarSettings, WorkspaceSettings,
153};
154use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
155
156use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::NotificationId};
157use crate::{
158 persistence::{
159 SerializedAxis,
160 model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
161 },
162 security_modal::SecurityModal,
163};
164
165pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
166
167static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
168 env::var("ZED_WINDOW_SIZE")
169 .ok()
170 .as_deref()
171 .and_then(parse_pixel_size_env_var)
172});
173
174static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
175 env::var("ZED_WINDOW_POSITION")
176 .ok()
177 .as_deref()
178 .and_then(parse_pixel_position_env_var)
179});
180
181pub trait TerminalProvider {
182 fn spawn(
183 &self,
184 task: SpawnInTerminal,
185 window: &mut Window,
186 cx: &mut App,
187 ) -> Task<Option<Result<ExitStatus>>>;
188}
189
190pub trait DebuggerProvider {
191 // `active_buffer` is used to resolve build task's name against language-specific tasks.
192 fn start_session(
193 &self,
194 definition: DebugScenario,
195 task_context: SharedTaskContext,
196 active_buffer: Option<Entity<Buffer>>,
197 worktree_id: Option<WorktreeId>,
198 window: &mut Window,
199 cx: &mut App,
200 );
201
202 fn spawn_task_or_modal(
203 &self,
204 workspace: &mut Workspace,
205 action: &Spawn,
206 window: &mut Window,
207 cx: &mut Context<Workspace>,
208 );
209
210 fn task_scheduled(&self, cx: &mut App);
211 fn debug_scenario_scheduled(&self, cx: &mut App);
212 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
213
214 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
215}
216
217/// Opens a file or directory.
218#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
219#[action(namespace = workspace)]
220pub struct Open {
221 /// When true, opens in a new window. When false, adds to the current
222 /// window as a new workspace (multi-workspace).
223 #[serde(default = "Open::default_create_new_window")]
224 pub create_new_window: bool,
225}
226
227impl Open {
228 pub const DEFAULT: Self = Self {
229 create_new_window: true,
230 };
231
232 /// Used by `#[serde(default)]` on the `create_new_window` field so that
233 /// the serde default and `Open::DEFAULT` stay in sync.
234 fn default_create_new_window() -> bool {
235 Self::DEFAULT.create_new_window
236 }
237}
238
239impl Default for Open {
240 fn default() -> Self {
241 Self::DEFAULT
242 }
243}
244
245actions!(
246 workspace,
247 [
248 /// Activates the next pane in the workspace.
249 ActivateNextPane,
250 /// Activates the previous pane in the workspace.
251 ActivatePreviousPane,
252 /// Activates the last pane in the workspace.
253 ActivateLastPane,
254 /// Switches to the next window.
255 ActivateNextWindow,
256 /// Switches to the previous window.
257 ActivatePreviousWindow,
258 /// Adds a folder to the current project.
259 AddFolderToProject,
260 /// Clears all notifications.
261 ClearAllNotifications,
262 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
263 ClearNavigationHistory,
264 /// Closes the active dock.
265 CloseActiveDock,
266 /// Closes all docks.
267 CloseAllDocks,
268 /// Toggles all docks.
269 ToggleAllDocks,
270 /// Closes the current window.
271 CloseWindow,
272 /// Closes the current project.
273 CloseProject,
274 /// Opens the feedback dialog.
275 Feedback,
276 /// Follows the next collaborator in the session.
277 FollowNextCollaborator,
278 /// Moves the focused panel to the next position.
279 MoveFocusedPanelToNextPosition,
280 /// Creates a new file.
281 NewFile,
282 /// Creates a new file in a vertical split.
283 NewFileSplitVertical,
284 /// Creates a new file in a horizontal split.
285 NewFileSplitHorizontal,
286 /// Opens a new search.
287 NewSearch,
288 /// Opens a new window.
289 NewWindow,
290 /// Opens multiple files.
291 OpenFiles,
292 /// Opens the current location in terminal.
293 OpenInTerminal,
294 /// Opens the component preview.
295 OpenComponentPreview,
296 /// Reloads the active item.
297 ReloadActiveItem,
298 /// Resets the active dock to its default size.
299 ResetActiveDockSize,
300 /// Resets all open docks to their default sizes.
301 ResetOpenDocksSize,
302 /// Reloads the application
303 Reload,
304 /// Saves the current file with a new name.
305 SaveAs,
306 /// Saves without formatting.
307 SaveWithoutFormat,
308 /// Shuts down all debug adapters.
309 ShutdownDebugAdapters,
310 /// Suppresses the current notification.
311 SuppressNotification,
312 /// Toggles the bottom dock.
313 ToggleBottomDock,
314 /// Toggles centered layout mode.
315 ToggleCenteredLayout,
316 /// Toggles edit prediction feature globally for all files.
317 ToggleEditPrediction,
318 /// Toggles the left dock.
319 ToggleLeftDock,
320 /// Toggles the right dock.
321 ToggleRightDock,
322 /// Toggles zoom on the active pane.
323 ToggleZoom,
324 /// Toggles read-only mode for the active item (if supported by that item).
325 ToggleReadOnlyFile,
326 /// Zooms in on the active pane.
327 ZoomIn,
328 /// Zooms out of the active pane.
329 ZoomOut,
330 /// If any worktrees are in restricted mode, shows a modal with possible actions.
331 /// If the modal is shown already, closes it without trusting any worktree.
332 ToggleWorktreeSecurity,
333 /// Clears all trusted worktrees, placing them in restricted mode on next open.
334 /// Requires restart to take effect on already opened projects.
335 ClearTrustedWorktrees,
336 /// Stops following a collaborator.
337 Unfollow,
338 /// Restores the banner.
339 RestoreBanner,
340 /// Toggles expansion of the selected item.
341 ToggleExpandItem,
342 ]
343);
344
345/// Activates a specific pane by its index.
346#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
347#[action(namespace = workspace)]
348pub struct ActivatePane(pub usize);
349
350/// Moves an item to a specific pane by index.
351#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
352#[action(namespace = workspace)]
353#[serde(deny_unknown_fields)]
354pub struct MoveItemToPane {
355 #[serde(default = "default_1")]
356 pub destination: usize,
357 #[serde(default = "default_true")]
358 pub focus: bool,
359 #[serde(default)]
360 pub clone: bool,
361}
362
363fn default_1() -> usize {
364 1
365}
366
367/// Moves an item to a pane in the specified direction.
368#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
369#[action(namespace = workspace)]
370#[serde(deny_unknown_fields)]
371pub struct MoveItemToPaneInDirection {
372 #[serde(default = "default_right")]
373 pub direction: SplitDirection,
374 #[serde(default = "default_true")]
375 pub focus: bool,
376 #[serde(default)]
377 pub clone: bool,
378}
379
380/// Creates a new file in a split of the desired direction.
381#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
382#[action(namespace = workspace)]
383#[serde(deny_unknown_fields)]
384pub struct NewFileSplit(pub SplitDirection);
385
386fn default_right() -> SplitDirection {
387 SplitDirection::Right
388}
389
390/// Saves all open files in the workspace.
391#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
392#[action(namespace = workspace)]
393#[serde(deny_unknown_fields)]
394pub struct SaveAll {
395 #[serde(default)]
396 pub save_intent: Option<SaveIntent>,
397}
398
399/// Saves the current file with the specified options.
400#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
401#[action(namespace = workspace)]
402#[serde(deny_unknown_fields)]
403pub struct Save {
404 #[serde(default)]
405 pub save_intent: Option<SaveIntent>,
406}
407
408/// Moves Focus to the central panes in the workspace.
409#[derive(Clone, Debug, PartialEq, Eq, Action)]
410#[action(namespace = workspace)]
411pub struct FocusCenterPane;
412
413/// Closes all items and panes in the workspace.
414#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
415#[action(namespace = workspace)]
416#[serde(deny_unknown_fields)]
417pub struct CloseAllItemsAndPanes {
418 #[serde(default)]
419 pub save_intent: Option<SaveIntent>,
420}
421
422/// Closes all inactive tabs and panes in the workspace.
423#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
424#[action(namespace = workspace)]
425#[serde(deny_unknown_fields)]
426pub struct CloseInactiveTabsAndPanes {
427 #[serde(default)]
428 pub save_intent: Option<SaveIntent>,
429}
430
431/// Closes the active item across all panes.
432#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
433#[action(namespace = workspace)]
434#[serde(deny_unknown_fields)]
435pub struct CloseItemInAllPanes {
436 #[serde(default)]
437 pub save_intent: Option<SaveIntent>,
438 #[serde(default)]
439 pub close_pinned: bool,
440}
441
442/// Sends a sequence of keystrokes to the active element.
443#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
444#[action(namespace = workspace)]
445pub struct SendKeystrokes(pub String);
446
447actions!(
448 project_symbols,
449 [
450 /// Toggles the project symbols search.
451 #[action(name = "Toggle")]
452 ToggleProjectSymbols
453 ]
454);
455
456/// Toggles the file finder interface.
457#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
458#[action(namespace = file_finder, name = "Toggle")]
459#[serde(deny_unknown_fields)]
460pub struct ToggleFileFinder {
461 #[serde(default)]
462 pub separate_history: bool,
463}
464
465/// Opens a new terminal in the center.
466#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
467#[action(namespace = workspace)]
468#[serde(deny_unknown_fields)]
469pub struct NewCenterTerminal {
470 /// If true, creates a local terminal even in remote projects.
471 #[serde(default)]
472 pub local: bool,
473}
474
475/// Opens a new terminal.
476#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
477#[action(namespace = workspace)]
478#[serde(deny_unknown_fields)]
479pub struct NewTerminal {
480 /// If true, creates a local terminal even in remote projects.
481 #[serde(default)]
482 pub local: bool,
483}
484
485/// Increases size of a currently focused dock by a given amount of pixels.
486#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
487#[action(namespace = workspace)]
488#[serde(deny_unknown_fields)]
489pub struct IncreaseActiveDockSize {
490 /// For 0px parameter, uses UI font size value.
491 #[serde(default)]
492 pub px: u32,
493}
494
495/// Decreases size of a currently focused dock by a given amount of pixels.
496#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
497#[action(namespace = workspace)]
498#[serde(deny_unknown_fields)]
499pub struct DecreaseActiveDockSize {
500 /// For 0px parameter, uses UI font size value.
501 #[serde(default)]
502 pub px: u32,
503}
504
505/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
506#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
507#[action(namespace = workspace)]
508#[serde(deny_unknown_fields)]
509pub struct IncreaseOpenDocksSize {
510 /// For 0px parameter, uses UI font size value.
511 #[serde(default)]
512 pub px: u32,
513}
514
515/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
516#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
517#[action(namespace = workspace)]
518#[serde(deny_unknown_fields)]
519pub struct DecreaseOpenDocksSize {
520 /// For 0px parameter, uses UI font size value.
521 #[serde(default)]
522 pub px: u32,
523}
524
525actions!(
526 workspace,
527 [
528 /// Activates the pane to the left.
529 ActivatePaneLeft,
530 /// Activates the pane to the right.
531 ActivatePaneRight,
532 /// Activates the pane above.
533 ActivatePaneUp,
534 /// Activates the pane below.
535 ActivatePaneDown,
536 /// Swaps the current pane with the one to the left.
537 SwapPaneLeft,
538 /// Swaps the current pane with the one to the right.
539 SwapPaneRight,
540 /// Swaps the current pane with the one above.
541 SwapPaneUp,
542 /// Swaps the current pane with the one below.
543 SwapPaneDown,
544 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
545 SwapPaneAdjacent,
546 /// Move the current pane to be at the far left.
547 MovePaneLeft,
548 /// Move the current pane to be at the far right.
549 MovePaneRight,
550 /// Move the current pane to be at the very top.
551 MovePaneUp,
552 /// Move the current pane to be at the very bottom.
553 MovePaneDown,
554 ]
555);
556
557#[derive(PartialEq, Eq, Debug)]
558pub enum CloseIntent {
559 /// Quit the program entirely.
560 Quit,
561 /// Close a window.
562 CloseWindow,
563 /// Replace the workspace in an existing window.
564 ReplaceWindow,
565}
566
567#[derive(Clone)]
568pub struct Toast {
569 id: NotificationId,
570 msg: Cow<'static, str>,
571 autohide: bool,
572 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
573}
574
575impl Toast {
576 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
577 Toast {
578 id,
579 msg: msg.into(),
580 on_click: None,
581 autohide: false,
582 }
583 }
584
585 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
586 where
587 M: Into<Cow<'static, str>>,
588 F: Fn(&mut Window, &mut App) + 'static,
589 {
590 self.on_click = Some((message.into(), Arc::new(on_click)));
591 self
592 }
593
594 pub fn autohide(mut self) -> Self {
595 self.autohide = true;
596 self
597 }
598}
599
600impl PartialEq for Toast {
601 fn eq(&self, other: &Self) -> bool {
602 self.id == other.id
603 && self.msg == other.msg
604 && self.on_click.is_some() == other.on_click.is_some()
605 }
606}
607
608/// Opens a new terminal with the specified working directory.
609#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
610#[action(namespace = workspace)]
611#[serde(deny_unknown_fields)]
612pub struct OpenTerminal {
613 pub working_directory: PathBuf,
614 /// If true, creates a local terminal even in remote projects.
615 #[serde(default)]
616 pub local: bool,
617}
618
619#[derive(
620 Clone,
621 Copy,
622 Debug,
623 Default,
624 Hash,
625 PartialEq,
626 Eq,
627 PartialOrd,
628 Ord,
629 serde::Serialize,
630 serde::Deserialize,
631)]
632pub struct WorkspaceId(i64);
633
634impl WorkspaceId {
635 pub fn from_i64(value: i64) -> Self {
636 Self(value)
637 }
638}
639
640impl StaticColumnCount for WorkspaceId {}
641impl Bind for WorkspaceId {
642 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
643 self.0.bind(statement, start_index)
644 }
645}
646impl Column for WorkspaceId {
647 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
648 i64::column(statement, start_index)
649 .map(|(i, next_index)| (Self(i), next_index))
650 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
651 }
652}
653impl From<WorkspaceId> for i64 {
654 fn from(val: WorkspaceId) -> Self {
655 val.0
656 }
657}
658
659fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
660 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
661 workspace_window
662 .update(cx, |multi_workspace, window, cx| {
663 let workspace = multi_workspace.workspace().clone();
664 workspace.update(cx, |workspace, cx| {
665 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
666 });
667 })
668 .ok();
669 } else {
670 let task = Workspace::new_local(
671 Vec::new(),
672 app_state.clone(),
673 None,
674 None,
675 None,
676 OpenMode::Activate,
677 cx,
678 );
679 cx.spawn(async move |cx| {
680 let OpenResult { window, .. } = task.await?;
681 window.update(cx, |multi_workspace, window, cx| {
682 window.activate_window();
683 let workspace = multi_workspace.workspace().clone();
684 workspace.update(cx, |workspace, cx| {
685 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
686 });
687 })?;
688 anyhow::Ok(())
689 })
690 .detach_and_log_err(cx);
691 }
692}
693
694pub fn prompt_for_open_path_and_open(
695 workspace: &mut Workspace,
696 app_state: Arc<AppState>,
697 options: PathPromptOptions,
698 create_new_window: bool,
699 window: &mut Window,
700 cx: &mut Context<Workspace>,
701) {
702 let paths = workspace.prompt_for_open_path(
703 options,
704 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
705 window,
706 cx,
707 );
708 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
709 cx.spawn_in(window, async move |this, cx| {
710 let Some(paths) = paths.await.log_err().flatten() else {
711 return;
712 };
713 if !create_new_window {
714 if let Some(handle) = multi_workspace_handle {
715 if let Some(task) = handle
716 .update(cx, |multi_workspace, window, cx| {
717 multi_workspace.open_project(paths, OpenMode::Activate, window, cx)
718 })
719 .log_err()
720 {
721 task.await.log_err();
722 }
723 return;
724 }
725 }
726 if let Some(task) = this
727 .update_in(cx, |this, window, cx| {
728 this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
729 })
730 .log_err()
731 {
732 task.await.log_err();
733 }
734 })
735 .detach();
736}
737
738pub fn init(app_state: Arc<AppState>, cx: &mut App) {
739 component::init();
740 theme_preview::init(cx);
741 toast_layer::init(cx);
742 history_manager::init(app_state.fs.clone(), cx);
743
744 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
745 .on_action(|_: &Reload, cx| reload(cx))
746 .on_action(|_: &Open, cx: &mut App| {
747 let app_state = AppState::global(cx);
748 prompt_and_open_paths(
749 app_state,
750 PathPromptOptions {
751 files: true,
752 directories: true,
753 multiple: true,
754 prompt: None,
755 },
756 cx,
757 );
758 })
759 .on_action(|_: &OpenFiles, cx: &mut App| {
760 let directories = cx.can_select_mixed_files_and_dirs();
761 let app_state = AppState::global(cx);
762 prompt_and_open_paths(
763 app_state,
764 PathPromptOptions {
765 files: true,
766 directories,
767 multiple: true,
768 prompt: None,
769 },
770 cx,
771 );
772 });
773}
774
775type BuildProjectItemFn =
776 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
777
778type BuildProjectItemForPathFn =
779 fn(
780 &Entity<Project>,
781 &ProjectPath,
782 &mut Window,
783 &mut App,
784 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
785
786#[derive(Clone, Default)]
787struct ProjectItemRegistry {
788 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
789 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
790}
791
792impl ProjectItemRegistry {
793 fn register<T: ProjectItem>(&mut self) {
794 self.build_project_item_fns_by_type.insert(
795 TypeId::of::<T::Item>(),
796 |item, project, pane, window, cx| {
797 let item = item.downcast().unwrap();
798 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
799 as Box<dyn ItemHandle>
800 },
801 );
802 self.build_project_item_for_path_fns
803 .push(|project, project_path, window, cx| {
804 let project_path = project_path.clone();
805 let is_file = project
806 .read(cx)
807 .entry_for_path(&project_path, cx)
808 .is_some_and(|entry| entry.is_file());
809 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
810 let is_local = project.read(cx).is_local();
811 let project_item =
812 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
813 let project = project.clone();
814 Some(window.spawn(cx, async move |cx| {
815 match project_item.await.with_context(|| {
816 format!(
817 "opening project path {:?}",
818 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
819 )
820 }) {
821 Ok(project_item) => {
822 let project_item = project_item;
823 let project_entry_id: Option<ProjectEntryId> =
824 project_item.read_with(cx, project::ProjectItem::entry_id);
825 let build_workspace_item = Box::new(
826 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
827 Box::new(cx.new(|cx| {
828 T::for_project_item(
829 project,
830 Some(pane),
831 project_item,
832 window,
833 cx,
834 )
835 })) as Box<dyn ItemHandle>
836 },
837 ) as Box<_>;
838 Ok((project_entry_id, build_workspace_item))
839 }
840 Err(e) => {
841 log::warn!("Failed to open a project item: {e:#}");
842 if e.error_code() == ErrorCode::Internal {
843 if let Some(abs_path) =
844 entry_abs_path.as_deref().filter(|_| is_file)
845 {
846 if let Some(broken_project_item_view) =
847 cx.update(|window, cx| {
848 T::for_broken_project_item(
849 abs_path, is_local, &e, window, cx,
850 )
851 })?
852 {
853 let build_workspace_item = Box::new(
854 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
855 cx.new(|_| broken_project_item_view).boxed_clone()
856 },
857 )
858 as Box<_>;
859 return Ok((None, build_workspace_item));
860 }
861 }
862 }
863 Err(e)
864 }
865 }
866 }))
867 });
868 }
869
870 fn open_path(
871 &self,
872 project: &Entity<Project>,
873 path: &ProjectPath,
874 window: &mut Window,
875 cx: &mut App,
876 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
877 let Some(open_project_item) = self
878 .build_project_item_for_path_fns
879 .iter()
880 .rev()
881 .find_map(|open_project_item| open_project_item(project, path, window, cx))
882 else {
883 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
884 };
885 open_project_item
886 }
887
888 fn build_item<T: project::ProjectItem>(
889 &self,
890 item: Entity<T>,
891 project: Entity<Project>,
892 pane: Option<&Pane>,
893 window: &mut Window,
894 cx: &mut App,
895 ) -> Option<Box<dyn ItemHandle>> {
896 let build = self
897 .build_project_item_fns_by_type
898 .get(&TypeId::of::<T>())?;
899 Some(build(item.into_any(), project, pane, window, cx))
900 }
901}
902
903type WorkspaceItemBuilder =
904 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
905
906impl Global for ProjectItemRegistry {}
907
908/// Registers a [ProjectItem] for the app. When opening a file, all the registered
909/// items will get a chance to open the file, starting from the project item that
910/// was added last.
911pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
912 cx.default_global::<ProjectItemRegistry>().register::<I>();
913}
914
915#[derive(Default)]
916pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
917
918struct FollowableViewDescriptor {
919 from_state_proto: fn(
920 Entity<Workspace>,
921 ViewId,
922 &mut Option<proto::view::Variant>,
923 &mut Window,
924 &mut App,
925 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
926 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
927}
928
929impl Global for FollowableViewRegistry {}
930
931impl FollowableViewRegistry {
932 pub fn register<I: FollowableItem>(cx: &mut App) {
933 cx.default_global::<Self>().0.insert(
934 TypeId::of::<I>(),
935 FollowableViewDescriptor {
936 from_state_proto: |workspace, id, state, window, cx| {
937 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
938 cx.foreground_executor()
939 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
940 })
941 },
942 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
943 },
944 );
945 }
946
947 pub fn from_state_proto(
948 workspace: Entity<Workspace>,
949 view_id: ViewId,
950 mut state: Option<proto::view::Variant>,
951 window: &mut Window,
952 cx: &mut App,
953 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
954 cx.update_default_global(|this: &mut Self, cx| {
955 this.0.values().find_map(|descriptor| {
956 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
957 })
958 })
959 }
960
961 pub fn to_followable_view(
962 view: impl Into<AnyView>,
963 cx: &App,
964 ) -> Option<Box<dyn FollowableItemHandle>> {
965 let this = cx.try_global::<Self>()?;
966 let view = view.into();
967 let descriptor = this.0.get(&view.entity_type())?;
968 Some((descriptor.to_followable_view)(&view))
969 }
970}
971
972#[derive(Copy, Clone)]
973struct SerializableItemDescriptor {
974 deserialize: fn(
975 Entity<Project>,
976 WeakEntity<Workspace>,
977 WorkspaceId,
978 ItemId,
979 &mut Window,
980 &mut Context<Pane>,
981 ) -> Task<Result<Box<dyn ItemHandle>>>,
982 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
983 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
984}
985
986#[derive(Default)]
987struct SerializableItemRegistry {
988 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
989 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
990}
991
992impl Global for SerializableItemRegistry {}
993
994impl SerializableItemRegistry {
995 fn deserialize(
996 item_kind: &str,
997 project: Entity<Project>,
998 workspace: WeakEntity<Workspace>,
999 workspace_id: WorkspaceId,
1000 item_item: ItemId,
1001 window: &mut Window,
1002 cx: &mut Context<Pane>,
1003 ) -> Task<Result<Box<dyn ItemHandle>>> {
1004 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1005 return Task::ready(Err(anyhow!(
1006 "cannot deserialize {}, descriptor not found",
1007 item_kind
1008 )));
1009 };
1010
1011 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1012 }
1013
1014 fn cleanup(
1015 item_kind: &str,
1016 workspace_id: WorkspaceId,
1017 loaded_items: Vec<ItemId>,
1018 window: &mut Window,
1019 cx: &mut App,
1020 ) -> Task<Result<()>> {
1021 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1022 return Task::ready(Err(anyhow!(
1023 "cannot cleanup {}, descriptor not found",
1024 item_kind
1025 )));
1026 };
1027
1028 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1029 }
1030
1031 fn view_to_serializable_item_handle(
1032 view: AnyView,
1033 cx: &App,
1034 ) -> Option<Box<dyn SerializableItemHandle>> {
1035 let this = cx.try_global::<Self>()?;
1036 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1037 Some((descriptor.view_to_serializable_item)(view))
1038 }
1039
1040 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1041 let this = cx.try_global::<Self>()?;
1042 this.descriptors_by_kind.get(item_kind).copied()
1043 }
1044}
1045
1046pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1047 let serialized_item_kind = I::serialized_item_kind();
1048
1049 let registry = cx.default_global::<SerializableItemRegistry>();
1050 let descriptor = SerializableItemDescriptor {
1051 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1052 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1053 cx.foreground_executor()
1054 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1055 },
1056 cleanup: |workspace_id, loaded_items, window, cx| {
1057 I::cleanup(workspace_id, loaded_items, window, cx)
1058 },
1059 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1060 };
1061 registry
1062 .descriptors_by_kind
1063 .insert(Arc::from(serialized_item_kind), descriptor);
1064 registry
1065 .descriptors_by_type
1066 .insert(TypeId::of::<I>(), descriptor);
1067}
1068
1069pub struct AppState {
1070 pub languages: Arc<LanguageRegistry>,
1071 pub client: Arc<Client>,
1072 pub user_store: Entity<UserStore>,
1073 pub workspace_store: Entity<WorkspaceStore>,
1074 pub fs: Arc<dyn fs::Fs>,
1075 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1076 pub node_runtime: NodeRuntime,
1077 pub session: Entity<AppSession>,
1078}
1079
1080struct GlobalAppState(Arc<AppState>);
1081
1082impl Global for GlobalAppState {}
1083
1084pub struct WorkspaceStore {
1085 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1086 client: Arc<Client>,
1087 _subscriptions: Vec<client::Subscription>,
1088}
1089
1090#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1091pub enum CollaboratorId {
1092 PeerId(PeerId),
1093 Agent,
1094}
1095
1096impl From<PeerId> for CollaboratorId {
1097 fn from(peer_id: PeerId) -> Self {
1098 CollaboratorId::PeerId(peer_id)
1099 }
1100}
1101
1102impl From<&PeerId> for CollaboratorId {
1103 fn from(peer_id: &PeerId) -> Self {
1104 CollaboratorId::PeerId(*peer_id)
1105 }
1106}
1107
1108#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1109struct Follower {
1110 project_id: Option<u64>,
1111 peer_id: PeerId,
1112}
1113
1114impl AppState {
1115 #[track_caller]
1116 pub fn global(cx: &App) -> Arc<Self> {
1117 cx.global::<GlobalAppState>().0.clone()
1118 }
1119 pub fn try_global(cx: &App) -> Option<Arc<Self>> {
1120 cx.try_global::<GlobalAppState>()
1121 .map(|state| state.0.clone())
1122 }
1123 pub fn set_global(state: Arc<AppState>, cx: &mut App) {
1124 cx.set_global(GlobalAppState(state));
1125 }
1126
1127 #[cfg(any(test, feature = "test-support"))]
1128 pub fn test(cx: &mut App) -> Arc<Self> {
1129 use fs::Fs;
1130 use node_runtime::NodeRuntime;
1131 use session::Session;
1132 use settings::SettingsStore;
1133
1134 if !cx.has_global::<SettingsStore>() {
1135 let settings_store = SettingsStore::test(cx);
1136 cx.set_global(settings_store);
1137 }
1138
1139 let fs = fs::FakeFs::new(cx.background_executor().clone());
1140 <dyn Fs>::set_global(fs.clone(), cx);
1141 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1142 let clock = Arc::new(clock::FakeSystemClock::new());
1143 let http_client = http_client::FakeHttpClient::with_404_response();
1144 let client = Client::new(clock, http_client, cx);
1145 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1146 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1147 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1148
1149 theme_settings::init(theme::LoadThemes::JustBase, cx);
1150 client::init(&client, cx);
1151
1152 Arc::new(Self {
1153 client,
1154 fs,
1155 languages,
1156 user_store,
1157 workspace_store,
1158 node_runtime: NodeRuntime::unavailable(),
1159 build_window_options: |_, _| Default::default(),
1160 session,
1161 })
1162 }
1163}
1164
1165struct DelayedDebouncedEditAction {
1166 task: Option<Task<()>>,
1167 cancel_channel: Option<oneshot::Sender<()>>,
1168}
1169
1170impl DelayedDebouncedEditAction {
1171 fn new() -> DelayedDebouncedEditAction {
1172 DelayedDebouncedEditAction {
1173 task: None,
1174 cancel_channel: None,
1175 }
1176 }
1177
1178 fn fire_new<F>(
1179 &mut self,
1180 delay: Duration,
1181 window: &mut Window,
1182 cx: &mut Context<Workspace>,
1183 func: F,
1184 ) where
1185 F: 'static
1186 + Send
1187 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1188 {
1189 if let Some(channel) = self.cancel_channel.take() {
1190 _ = channel.send(());
1191 }
1192
1193 let (sender, mut receiver) = oneshot::channel::<()>();
1194 self.cancel_channel = Some(sender);
1195
1196 let previous_task = self.task.take();
1197 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1198 let mut timer = cx.background_executor().timer(delay).fuse();
1199 if let Some(previous_task) = previous_task {
1200 previous_task.await;
1201 }
1202
1203 futures::select_biased! {
1204 _ = receiver => return,
1205 _ = timer => {}
1206 }
1207
1208 if let Some(result) = workspace
1209 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1210 .log_err()
1211 {
1212 result.await.log_err();
1213 }
1214 }));
1215 }
1216}
1217
1218pub enum Event {
1219 PaneAdded(Entity<Pane>),
1220 PaneRemoved,
1221 ItemAdded {
1222 item: Box<dyn ItemHandle>,
1223 },
1224 ActiveItemChanged,
1225 ItemRemoved {
1226 item_id: EntityId,
1227 },
1228 UserSavedItem {
1229 pane: WeakEntity<Pane>,
1230 item: Box<dyn WeakItemHandle>,
1231 save_intent: SaveIntent,
1232 },
1233 ContactRequestedJoin(u64),
1234 WorkspaceCreated(WeakEntity<Workspace>),
1235 OpenBundledFile {
1236 text: Cow<'static, str>,
1237 title: &'static str,
1238 language: &'static str,
1239 },
1240 ZoomChanged,
1241 ModalOpened,
1242 Activate,
1243 PanelAdded(AnyView),
1244}
1245
1246#[derive(Debug, Clone)]
1247pub enum OpenVisible {
1248 All,
1249 None,
1250 OnlyFiles,
1251 OnlyDirectories,
1252}
1253
1254enum WorkspaceLocation {
1255 // Valid local paths or SSH project to serialize
1256 Location(SerializedWorkspaceLocation, PathList),
1257 // No valid location found hence clear session id
1258 DetachFromSession,
1259 // No valid location found to serialize
1260 None,
1261}
1262
1263type PromptForNewPath = Box<
1264 dyn Fn(
1265 &mut Workspace,
1266 DirectoryLister,
1267 Option<String>,
1268 &mut Window,
1269 &mut Context<Workspace>,
1270 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1271>;
1272
1273type PromptForOpenPath = Box<
1274 dyn Fn(
1275 &mut Workspace,
1276 DirectoryLister,
1277 &mut Window,
1278 &mut Context<Workspace>,
1279 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1280>;
1281
1282#[derive(Default)]
1283struct DispatchingKeystrokes {
1284 dispatched: HashSet<Vec<Keystroke>>,
1285 queue: VecDeque<Keystroke>,
1286 task: Option<Shared<Task<()>>>,
1287}
1288
1289/// Collects everything project-related for a certain window opened.
1290/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1291///
1292/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1293/// The `Workspace` owns everybody's state and serves as a default, "global context",
1294/// that can be used to register a global action to be triggered from any place in the window.
1295pub struct Workspace {
1296 weak_self: WeakEntity<Self>,
1297 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1298 zoomed: Option<AnyWeakView>,
1299 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1300 zoomed_position: Option<DockPosition>,
1301 center: PaneGroup,
1302 left_dock: Entity<Dock>,
1303 bottom_dock: Entity<Dock>,
1304 right_dock: Entity<Dock>,
1305 panes: Vec<Entity<Pane>>,
1306 active_worktree_override: Option<WorktreeId>,
1307 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1308 active_pane: Entity<Pane>,
1309 last_active_center_pane: Option<WeakEntity<Pane>>,
1310 last_active_view_id: Option<proto::ViewId>,
1311 status_bar: Entity<StatusBar>,
1312 pub(crate) modal_layer: Entity<ModalLayer>,
1313 toast_layer: Entity<ToastLayer>,
1314 titlebar_item: Option<AnyView>,
1315 notifications: Notifications,
1316 suppressed_notifications: HashSet<NotificationId>,
1317 project: Entity<Project>,
1318 follower_states: HashMap<CollaboratorId, FollowerState>,
1319 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1320 window_edited: bool,
1321 last_window_title: Option<String>,
1322 dirty_items: HashMap<EntityId, Subscription>,
1323 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1324 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1325 database_id: Option<WorkspaceId>,
1326 app_state: Arc<AppState>,
1327 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1328 _subscriptions: Vec<Subscription>,
1329 _apply_leader_updates: Task<Result<()>>,
1330 _observe_current_user: Task<Result<()>>,
1331 _schedule_serialize_workspace: Option<Task<()>>,
1332 _serialize_workspace_task: Option<Task<()>>,
1333 _schedule_serialize_ssh_paths: Option<Task<()>>,
1334 pane_history_timestamp: Arc<AtomicUsize>,
1335 bounds: Bounds<Pixels>,
1336 pub centered_layout: bool,
1337 bounds_save_task_queued: Option<Task<()>>,
1338 on_prompt_for_new_path: Option<PromptForNewPath>,
1339 on_prompt_for_open_path: Option<PromptForOpenPath>,
1340 terminal_provider: Option<Box<dyn TerminalProvider>>,
1341 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1342 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1343 _items_serializer: Task<Result<()>>,
1344 session_id: Option<String>,
1345 scheduled_tasks: Vec<Task<()>>,
1346 last_open_dock_positions: Vec<DockPosition>,
1347 removing: bool,
1348 open_in_dev_container: bool,
1349 _dev_container_task: Option<Task<Result<()>>>,
1350 _panels_task: Option<Task<Result<()>>>,
1351 sidebar_focus_handle: Option<FocusHandle>,
1352 multi_workspace: Option<WeakEntity<MultiWorkspace>>,
1353}
1354
1355impl EventEmitter<Event> for Workspace {}
1356
1357#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1358pub struct ViewId {
1359 pub creator: CollaboratorId,
1360 pub id: u64,
1361}
1362
1363pub struct FollowerState {
1364 center_pane: Entity<Pane>,
1365 dock_pane: Option<Entity<Pane>>,
1366 active_view_id: Option<ViewId>,
1367 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1368}
1369
1370struct FollowerView {
1371 view: Box<dyn FollowableItemHandle>,
1372 location: Option<proto::PanelId>,
1373}
1374
1375#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1376pub enum OpenMode {
1377 /// Open the workspace in a new window.
1378 NewWindow,
1379 /// Add to the window's multi workspace without activating it (used during deserialization).
1380 Add,
1381 /// Add to the window's multi workspace and activate it.
1382 #[default]
1383 Activate,
1384}
1385
1386impl Workspace {
1387 pub fn new(
1388 workspace_id: Option<WorkspaceId>,
1389 project: Entity<Project>,
1390 app_state: Arc<AppState>,
1391 window: &mut Window,
1392 cx: &mut Context<Self>,
1393 ) -> Self {
1394 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1395 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1396 if let TrustedWorktreesEvent::Trusted(..) = e {
1397 // Do not persist auto trusted worktrees
1398 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1399 worktrees_store.update(cx, |worktrees_store, cx| {
1400 worktrees_store.schedule_serialization(
1401 cx,
1402 |new_trusted_worktrees, cx| {
1403 let timeout =
1404 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1405 let db = WorkspaceDb::global(cx);
1406 cx.background_spawn(async move {
1407 timeout.await;
1408 db.save_trusted_worktrees(new_trusted_worktrees)
1409 .await
1410 .log_err();
1411 })
1412 },
1413 )
1414 });
1415 }
1416 }
1417 })
1418 .detach();
1419
1420 cx.observe_global::<SettingsStore>(|_, cx| {
1421 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1422 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1423 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1424 trusted_worktrees.auto_trust_all(cx);
1425 })
1426 }
1427 }
1428 })
1429 .detach();
1430 }
1431
1432 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1433 match event {
1434 project::Event::RemoteIdChanged(_) => {
1435 this.update_window_title(window, cx);
1436 }
1437
1438 project::Event::CollaboratorLeft(peer_id) => {
1439 this.collaborator_left(*peer_id, window, cx);
1440 }
1441
1442 &project::Event::WorktreeRemoved(_) => {
1443 this.update_window_title(window, cx);
1444 this.serialize_workspace(window, cx);
1445 this.update_history(cx);
1446 }
1447
1448 &project::Event::WorktreeAdded(id) => {
1449 this.update_window_title(window, cx);
1450 if this
1451 .project()
1452 .read(cx)
1453 .worktree_for_id(id, cx)
1454 .is_some_and(|wt| wt.read(cx).is_visible())
1455 {
1456 this.serialize_workspace(window, cx);
1457 this.update_history(cx);
1458 }
1459 }
1460 project::Event::WorktreeUpdatedEntries(..) => {
1461 this.update_window_title(window, cx);
1462 this.serialize_workspace(window, cx);
1463 }
1464
1465 project::Event::DisconnectedFromHost => {
1466 this.update_window_edited(window, cx);
1467 let leaders_to_unfollow =
1468 this.follower_states.keys().copied().collect::<Vec<_>>();
1469 for leader_id in leaders_to_unfollow {
1470 this.unfollow(leader_id, window, cx);
1471 }
1472 }
1473
1474 project::Event::DisconnectedFromRemote {
1475 server_not_running: _,
1476 } => {
1477 this.update_window_edited(window, cx);
1478 }
1479
1480 project::Event::Closed => {
1481 window.remove_window();
1482 }
1483
1484 project::Event::DeletedEntry(_, entry_id) => {
1485 for pane in this.panes.iter() {
1486 pane.update(cx, |pane, cx| {
1487 pane.handle_deleted_project_item(*entry_id, window, cx)
1488 });
1489 }
1490 }
1491
1492 project::Event::Toast {
1493 notification_id,
1494 message,
1495 link,
1496 } => this.show_notification(
1497 NotificationId::named(notification_id.clone()),
1498 cx,
1499 |cx| {
1500 let mut notification = MessageNotification::new(message.clone(), cx);
1501 if let Some(link) = link {
1502 notification = notification
1503 .more_info_message(link.label)
1504 .more_info_url(link.url);
1505 }
1506
1507 cx.new(|_| notification)
1508 },
1509 ),
1510
1511 project::Event::HideToast { notification_id } => {
1512 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1513 }
1514
1515 project::Event::LanguageServerPrompt(request) => {
1516 struct LanguageServerPrompt;
1517
1518 this.show_notification(
1519 NotificationId::composite::<LanguageServerPrompt>(request.id),
1520 cx,
1521 |cx| {
1522 cx.new(|cx| {
1523 notifications::LanguageServerPrompt::new(request.clone(), cx)
1524 })
1525 },
1526 );
1527 }
1528
1529 project::Event::AgentLocationChanged => {
1530 this.handle_agent_location_changed(window, cx)
1531 }
1532
1533 _ => {}
1534 }
1535 cx.notify()
1536 })
1537 .detach();
1538
1539 cx.subscribe_in(
1540 &project.read(cx).breakpoint_store(),
1541 window,
1542 |workspace, _, event, window, cx| match event {
1543 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1544 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1545 workspace.serialize_workspace(window, cx);
1546 }
1547 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1548 },
1549 )
1550 .detach();
1551 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1552 cx.subscribe_in(
1553 &toolchain_store,
1554 window,
1555 |workspace, _, event, window, cx| match event {
1556 ToolchainStoreEvent::CustomToolchainsModified => {
1557 workspace.serialize_workspace(window, cx);
1558 }
1559 _ => {}
1560 },
1561 )
1562 .detach();
1563 }
1564
1565 cx.on_focus_lost(window, |this, window, cx| {
1566 let focus_handle = this.focus_handle(cx);
1567 window.focus(&focus_handle, cx);
1568 })
1569 .detach();
1570
1571 let weak_handle = cx.entity().downgrade();
1572 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1573
1574 let center_pane = cx.new(|cx| {
1575 let mut center_pane = Pane::new(
1576 weak_handle.clone(),
1577 project.clone(),
1578 pane_history_timestamp.clone(),
1579 None,
1580 NewFile.boxed_clone(),
1581 true,
1582 window,
1583 cx,
1584 );
1585 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1586 center_pane.set_should_display_welcome_page(true);
1587 center_pane
1588 });
1589 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1590 .detach();
1591
1592 window.focus(¢er_pane.focus_handle(cx), cx);
1593
1594 cx.emit(Event::PaneAdded(center_pane.clone()));
1595
1596 let any_window_handle = window.window_handle();
1597 app_state.workspace_store.update(cx, |store, _| {
1598 store
1599 .workspaces
1600 .insert((any_window_handle, weak_handle.clone()));
1601 });
1602
1603 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1604 let mut connection_status = app_state.client.status();
1605 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1606 current_user.next().await;
1607 connection_status.next().await;
1608 let mut stream =
1609 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1610
1611 while stream.recv().await.is_some() {
1612 this.update(cx, |_, cx| cx.notify())?;
1613 }
1614 anyhow::Ok(())
1615 });
1616
1617 // All leader updates are enqueued and then processed in a single task, so
1618 // that each asynchronous operation can be run in order.
1619 let (leader_updates_tx, mut leader_updates_rx) =
1620 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1621 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1622 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1623 Self::process_leader_update(&this, leader_id, update, cx)
1624 .await
1625 .log_err();
1626 }
1627
1628 Ok(())
1629 });
1630
1631 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1632 let modal_layer = cx.new(|_| ModalLayer::new());
1633 let toast_layer = cx.new(|_| ToastLayer::new());
1634 cx.subscribe(
1635 &modal_layer,
1636 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1637 cx.emit(Event::ModalOpened);
1638 },
1639 )
1640 .detach();
1641
1642 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1643 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1644 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1645 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1646 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1647 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1648 let multi_workspace = window
1649 .root::<MultiWorkspace>()
1650 .flatten()
1651 .map(|mw| mw.downgrade());
1652 let status_bar = cx.new(|cx| {
1653 let mut status_bar =
1654 StatusBar::new(¢er_pane.clone(), multi_workspace.clone(), window, cx);
1655 status_bar.add_left_item(left_dock_buttons, window, cx);
1656 status_bar.add_right_item(right_dock_buttons, window, cx);
1657 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1658 status_bar
1659 });
1660
1661 let session_id = app_state.session.read(cx).id().to_owned();
1662
1663 let mut active_call = None;
1664 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1665 let subscriptions =
1666 vec![
1667 call.0
1668 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1669 ];
1670 active_call = Some((call, subscriptions));
1671 }
1672
1673 let (serializable_items_tx, serializable_items_rx) =
1674 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1675 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1676 Self::serialize_items(&this, serializable_items_rx, cx).await
1677 });
1678
1679 let subscriptions = vec![
1680 cx.observe_window_activation(window, Self::on_window_activation_changed),
1681 cx.observe_window_bounds(window, move |this, window, cx| {
1682 if this.bounds_save_task_queued.is_some() {
1683 return;
1684 }
1685 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1686 cx.background_executor()
1687 .timer(Duration::from_millis(100))
1688 .await;
1689 this.update_in(cx, |this, window, cx| {
1690 this.save_window_bounds(window, cx).detach();
1691 this.bounds_save_task_queued.take();
1692 })
1693 .ok();
1694 }));
1695 cx.notify();
1696 }),
1697 cx.observe_window_appearance(window, |_, window, cx| {
1698 let window_appearance = window.appearance();
1699
1700 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1701
1702 theme_settings::reload_theme(cx);
1703 theme_settings::reload_icon_theme(cx);
1704 }),
1705 cx.on_release({
1706 let weak_handle = weak_handle.clone();
1707 move |this, cx| {
1708 this.app_state.workspace_store.update(cx, move |store, _| {
1709 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1710 })
1711 }
1712 }),
1713 ];
1714
1715 cx.defer_in(window, move |this, window, cx| {
1716 this.update_window_title(window, cx);
1717 this.show_initial_notifications(cx);
1718 });
1719
1720 let mut center = PaneGroup::new(center_pane.clone());
1721 center.set_is_center(true);
1722 center.mark_positions(cx);
1723
1724 Workspace {
1725 weak_self: weak_handle.clone(),
1726 zoomed: None,
1727 zoomed_position: None,
1728 previous_dock_drag_coordinates: None,
1729 center,
1730 panes: vec![center_pane.clone()],
1731 panes_by_item: Default::default(),
1732 active_pane: center_pane.clone(),
1733 last_active_center_pane: Some(center_pane.downgrade()),
1734 last_active_view_id: None,
1735 status_bar,
1736 modal_layer,
1737 toast_layer,
1738 titlebar_item: None,
1739 active_worktree_override: None,
1740 notifications: Notifications::default(),
1741 suppressed_notifications: HashSet::default(),
1742 left_dock,
1743 bottom_dock,
1744 right_dock,
1745 _panels_task: None,
1746 project: project.clone(),
1747 follower_states: Default::default(),
1748 last_leaders_by_pane: Default::default(),
1749 dispatching_keystrokes: Default::default(),
1750 window_edited: false,
1751 last_window_title: None,
1752 dirty_items: Default::default(),
1753 active_call,
1754 database_id: workspace_id,
1755 app_state,
1756 _observe_current_user,
1757 _apply_leader_updates,
1758 _schedule_serialize_workspace: None,
1759 _serialize_workspace_task: None,
1760 _schedule_serialize_ssh_paths: None,
1761 leader_updates_tx,
1762 _subscriptions: subscriptions,
1763 pane_history_timestamp,
1764 workspace_actions: Default::default(),
1765 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1766 bounds: Default::default(),
1767 centered_layout: false,
1768 bounds_save_task_queued: None,
1769 on_prompt_for_new_path: None,
1770 on_prompt_for_open_path: None,
1771 terminal_provider: None,
1772 debugger_provider: None,
1773 serializable_items_tx,
1774 _items_serializer,
1775 session_id: Some(session_id),
1776
1777 scheduled_tasks: Vec::new(),
1778 last_open_dock_positions: Vec::new(),
1779 removing: false,
1780 sidebar_focus_handle: None,
1781 multi_workspace,
1782 open_in_dev_container: false,
1783 _dev_container_task: None,
1784 }
1785 }
1786
1787 pub fn new_local(
1788 abs_paths: Vec<PathBuf>,
1789 app_state: Arc<AppState>,
1790 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1791 env: Option<HashMap<String, String>>,
1792 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1793 open_mode: OpenMode,
1794 cx: &mut App,
1795 ) -> Task<anyhow::Result<OpenResult>> {
1796 let project_handle = Project::local(
1797 app_state.client.clone(),
1798 app_state.node_runtime.clone(),
1799 app_state.user_store.clone(),
1800 app_state.languages.clone(),
1801 app_state.fs.clone(),
1802 env,
1803 Default::default(),
1804 cx,
1805 );
1806
1807 let db = WorkspaceDb::global(cx);
1808 let kvp = db::kvp::KeyValueStore::global(cx);
1809 cx.spawn(async move |cx| {
1810 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1811 for path in abs_paths.into_iter() {
1812 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1813 paths_to_open.push(canonical)
1814 } else {
1815 paths_to_open.push(path)
1816 }
1817 }
1818
1819 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1820
1821 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1822 paths_to_open = paths.ordered_paths().cloned().collect();
1823 if !paths.is_lexicographically_ordered() {
1824 project_handle.update(cx, |project, cx| {
1825 project.set_worktrees_reordered(true, cx);
1826 });
1827 }
1828 }
1829
1830 // Get project paths for all of the abs_paths
1831 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1832 Vec::with_capacity(paths_to_open.len());
1833
1834 for path in paths_to_open.into_iter() {
1835 if let Some((_, project_entry)) = cx
1836 .update(|cx| {
1837 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1838 })
1839 .await
1840 .log_err()
1841 {
1842 project_paths.push((path, Some(project_entry)));
1843 } else {
1844 project_paths.push((path, None));
1845 }
1846 }
1847
1848 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1849 serialized_workspace.id
1850 } else {
1851 db.next_id().await.unwrap_or_else(|_| Default::default())
1852 };
1853
1854 let toolchains = db.toolchains(workspace_id).await?;
1855
1856 for (toolchain, worktree_path, path) in toolchains {
1857 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1858 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1859 this.find_worktree(&worktree_path, cx)
1860 .and_then(|(worktree, rel_path)| {
1861 if rel_path.is_empty() {
1862 Some(worktree.read(cx).id())
1863 } else {
1864 None
1865 }
1866 })
1867 }) else {
1868 // We did not find a worktree with a given path, but that's whatever.
1869 continue;
1870 };
1871 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1872 continue;
1873 }
1874
1875 project_handle
1876 .update(cx, |this, cx| {
1877 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1878 })
1879 .await;
1880 }
1881 if let Some(workspace) = serialized_workspace.as_ref() {
1882 project_handle.update(cx, |this, cx| {
1883 for (scope, toolchains) in &workspace.user_toolchains {
1884 for toolchain in toolchains {
1885 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1886 }
1887 }
1888 });
1889 }
1890
1891 let window_to_replace = match open_mode {
1892 OpenMode::NewWindow => None,
1893 _ => requesting_window,
1894 };
1895
1896 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1897 if let Some(window) = window_to_replace {
1898 let centered_layout = serialized_workspace
1899 .as_ref()
1900 .map(|w| w.centered_layout)
1901 .unwrap_or(false);
1902
1903 let workspace = window.update(cx, |multi_workspace, window, cx| {
1904 let workspace = cx.new(|cx| {
1905 let mut workspace = Workspace::new(
1906 Some(workspace_id),
1907 project_handle.clone(),
1908 app_state.clone(),
1909 window,
1910 cx,
1911 );
1912
1913 workspace.centered_layout = centered_layout;
1914
1915 // Call init callback to add items before window renders
1916 if let Some(init) = init {
1917 init(&mut workspace, window, cx);
1918 }
1919
1920 workspace
1921 });
1922 match open_mode {
1923 OpenMode::Activate => {
1924 multi_workspace.activate(workspace.clone(), window, cx);
1925 }
1926 OpenMode::Add => {
1927 multi_workspace.add(workspace.clone(), &*window, cx);
1928 }
1929 OpenMode::NewWindow => {
1930 unreachable!()
1931 }
1932 }
1933 workspace
1934 })?;
1935 (window, workspace)
1936 } else {
1937 let window_bounds_override = window_bounds_env_override();
1938
1939 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1940 (Some(WindowBounds::Windowed(bounds)), None)
1941 } else if let Some(workspace) = serialized_workspace.as_ref()
1942 && let Some(display) = workspace.display
1943 && let Some(bounds) = workspace.window_bounds.as_ref()
1944 {
1945 // Reopening an existing workspace - restore its saved bounds
1946 (Some(bounds.0), Some(display))
1947 } else if let Some((display, bounds)) =
1948 persistence::read_default_window_bounds(&kvp)
1949 {
1950 // New or empty workspace - use the last known window bounds
1951 (Some(bounds), Some(display))
1952 } else {
1953 // New window - let GPUI's default_bounds() handle cascading
1954 (None, None)
1955 };
1956
1957 // Use the serialized workspace to construct the new window
1958 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1959 options.window_bounds = window_bounds;
1960 let centered_layout = serialized_workspace
1961 .as_ref()
1962 .map(|w| w.centered_layout)
1963 .unwrap_or(false);
1964 let window = cx.open_window(options, {
1965 let app_state = app_state.clone();
1966 let project_handle = project_handle.clone();
1967 move |window, cx| {
1968 let workspace = cx.new(|cx| {
1969 let mut workspace = Workspace::new(
1970 Some(workspace_id),
1971 project_handle,
1972 app_state,
1973 window,
1974 cx,
1975 );
1976 workspace.centered_layout = centered_layout;
1977
1978 // Call init callback to add items before window renders
1979 if let Some(init) = init {
1980 init(&mut workspace, window, cx);
1981 }
1982
1983 workspace
1984 });
1985 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1986 }
1987 })?;
1988 let workspace =
1989 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1990 multi_workspace.workspace().clone()
1991 })?;
1992 (window, workspace)
1993 };
1994
1995 notify_if_database_failed(window, cx);
1996 // Check if this is an empty workspace (no paths to open)
1997 // An empty workspace is one where project_paths is empty
1998 let is_empty_workspace = project_paths.is_empty();
1999 // Check if serialized workspace has paths before it's moved
2000 let serialized_workspace_has_paths = serialized_workspace
2001 .as_ref()
2002 .map(|ws| !ws.paths.is_empty())
2003 .unwrap_or(false);
2004
2005 let opened_items = window
2006 .update(cx, |_, window, cx| {
2007 workspace.update(cx, |_workspace: &mut Workspace, cx| {
2008 open_items(serialized_workspace, project_paths, window, cx)
2009 })
2010 })?
2011 .await
2012 .unwrap_or_default();
2013
2014 // Restore default dock state for empty workspaces
2015 // Only restore if:
2016 // 1. This is an empty workspace (no paths), AND
2017 // 2. The serialized workspace either doesn't exist or has no paths
2018 if is_empty_workspace && !serialized_workspace_has_paths {
2019 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
2020 window
2021 .update(cx, |_, window, cx| {
2022 workspace.update(cx, |workspace, cx| {
2023 for (dock, serialized_dock) in [
2024 (&workspace.right_dock, &default_docks.right),
2025 (&workspace.left_dock, &default_docks.left),
2026 (&workspace.bottom_dock, &default_docks.bottom),
2027 ] {
2028 dock.update(cx, |dock, cx| {
2029 dock.serialized_dock = Some(serialized_dock.clone());
2030 dock.restore_state(window, cx);
2031 });
2032 }
2033 cx.notify();
2034 });
2035 })
2036 .log_err();
2037 }
2038 }
2039
2040 window
2041 .update(cx, |_, _window, cx| {
2042 workspace.update(cx, |this: &mut Workspace, cx| {
2043 this.update_history(cx);
2044 });
2045 })
2046 .log_err();
2047 Ok(OpenResult {
2048 window,
2049 workspace,
2050 opened_items,
2051 })
2052 })
2053 }
2054
2055 pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
2056 self.project.read(cx).project_group_key(cx)
2057 }
2058
2059 pub fn weak_handle(&self) -> WeakEntity<Self> {
2060 self.weak_self.clone()
2061 }
2062
2063 pub fn left_dock(&self) -> &Entity<Dock> {
2064 &self.left_dock
2065 }
2066
2067 pub fn bottom_dock(&self) -> &Entity<Dock> {
2068 &self.bottom_dock
2069 }
2070
2071 pub fn set_bottom_dock_layout(
2072 &mut self,
2073 layout: BottomDockLayout,
2074 window: &mut Window,
2075 cx: &mut Context<Self>,
2076 ) {
2077 let fs = self.project().read(cx).fs();
2078 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2079 content.workspace.bottom_dock_layout = Some(layout);
2080 });
2081
2082 cx.notify();
2083 self.serialize_workspace(window, cx);
2084 }
2085
2086 pub fn right_dock(&self) -> &Entity<Dock> {
2087 &self.right_dock
2088 }
2089
2090 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2091 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2092 }
2093
2094 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2095 let left_dock = self.left_dock.read(cx);
2096 let left_visible = left_dock.is_open();
2097 let left_active_panel = left_dock
2098 .active_panel()
2099 .map(|panel| panel.persistent_name().to_string());
2100 // `zoomed_position` is kept in sync with individual panel zoom state
2101 // by the dock code in `Dock::new` and `Dock::add_panel`.
2102 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2103
2104 let right_dock = self.right_dock.read(cx);
2105 let right_visible = right_dock.is_open();
2106 let right_active_panel = right_dock
2107 .active_panel()
2108 .map(|panel| panel.persistent_name().to_string());
2109 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2110
2111 let bottom_dock = self.bottom_dock.read(cx);
2112 let bottom_visible = bottom_dock.is_open();
2113 let bottom_active_panel = bottom_dock
2114 .active_panel()
2115 .map(|panel| panel.persistent_name().to_string());
2116 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2117
2118 DockStructure {
2119 left: DockData {
2120 visible: left_visible,
2121 active_panel: left_active_panel,
2122 zoom: left_dock_zoom,
2123 },
2124 right: DockData {
2125 visible: right_visible,
2126 active_panel: right_active_panel,
2127 zoom: right_dock_zoom,
2128 },
2129 bottom: DockData {
2130 visible: bottom_visible,
2131 active_panel: bottom_active_panel,
2132 zoom: bottom_dock_zoom,
2133 },
2134 }
2135 }
2136
2137 pub fn set_dock_structure(
2138 &self,
2139 docks: DockStructure,
2140 window: &mut Window,
2141 cx: &mut Context<Self>,
2142 ) {
2143 for (dock, data) in [
2144 (&self.left_dock, docks.left),
2145 (&self.bottom_dock, docks.bottom),
2146 (&self.right_dock, docks.right),
2147 ] {
2148 dock.update(cx, |dock, cx| {
2149 dock.serialized_dock = Some(data);
2150 dock.restore_state(window, cx);
2151 });
2152 }
2153 }
2154
2155 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2156 self.items(cx)
2157 .filter_map(|item| {
2158 let project_path = item.project_path(cx)?;
2159 self.project.read(cx).absolute_path(&project_path, cx)
2160 })
2161 .collect()
2162 }
2163
2164 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2165 match position {
2166 DockPosition::Left => &self.left_dock,
2167 DockPosition::Bottom => &self.bottom_dock,
2168 DockPosition::Right => &self.right_dock,
2169 }
2170 }
2171
2172 pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
2173 self.all_docks().into_iter().find_map(|dock| {
2174 let dock = dock.read(cx);
2175 dock.has_agent_panel(cx).then_some(dock.position())
2176 })
2177 }
2178
2179 pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
2180 self.all_docks().into_iter().find_map(|dock| {
2181 let dock = dock.read(cx);
2182 let panel = dock.panel::<T>()?;
2183 dock.stored_panel_size_state(&panel)
2184 })
2185 }
2186
2187 pub fn persisted_panel_size_state(
2188 &self,
2189 panel_key: &'static str,
2190 cx: &App,
2191 ) -> Option<dock::PanelSizeState> {
2192 dock::Dock::load_persisted_size_state(self, panel_key, cx)
2193 }
2194
2195 pub fn persist_panel_size_state(
2196 &self,
2197 panel_key: &str,
2198 size_state: dock::PanelSizeState,
2199 cx: &mut App,
2200 ) {
2201 let Some(workspace_id) = self
2202 .database_id()
2203 .map(|id| i64::from(id).to_string())
2204 .or(self.session_id())
2205 else {
2206 return;
2207 };
2208
2209 let kvp = db::kvp::KeyValueStore::global(cx);
2210 let panel_key = panel_key.to_string();
2211 cx.background_spawn(async move {
2212 let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
2213 scope
2214 .write(
2215 format!("{workspace_id}:{panel_key}"),
2216 serde_json::to_string(&size_state)?,
2217 )
2218 .await
2219 })
2220 .detach_and_log_err(cx);
2221 }
2222
2223 pub fn set_panel_size_state<T: Panel>(
2224 &mut self,
2225 size_state: dock::PanelSizeState,
2226 window: &mut Window,
2227 cx: &mut Context<Self>,
2228 ) -> bool {
2229 let Some(panel) = self.panel::<T>(cx) else {
2230 return false;
2231 };
2232
2233 let dock = self.dock_at_position(panel.position(window, cx));
2234 let did_set = dock.update(cx, |dock, cx| {
2235 dock.set_panel_size_state(&panel, size_state, cx)
2236 });
2237
2238 if did_set {
2239 self.persist_panel_size_state(T::panel_key(), size_state, cx);
2240 }
2241
2242 did_set
2243 }
2244
2245 pub fn toggle_dock_panel_flexible_size(
2246 &self,
2247 dock: &Entity<Dock>,
2248 panel: &dyn PanelHandle,
2249 window: &mut Window,
2250 cx: &mut App,
2251 ) {
2252 let position = dock.read(cx).position();
2253 let current_size = self.dock_size(&dock.read(cx), window, cx);
2254 let current_flex =
2255 current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
2256 dock.update(cx, |dock, cx| {
2257 dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
2258 });
2259 }
2260
2261 fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
2262 let panel = dock.active_panel()?;
2263 let size_state = dock
2264 .stored_panel_size_state(panel.as_ref())
2265 .unwrap_or_default();
2266 let position = dock.position();
2267
2268 let use_flex = panel.has_flexible_size(window, cx);
2269
2270 if position.axis() == Axis::Horizontal
2271 && use_flex
2272 && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
2273 {
2274 let workspace_width = self.bounds.size.width;
2275 if workspace_width <= Pixels::ZERO {
2276 return None;
2277 }
2278 let flex = flex.max(0.001);
2279 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2280 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2281 // Both docks are flex items sharing the full workspace width.
2282 let total_flex = flex + 1.0 + opposite_flex;
2283 return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
2284 } else {
2285 // Opposite dock is fixed-width; flex items share (W - fixed).
2286 let opposite_fixed = opposite
2287 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2288 .unwrap_or_default();
2289 let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
2290 return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
2291 }
2292 }
2293
2294 Some(
2295 size_state
2296 .size
2297 .unwrap_or_else(|| panel.default_size(window, cx)),
2298 )
2299 }
2300
2301 pub fn dock_flex_for_size(
2302 &self,
2303 position: DockPosition,
2304 size: Pixels,
2305 window: &Window,
2306 cx: &App,
2307 ) -> Option<f32> {
2308 if position.axis() != Axis::Horizontal {
2309 return None;
2310 }
2311
2312 let workspace_width = self.bounds.size.width;
2313 if workspace_width <= Pixels::ZERO {
2314 return None;
2315 }
2316
2317 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2318 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2319 let size = size.clamp(px(0.), workspace_width - px(1.));
2320 Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
2321 } else {
2322 let opposite_width = opposite
2323 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2324 .unwrap_or_default();
2325 let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
2326 let remaining = (available - size).max(px(1.));
2327 Some((size / remaining).max(0.0))
2328 }
2329 }
2330
2331 fn opposite_dock_panel_and_size_state(
2332 &self,
2333 position: DockPosition,
2334 window: &Window,
2335 cx: &App,
2336 ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
2337 let opposite_position = match position {
2338 DockPosition::Left => DockPosition::Right,
2339 DockPosition::Right => DockPosition::Left,
2340 DockPosition::Bottom => return None,
2341 };
2342
2343 let opposite_dock = self.dock_at_position(opposite_position).read(cx);
2344 let panel = opposite_dock.visible_panel()?;
2345 let mut size_state = opposite_dock
2346 .stored_panel_size_state(panel.as_ref())
2347 .unwrap_or_default();
2348 if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
2349 size_state.flex = self.default_dock_flex(opposite_position);
2350 }
2351 Some((panel.clone(), size_state))
2352 }
2353
2354 pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
2355 if position.axis() != Axis::Horizontal {
2356 return None;
2357 }
2358
2359 let pane = self.last_active_center_pane.clone()?.upgrade()?;
2360 Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
2361 }
2362
2363 pub fn is_edited(&self) -> bool {
2364 self.window_edited
2365 }
2366
2367 pub fn add_panel<T: Panel>(
2368 &mut self,
2369 panel: Entity<T>,
2370 window: &mut Window,
2371 cx: &mut Context<Self>,
2372 ) {
2373 let focus_handle = panel.panel_focus_handle(cx);
2374 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2375 .detach();
2376
2377 let dock_position = panel.position(window, cx);
2378 let dock = self.dock_at_position(dock_position);
2379 let any_panel = panel.to_any();
2380 let persisted_size_state =
2381 self.persisted_panel_size_state(T::panel_key(), cx)
2382 .or_else(|| {
2383 load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
2384 let state = dock::PanelSizeState {
2385 size: Some(size),
2386 flex: None,
2387 };
2388 self.persist_panel_size_state(T::panel_key(), state, cx);
2389 state
2390 })
2391 });
2392
2393 dock.update(cx, |dock, cx| {
2394 let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
2395 if let Some(size_state) = persisted_size_state {
2396 dock.set_panel_size_state(&panel, size_state, cx);
2397 }
2398 index
2399 });
2400
2401 cx.emit(Event::PanelAdded(any_panel));
2402 }
2403
2404 pub fn remove_panel<T: Panel>(
2405 &mut self,
2406 panel: &Entity<T>,
2407 window: &mut Window,
2408 cx: &mut Context<Self>,
2409 ) {
2410 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2411 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2412 }
2413 }
2414
2415 pub fn status_bar(&self) -> &Entity<StatusBar> {
2416 &self.status_bar
2417 }
2418
2419 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2420 self.sidebar_focus_handle = handle;
2421 }
2422
2423 pub fn status_bar_visible(&self, cx: &App) -> bool {
2424 StatusBarSettings::get_global(cx).show
2425 }
2426
2427 pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
2428 self.multi_workspace.as_ref()
2429 }
2430
2431 pub fn set_multi_workspace(
2432 &mut self,
2433 multi_workspace: WeakEntity<MultiWorkspace>,
2434 cx: &mut App,
2435 ) {
2436 self.status_bar.update(cx, |status_bar, cx| {
2437 status_bar.set_multi_workspace(multi_workspace.clone(), cx);
2438 });
2439 self.multi_workspace = Some(multi_workspace);
2440 }
2441
2442 pub fn app_state(&self) -> &Arc<AppState> {
2443 &self.app_state
2444 }
2445
2446 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2447 self._panels_task = Some(task);
2448 }
2449
2450 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2451 self._panels_task.take()
2452 }
2453
2454 pub fn user_store(&self) -> &Entity<UserStore> {
2455 &self.app_state.user_store
2456 }
2457
2458 pub fn project(&self) -> &Entity<Project> {
2459 &self.project
2460 }
2461
2462 pub fn path_style(&self, cx: &App) -> PathStyle {
2463 self.project.read(cx).path_style(cx)
2464 }
2465
2466 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2467 let mut history: HashMap<EntityId, usize> = HashMap::default();
2468
2469 for pane_handle in &self.panes {
2470 let pane = pane_handle.read(cx);
2471
2472 for entry in pane.activation_history() {
2473 history.insert(
2474 entry.entity_id,
2475 history
2476 .get(&entry.entity_id)
2477 .cloned()
2478 .unwrap_or(0)
2479 .max(entry.timestamp),
2480 );
2481 }
2482 }
2483
2484 history
2485 }
2486
2487 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2488 let mut recent_item: Option<Entity<T>> = None;
2489 let mut recent_timestamp = 0;
2490 for pane_handle in &self.panes {
2491 let pane = pane_handle.read(cx);
2492 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2493 pane.items().map(|item| (item.item_id(), item)).collect();
2494 for entry in pane.activation_history() {
2495 if entry.timestamp > recent_timestamp
2496 && let Some(&item) = item_map.get(&entry.entity_id)
2497 && let Some(typed_item) = item.act_as::<T>(cx)
2498 {
2499 recent_timestamp = entry.timestamp;
2500 recent_item = Some(typed_item);
2501 }
2502 }
2503 }
2504 recent_item
2505 }
2506
2507 pub fn recent_navigation_history_iter(
2508 &self,
2509 cx: &App,
2510 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2511 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2512 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2513
2514 for pane in &self.panes {
2515 let pane = pane.read(cx);
2516
2517 pane.nav_history()
2518 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2519 if let Some(fs_path) = &fs_path {
2520 abs_paths_opened
2521 .entry(fs_path.clone())
2522 .or_default()
2523 .insert(project_path.clone());
2524 }
2525 let timestamp = entry.timestamp;
2526 match history.entry(project_path) {
2527 hash_map::Entry::Occupied(mut entry) => {
2528 let (_, old_timestamp) = entry.get();
2529 if ×tamp > old_timestamp {
2530 entry.insert((fs_path, timestamp));
2531 }
2532 }
2533 hash_map::Entry::Vacant(entry) => {
2534 entry.insert((fs_path, timestamp));
2535 }
2536 }
2537 });
2538
2539 if let Some(item) = pane.active_item()
2540 && let Some(project_path) = item.project_path(cx)
2541 {
2542 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2543
2544 if let Some(fs_path) = &fs_path {
2545 abs_paths_opened
2546 .entry(fs_path.clone())
2547 .or_default()
2548 .insert(project_path.clone());
2549 }
2550
2551 history.insert(project_path, (fs_path, std::usize::MAX));
2552 }
2553 }
2554
2555 history
2556 .into_iter()
2557 .sorted_by_key(|(_, (_, order))| *order)
2558 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2559 .rev()
2560 .filter(move |(history_path, abs_path)| {
2561 let latest_project_path_opened = abs_path
2562 .as_ref()
2563 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2564 .and_then(|project_paths| {
2565 project_paths
2566 .iter()
2567 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2568 });
2569
2570 latest_project_path_opened.is_none_or(|path| path == history_path)
2571 })
2572 }
2573
2574 pub fn recent_navigation_history(
2575 &self,
2576 limit: Option<usize>,
2577 cx: &App,
2578 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2579 self.recent_navigation_history_iter(cx)
2580 .take(limit.unwrap_or(usize::MAX))
2581 .collect()
2582 }
2583
2584 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2585 for pane in &self.panes {
2586 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2587 }
2588 }
2589
2590 fn navigate_history(
2591 &mut self,
2592 pane: WeakEntity<Pane>,
2593 mode: NavigationMode,
2594 window: &mut Window,
2595 cx: &mut Context<Workspace>,
2596 ) -> Task<Result<()>> {
2597 self.navigate_history_impl(
2598 pane,
2599 mode,
2600 window,
2601 &mut |history, cx| history.pop(mode, cx),
2602 cx,
2603 )
2604 }
2605
2606 fn navigate_tag_history(
2607 &mut self,
2608 pane: WeakEntity<Pane>,
2609 mode: TagNavigationMode,
2610 window: &mut Window,
2611 cx: &mut Context<Workspace>,
2612 ) -> Task<Result<()>> {
2613 self.navigate_history_impl(
2614 pane,
2615 NavigationMode::Normal,
2616 window,
2617 &mut |history, _cx| history.pop_tag(mode),
2618 cx,
2619 )
2620 }
2621
2622 fn navigate_history_impl(
2623 &mut self,
2624 pane: WeakEntity<Pane>,
2625 mode: NavigationMode,
2626 window: &mut Window,
2627 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2628 cx: &mut Context<Workspace>,
2629 ) -> Task<Result<()>> {
2630 let to_load = if let Some(pane) = pane.upgrade() {
2631 pane.update(cx, |pane, cx| {
2632 window.focus(&pane.focus_handle(cx), cx);
2633 loop {
2634 // Retrieve the weak item handle from the history.
2635 let entry = cb(pane.nav_history_mut(), cx)?;
2636
2637 // If the item is still present in this pane, then activate it.
2638 if let Some(index) = entry
2639 .item
2640 .upgrade()
2641 .and_then(|v| pane.index_for_item(v.as_ref()))
2642 {
2643 let prev_active_item_index = pane.active_item_index();
2644 pane.nav_history_mut().set_mode(mode);
2645 pane.activate_item(index, true, true, window, cx);
2646 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2647
2648 let mut navigated = prev_active_item_index != pane.active_item_index();
2649 if let Some(data) = entry.data {
2650 navigated |= pane.active_item()?.navigate(data, window, cx);
2651 }
2652
2653 if navigated {
2654 break None;
2655 }
2656 } else {
2657 // If the item is no longer present in this pane, then retrieve its
2658 // path info in order to reopen it.
2659 break pane
2660 .nav_history()
2661 .path_for_item(entry.item.id())
2662 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2663 }
2664 }
2665 })
2666 } else {
2667 None
2668 };
2669
2670 if let Some((project_path, abs_path, entry)) = to_load {
2671 // If the item was no longer present, then load it again from its previous path, first try the local path
2672 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2673
2674 cx.spawn_in(window, async move |workspace, cx| {
2675 let open_by_project_path = open_by_project_path.await;
2676 let mut navigated = false;
2677 match open_by_project_path
2678 .with_context(|| format!("Navigating to {project_path:?}"))
2679 {
2680 Ok((project_entry_id, build_item)) => {
2681 let prev_active_item_id = pane.update(cx, |pane, _| {
2682 pane.nav_history_mut().set_mode(mode);
2683 pane.active_item().map(|p| p.item_id())
2684 })?;
2685
2686 pane.update_in(cx, |pane, window, cx| {
2687 let item = pane.open_item(
2688 project_entry_id,
2689 project_path,
2690 true,
2691 entry.is_preview,
2692 true,
2693 None,
2694 window, cx,
2695 build_item,
2696 );
2697 navigated |= Some(item.item_id()) != prev_active_item_id;
2698 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2699 if let Some(data) = entry.data {
2700 navigated |= item.navigate(data, window, cx);
2701 }
2702 })?;
2703 }
2704 Err(open_by_project_path_e) => {
2705 // Fall back to opening by abs path, in case an external file was opened and closed,
2706 // and its worktree is now dropped
2707 if let Some(abs_path) = abs_path {
2708 let prev_active_item_id = pane.update(cx, |pane, _| {
2709 pane.nav_history_mut().set_mode(mode);
2710 pane.active_item().map(|p| p.item_id())
2711 })?;
2712 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2713 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2714 })?;
2715 match open_by_abs_path
2716 .await
2717 .with_context(|| format!("Navigating to {abs_path:?}"))
2718 {
2719 Ok(item) => {
2720 pane.update_in(cx, |pane, window, cx| {
2721 navigated |= Some(item.item_id()) != prev_active_item_id;
2722 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2723 if let Some(data) = entry.data {
2724 navigated |= item.navigate(data, window, cx);
2725 }
2726 })?;
2727 }
2728 Err(open_by_abs_path_e) => {
2729 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2730 }
2731 }
2732 }
2733 }
2734 }
2735
2736 if !navigated {
2737 workspace
2738 .update_in(cx, |workspace, window, cx| {
2739 Self::navigate_history(workspace, pane, mode, window, cx)
2740 })?
2741 .await?;
2742 }
2743
2744 Ok(())
2745 })
2746 } else {
2747 Task::ready(Ok(()))
2748 }
2749 }
2750
2751 pub fn go_back(
2752 &mut self,
2753 pane: WeakEntity<Pane>,
2754 window: &mut Window,
2755 cx: &mut Context<Workspace>,
2756 ) -> Task<Result<()>> {
2757 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2758 }
2759
2760 pub fn go_forward(
2761 &mut self,
2762 pane: WeakEntity<Pane>,
2763 window: &mut Window,
2764 cx: &mut Context<Workspace>,
2765 ) -> Task<Result<()>> {
2766 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2767 }
2768
2769 pub fn reopen_closed_item(
2770 &mut self,
2771 window: &mut Window,
2772 cx: &mut Context<Workspace>,
2773 ) -> Task<Result<()>> {
2774 self.navigate_history(
2775 self.active_pane().downgrade(),
2776 NavigationMode::ReopeningClosedItem,
2777 window,
2778 cx,
2779 )
2780 }
2781
2782 pub fn client(&self) -> &Arc<Client> {
2783 &self.app_state.client
2784 }
2785
2786 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2787 self.titlebar_item = Some(item);
2788 cx.notify();
2789 }
2790
2791 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2792 self.on_prompt_for_new_path = Some(prompt)
2793 }
2794
2795 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2796 self.on_prompt_for_open_path = Some(prompt)
2797 }
2798
2799 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2800 self.terminal_provider = Some(Box::new(provider));
2801 }
2802
2803 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2804 self.debugger_provider = Some(Arc::new(provider));
2805 }
2806
2807 pub fn set_open_in_dev_container(&mut self, value: bool) {
2808 self.open_in_dev_container = value;
2809 }
2810
2811 pub fn open_in_dev_container(&self) -> bool {
2812 self.open_in_dev_container
2813 }
2814
2815 pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
2816 self._dev_container_task = Some(task);
2817 }
2818
2819 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2820 self.debugger_provider.clone()
2821 }
2822
2823 pub fn prompt_for_open_path(
2824 &mut self,
2825 path_prompt_options: PathPromptOptions,
2826 lister: DirectoryLister,
2827 window: &mut Window,
2828 cx: &mut Context<Self>,
2829 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2830 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2831 let prompt = self.on_prompt_for_open_path.take().unwrap();
2832 let rx = prompt(self, lister, window, cx);
2833 self.on_prompt_for_open_path = Some(prompt);
2834 rx
2835 } else {
2836 let (tx, rx) = oneshot::channel();
2837 let abs_path = cx.prompt_for_paths(path_prompt_options);
2838
2839 cx.spawn_in(window, async move |workspace, cx| {
2840 let Ok(result) = abs_path.await else {
2841 return Ok(());
2842 };
2843
2844 match result {
2845 Ok(result) => {
2846 tx.send(result).ok();
2847 }
2848 Err(err) => {
2849 let rx = workspace.update_in(cx, |workspace, window, cx| {
2850 workspace.show_portal_error(err.to_string(), cx);
2851 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2852 let rx = prompt(workspace, lister, window, cx);
2853 workspace.on_prompt_for_open_path = Some(prompt);
2854 rx
2855 })?;
2856 if let Ok(path) = rx.await {
2857 tx.send(path).ok();
2858 }
2859 }
2860 };
2861 anyhow::Ok(())
2862 })
2863 .detach();
2864
2865 rx
2866 }
2867 }
2868
2869 pub fn prompt_for_new_path(
2870 &mut self,
2871 lister: DirectoryLister,
2872 suggested_name: Option<String>,
2873 window: &mut Window,
2874 cx: &mut Context<Self>,
2875 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2876 if self.project.read(cx).is_via_collab()
2877 || self.project.read(cx).is_via_remote_server()
2878 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2879 {
2880 let prompt = self.on_prompt_for_new_path.take().unwrap();
2881 let rx = prompt(self, lister, suggested_name, window, cx);
2882 self.on_prompt_for_new_path = Some(prompt);
2883 return rx;
2884 }
2885
2886 let (tx, rx) = oneshot::channel();
2887 cx.spawn_in(window, async move |workspace, cx| {
2888 let abs_path = workspace.update(cx, |workspace, cx| {
2889 let relative_to = workspace
2890 .most_recent_active_path(cx)
2891 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2892 .or_else(|| {
2893 let project = workspace.project.read(cx);
2894 project.visible_worktrees(cx).find_map(|worktree| {
2895 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2896 })
2897 })
2898 .or_else(std::env::home_dir)
2899 .unwrap_or_else(|| PathBuf::from(""));
2900 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2901 })?;
2902 let abs_path = match abs_path.await? {
2903 Ok(path) => path,
2904 Err(err) => {
2905 let rx = workspace.update_in(cx, |workspace, window, cx| {
2906 workspace.show_portal_error(err.to_string(), cx);
2907
2908 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2909 let rx = prompt(workspace, lister, suggested_name, window, cx);
2910 workspace.on_prompt_for_new_path = Some(prompt);
2911 rx
2912 })?;
2913 if let Ok(path) = rx.await {
2914 tx.send(path).ok();
2915 }
2916 return anyhow::Ok(());
2917 }
2918 };
2919
2920 tx.send(abs_path.map(|path| vec![path])).ok();
2921 anyhow::Ok(())
2922 })
2923 .detach();
2924
2925 rx
2926 }
2927
2928 pub fn titlebar_item(&self) -> Option<AnyView> {
2929 self.titlebar_item.clone()
2930 }
2931
2932 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2933 /// When set, git-related operations should use this worktree instead of deriving
2934 /// the active worktree from the focused file.
2935 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2936 self.active_worktree_override
2937 }
2938
2939 pub fn set_active_worktree_override(
2940 &mut self,
2941 worktree_id: Option<WorktreeId>,
2942 cx: &mut Context<Self>,
2943 ) {
2944 self.active_worktree_override = worktree_id;
2945 cx.notify();
2946 }
2947
2948 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2949 self.active_worktree_override = None;
2950 cx.notify();
2951 }
2952
2953 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2954 ///
2955 /// If the given workspace has a local project, then it will be passed
2956 /// to the callback. Otherwise, a new empty window will be created.
2957 pub fn with_local_workspace<T, F>(
2958 &mut self,
2959 window: &mut Window,
2960 cx: &mut Context<Self>,
2961 callback: F,
2962 ) -> Task<Result<T>>
2963 where
2964 T: 'static,
2965 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2966 {
2967 if self.project.read(cx).is_local() {
2968 Task::ready(Ok(callback(self, window, cx)))
2969 } else {
2970 let env = self.project.read(cx).cli_environment(cx);
2971 let task = Self::new_local(
2972 Vec::new(),
2973 self.app_state.clone(),
2974 None,
2975 env,
2976 None,
2977 OpenMode::Activate,
2978 cx,
2979 );
2980 cx.spawn_in(window, async move |_vh, cx| {
2981 let OpenResult {
2982 window: multi_workspace_window,
2983 ..
2984 } = task.await?;
2985 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2986 let workspace = multi_workspace.workspace().clone();
2987 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2988 })
2989 })
2990 }
2991 }
2992
2993 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2994 ///
2995 /// If the given workspace has a local project, then it will be passed
2996 /// to the callback. Otherwise, a new empty window will be created.
2997 pub fn with_local_or_wsl_workspace<T, F>(
2998 &mut self,
2999 window: &mut Window,
3000 cx: &mut Context<Self>,
3001 callback: F,
3002 ) -> Task<Result<T>>
3003 where
3004 T: 'static,
3005 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
3006 {
3007 let project = self.project.read(cx);
3008 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
3009 Task::ready(Ok(callback(self, window, cx)))
3010 } else {
3011 let env = self.project.read(cx).cli_environment(cx);
3012 let task = Self::new_local(
3013 Vec::new(),
3014 self.app_state.clone(),
3015 None,
3016 env,
3017 None,
3018 OpenMode::Activate,
3019 cx,
3020 );
3021 cx.spawn_in(window, async move |_vh, cx| {
3022 let OpenResult {
3023 window: multi_workspace_window,
3024 ..
3025 } = task.await?;
3026 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
3027 let workspace = multi_workspace.workspace().clone();
3028 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3029 })
3030 })
3031 }
3032 }
3033
3034 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3035 self.project.read(cx).worktrees(cx)
3036 }
3037
3038 pub fn visible_worktrees<'a>(
3039 &self,
3040 cx: &'a App,
3041 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3042 self.project.read(cx).visible_worktrees(cx)
3043 }
3044
3045 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
3046 let futures = self
3047 .worktrees(cx)
3048 .filter_map(|worktree| worktree.read(cx).as_local())
3049 .map(|worktree| worktree.scan_complete())
3050 .collect::<Vec<_>>();
3051 async move {
3052 for future in futures {
3053 future.await;
3054 }
3055 }
3056 }
3057
3058 pub fn close_global(cx: &mut App) {
3059 cx.defer(|cx| {
3060 cx.windows().iter().find(|window| {
3061 window
3062 .update(cx, |_, window, _| {
3063 if window.is_window_active() {
3064 //This can only get called when the window's project connection has been lost
3065 //so we don't need to prompt the user for anything and instead just close the window
3066 window.remove_window();
3067 true
3068 } else {
3069 false
3070 }
3071 })
3072 .unwrap_or(false)
3073 });
3074 });
3075 }
3076
3077 pub fn move_focused_panel_to_next_position(
3078 &mut self,
3079 _: &MoveFocusedPanelToNextPosition,
3080 window: &mut Window,
3081 cx: &mut Context<Self>,
3082 ) {
3083 let docks = self.all_docks();
3084 let active_dock = docks
3085 .into_iter()
3086 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
3087
3088 if let Some(dock) = active_dock {
3089 dock.update(cx, |dock, cx| {
3090 let active_panel = dock
3091 .active_panel()
3092 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
3093
3094 if let Some(panel) = active_panel {
3095 panel.move_to_next_position(window, cx);
3096 }
3097 })
3098 }
3099 }
3100
3101 pub fn prepare_to_close(
3102 &mut self,
3103 close_intent: CloseIntent,
3104 window: &mut Window,
3105 cx: &mut Context<Self>,
3106 ) -> Task<Result<bool>> {
3107 let active_call = self.active_global_call();
3108
3109 cx.spawn_in(window, async move |this, cx| {
3110 this.update(cx, |this, _| {
3111 if close_intent == CloseIntent::CloseWindow {
3112 this.removing = true;
3113 }
3114 })?;
3115
3116 let workspace_count = cx.update(|_window, cx| {
3117 cx.windows()
3118 .iter()
3119 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
3120 .count()
3121 })?;
3122
3123 #[cfg(target_os = "macos")]
3124 let save_last_workspace = false;
3125
3126 // On Linux and Windows, closing the last window should restore the last workspace.
3127 #[cfg(not(target_os = "macos"))]
3128 let save_last_workspace = {
3129 let remaining_workspaces = cx.update(|_window, cx| {
3130 cx.windows()
3131 .iter()
3132 .filter_map(|window| window.downcast::<MultiWorkspace>())
3133 .filter_map(|multi_workspace| {
3134 multi_workspace
3135 .update(cx, |multi_workspace, _, cx| {
3136 multi_workspace.workspace().read(cx).removing
3137 })
3138 .ok()
3139 })
3140 .filter(|removing| !removing)
3141 .count()
3142 })?;
3143
3144 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
3145 };
3146
3147 if let Some(active_call) = active_call
3148 && workspace_count == 1
3149 && cx
3150 .update(|_window, cx| active_call.0.is_in_room(cx))
3151 .unwrap_or(false)
3152 {
3153 if close_intent == CloseIntent::CloseWindow {
3154 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
3155 let answer = cx.update(|window, cx| {
3156 window.prompt(
3157 PromptLevel::Warning,
3158 "Do you want to leave the current call?",
3159 None,
3160 &["Close window and hang up", "Cancel"],
3161 cx,
3162 )
3163 })?;
3164
3165 if answer.await.log_err() == Some(1) {
3166 return anyhow::Ok(false);
3167 } else {
3168 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
3169 task.await.log_err();
3170 }
3171 }
3172 }
3173 if close_intent == CloseIntent::ReplaceWindow {
3174 _ = cx.update(|_window, cx| {
3175 let multi_workspace = cx
3176 .windows()
3177 .iter()
3178 .filter_map(|window| window.downcast::<MultiWorkspace>())
3179 .next()
3180 .unwrap();
3181 let project = multi_workspace
3182 .read(cx)?
3183 .workspace()
3184 .read(cx)
3185 .project
3186 .clone();
3187 if project.read(cx).is_shared() {
3188 active_call.0.unshare_project(project, cx)?;
3189 }
3190 Ok::<_, anyhow::Error>(())
3191 });
3192 }
3193 }
3194
3195 let save_result = this
3196 .update_in(cx, |this, window, cx| {
3197 this.save_all_internal(SaveIntent::Close, window, cx)
3198 })?
3199 .await;
3200
3201 // If we're not quitting, but closing, we remove the workspace from
3202 // the current session.
3203 if close_intent != CloseIntent::Quit
3204 && !save_last_workspace
3205 && save_result.as_ref().is_ok_and(|&res| res)
3206 {
3207 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
3208 .await;
3209 }
3210
3211 save_result
3212 })
3213 }
3214
3215 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
3216 self.save_all_internal(
3217 action.save_intent.unwrap_or(SaveIntent::SaveAll),
3218 window,
3219 cx,
3220 )
3221 .detach_and_log_err(cx);
3222 }
3223
3224 fn send_keystrokes(
3225 &mut self,
3226 action: &SendKeystrokes,
3227 window: &mut Window,
3228 cx: &mut Context<Self>,
3229 ) {
3230 let keystrokes: Vec<Keystroke> = action
3231 .0
3232 .split(' ')
3233 .flat_map(|k| Keystroke::parse(k).log_err())
3234 .map(|k| {
3235 cx.keyboard_mapper()
3236 .map_key_equivalent(k, false)
3237 .inner()
3238 .clone()
3239 })
3240 .collect();
3241 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
3242 }
3243
3244 pub fn send_keystrokes_impl(
3245 &mut self,
3246 keystrokes: Vec<Keystroke>,
3247 window: &mut Window,
3248 cx: &mut Context<Self>,
3249 ) -> Shared<Task<()>> {
3250 let mut state = self.dispatching_keystrokes.borrow_mut();
3251 if !state.dispatched.insert(keystrokes.clone()) {
3252 cx.propagate();
3253 return state.task.clone().unwrap();
3254 }
3255
3256 state.queue.extend(keystrokes);
3257
3258 let keystrokes = self.dispatching_keystrokes.clone();
3259 if state.task.is_none() {
3260 state.task = Some(
3261 window
3262 .spawn(cx, async move |cx| {
3263 // limit to 100 keystrokes to avoid infinite recursion.
3264 for _ in 0..100 {
3265 let keystroke = {
3266 let mut state = keystrokes.borrow_mut();
3267 let Some(keystroke) = state.queue.pop_front() else {
3268 state.dispatched.clear();
3269 state.task.take();
3270 return;
3271 };
3272 keystroke
3273 };
3274 cx.update(|window, cx| {
3275 let focused = window.focused(cx);
3276 window.dispatch_keystroke(keystroke.clone(), cx);
3277 if window.focused(cx) != focused {
3278 // dispatch_keystroke may cause the focus to change.
3279 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3280 // And we need that to happen before the next keystroke to keep vim mode happy...
3281 // (Note that the tests always do this implicitly, so you must manually test with something like:
3282 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3283 // )
3284 window.draw(cx).clear();
3285 }
3286 })
3287 .ok();
3288
3289 // Yield between synthetic keystrokes so deferred focus and
3290 // other effects can settle before dispatching the next key.
3291 yield_now().await;
3292 }
3293
3294 *keystrokes.borrow_mut() = Default::default();
3295 log::error!("over 100 keystrokes passed to send_keystrokes");
3296 })
3297 .shared(),
3298 );
3299 }
3300 state.task.clone().unwrap()
3301 }
3302
3303 pub fn save_for_root_removal(
3304 &mut self,
3305 window: &mut Window,
3306 cx: &mut Context<Self>,
3307 ) -> Task<Result<bool>> {
3308 self.save_all_internal(SaveIntent::Close, window, cx)
3309 }
3310
3311 fn save_all_internal(
3312 &mut self,
3313 mut save_intent: SaveIntent,
3314 window: &mut Window,
3315 cx: &mut Context<Self>,
3316 ) -> Task<Result<bool>> {
3317 if self.project.read(cx).is_disconnected(cx) {
3318 return Task::ready(Ok(true));
3319 }
3320 let dirty_items = self
3321 .panes
3322 .iter()
3323 .flat_map(|pane| {
3324 pane.read(cx).items().filter_map(|item| {
3325 if item.is_dirty(cx) {
3326 item.tab_content_text(0, cx);
3327 Some((pane.downgrade(), item.boxed_clone()))
3328 } else {
3329 None
3330 }
3331 })
3332 })
3333 .collect::<Vec<_>>();
3334
3335 let project = self.project.clone();
3336 cx.spawn_in(window, async move |workspace, cx| {
3337 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3338 let (serialize_tasks, remaining_dirty_items) =
3339 workspace.update_in(cx, |workspace, window, cx| {
3340 let mut remaining_dirty_items = Vec::new();
3341 let mut serialize_tasks = Vec::new();
3342 for (pane, item) in dirty_items {
3343 if let Some(task) = item
3344 .to_serializable_item_handle(cx)
3345 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3346 {
3347 serialize_tasks.push(task);
3348 } else {
3349 remaining_dirty_items.push((pane, item));
3350 }
3351 }
3352 (serialize_tasks, remaining_dirty_items)
3353 })?;
3354
3355 futures::future::try_join_all(serialize_tasks).await?;
3356
3357 if !remaining_dirty_items.is_empty() {
3358 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3359 }
3360
3361 if remaining_dirty_items.len() > 1 {
3362 let answer = workspace.update_in(cx, |_, window, cx| {
3363 let detail = Pane::file_names_for_prompt(
3364 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3365 cx,
3366 );
3367 window.prompt(
3368 PromptLevel::Warning,
3369 "Do you want to save all changes in the following files?",
3370 Some(&detail),
3371 &["Save all", "Discard all", "Cancel"],
3372 cx,
3373 )
3374 })?;
3375 match answer.await.log_err() {
3376 Some(0) => save_intent = SaveIntent::SaveAll,
3377 Some(1) => save_intent = SaveIntent::Skip,
3378 Some(2) => return Ok(false),
3379 _ => {}
3380 }
3381 }
3382
3383 remaining_dirty_items
3384 } else {
3385 dirty_items
3386 };
3387
3388 for (pane, item) in dirty_items {
3389 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3390 (
3391 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3392 item.project_entry_ids(cx),
3393 )
3394 })?;
3395 if (singleton || !project_entry_ids.is_empty())
3396 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3397 {
3398 return Ok(false);
3399 }
3400 }
3401 Ok(true)
3402 })
3403 }
3404
3405 pub fn open_workspace_for_paths(
3406 &mut self,
3407 // replace_current_window: bool,
3408 mut open_mode: OpenMode,
3409 paths: Vec<PathBuf>,
3410 window: &mut Window,
3411 cx: &mut Context<Self>,
3412 ) -> Task<Result<Entity<Workspace>>> {
3413 let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
3414 let is_remote = self.project.read(cx).is_via_collab();
3415 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3416 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3417
3418 let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
3419 if workspace_is_empty {
3420 open_mode = OpenMode::Activate;
3421 }
3422
3423 let app_state = self.app_state.clone();
3424
3425 cx.spawn(async move |_, cx| {
3426 let OpenResult { workspace, .. } = cx
3427 .update(|cx| {
3428 open_paths(
3429 &paths,
3430 app_state,
3431 OpenOptions {
3432 requesting_window,
3433 open_mode,
3434 ..Default::default()
3435 },
3436 cx,
3437 )
3438 })
3439 .await?;
3440 Ok(workspace)
3441 })
3442 }
3443
3444 #[allow(clippy::type_complexity)]
3445 pub fn open_paths(
3446 &mut self,
3447 mut abs_paths: Vec<PathBuf>,
3448 options: OpenOptions,
3449 pane: Option<WeakEntity<Pane>>,
3450 window: &mut Window,
3451 cx: &mut Context<Self>,
3452 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3453 let fs = self.app_state.fs.clone();
3454
3455 let caller_ordered_abs_paths = abs_paths.clone();
3456
3457 // Sort the paths to ensure we add worktrees for parents before their children.
3458 abs_paths.sort_unstable();
3459 cx.spawn_in(window, async move |this, cx| {
3460 let mut tasks = Vec::with_capacity(abs_paths.len());
3461
3462 for abs_path in &abs_paths {
3463 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3464 OpenVisible::All => Some(true),
3465 OpenVisible::None => Some(false),
3466 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3467 Some(Some(metadata)) => Some(!metadata.is_dir),
3468 Some(None) => Some(true),
3469 None => None,
3470 },
3471 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3472 Some(Some(metadata)) => Some(metadata.is_dir),
3473 Some(None) => Some(false),
3474 None => None,
3475 },
3476 };
3477 let project_path = match visible {
3478 Some(visible) => match this
3479 .update(cx, |this, cx| {
3480 Workspace::project_path_for_path(
3481 this.project.clone(),
3482 abs_path,
3483 visible,
3484 cx,
3485 )
3486 })
3487 .log_err()
3488 {
3489 Some(project_path) => project_path.await.log_err(),
3490 None => None,
3491 },
3492 None => None,
3493 };
3494
3495 let this = this.clone();
3496 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3497 let fs = fs.clone();
3498 let pane = pane.clone();
3499 let task = cx.spawn(async move |cx| {
3500 let (_worktree, project_path) = project_path?;
3501 if fs.is_dir(&abs_path).await {
3502 // Opening a directory should not race to update the active entry.
3503 // We'll select/reveal a deterministic final entry after all paths finish opening.
3504 None
3505 } else {
3506 Some(
3507 this.update_in(cx, |this, window, cx| {
3508 this.open_path(
3509 project_path,
3510 pane,
3511 options.focus.unwrap_or(true),
3512 window,
3513 cx,
3514 )
3515 })
3516 .ok()?
3517 .await,
3518 )
3519 }
3520 });
3521 tasks.push(task);
3522 }
3523
3524 let results = futures::future::join_all(tasks).await;
3525
3526 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3527 let mut winner: Option<(PathBuf, bool)> = None;
3528 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3529 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3530 if !metadata.is_dir {
3531 winner = Some((abs_path, false));
3532 break;
3533 }
3534 if winner.is_none() {
3535 winner = Some((abs_path, true));
3536 }
3537 } else if winner.is_none() {
3538 winner = Some((abs_path, false));
3539 }
3540 }
3541
3542 // Compute the winner entry id on the foreground thread and emit once, after all
3543 // paths finish opening. This avoids races between concurrently-opening paths
3544 // (directories in particular) and makes the resulting project panel selection
3545 // deterministic.
3546 if let Some((winner_abs_path, winner_is_dir)) = winner {
3547 'emit_winner: {
3548 let winner_abs_path: Arc<Path> =
3549 SanitizedPath::new(&winner_abs_path).as_path().into();
3550
3551 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3552 OpenVisible::All => true,
3553 OpenVisible::None => false,
3554 OpenVisible::OnlyFiles => !winner_is_dir,
3555 OpenVisible::OnlyDirectories => winner_is_dir,
3556 };
3557
3558 let Some(worktree_task) = this
3559 .update(cx, |workspace, cx| {
3560 workspace.project.update(cx, |project, cx| {
3561 project.find_or_create_worktree(
3562 winner_abs_path.as_ref(),
3563 visible,
3564 cx,
3565 )
3566 })
3567 })
3568 .ok()
3569 else {
3570 break 'emit_winner;
3571 };
3572
3573 let Ok((worktree, _)) = worktree_task.await else {
3574 break 'emit_winner;
3575 };
3576
3577 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3578 let worktree = worktree.read(cx);
3579 let worktree_abs_path = worktree.abs_path();
3580 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3581 worktree.root_entry()
3582 } else {
3583 winner_abs_path
3584 .strip_prefix(worktree_abs_path.as_ref())
3585 .ok()
3586 .and_then(|relative_path| {
3587 let relative_path =
3588 RelPath::new(relative_path, PathStyle::local())
3589 .log_err()?;
3590 worktree.entry_for_path(&relative_path)
3591 })
3592 }?;
3593 Some(entry.id)
3594 }) else {
3595 break 'emit_winner;
3596 };
3597
3598 this.update(cx, |workspace, cx| {
3599 workspace.project.update(cx, |_, cx| {
3600 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3601 });
3602 })
3603 .ok();
3604 }
3605 }
3606
3607 results
3608 })
3609 }
3610
3611 pub fn open_resolved_path(
3612 &mut self,
3613 path: ResolvedPath,
3614 window: &mut Window,
3615 cx: &mut Context<Self>,
3616 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3617 match path {
3618 ResolvedPath::ProjectPath { project_path, .. } => {
3619 self.open_path(project_path, None, true, window, cx)
3620 }
3621 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3622 PathBuf::from(path),
3623 OpenOptions {
3624 visible: Some(OpenVisible::None),
3625 ..Default::default()
3626 },
3627 window,
3628 cx,
3629 ),
3630 }
3631 }
3632
3633 pub fn absolute_path_of_worktree(
3634 &self,
3635 worktree_id: WorktreeId,
3636 cx: &mut Context<Self>,
3637 ) -> Option<PathBuf> {
3638 self.project
3639 .read(cx)
3640 .worktree_for_id(worktree_id, cx)
3641 // TODO: use `abs_path` or `root_dir`
3642 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3643 }
3644
3645 pub fn add_folder_to_project(
3646 &mut self,
3647 _: &AddFolderToProject,
3648 window: &mut Window,
3649 cx: &mut Context<Self>,
3650 ) {
3651 let project = self.project.read(cx);
3652 if project.is_via_collab() {
3653 self.show_error(
3654 &anyhow!("You cannot add folders to someone else's project"),
3655 cx,
3656 );
3657 return;
3658 }
3659 let paths = self.prompt_for_open_path(
3660 PathPromptOptions {
3661 files: false,
3662 directories: true,
3663 multiple: true,
3664 prompt: None,
3665 },
3666 DirectoryLister::Project(self.project.clone()),
3667 window,
3668 cx,
3669 );
3670 cx.spawn_in(window, async move |this, cx| {
3671 if let Some(paths) = paths.await.log_err().flatten() {
3672 let results = this
3673 .update_in(cx, |this, window, cx| {
3674 this.open_paths(
3675 paths,
3676 OpenOptions {
3677 visible: Some(OpenVisible::All),
3678 ..Default::default()
3679 },
3680 None,
3681 window,
3682 cx,
3683 )
3684 })?
3685 .await;
3686 for result in results.into_iter().flatten() {
3687 result.log_err();
3688 }
3689 }
3690 anyhow::Ok(())
3691 })
3692 .detach_and_log_err(cx);
3693 }
3694
3695 pub fn project_path_for_path(
3696 project: Entity<Project>,
3697 abs_path: &Path,
3698 visible: bool,
3699 cx: &mut App,
3700 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3701 let entry = project.update(cx, |project, cx| {
3702 project.find_or_create_worktree(abs_path, visible, cx)
3703 });
3704 cx.spawn(async move |cx| {
3705 let (worktree, path) = entry.await?;
3706 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3707 Ok((worktree, ProjectPath { worktree_id, path }))
3708 })
3709 }
3710
3711 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3712 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3713 }
3714
3715 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3716 self.items_of_type(cx).max_by_key(|item| item.item_id())
3717 }
3718
3719 pub fn items_of_type<'a, T: Item>(
3720 &'a self,
3721 cx: &'a App,
3722 ) -> impl 'a + Iterator<Item = Entity<T>> {
3723 self.panes
3724 .iter()
3725 .flat_map(|pane| pane.read(cx).items_of_type())
3726 }
3727
3728 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3729 self.active_pane().read(cx).active_item()
3730 }
3731
3732 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3733 let item = self.active_item(cx)?;
3734 item.to_any_view().downcast::<I>().ok()
3735 }
3736
3737 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3738 self.active_item(cx).and_then(|item| item.project_path(cx))
3739 }
3740
3741 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3742 self.recent_navigation_history_iter(cx)
3743 .filter_map(|(path, abs_path)| {
3744 let worktree = self
3745 .project
3746 .read(cx)
3747 .worktree_for_id(path.worktree_id, cx)?;
3748 if worktree.read(cx).is_visible() {
3749 abs_path
3750 } else {
3751 None
3752 }
3753 })
3754 .next()
3755 }
3756
3757 pub fn save_active_item(
3758 &mut self,
3759 save_intent: SaveIntent,
3760 window: &mut Window,
3761 cx: &mut App,
3762 ) -> Task<Result<()>> {
3763 let project = self.project.clone();
3764 let pane = self.active_pane();
3765 let item = pane.read(cx).active_item();
3766 let pane = pane.downgrade();
3767
3768 window.spawn(cx, async move |cx| {
3769 if let Some(item) = item {
3770 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3771 .await
3772 .map(|_| ())
3773 } else {
3774 Ok(())
3775 }
3776 })
3777 }
3778
3779 pub fn close_inactive_items_and_panes(
3780 &mut self,
3781 action: &CloseInactiveTabsAndPanes,
3782 window: &mut Window,
3783 cx: &mut Context<Self>,
3784 ) {
3785 if let Some(task) = self.close_all_internal(
3786 true,
3787 action.save_intent.unwrap_or(SaveIntent::Close),
3788 window,
3789 cx,
3790 ) {
3791 task.detach_and_log_err(cx)
3792 }
3793 }
3794
3795 pub fn close_all_items_and_panes(
3796 &mut self,
3797 action: &CloseAllItemsAndPanes,
3798 window: &mut Window,
3799 cx: &mut Context<Self>,
3800 ) {
3801 if let Some(task) = self.close_all_internal(
3802 false,
3803 action.save_intent.unwrap_or(SaveIntent::Close),
3804 window,
3805 cx,
3806 ) {
3807 task.detach_and_log_err(cx)
3808 }
3809 }
3810
3811 /// Closes the active item across all panes.
3812 pub fn close_item_in_all_panes(
3813 &mut self,
3814 action: &CloseItemInAllPanes,
3815 window: &mut Window,
3816 cx: &mut Context<Self>,
3817 ) {
3818 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3819 return;
3820 };
3821
3822 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3823 let close_pinned = action.close_pinned;
3824
3825 if let Some(project_path) = active_item.project_path(cx) {
3826 self.close_items_with_project_path(
3827 &project_path,
3828 save_intent,
3829 close_pinned,
3830 window,
3831 cx,
3832 );
3833 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3834 let item_id = active_item.item_id();
3835 self.active_pane().update(cx, |pane, cx| {
3836 pane.close_item_by_id(item_id, save_intent, window, cx)
3837 .detach_and_log_err(cx);
3838 });
3839 }
3840 }
3841
3842 /// Closes all items with the given project path across all panes.
3843 pub fn close_items_with_project_path(
3844 &mut self,
3845 project_path: &ProjectPath,
3846 save_intent: SaveIntent,
3847 close_pinned: bool,
3848 window: &mut Window,
3849 cx: &mut Context<Self>,
3850 ) {
3851 let panes = self.panes().to_vec();
3852 for pane in panes {
3853 pane.update(cx, |pane, cx| {
3854 pane.close_items_for_project_path(
3855 project_path,
3856 save_intent,
3857 close_pinned,
3858 window,
3859 cx,
3860 )
3861 .detach_and_log_err(cx);
3862 });
3863 }
3864 }
3865
3866 fn close_all_internal(
3867 &mut self,
3868 retain_active_pane: bool,
3869 save_intent: SaveIntent,
3870 window: &mut Window,
3871 cx: &mut Context<Self>,
3872 ) -> Option<Task<Result<()>>> {
3873 let current_pane = self.active_pane();
3874
3875 let mut tasks = Vec::new();
3876
3877 if retain_active_pane {
3878 let current_pane_close = current_pane.update(cx, |pane, cx| {
3879 pane.close_other_items(
3880 &CloseOtherItems {
3881 save_intent: None,
3882 close_pinned: false,
3883 },
3884 None,
3885 window,
3886 cx,
3887 )
3888 });
3889
3890 tasks.push(current_pane_close);
3891 }
3892
3893 for pane in self.panes() {
3894 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3895 continue;
3896 }
3897
3898 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3899 pane.close_all_items(
3900 &CloseAllItems {
3901 save_intent: Some(save_intent),
3902 close_pinned: false,
3903 },
3904 window,
3905 cx,
3906 )
3907 });
3908
3909 tasks.push(close_pane_items)
3910 }
3911
3912 if tasks.is_empty() {
3913 None
3914 } else {
3915 Some(cx.spawn_in(window, async move |_, _| {
3916 for task in tasks {
3917 task.await?
3918 }
3919 Ok(())
3920 }))
3921 }
3922 }
3923
3924 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3925 self.dock_at_position(position).read(cx).is_open()
3926 }
3927
3928 pub fn toggle_dock(
3929 &mut self,
3930 dock_side: DockPosition,
3931 window: &mut Window,
3932 cx: &mut Context<Self>,
3933 ) {
3934 let mut focus_center = false;
3935 let mut reveal_dock = false;
3936
3937 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3938 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3939
3940 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3941 telemetry::event!(
3942 "Panel Button Clicked",
3943 name = panel.persistent_name(),
3944 toggle_state = !was_visible
3945 );
3946 }
3947 if was_visible {
3948 self.save_open_dock_positions(cx);
3949 }
3950
3951 let dock = self.dock_at_position(dock_side);
3952 dock.update(cx, |dock, cx| {
3953 dock.set_open(!was_visible, window, cx);
3954
3955 if dock.active_panel().is_none() {
3956 let Some(panel_ix) = dock
3957 .first_enabled_panel_idx(cx)
3958 .log_with_level(log::Level::Info)
3959 else {
3960 return;
3961 };
3962 dock.activate_panel(panel_ix, window, cx);
3963 }
3964
3965 if let Some(active_panel) = dock.active_panel() {
3966 if was_visible {
3967 if active_panel
3968 .panel_focus_handle(cx)
3969 .contains_focused(window, cx)
3970 {
3971 focus_center = true;
3972 }
3973 } else {
3974 let focus_handle = &active_panel.panel_focus_handle(cx);
3975 window.focus(focus_handle, cx);
3976 reveal_dock = true;
3977 }
3978 }
3979 });
3980
3981 if reveal_dock {
3982 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3983 }
3984
3985 if focus_center {
3986 self.active_pane
3987 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3988 }
3989
3990 cx.notify();
3991 self.serialize_workspace(window, cx);
3992 }
3993
3994 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3995 self.all_docks().into_iter().find(|&dock| {
3996 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3997 })
3998 }
3999
4000 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
4001 if let Some(dock) = self.active_dock(window, cx).cloned() {
4002 self.save_open_dock_positions(cx);
4003 dock.update(cx, |dock, cx| {
4004 dock.set_open(false, window, cx);
4005 });
4006 return true;
4007 }
4008 false
4009 }
4010
4011 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4012 self.save_open_dock_positions(cx);
4013 for dock in self.all_docks() {
4014 dock.update(cx, |dock, cx| {
4015 dock.set_open(false, window, cx);
4016 });
4017 }
4018
4019 cx.focus_self(window);
4020 cx.notify();
4021 self.serialize_workspace(window, cx);
4022 }
4023
4024 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
4025 self.all_docks()
4026 .into_iter()
4027 .filter_map(|dock| {
4028 let dock_ref = dock.read(cx);
4029 if dock_ref.is_open() {
4030 Some(dock_ref.position())
4031 } else {
4032 None
4033 }
4034 })
4035 .collect()
4036 }
4037
4038 /// Saves the positions of currently open docks.
4039 ///
4040 /// Updates `last_open_dock_positions` with positions of all currently open
4041 /// docks, to later be restored by the 'Toggle All Docks' action.
4042 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
4043 let open_dock_positions = self.get_open_dock_positions(cx);
4044 if !open_dock_positions.is_empty() {
4045 self.last_open_dock_positions = open_dock_positions;
4046 }
4047 }
4048
4049 /// Toggles all docks between open and closed states.
4050 ///
4051 /// If any docks are open, closes all and remembers their positions. If all
4052 /// docks are closed, restores the last remembered dock configuration.
4053 fn toggle_all_docks(
4054 &mut self,
4055 _: &ToggleAllDocks,
4056 window: &mut Window,
4057 cx: &mut Context<Self>,
4058 ) {
4059 let open_dock_positions = self.get_open_dock_positions(cx);
4060
4061 if !open_dock_positions.is_empty() {
4062 self.close_all_docks(window, cx);
4063 } else if !self.last_open_dock_positions.is_empty() {
4064 self.restore_last_open_docks(window, cx);
4065 }
4066 }
4067
4068 /// Reopens docks from the most recently remembered configuration.
4069 ///
4070 /// Opens all docks whose positions are stored in `last_open_dock_positions`
4071 /// and clears the stored positions.
4072 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4073 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
4074
4075 for position in positions_to_open {
4076 let dock = self.dock_at_position(position);
4077 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
4078 }
4079
4080 cx.focus_self(window);
4081 cx.notify();
4082 self.serialize_workspace(window, cx);
4083 }
4084
4085 /// Transfer focus to the panel of the given type.
4086 pub fn focus_panel<T: Panel>(
4087 &mut self,
4088 window: &mut Window,
4089 cx: &mut Context<Self>,
4090 ) -> Option<Entity<T>> {
4091 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
4092 panel.to_any().downcast().ok()
4093 }
4094
4095 /// Focus the panel of the given type if it isn't already focused. If it is
4096 /// already focused, then transfer focus back to the workspace center.
4097 /// When the `close_panel_on_toggle` setting is enabled, also closes the
4098 /// panel when transferring focus back to the center.
4099 pub fn toggle_panel_focus<T: Panel>(
4100 &mut self,
4101 window: &mut Window,
4102 cx: &mut Context<Self>,
4103 ) -> bool {
4104 let mut did_focus_panel = false;
4105 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
4106 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
4107 did_focus_panel
4108 });
4109
4110 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
4111 self.close_panel::<T>(window, cx);
4112 }
4113
4114 telemetry::event!(
4115 "Panel Button Clicked",
4116 name = T::persistent_name(),
4117 toggle_state = did_focus_panel
4118 );
4119
4120 did_focus_panel
4121 }
4122
4123 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4124 if let Some(item) = self.active_item(cx) {
4125 item.item_focus_handle(cx).focus(window, cx);
4126 } else {
4127 log::error!("Could not find a focus target when switching focus to the center panes",);
4128 }
4129 }
4130
4131 pub fn activate_panel_for_proto_id(
4132 &mut self,
4133 panel_id: PanelId,
4134 window: &mut Window,
4135 cx: &mut Context<Self>,
4136 ) -> Option<Arc<dyn PanelHandle>> {
4137 let mut panel = None;
4138 for dock in self.all_docks() {
4139 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
4140 panel = dock.update(cx, |dock, cx| {
4141 dock.activate_panel(panel_index, window, cx);
4142 dock.set_open(true, window, cx);
4143 dock.active_panel().cloned()
4144 });
4145 break;
4146 }
4147 }
4148
4149 if panel.is_some() {
4150 cx.notify();
4151 self.serialize_workspace(window, cx);
4152 }
4153
4154 panel
4155 }
4156
4157 /// Focus or unfocus the given panel type, depending on the given callback.
4158 fn focus_or_unfocus_panel<T: Panel>(
4159 &mut self,
4160 window: &mut Window,
4161 cx: &mut Context<Self>,
4162 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
4163 ) -> Option<Arc<dyn PanelHandle>> {
4164 let mut result_panel = None;
4165 let mut serialize = false;
4166 for dock in self.all_docks() {
4167 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4168 let mut focus_center = false;
4169 let panel = dock.update(cx, |dock, cx| {
4170 dock.activate_panel(panel_index, window, cx);
4171
4172 let panel = dock.active_panel().cloned();
4173 if let Some(panel) = panel.as_ref() {
4174 if should_focus(&**panel, window, cx) {
4175 dock.set_open(true, window, cx);
4176 panel.panel_focus_handle(cx).focus(window, cx);
4177 } else {
4178 focus_center = true;
4179 }
4180 }
4181 panel
4182 });
4183
4184 if focus_center {
4185 self.active_pane
4186 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4187 }
4188
4189 result_panel = panel;
4190 serialize = true;
4191 break;
4192 }
4193 }
4194
4195 if serialize {
4196 self.serialize_workspace(window, cx);
4197 }
4198
4199 cx.notify();
4200 result_panel
4201 }
4202
4203 /// Open the panel of the given type
4204 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4205 for dock in self.all_docks() {
4206 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4207 dock.update(cx, |dock, cx| {
4208 dock.activate_panel(panel_index, window, cx);
4209 dock.set_open(true, window, cx);
4210 });
4211 }
4212 }
4213 }
4214
4215 /// Open the panel of the given type, dismissing any zoomed items that
4216 /// would obscure it (e.g. a zoomed terminal).
4217 pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4218 let dock_position = self.all_docks().iter().find_map(|dock| {
4219 let dock = dock.read(cx);
4220 dock.panel_index_for_type::<T>().map(|_| dock.position())
4221 });
4222 self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
4223 self.open_panel::<T>(window, cx);
4224 }
4225
4226 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
4227 for dock in self.all_docks().iter() {
4228 dock.update(cx, |dock, cx| {
4229 if dock.panel::<T>().is_some() {
4230 dock.set_open(false, window, cx)
4231 }
4232 })
4233 }
4234 }
4235
4236 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
4237 self.all_docks()
4238 .iter()
4239 .find_map(|dock| dock.read(cx).panel::<T>())
4240 }
4241
4242 fn dismiss_zoomed_items_to_reveal(
4243 &mut self,
4244 dock_to_reveal: Option<DockPosition>,
4245 window: &mut Window,
4246 cx: &mut Context<Self>,
4247 ) {
4248 // If a center pane is zoomed, unzoom it.
4249 for pane in &self.panes {
4250 if pane != &self.active_pane || dock_to_reveal.is_some() {
4251 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4252 }
4253 }
4254
4255 // If another dock is zoomed, hide it.
4256 let mut focus_center = false;
4257 for dock in self.all_docks() {
4258 dock.update(cx, |dock, cx| {
4259 if Some(dock.position()) != dock_to_reveal
4260 && let Some(panel) = dock.active_panel()
4261 && panel.is_zoomed(window, cx)
4262 {
4263 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
4264 dock.set_open(false, window, cx);
4265 }
4266 });
4267 }
4268
4269 if focus_center {
4270 self.active_pane
4271 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4272 }
4273
4274 if self.zoomed_position != dock_to_reveal {
4275 self.zoomed = None;
4276 self.zoomed_position = None;
4277 cx.emit(Event::ZoomChanged);
4278 }
4279
4280 cx.notify();
4281 }
4282
4283 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4284 let pane = cx.new(|cx| {
4285 let mut pane = Pane::new(
4286 self.weak_handle(),
4287 self.project.clone(),
4288 self.pane_history_timestamp.clone(),
4289 None,
4290 NewFile.boxed_clone(),
4291 true,
4292 window,
4293 cx,
4294 );
4295 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4296 pane
4297 });
4298 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4299 .detach();
4300 self.panes.push(pane.clone());
4301
4302 window.focus(&pane.focus_handle(cx), cx);
4303
4304 cx.emit(Event::PaneAdded(pane.clone()));
4305 pane
4306 }
4307
4308 pub fn add_item_to_center(
4309 &mut self,
4310 item: Box<dyn ItemHandle>,
4311 window: &mut Window,
4312 cx: &mut Context<Self>,
4313 ) -> bool {
4314 if let Some(center_pane) = self.last_active_center_pane.clone() {
4315 if let Some(center_pane) = center_pane.upgrade() {
4316 center_pane.update(cx, |pane, cx| {
4317 pane.add_item(item, true, true, None, window, cx)
4318 });
4319 true
4320 } else {
4321 false
4322 }
4323 } else {
4324 false
4325 }
4326 }
4327
4328 pub fn add_item_to_active_pane(
4329 &mut self,
4330 item: Box<dyn ItemHandle>,
4331 destination_index: Option<usize>,
4332 focus_item: bool,
4333 window: &mut Window,
4334 cx: &mut App,
4335 ) {
4336 self.add_item(
4337 self.active_pane.clone(),
4338 item,
4339 destination_index,
4340 false,
4341 focus_item,
4342 window,
4343 cx,
4344 )
4345 }
4346
4347 pub fn add_item(
4348 &mut self,
4349 pane: Entity<Pane>,
4350 item: Box<dyn ItemHandle>,
4351 destination_index: Option<usize>,
4352 activate_pane: bool,
4353 focus_item: bool,
4354 window: &mut Window,
4355 cx: &mut App,
4356 ) {
4357 pane.update(cx, |pane, cx| {
4358 pane.add_item(
4359 item,
4360 activate_pane,
4361 focus_item,
4362 destination_index,
4363 window,
4364 cx,
4365 )
4366 });
4367 }
4368
4369 pub fn split_item(
4370 &mut self,
4371 split_direction: SplitDirection,
4372 item: Box<dyn ItemHandle>,
4373 window: &mut Window,
4374 cx: &mut Context<Self>,
4375 ) {
4376 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4377 self.add_item(new_pane, item, None, true, true, window, cx);
4378 }
4379
4380 pub fn open_abs_path(
4381 &mut self,
4382 abs_path: PathBuf,
4383 options: OpenOptions,
4384 window: &mut Window,
4385 cx: &mut Context<Self>,
4386 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4387 cx.spawn_in(window, async move |workspace, cx| {
4388 let open_paths_task_result = workspace
4389 .update_in(cx, |workspace, window, cx| {
4390 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4391 })
4392 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4393 .await;
4394 anyhow::ensure!(
4395 open_paths_task_result.len() == 1,
4396 "open abs path {abs_path:?} task returned incorrect number of results"
4397 );
4398 match open_paths_task_result
4399 .into_iter()
4400 .next()
4401 .expect("ensured single task result")
4402 {
4403 Some(open_result) => {
4404 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4405 }
4406 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4407 }
4408 })
4409 }
4410
4411 pub fn split_abs_path(
4412 &mut self,
4413 abs_path: PathBuf,
4414 visible: bool,
4415 window: &mut Window,
4416 cx: &mut Context<Self>,
4417 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4418 let project_path_task =
4419 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4420 cx.spawn_in(window, async move |this, cx| {
4421 let (_, path) = project_path_task.await?;
4422 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4423 .await
4424 })
4425 }
4426
4427 pub fn open_path(
4428 &mut self,
4429 path: impl Into<ProjectPath>,
4430 pane: Option<WeakEntity<Pane>>,
4431 focus_item: bool,
4432 window: &mut Window,
4433 cx: &mut App,
4434 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4435 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4436 }
4437
4438 pub fn open_path_preview(
4439 &mut self,
4440 path: impl Into<ProjectPath>,
4441 pane: Option<WeakEntity<Pane>>,
4442 focus_item: bool,
4443 allow_preview: bool,
4444 activate: bool,
4445 window: &mut Window,
4446 cx: &mut App,
4447 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4448 let pane = pane.unwrap_or_else(|| {
4449 self.last_active_center_pane.clone().unwrap_or_else(|| {
4450 self.panes
4451 .first()
4452 .expect("There must be an active pane")
4453 .downgrade()
4454 })
4455 });
4456
4457 let project_path = path.into();
4458 let task = self.load_path(project_path.clone(), window, cx);
4459 window.spawn(cx, async move |cx| {
4460 let (project_entry_id, build_item) = task.await?;
4461
4462 pane.update_in(cx, |pane, window, cx| {
4463 pane.open_item(
4464 project_entry_id,
4465 project_path,
4466 focus_item,
4467 allow_preview,
4468 activate,
4469 None,
4470 window,
4471 cx,
4472 build_item,
4473 )
4474 })
4475 })
4476 }
4477
4478 pub fn split_path(
4479 &mut self,
4480 path: impl Into<ProjectPath>,
4481 window: &mut Window,
4482 cx: &mut Context<Self>,
4483 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4484 self.split_path_preview(path, false, None, window, cx)
4485 }
4486
4487 pub fn split_path_preview(
4488 &mut self,
4489 path: impl Into<ProjectPath>,
4490 allow_preview: bool,
4491 split_direction: Option<SplitDirection>,
4492 window: &mut Window,
4493 cx: &mut Context<Self>,
4494 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4495 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4496 self.panes
4497 .first()
4498 .expect("There must be an active pane")
4499 .downgrade()
4500 });
4501
4502 if let Member::Pane(center_pane) = &self.center.root
4503 && center_pane.read(cx).items_len() == 0
4504 {
4505 return self.open_path(path, Some(pane), true, window, cx);
4506 }
4507
4508 let project_path = path.into();
4509 let task = self.load_path(project_path.clone(), window, cx);
4510 cx.spawn_in(window, async move |this, cx| {
4511 let (project_entry_id, build_item) = task.await?;
4512 this.update_in(cx, move |this, window, cx| -> Option<_> {
4513 let pane = pane.upgrade()?;
4514 let new_pane = this.split_pane(
4515 pane,
4516 split_direction.unwrap_or(SplitDirection::Right),
4517 window,
4518 cx,
4519 );
4520 new_pane.update(cx, |new_pane, cx| {
4521 Some(new_pane.open_item(
4522 project_entry_id,
4523 project_path,
4524 true,
4525 allow_preview,
4526 true,
4527 None,
4528 window,
4529 cx,
4530 build_item,
4531 ))
4532 })
4533 })
4534 .map(|option| option.context("pane was dropped"))?
4535 })
4536 }
4537
4538 fn load_path(
4539 &mut self,
4540 path: ProjectPath,
4541 window: &mut Window,
4542 cx: &mut App,
4543 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4544 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4545 registry.open_path(self.project(), &path, window, cx)
4546 }
4547
4548 pub fn find_project_item<T>(
4549 &self,
4550 pane: &Entity<Pane>,
4551 project_item: &Entity<T::Item>,
4552 cx: &App,
4553 ) -> Option<Entity<T>>
4554 where
4555 T: ProjectItem,
4556 {
4557 use project::ProjectItem as _;
4558 let project_item = project_item.read(cx);
4559 let entry_id = project_item.entry_id(cx);
4560 let project_path = project_item.project_path(cx);
4561
4562 let mut item = None;
4563 if let Some(entry_id) = entry_id {
4564 item = pane.read(cx).item_for_entry(entry_id, cx);
4565 }
4566 if item.is_none()
4567 && let Some(project_path) = project_path
4568 {
4569 item = pane.read(cx).item_for_path(project_path, cx);
4570 }
4571
4572 item.and_then(|item| item.downcast::<T>())
4573 }
4574
4575 pub fn is_project_item_open<T>(
4576 &self,
4577 pane: &Entity<Pane>,
4578 project_item: &Entity<T::Item>,
4579 cx: &App,
4580 ) -> bool
4581 where
4582 T: ProjectItem,
4583 {
4584 self.find_project_item::<T>(pane, project_item, cx)
4585 .is_some()
4586 }
4587
4588 pub fn open_project_item<T>(
4589 &mut self,
4590 pane: Entity<Pane>,
4591 project_item: Entity<T::Item>,
4592 activate_pane: bool,
4593 focus_item: bool,
4594 keep_old_preview: bool,
4595 allow_new_preview: bool,
4596 window: &mut Window,
4597 cx: &mut Context<Self>,
4598 ) -> Entity<T>
4599 where
4600 T: ProjectItem,
4601 {
4602 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4603
4604 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4605 if !keep_old_preview
4606 && let Some(old_id) = old_item_id
4607 && old_id != item.item_id()
4608 {
4609 // switching to a different item, so unpreview old active item
4610 pane.update(cx, |pane, _| {
4611 pane.unpreview_item_if_preview(old_id);
4612 });
4613 }
4614
4615 self.activate_item(&item, activate_pane, focus_item, window, cx);
4616 if !allow_new_preview {
4617 pane.update(cx, |pane, _| {
4618 pane.unpreview_item_if_preview(item.item_id());
4619 });
4620 }
4621 return item;
4622 }
4623
4624 let item = pane.update(cx, |pane, cx| {
4625 cx.new(|cx| {
4626 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4627 })
4628 });
4629 let mut destination_index = None;
4630 pane.update(cx, |pane, cx| {
4631 if !keep_old_preview && let Some(old_id) = old_item_id {
4632 pane.unpreview_item_if_preview(old_id);
4633 }
4634 if allow_new_preview {
4635 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4636 }
4637 });
4638
4639 self.add_item(
4640 pane,
4641 Box::new(item.clone()),
4642 destination_index,
4643 activate_pane,
4644 focus_item,
4645 window,
4646 cx,
4647 );
4648 item
4649 }
4650
4651 pub fn open_shared_screen(
4652 &mut self,
4653 peer_id: PeerId,
4654 window: &mut Window,
4655 cx: &mut Context<Self>,
4656 ) {
4657 if let Some(shared_screen) =
4658 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4659 {
4660 self.active_pane.update(cx, |pane, cx| {
4661 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4662 });
4663 }
4664 }
4665
4666 pub fn activate_item(
4667 &mut self,
4668 item: &dyn ItemHandle,
4669 activate_pane: bool,
4670 focus_item: bool,
4671 window: &mut Window,
4672 cx: &mut App,
4673 ) -> bool {
4674 let result = self.panes.iter().find_map(|pane| {
4675 pane.read(cx)
4676 .index_for_item(item)
4677 .map(|ix| (pane.clone(), ix))
4678 });
4679 if let Some((pane, ix)) = result {
4680 pane.update(cx, |pane, cx| {
4681 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4682 });
4683 true
4684 } else {
4685 false
4686 }
4687 }
4688
4689 fn activate_pane_at_index(
4690 &mut self,
4691 action: &ActivatePane,
4692 window: &mut Window,
4693 cx: &mut Context<Self>,
4694 ) {
4695 let panes = self.center.panes();
4696 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4697 window.focus(&pane.focus_handle(cx), cx);
4698 } else {
4699 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4700 .detach();
4701 }
4702 }
4703
4704 fn move_item_to_pane_at_index(
4705 &mut self,
4706 action: &MoveItemToPane,
4707 window: &mut Window,
4708 cx: &mut Context<Self>,
4709 ) {
4710 let panes = self.center.panes();
4711 let destination = match panes.get(action.destination) {
4712 Some(&destination) => destination.clone(),
4713 None => {
4714 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4715 return;
4716 }
4717 let direction = SplitDirection::Right;
4718 let split_off_pane = self
4719 .find_pane_in_direction(direction, cx)
4720 .unwrap_or_else(|| self.active_pane.clone());
4721 let new_pane = self.add_pane(window, cx);
4722 self.center.split(&split_off_pane, &new_pane, direction, cx);
4723 new_pane
4724 }
4725 };
4726
4727 if action.clone {
4728 if self
4729 .active_pane
4730 .read(cx)
4731 .active_item()
4732 .is_some_and(|item| item.can_split(cx))
4733 {
4734 clone_active_item(
4735 self.database_id(),
4736 &self.active_pane,
4737 &destination,
4738 action.focus,
4739 window,
4740 cx,
4741 );
4742 return;
4743 }
4744 }
4745 move_active_item(
4746 &self.active_pane,
4747 &destination,
4748 action.focus,
4749 true,
4750 window,
4751 cx,
4752 )
4753 }
4754
4755 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4756 let panes = self.center.panes();
4757 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4758 let next_ix = (ix + 1) % panes.len();
4759 let next_pane = panes[next_ix].clone();
4760 window.focus(&next_pane.focus_handle(cx), cx);
4761 }
4762 }
4763
4764 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4765 let panes = self.center.panes();
4766 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4767 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4768 let prev_pane = panes[prev_ix].clone();
4769 window.focus(&prev_pane.focus_handle(cx), cx);
4770 }
4771 }
4772
4773 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4774 let last_pane = self.center.last_pane();
4775 window.focus(&last_pane.focus_handle(cx), cx);
4776 }
4777
4778 pub fn activate_pane_in_direction(
4779 &mut self,
4780 direction: SplitDirection,
4781 window: &mut Window,
4782 cx: &mut App,
4783 ) {
4784 use ActivateInDirectionTarget as Target;
4785 enum Origin {
4786 Sidebar,
4787 LeftDock,
4788 RightDock,
4789 BottomDock,
4790 Center,
4791 }
4792
4793 let origin: Origin = if self
4794 .sidebar_focus_handle
4795 .as_ref()
4796 .is_some_and(|h| h.contains_focused(window, cx))
4797 {
4798 Origin::Sidebar
4799 } else {
4800 [
4801 (&self.left_dock, Origin::LeftDock),
4802 (&self.right_dock, Origin::RightDock),
4803 (&self.bottom_dock, Origin::BottomDock),
4804 ]
4805 .into_iter()
4806 .find_map(|(dock, origin)| {
4807 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4808 Some(origin)
4809 } else {
4810 None
4811 }
4812 })
4813 .unwrap_or(Origin::Center)
4814 };
4815
4816 let get_last_active_pane = || {
4817 let pane = self
4818 .last_active_center_pane
4819 .clone()
4820 .unwrap_or_else(|| {
4821 self.panes
4822 .first()
4823 .expect("There must be an active pane")
4824 .downgrade()
4825 })
4826 .upgrade()?;
4827 (pane.read(cx).items_len() != 0).then_some(pane)
4828 };
4829
4830 let try_dock =
4831 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4832
4833 let sidebar_target = self
4834 .sidebar_focus_handle
4835 .as_ref()
4836 .map(|h| Target::Sidebar(h.clone()));
4837
4838 let target = match (origin, direction) {
4839 // From the sidebar, only Right navigates into the workspace.
4840 (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
4841 .or_else(|| get_last_active_pane().map(Target::Pane))
4842 .or_else(|| try_dock(&self.bottom_dock))
4843 .or_else(|| try_dock(&self.right_dock)),
4844
4845 (Origin::Sidebar, _) => None,
4846
4847 // We're in the center, so we first try to go to a different pane,
4848 // otherwise try to go to a dock.
4849 (Origin::Center, direction) => {
4850 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4851 Some(Target::Pane(pane))
4852 } else {
4853 match direction {
4854 SplitDirection::Up => None,
4855 SplitDirection::Down => try_dock(&self.bottom_dock),
4856 SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
4857 SplitDirection::Right => try_dock(&self.right_dock),
4858 }
4859 }
4860 }
4861
4862 (Origin::LeftDock, SplitDirection::Right) => {
4863 if let Some(last_active_pane) = get_last_active_pane() {
4864 Some(Target::Pane(last_active_pane))
4865 } else {
4866 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4867 }
4868 }
4869
4870 (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
4871
4872 (Origin::LeftDock, SplitDirection::Down)
4873 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4874
4875 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4876 (Origin::BottomDock, SplitDirection::Left) => {
4877 try_dock(&self.left_dock).or(sidebar_target)
4878 }
4879 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4880
4881 (Origin::RightDock, SplitDirection::Left) => {
4882 if let Some(last_active_pane) = get_last_active_pane() {
4883 Some(Target::Pane(last_active_pane))
4884 } else {
4885 try_dock(&self.bottom_dock)
4886 .or_else(|| try_dock(&self.left_dock))
4887 .or(sidebar_target)
4888 }
4889 }
4890
4891 _ => None,
4892 };
4893
4894 match target {
4895 Some(ActivateInDirectionTarget::Pane(pane)) => {
4896 let pane = pane.read(cx);
4897 if let Some(item) = pane.active_item() {
4898 item.item_focus_handle(cx).focus(window, cx);
4899 } else {
4900 log::error!(
4901 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4902 );
4903 }
4904 }
4905 Some(ActivateInDirectionTarget::Dock(dock)) => {
4906 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4907 window.defer(cx, move |window, cx| {
4908 let dock = dock.read(cx);
4909 if let Some(panel) = dock.active_panel() {
4910 panel.panel_focus_handle(cx).focus(window, cx);
4911 } else {
4912 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4913 }
4914 })
4915 }
4916 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4917 focus_handle.focus(window, cx);
4918 }
4919 None => {}
4920 }
4921 }
4922
4923 pub fn move_item_to_pane_in_direction(
4924 &mut self,
4925 action: &MoveItemToPaneInDirection,
4926 window: &mut Window,
4927 cx: &mut Context<Self>,
4928 ) {
4929 let destination = match self.find_pane_in_direction(action.direction, cx) {
4930 Some(destination) => destination,
4931 None => {
4932 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4933 return;
4934 }
4935 let new_pane = self.add_pane(window, cx);
4936 self.center
4937 .split(&self.active_pane, &new_pane, action.direction, cx);
4938 new_pane
4939 }
4940 };
4941
4942 if action.clone {
4943 if self
4944 .active_pane
4945 .read(cx)
4946 .active_item()
4947 .is_some_and(|item| item.can_split(cx))
4948 {
4949 clone_active_item(
4950 self.database_id(),
4951 &self.active_pane,
4952 &destination,
4953 action.focus,
4954 window,
4955 cx,
4956 );
4957 return;
4958 }
4959 }
4960 move_active_item(
4961 &self.active_pane,
4962 &destination,
4963 action.focus,
4964 true,
4965 window,
4966 cx,
4967 );
4968 }
4969
4970 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4971 self.center.bounding_box_for_pane(pane)
4972 }
4973
4974 pub fn find_pane_in_direction(
4975 &mut self,
4976 direction: SplitDirection,
4977 cx: &App,
4978 ) -> Option<Entity<Pane>> {
4979 self.center
4980 .find_pane_in_direction(&self.active_pane, direction, cx)
4981 .cloned()
4982 }
4983
4984 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4985 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4986 self.center.swap(&self.active_pane, &to, cx);
4987 cx.notify();
4988 }
4989 }
4990
4991 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4992 if self
4993 .center
4994 .move_to_border(&self.active_pane, direction, cx)
4995 .unwrap()
4996 {
4997 cx.notify();
4998 }
4999 }
5000
5001 pub fn resize_pane(
5002 &mut self,
5003 axis: gpui::Axis,
5004 amount: Pixels,
5005 window: &mut Window,
5006 cx: &mut Context<Self>,
5007 ) {
5008 let docks = self.all_docks();
5009 let active_dock = docks
5010 .into_iter()
5011 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
5012
5013 if let Some(dock_entity) = active_dock {
5014 let dock = dock_entity.read(cx);
5015 let Some(panel_size) = self.dock_size(&dock, window, cx) else {
5016 return;
5017 };
5018 match dock.position() {
5019 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
5020 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
5021 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
5022 }
5023 } else {
5024 self.center
5025 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
5026 }
5027 cx.notify();
5028 }
5029
5030 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
5031 self.center.reset_pane_sizes(cx);
5032 cx.notify();
5033 }
5034
5035 fn handle_pane_focused(
5036 &mut self,
5037 pane: Entity<Pane>,
5038 window: &mut Window,
5039 cx: &mut Context<Self>,
5040 ) {
5041 // This is explicitly hoisted out of the following check for pane identity as
5042 // terminal panel panes are not registered as a center panes.
5043 self.status_bar.update(cx, |status_bar, cx| {
5044 status_bar.set_active_pane(&pane, window, cx);
5045 });
5046 if self.active_pane != pane {
5047 self.set_active_pane(&pane, window, cx);
5048 }
5049
5050 if self.last_active_center_pane.is_none() {
5051 self.last_active_center_pane = Some(pane.downgrade());
5052 }
5053
5054 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
5055 // This prevents the dock from closing when focus events fire during window activation.
5056 // We also preserve any dock whose active panel itself has focus — this covers
5057 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
5058 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
5059 let dock_read = dock.read(cx);
5060 if let Some(panel) = dock_read.active_panel() {
5061 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
5062 || panel.panel_focus_handle(cx).contains_focused(window, cx)
5063 {
5064 return Some(dock_read.position());
5065 }
5066 }
5067 None
5068 });
5069
5070 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
5071 if pane.read(cx).is_zoomed() {
5072 self.zoomed = Some(pane.downgrade().into());
5073 } else {
5074 self.zoomed = None;
5075 }
5076 self.zoomed_position = None;
5077 cx.emit(Event::ZoomChanged);
5078 self.update_active_view_for_followers(window, cx);
5079 pane.update(cx, |pane, _| {
5080 pane.track_alternate_file_items();
5081 });
5082
5083 cx.notify();
5084 }
5085
5086 fn set_active_pane(
5087 &mut self,
5088 pane: &Entity<Pane>,
5089 window: &mut Window,
5090 cx: &mut Context<Self>,
5091 ) {
5092 self.active_pane = pane.clone();
5093 self.active_item_path_changed(true, window, cx);
5094 self.last_active_center_pane = Some(pane.downgrade());
5095 }
5096
5097 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5098 self.update_active_view_for_followers(window, cx);
5099 }
5100
5101 fn handle_pane_event(
5102 &mut self,
5103 pane: &Entity<Pane>,
5104 event: &pane::Event,
5105 window: &mut Window,
5106 cx: &mut Context<Self>,
5107 ) {
5108 let mut serialize_workspace = true;
5109 match event {
5110 pane::Event::AddItem { item } => {
5111 item.added_to_pane(self, pane.clone(), window, cx);
5112 cx.emit(Event::ItemAdded {
5113 item: item.boxed_clone(),
5114 });
5115 }
5116 pane::Event::Split { direction, mode } => {
5117 match mode {
5118 SplitMode::ClonePane => {
5119 self.split_and_clone(pane.clone(), *direction, window, cx)
5120 .detach();
5121 }
5122 SplitMode::EmptyPane => {
5123 self.split_pane(pane.clone(), *direction, window, cx);
5124 }
5125 SplitMode::MovePane => {
5126 self.split_and_move(pane.clone(), *direction, window, cx);
5127 }
5128 };
5129 }
5130 pane::Event::JoinIntoNext => {
5131 self.join_pane_into_next(pane.clone(), window, cx);
5132 }
5133 pane::Event::JoinAll => {
5134 self.join_all_panes(window, cx);
5135 }
5136 pane::Event::Remove { focus_on_pane } => {
5137 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
5138 }
5139 pane::Event::ActivateItem {
5140 local,
5141 focus_changed,
5142 } => {
5143 window.invalidate_character_coordinates();
5144
5145 pane.update(cx, |pane, _| {
5146 pane.track_alternate_file_items();
5147 });
5148 if *local {
5149 self.unfollow_in_pane(pane, window, cx);
5150 }
5151 serialize_workspace = *focus_changed || pane != self.active_pane();
5152 if pane == self.active_pane() {
5153 self.active_item_path_changed(*focus_changed, window, cx);
5154 self.update_active_view_for_followers(window, cx);
5155 } else if *local {
5156 self.set_active_pane(pane, window, cx);
5157 }
5158 }
5159 pane::Event::UserSavedItem { item, save_intent } => {
5160 cx.emit(Event::UserSavedItem {
5161 pane: pane.downgrade(),
5162 item: item.boxed_clone(),
5163 save_intent: *save_intent,
5164 });
5165 serialize_workspace = false;
5166 }
5167 pane::Event::ChangeItemTitle => {
5168 if *pane == self.active_pane {
5169 self.active_item_path_changed(false, window, cx);
5170 }
5171 serialize_workspace = false;
5172 }
5173 pane::Event::RemovedItem { item } => {
5174 cx.emit(Event::ActiveItemChanged);
5175 self.update_window_edited(window, cx);
5176 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
5177 && entry.get().entity_id() == pane.entity_id()
5178 {
5179 entry.remove();
5180 }
5181 cx.emit(Event::ItemRemoved {
5182 item_id: item.item_id(),
5183 });
5184 }
5185 pane::Event::Focus => {
5186 window.invalidate_character_coordinates();
5187 self.handle_pane_focused(pane.clone(), window, cx);
5188 }
5189 pane::Event::ZoomIn => {
5190 if *pane == self.active_pane {
5191 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
5192 if pane.read(cx).has_focus(window, cx) {
5193 self.zoomed = Some(pane.downgrade().into());
5194 self.zoomed_position = None;
5195 cx.emit(Event::ZoomChanged);
5196 }
5197 cx.notify();
5198 }
5199 }
5200 pane::Event::ZoomOut => {
5201 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
5202 if self.zoomed_position.is_none() {
5203 self.zoomed = None;
5204 cx.emit(Event::ZoomChanged);
5205 }
5206 cx.notify();
5207 }
5208 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
5209 }
5210
5211 if serialize_workspace {
5212 self.serialize_workspace(window, cx);
5213 }
5214 }
5215
5216 pub fn unfollow_in_pane(
5217 &mut self,
5218 pane: &Entity<Pane>,
5219 window: &mut Window,
5220 cx: &mut Context<Workspace>,
5221 ) -> Option<CollaboratorId> {
5222 let leader_id = self.leader_for_pane(pane)?;
5223 self.unfollow(leader_id, window, cx);
5224 Some(leader_id)
5225 }
5226
5227 pub fn split_pane(
5228 &mut self,
5229 pane_to_split: Entity<Pane>,
5230 split_direction: SplitDirection,
5231 window: &mut Window,
5232 cx: &mut Context<Self>,
5233 ) -> Entity<Pane> {
5234 let new_pane = self.add_pane(window, cx);
5235 self.center
5236 .split(&pane_to_split, &new_pane, split_direction, cx);
5237 cx.notify();
5238 new_pane
5239 }
5240
5241 pub fn split_and_move(
5242 &mut self,
5243 pane: Entity<Pane>,
5244 direction: SplitDirection,
5245 window: &mut Window,
5246 cx: &mut Context<Self>,
5247 ) {
5248 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
5249 return;
5250 };
5251 let new_pane = self.add_pane(window, cx);
5252 new_pane.update(cx, |pane, cx| {
5253 pane.add_item(item, true, true, None, window, cx)
5254 });
5255 self.center.split(&pane, &new_pane, direction, cx);
5256 cx.notify();
5257 }
5258
5259 pub fn split_and_clone(
5260 &mut self,
5261 pane: Entity<Pane>,
5262 direction: SplitDirection,
5263 window: &mut Window,
5264 cx: &mut Context<Self>,
5265 ) -> Task<Option<Entity<Pane>>> {
5266 let Some(item) = pane.read(cx).active_item() else {
5267 return Task::ready(None);
5268 };
5269 if !item.can_split(cx) {
5270 return Task::ready(None);
5271 }
5272 let task = item.clone_on_split(self.database_id(), window, cx);
5273 cx.spawn_in(window, async move |this, cx| {
5274 if let Some(clone) = task.await {
5275 this.update_in(cx, |this, window, cx| {
5276 let new_pane = this.add_pane(window, cx);
5277 let nav_history = pane.read(cx).fork_nav_history();
5278 new_pane.update(cx, |pane, cx| {
5279 pane.set_nav_history(nav_history, cx);
5280 pane.add_item(clone, true, true, None, window, cx)
5281 });
5282 this.center.split(&pane, &new_pane, direction, cx);
5283 cx.notify();
5284 new_pane
5285 })
5286 .ok()
5287 } else {
5288 None
5289 }
5290 })
5291 }
5292
5293 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5294 let active_item = self.active_pane.read(cx).active_item();
5295 for pane in &self.panes {
5296 join_pane_into_active(&self.active_pane, pane, window, cx);
5297 }
5298 if let Some(active_item) = active_item {
5299 self.activate_item(active_item.as_ref(), true, true, window, cx);
5300 }
5301 cx.notify();
5302 }
5303
5304 pub fn join_pane_into_next(
5305 &mut self,
5306 pane: Entity<Pane>,
5307 window: &mut Window,
5308 cx: &mut Context<Self>,
5309 ) {
5310 let next_pane = self
5311 .find_pane_in_direction(SplitDirection::Right, cx)
5312 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5313 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5314 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5315 let Some(next_pane) = next_pane else {
5316 return;
5317 };
5318 move_all_items(&pane, &next_pane, window, cx);
5319 cx.notify();
5320 }
5321
5322 fn remove_pane(
5323 &mut self,
5324 pane: Entity<Pane>,
5325 focus_on: Option<Entity<Pane>>,
5326 window: &mut Window,
5327 cx: &mut Context<Self>,
5328 ) {
5329 if self.center.remove(&pane, cx).unwrap() {
5330 self.force_remove_pane(&pane, &focus_on, window, cx);
5331 self.unfollow_in_pane(&pane, window, cx);
5332 self.last_leaders_by_pane.remove(&pane.downgrade());
5333 for removed_item in pane.read(cx).items() {
5334 self.panes_by_item.remove(&removed_item.item_id());
5335 }
5336
5337 cx.notify();
5338 } else {
5339 self.active_item_path_changed(true, window, cx);
5340 }
5341 cx.emit(Event::PaneRemoved);
5342 }
5343
5344 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5345 &mut self.panes
5346 }
5347
5348 pub fn panes(&self) -> &[Entity<Pane>] {
5349 &self.panes
5350 }
5351
5352 pub fn active_pane(&self) -> &Entity<Pane> {
5353 &self.active_pane
5354 }
5355
5356 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5357 for dock in self.all_docks() {
5358 if dock.focus_handle(cx).contains_focused(window, cx)
5359 && let Some(pane) = dock
5360 .read(cx)
5361 .active_panel()
5362 .and_then(|panel| panel.pane(cx))
5363 {
5364 return pane;
5365 }
5366 }
5367 self.active_pane().clone()
5368 }
5369
5370 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5371 self.find_pane_in_direction(SplitDirection::Right, cx)
5372 .unwrap_or_else(|| {
5373 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5374 })
5375 }
5376
5377 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5378 self.pane_for_item_id(handle.item_id())
5379 }
5380
5381 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5382 let weak_pane = self.panes_by_item.get(&item_id)?;
5383 weak_pane.upgrade()
5384 }
5385
5386 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5387 self.panes
5388 .iter()
5389 .find(|pane| pane.entity_id() == entity_id)
5390 .cloned()
5391 }
5392
5393 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5394 self.follower_states.retain(|leader_id, state| {
5395 if *leader_id == CollaboratorId::PeerId(peer_id) {
5396 for item in state.items_by_leader_view_id.values() {
5397 item.view.set_leader_id(None, window, cx);
5398 }
5399 false
5400 } else {
5401 true
5402 }
5403 });
5404 cx.notify();
5405 }
5406
5407 pub fn start_following(
5408 &mut self,
5409 leader_id: impl Into<CollaboratorId>,
5410 window: &mut Window,
5411 cx: &mut Context<Self>,
5412 ) -> Option<Task<Result<()>>> {
5413 let leader_id = leader_id.into();
5414 let pane = self.active_pane().clone();
5415
5416 self.last_leaders_by_pane
5417 .insert(pane.downgrade(), leader_id);
5418 self.unfollow(leader_id, window, cx);
5419 self.unfollow_in_pane(&pane, window, cx);
5420 self.follower_states.insert(
5421 leader_id,
5422 FollowerState {
5423 center_pane: pane.clone(),
5424 dock_pane: None,
5425 active_view_id: None,
5426 items_by_leader_view_id: Default::default(),
5427 },
5428 );
5429 cx.notify();
5430
5431 match leader_id {
5432 CollaboratorId::PeerId(leader_peer_id) => {
5433 let room_id = self.active_call()?.room_id(cx)?;
5434 let project_id = self.project.read(cx).remote_id();
5435 let request = self.app_state.client.request(proto::Follow {
5436 room_id,
5437 project_id,
5438 leader_id: Some(leader_peer_id),
5439 });
5440
5441 Some(cx.spawn_in(window, async move |this, cx| {
5442 let response = request.await?;
5443 this.update(cx, |this, _| {
5444 let state = this
5445 .follower_states
5446 .get_mut(&leader_id)
5447 .context("following interrupted")?;
5448 state.active_view_id = response
5449 .active_view
5450 .as_ref()
5451 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5452 anyhow::Ok(())
5453 })??;
5454 if let Some(view) = response.active_view {
5455 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5456 }
5457 this.update_in(cx, |this, window, cx| {
5458 this.leader_updated(leader_id, window, cx)
5459 })?;
5460 Ok(())
5461 }))
5462 }
5463 CollaboratorId::Agent => {
5464 self.leader_updated(leader_id, window, cx)?;
5465 Some(Task::ready(Ok(())))
5466 }
5467 }
5468 }
5469
5470 pub fn follow_next_collaborator(
5471 &mut self,
5472 _: &FollowNextCollaborator,
5473 window: &mut Window,
5474 cx: &mut Context<Self>,
5475 ) {
5476 let collaborators = self.project.read(cx).collaborators();
5477 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5478 let mut collaborators = collaborators.keys().copied();
5479 for peer_id in collaborators.by_ref() {
5480 if CollaboratorId::PeerId(peer_id) == leader_id {
5481 break;
5482 }
5483 }
5484 collaborators.next().map(CollaboratorId::PeerId)
5485 } else if let Some(last_leader_id) =
5486 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5487 {
5488 match last_leader_id {
5489 CollaboratorId::PeerId(peer_id) => {
5490 if collaborators.contains_key(peer_id) {
5491 Some(*last_leader_id)
5492 } else {
5493 None
5494 }
5495 }
5496 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5497 }
5498 } else {
5499 None
5500 };
5501
5502 let pane = self.active_pane.clone();
5503 let Some(leader_id) = next_leader_id.or_else(|| {
5504 Some(CollaboratorId::PeerId(
5505 collaborators.keys().copied().next()?,
5506 ))
5507 }) else {
5508 return;
5509 };
5510 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5511 return;
5512 }
5513 if let Some(task) = self.start_following(leader_id, window, cx) {
5514 task.detach_and_log_err(cx)
5515 }
5516 }
5517
5518 pub fn follow(
5519 &mut self,
5520 leader_id: impl Into<CollaboratorId>,
5521 window: &mut Window,
5522 cx: &mut Context<Self>,
5523 ) {
5524 let leader_id = leader_id.into();
5525
5526 if let CollaboratorId::PeerId(peer_id) = leader_id {
5527 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5528 return;
5529 };
5530 let Some(remote_participant) =
5531 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5532 else {
5533 return;
5534 };
5535
5536 let project = self.project.read(cx);
5537
5538 let other_project_id = match remote_participant.location {
5539 ParticipantLocation::External => None,
5540 ParticipantLocation::UnsharedProject => None,
5541 ParticipantLocation::SharedProject { project_id } => {
5542 if Some(project_id) == project.remote_id() {
5543 None
5544 } else {
5545 Some(project_id)
5546 }
5547 }
5548 };
5549
5550 // if they are active in another project, follow there.
5551 if let Some(project_id) = other_project_id {
5552 let app_state = self.app_state.clone();
5553 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5554 .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
5555 Some(format!("{error:#}"))
5556 });
5557 }
5558 }
5559
5560 // if you're already following, find the right pane and focus it.
5561 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5562 window.focus(&follower_state.pane().focus_handle(cx), cx);
5563
5564 return;
5565 }
5566
5567 // Otherwise, follow.
5568 if let Some(task) = self.start_following(leader_id, window, cx) {
5569 task.detach_and_log_err(cx)
5570 }
5571 }
5572
5573 pub fn unfollow(
5574 &mut self,
5575 leader_id: impl Into<CollaboratorId>,
5576 window: &mut Window,
5577 cx: &mut Context<Self>,
5578 ) -> Option<()> {
5579 cx.notify();
5580
5581 let leader_id = leader_id.into();
5582 let state = self.follower_states.remove(&leader_id)?;
5583 for (_, item) in state.items_by_leader_view_id {
5584 item.view.set_leader_id(None, window, cx);
5585 }
5586
5587 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5588 let project_id = self.project.read(cx).remote_id();
5589 let room_id = self.active_call()?.room_id(cx)?;
5590 self.app_state
5591 .client
5592 .send(proto::Unfollow {
5593 room_id,
5594 project_id,
5595 leader_id: Some(leader_peer_id),
5596 })
5597 .log_err();
5598 }
5599
5600 Some(())
5601 }
5602
5603 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5604 self.follower_states.contains_key(&id.into())
5605 }
5606
5607 fn active_item_path_changed(
5608 &mut self,
5609 focus_changed: bool,
5610 window: &mut Window,
5611 cx: &mut Context<Self>,
5612 ) {
5613 cx.emit(Event::ActiveItemChanged);
5614 let active_entry = self.active_project_path(cx);
5615 self.project.update(cx, |project, cx| {
5616 project.set_active_path(active_entry.clone(), cx)
5617 });
5618
5619 if focus_changed && let Some(project_path) = &active_entry {
5620 let git_store_entity = self.project.read(cx).git_store().clone();
5621 git_store_entity.update(cx, |git_store, cx| {
5622 git_store.set_active_repo_for_path(project_path, cx);
5623 });
5624 }
5625
5626 self.update_window_title(window, cx);
5627 }
5628
5629 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5630 let project = self.project().read(cx);
5631 let mut title = String::new();
5632
5633 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5634 let name = {
5635 let settings_location = SettingsLocation {
5636 worktree_id: worktree.read(cx).id(),
5637 path: RelPath::empty(),
5638 };
5639
5640 let settings = WorktreeSettings::get(Some(settings_location), cx);
5641 match &settings.project_name {
5642 Some(name) => name.as_str(),
5643 None => worktree.read(cx).root_name_str(),
5644 }
5645 };
5646 if i > 0 {
5647 title.push_str(", ");
5648 }
5649 title.push_str(name);
5650 }
5651
5652 if title.is_empty() {
5653 title = "empty project".to_string();
5654 }
5655
5656 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5657 let filename = path.path.file_name().or_else(|| {
5658 Some(
5659 project
5660 .worktree_for_id(path.worktree_id, cx)?
5661 .read(cx)
5662 .root_name_str(),
5663 )
5664 });
5665
5666 if let Some(filename) = filename {
5667 title.push_str(" — ");
5668 title.push_str(filename.as_ref());
5669 }
5670 }
5671
5672 if project.is_via_collab() {
5673 title.push_str(" ↙");
5674 } else if project.is_shared() {
5675 title.push_str(" ↗");
5676 }
5677
5678 if let Some(last_title) = self.last_window_title.as_ref()
5679 && &title == last_title
5680 {
5681 return;
5682 }
5683 window.set_window_title(&title);
5684 SystemWindowTabController::update_tab_title(
5685 cx,
5686 window.window_handle().window_id(),
5687 SharedString::from(&title),
5688 );
5689 self.last_window_title = Some(title);
5690 }
5691
5692 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5693 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5694 if is_edited != self.window_edited {
5695 self.window_edited = is_edited;
5696 window.set_window_edited(self.window_edited)
5697 }
5698 }
5699
5700 fn update_item_dirty_state(
5701 &mut self,
5702 item: &dyn ItemHandle,
5703 window: &mut Window,
5704 cx: &mut App,
5705 ) {
5706 let is_dirty = item.is_dirty(cx);
5707 let item_id = item.item_id();
5708 let was_dirty = self.dirty_items.contains_key(&item_id);
5709 if is_dirty == was_dirty {
5710 return;
5711 }
5712 if was_dirty {
5713 self.dirty_items.remove(&item_id);
5714 self.update_window_edited(window, cx);
5715 return;
5716 }
5717
5718 let workspace = self.weak_handle();
5719 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5720 return;
5721 };
5722 let on_release_callback = Box::new(move |cx: &mut App| {
5723 window_handle
5724 .update(cx, |_, window, cx| {
5725 workspace
5726 .update(cx, |workspace, cx| {
5727 workspace.dirty_items.remove(&item_id);
5728 workspace.update_window_edited(window, cx)
5729 })
5730 .ok();
5731 })
5732 .ok();
5733 });
5734
5735 let s = item.on_release(cx, on_release_callback);
5736 self.dirty_items.insert(item_id, s);
5737 self.update_window_edited(window, cx);
5738 }
5739
5740 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5741 if self.notifications.is_empty() {
5742 None
5743 } else {
5744 Some(
5745 div()
5746 .absolute()
5747 .right_3()
5748 .bottom_3()
5749 .w_112()
5750 .h_full()
5751 .flex()
5752 .flex_col()
5753 .justify_end()
5754 .gap_2()
5755 .children(
5756 self.notifications
5757 .iter()
5758 .map(|(_, notification)| notification.clone().into_any()),
5759 ),
5760 )
5761 }
5762 }
5763
5764 // RPC handlers
5765
5766 fn active_view_for_follower(
5767 &self,
5768 follower_project_id: Option<u64>,
5769 window: &mut Window,
5770 cx: &mut Context<Self>,
5771 ) -> Option<proto::View> {
5772 let (item, panel_id) = self.active_item_for_followers(window, cx);
5773 let item = item?;
5774 let leader_id = self
5775 .pane_for(&*item)
5776 .and_then(|pane| self.leader_for_pane(&pane));
5777 let leader_peer_id = match leader_id {
5778 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5779 Some(CollaboratorId::Agent) | None => None,
5780 };
5781
5782 let item_handle = item.to_followable_item_handle(cx)?;
5783 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5784 let variant = item_handle.to_state_proto(window, cx)?;
5785
5786 if item_handle.is_project_item(window, cx)
5787 && (follower_project_id.is_none()
5788 || follower_project_id != self.project.read(cx).remote_id())
5789 {
5790 return None;
5791 }
5792
5793 Some(proto::View {
5794 id: id.to_proto(),
5795 leader_id: leader_peer_id,
5796 variant: Some(variant),
5797 panel_id: panel_id.map(|id| id as i32),
5798 })
5799 }
5800
5801 fn handle_follow(
5802 &mut self,
5803 follower_project_id: Option<u64>,
5804 window: &mut Window,
5805 cx: &mut Context<Self>,
5806 ) -> proto::FollowResponse {
5807 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5808
5809 cx.notify();
5810 proto::FollowResponse {
5811 views: active_view.iter().cloned().collect(),
5812 active_view,
5813 }
5814 }
5815
5816 fn handle_update_followers(
5817 &mut self,
5818 leader_id: PeerId,
5819 message: proto::UpdateFollowers,
5820 _window: &mut Window,
5821 _cx: &mut Context<Self>,
5822 ) {
5823 self.leader_updates_tx
5824 .unbounded_send((leader_id, message))
5825 .ok();
5826 }
5827
5828 async fn process_leader_update(
5829 this: &WeakEntity<Self>,
5830 leader_id: PeerId,
5831 update: proto::UpdateFollowers,
5832 cx: &mut AsyncWindowContext,
5833 ) -> Result<()> {
5834 match update.variant.context("invalid update")? {
5835 proto::update_followers::Variant::CreateView(view) => {
5836 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5837 let should_add_view = this.update(cx, |this, _| {
5838 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5839 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5840 } else {
5841 anyhow::Ok(false)
5842 }
5843 })??;
5844
5845 if should_add_view {
5846 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5847 }
5848 }
5849 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5850 let should_add_view = this.update(cx, |this, _| {
5851 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5852 state.active_view_id = update_active_view
5853 .view
5854 .as_ref()
5855 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5856
5857 if state.active_view_id.is_some_and(|view_id| {
5858 !state.items_by_leader_view_id.contains_key(&view_id)
5859 }) {
5860 anyhow::Ok(true)
5861 } else {
5862 anyhow::Ok(false)
5863 }
5864 } else {
5865 anyhow::Ok(false)
5866 }
5867 })??;
5868
5869 if should_add_view && let Some(view) = update_active_view.view {
5870 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5871 }
5872 }
5873 proto::update_followers::Variant::UpdateView(update_view) => {
5874 let variant = update_view.variant.context("missing update view variant")?;
5875 let id = update_view.id.context("missing update view id")?;
5876 let mut tasks = Vec::new();
5877 this.update_in(cx, |this, window, cx| {
5878 let project = this.project.clone();
5879 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5880 let view_id = ViewId::from_proto(id.clone())?;
5881 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5882 tasks.push(item.view.apply_update_proto(
5883 &project,
5884 variant.clone(),
5885 window,
5886 cx,
5887 ));
5888 }
5889 }
5890 anyhow::Ok(())
5891 })??;
5892 try_join_all(tasks).await.log_err();
5893 }
5894 }
5895 this.update_in(cx, |this, window, cx| {
5896 this.leader_updated(leader_id, window, cx)
5897 })?;
5898 Ok(())
5899 }
5900
5901 async fn add_view_from_leader(
5902 this: WeakEntity<Self>,
5903 leader_id: PeerId,
5904 view: &proto::View,
5905 cx: &mut AsyncWindowContext,
5906 ) -> Result<()> {
5907 let this = this.upgrade().context("workspace dropped")?;
5908
5909 let Some(id) = view.id.clone() else {
5910 anyhow::bail!("no id for view");
5911 };
5912 let id = ViewId::from_proto(id)?;
5913 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5914
5915 let pane = this.update(cx, |this, _cx| {
5916 let state = this
5917 .follower_states
5918 .get(&leader_id.into())
5919 .context("stopped following")?;
5920 anyhow::Ok(state.pane().clone())
5921 })?;
5922 let existing_item = pane.update_in(cx, |pane, window, cx| {
5923 let client = this.read(cx).client().clone();
5924 pane.items().find_map(|item| {
5925 let item = item.to_followable_item_handle(cx)?;
5926 if item.remote_id(&client, window, cx) == Some(id) {
5927 Some(item)
5928 } else {
5929 None
5930 }
5931 })
5932 })?;
5933 let item = if let Some(existing_item) = existing_item {
5934 existing_item
5935 } else {
5936 let variant = view.variant.clone();
5937 anyhow::ensure!(variant.is_some(), "missing view variant");
5938
5939 let task = cx.update(|window, cx| {
5940 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5941 })?;
5942
5943 let Some(task) = task else {
5944 anyhow::bail!(
5945 "failed to construct view from leader (maybe from a different version of zed?)"
5946 );
5947 };
5948
5949 let mut new_item = task.await?;
5950 pane.update_in(cx, |pane, window, cx| {
5951 let mut item_to_remove = None;
5952 for (ix, item) in pane.items().enumerate() {
5953 if let Some(item) = item.to_followable_item_handle(cx) {
5954 match new_item.dedup(item.as_ref(), window, cx) {
5955 Some(item::Dedup::KeepExisting) => {
5956 new_item =
5957 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5958 break;
5959 }
5960 Some(item::Dedup::ReplaceExisting) => {
5961 item_to_remove = Some((ix, item.item_id()));
5962 break;
5963 }
5964 None => {}
5965 }
5966 }
5967 }
5968
5969 if let Some((ix, id)) = item_to_remove {
5970 pane.remove_item(id, false, false, window, cx);
5971 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5972 }
5973 })?;
5974
5975 new_item
5976 };
5977
5978 this.update_in(cx, |this, window, cx| {
5979 let state = this.follower_states.get_mut(&leader_id.into())?;
5980 item.set_leader_id(Some(leader_id.into()), window, cx);
5981 state.items_by_leader_view_id.insert(
5982 id,
5983 FollowerView {
5984 view: item,
5985 location: panel_id,
5986 },
5987 );
5988
5989 Some(())
5990 })
5991 .context("no follower state")?;
5992
5993 Ok(())
5994 }
5995
5996 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5997 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5998 return;
5999 };
6000
6001 if let Some(agent_location) = self.project.read(cx).agent_location() {
6002 let buffer_entity_id = agent_location.buffer.entity_id();
6003 let view_id = ViewId {
6004 creator: CollaboratorId::Agent,
6005 id: buffer_entity_id.as_u64(),
6006 };
6007 follower_state.active_view_id = Some(view_id);
6008
6009 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
6010 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
6011 hash_map::Entry::Vacant(entry) => {
6012 let existing_view =
6013 follower_state
6014 .center_pane
6015 .read(cx)
6016 .items()
6017 .find_map(|item| {
6018 let item = item.to_followable_item_handle(cx)?;
6019 if item.buffer_kind(cx) == ItemBufferKind::Singleton
6020 && item.project_item_model_ids(cx).as_slice()
6021 == [buffer_entity_id]
6022 {
6023 Some(item)
6024 } else {
6025 None
6026 }
6027 });
6028 let view = existing_view.or_else(|| {
6029 agent_location.buffer.upgrade().and_then(|buffer| {
6030 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
6031 registry.build_item(buffer, self.project.clone(), None, window, cx)
6032 })?
6033 .to_followable_item_handle(cx)
6034 })
6035 });
6036
6037 view.map(|view| {
6038 entry.insert(FollowerView {
6039 view,
6040 location: None,
6041 })
6042 })
6043 }
6044 };
6045
6046 if let Some(item) = item {
6047 item.view
6048 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
6049 item.view
6050 .update_agent_location(agent_location.position, window, cx);
6051 }
6052 } else {
6053 follower_state.active_view_id = None;
6054 }
6055
6056 self.leader_updated(CollaboratorId::Agent, window, cx);
6057 }
6058
6059 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
6060 let mut is_project_item = true;
6061 let mut update = proto::UpdateActiveView::default();
6062 if window.is_window_active() {
6063 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
6064
6065 if let Some(item) = active_item
6066 && item.item_focus_handle(cx).contains_focused(window, cx)
6067 {
6068 let leader_id = self
6069 .pane_for(&*item)
6070 .and_then(|pane| self.leader_for_pane(&pane));
6071 let leader_peer_id = match leader_id {
6072 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
6073 Some(CollaboratorId::Agent) | None => None,
6074 };
6075
6076 if let Some(item) = item.to_followable_item_handle(cx) {
6077 let id = item
6078 .remote_id(&self.app_state.client, window, cx)
6079 .map(|id| id.to_proto());
6080
6081 if let Some(id) = id
6082 && let Some(variant) = item.to_state_proto(window, cx)
6083 {
6084 let view = Some(proto::View {
6085 id,
6086 leader_id: leader_peer_id,
6087 variant: Some(variant),
6088 panel_id: panel_id.map(|id| id as i32),
6089 });
6090
6091 is_project_item = item.is_project_item(window, cx);
6092 update = proto::UpdateActiveView { view };
6093 };
6094 }
6095 }
6096 }
6097
6098 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
6099 if active_view_id != self.last_active_view_id.as_ref() {
6100 self.last_active_view_id = active_view_id.cloned();
6101 self.update_followers(
6102 is_project_item,
6103 proto::update_followers::Variant::UpdateActiveView(update),
6104 window,
6105 cx,
6106 );
6107 }
6108 }
6109
6110 fn active_item_for_followers(
6111 &self,
6112 window: &mut Window,
6113 cx: &mut App,
6114 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
6115 let mut active_item = None;
6116 let mut panel_id = None;
6117 for dock in self.all_docks() {
6118 if dock.focus_handle(cx).contains_focused(window, cx)
6119 && let Some(panel) = dock.read(cx).active_panel()
6120 && let Some(pane) = panel.pane(cx)
6121 && let Some(item) = pane.read(cx).active_item()
6122 {
6123 active_item = Some(item);
6124 panel_id = panel.remote_id();
6125 break;
6126 }
6127 }
6128
6129 if active_item.is_none() {
6130 active_item = self.active_pane().read(cx).active_item();
6131 }
6132 (active_item, panel_id)
6133 }
6134
6135 fn update_followers(
6136 &self,
6137 project_only: bool,
6138 update: proto::update_followers::Variant,
6139 _: &mut Window,
6140 cx: &mut App,
6141 ) -> Option<()> {
6142 // If this update only applies to for followers in the current project,
6143 // then skip it unless this project is shared. If it applies to all
6144 // followers, regardless of project, then set `project_id` to none,
6145 // indicating that it goes to all followers.
6146 let project_id = if project_only {
6147 Some(self.project.read(cx).remote_id()?)
6148 } else {
6149 None
6150 };
6151 self.app_state().workspace_store.update(cx, |store, cx| {
6152 store.update_followers(project_id, update, cx)
6153 })
6154 }
6155
6156 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
6157 self.follower_states.iter().find_map(|(leader_id, state)| {
6158 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
6159 Some(*leader_id)
6160 } else {
6161 None
6162 }
6163 })
6164 }
6165
6166 fn leader_updated(
6167 &mut self,
6168 leader_id: impl Into<CollaboratorId>,
6169 window: &mut Window,
6170 cx: &mut Context<Self>,
6171 ) -> Option<Box<dyn ItemHandle>> {
6172 cx.notify();
6173
6174 let leader_id = leader_id.into();
6175 let (panel_id, item) = match leader_id {
6176 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
6177 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
6178 };
6179
6180 let state = self.follower_states.get(&leader_id)?;
6181 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
6182 let pane;
6183 if let Some(panel_id) = panel_id {
6184 pane = self
6185 .activate_panel_for_proto_id(panel_id, window, cx)?
6186 .pane(cx)?;
6187 let state = self.follower_states.get_mut(&leader_id)?;
6188 state.dock_pane = Some(pane.clone());
6189 } else {
6190 pane = state.center_pane.clone();
6191 let state = self.follower_states.get_mut(&leader_id)?;
6192 if let Some(dock_pane) = state.dock_pane.take() {
6193 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
6194 }
6195 }
6196
6197 pane.update(cx, |pane, cx| {
6198 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
6199 if let Some(index) = pane.index_for_item(item.as_ref()) {
6200 pane.activate_item(index, false, false, window, cx);
6201 } else {
6202 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
6203 }
6204
6205 if focus_active_item {
6206 pane.focus_active_item(window, cx)
6207 }
6208 });
6209
6210 Some(item)
6211 }
6212
6213 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
6214 let state = self.follower_states.get(&CollaboratorId::Agent)?;
6215 let active_view_id = state.active_view_id?;
6216 Some(
6217 state
6218 .items_by_leader_view_id
6219 .get(&active_view_id)?
6220 .view
6221 .boxed_clone(),
6222 )
6223 }
6224
6225 fn active_item_for_peer(
6226 &self,
6227 peer_id: PeerId,
6228 window: &mut Window,
6229 cx: &mut Context<Self>,
6230 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
6231 let call = self.active_call()?;
6232 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
6233 let leader_in_this_app;
6234 let leader_in_this_project;
6235 match participant.location {
6236 ParticipantLocation::SharedProject { project_id } => {
6237 leader_in_this_app = true;
6238 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
6239 }
6240 ParticipantLocation::UnsharedProject => {
6241 leader_in_this_app = true;
6242 leader_in_this_project = false;
6243 }
6244 ParticipantLocation::External => {
6245 leader_in_this_app = false;
6246 leader_in_this_project = false;
6247 }
6248 };
6249 let state = self.follower_states.get(&peer_id.into())?;
6250 let mut item_to_activate = None;
6251 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
6252 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
6253 && (leader_in_this_project || !item.view.is_project_item(window, cx))
6254 {
6255 item_to_activate = Some((item.location, item.view.boxed_clone()));
6256 }
6257 } else if let Some(shared_screen) =
6258 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
6259 {
6260 item_to_activate = Some((None, Box::new(shared_screen)));
6261 }
6262 item_to_activate
6263 }
6264
6265 fn shared_screen_for_peer(
6266 &self,
6267 peer_id: PeerId,
6268 pane: &Entity<Pane>,
6269 window: &mut Window,
6270 cx: &mut App,
6271 ) -> Option<Entity<SharedScreen>> {
6272 self.active_call()?
6273 .create_shared_screen(peer_id, pane, window, cx)
6274 }
6275
6276 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6277 if window.is_window_active() {
6278 self.update_active_view_for_followers(window, cx);
6279
6280 if let Some(database_id) = self.database_id {
6281 let db = WorkspaceDb::global(cx);
6282 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6283 .detach();
6284 }
6285 } else {
6286 for pane in &self.panes {
6287 pane.update(cx, |pane, cx| {
6288 if let Some(item) = pane.active_item() {
6289 item.workspace_deactivated(window, cx);
6290 }
6291 for item in pane.items() {
6292 if matches!(
6293 item.workspace_settings(cx).autosave,
6294 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6295 ) {
6296 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6297 .detach_and_log_err(cx);
6298 }
6299 }
6300 });
6301 }
6302 }
6303 }
6304
6305 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6306 self.active_call.as_ref().map(|(call, _)| &*call.0)
6307 }
6308
6309 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6310 self.active_call.as_ref().map(|(call, _)| call.clone())
6311 }
6312
6313 fn on_active_call_event(
6314 &mut self,
6315 event: &ActiveCallEvent,
6316 window: &mut Window,
6317 cx: &mut Context<Self>,
6318 ) {
6319 match event {
6320 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6321 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6322 self.leader_updated(participant_id, window, cx);
6323 }
6324 }
6325 }
6326
6327 pub fn database_id(&self) -> Option<WorkspaceId> {
6328 self.database_id
6329 }
6330
6331 #[cfg(any(test, feature = "test-support"))]
6332 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6333 self.database_id = Some(id);
6334 }
6335
6336 pub fn session_id(&self) -> Option<String> {
6337 self.session_id.clone()
6338 }
6339
6340 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6341 let Some(display) = window.display(cx) else {
6342 return Task::ready(());
6343 };
6344 let Ok(display_uuid) = display.uuid() else {
6345 return Task::ready(());
6346 };
6347
6348 let window_bounds = window.inner_window_bounds();
6349 let database_id = self.database_id;
6350 let has_paths = !self.root_paths(cx).is_empty();
6351 let db = WorkspaceDb::global(cx);
6352 let kvp = db::kvp::KeyValueStore::global(cx);
6353
6354 cx.background_executor().spawn(async move {
6355 if !has_paths {
6356 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6357 .await
6358 .log_err();
6359 }
6360 if let Some(database_id) = database_id {
6361 db.set_window_open_status(
6362 database_id,
6363 SerializedWindowBounds(window_bounds),
6364 display_uuid,
6365 )
6366 .await
6367 .log_err();
6368 } else {
6369 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6370 .await
6371 .log_err();
6372 }
6373 })
6374 }
6375
6376 /// Bypass the 200ms serialization throttle and write workspace state to
6377 /// the DB immediately. Returns a task the caller can await to ensure the
6378 /// write completes. Used by the quit handler so the most recent state
6379 /// isn't lost to a pending throttle timer when the process exits.
6380 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6381 self._schedule_serialize_workspace.take();
6382 self._serialize_workspace_task.take();
6383 self.bounds_save_task_queued.take();
6384
6385 let bounds_task = self.save_window_bounds(window, cx);
6386 let serialize_task = self.serialize_workspace_internal(window, cx);
6387 cx.spawn(async move |_| {
6388 bounds_task.await;
6389 serialize_task.await;
6390 })
6391 }
6392
6393 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6394 let project = self.project().read(cx);
6395 project
6396 .visible_worktrees(cx)
6397 .map(|worktree| worktree.read(cx).abs_path())
6398 .collect::<Vec<_>>()
6399 }
6400
6401 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6402 match member {
6403 Member::Axis(PaneAxis { members, .. }) => {
6404 for child in members.iter() {
6405 self.remove_panes(child.clone(), window, cx)
6406 }
6407 }
6408 Member::Pane(pane) => {
6409 self.force_remove_pane(&pane, &None, window, cx);
6410 }
6411 }
6412 }
6413
6414 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6415 self.session_id.take();
6416 self.serialize_workspace_internal(window, cx)
6417 }
6418
6419 fn force_remove_pane(
6420 &mut self,
6421 pane: &Entity<Pane>,
6422 focus_on: &Option<Entity<Pane>>,
6423 window: &mut Window,
6424 cx: &mut Context<Workspace>,
6425 ) {
6426 self.panes.retain(|p| p != pane);
6427 if let Some(focus_on) = focus_on {
6428 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6429 } else if self.active_pane() == pane {
6430 self.panes
6431 .last()
6432 .unwrap()
6433 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6434 }
6435 if self.last_active_center_pane == Some(pane.downgrade()) {
6436 self.last_active_center_pane = None;
6437 }
6438 cx.notify();
6439 }
6440
6441 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6442 if self._schedule_serialize_workspace.is_none() {
6443 self._schedule_serialize_workspace =
6444 Some(cx.spawn_in(window, async move |this, cx| {
6445 cx.background_executor()
6446 .timer(SERIALIZATION_THROTTLE_TIME)
6447 .await;
6448 this.update_in(cx, |this, window, cx| {
6449 this._serialize_workspace_task =
6450 Some(this.serialize_workspace_internal(window, cx));
6451 this._schedule_serialize_workspace.take();
6452 })
6453 .log_err();
6454 }));
6455 }
6456 }
6457
6458 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6459 let Some(database_id) = self.database_id() else {
6460 return Task::ready(());
6461 };
6462
6463 fn serialize_pane_handle(
6464 pane_handle: &Entity<Pane>,
6465 window: &mut Window,
6466 cx: &mut App,
6467 ) -> SerializedPane {
6468 let (items, active, pinned_count) = {
6469 let pane = pane_handle.read(cx);
6470 let active_item_id = pane.active_item().map(|item| item.item_id());
6471 (
6472 pane.items()
6473 .filter_map(|handle| {
6474 let handle = handle.to_serializable_item_handle(cx)?;
6475
6476 Some(SerializedItem {
6477 kind: Arc::from(handle.serialized_item_kind()),
6478 item_id: handle.item_id().as_u64(),
6479 active: Some(handle.item_id()) == active_item_id,
6480 preview: pane.is_active_preview_item(handle.item_id()),
6481 })
6482 })
6483 .collect::<Vec<_>>(),
6484 pane.has_focus(window, cx),
6485 pane.pinned_count(),
6486 )
6487 };
6488
6489 SerializedPane::new(items, active, pinned_count)
6490 }
6491
6492 fn build_serialized_pane_group(
6493 pane_group: &Member,
6494 window: &mut Window,
6495 cx: &mut App,
6496 ) -> SerializedPaneGroup {
6497 match pane_group {
6498 Member::Axis(PaneAxis {
6499 axis,
6500 members,
6501 flexes,
6502 bounding_boxes: _,
6503 }) => SerializedPaneGroup::Group {
6504 axis: SerializedAxis(*axis),
6505 children: members
6506 .iter()
6507 .map(|member| build_serialized_pane_group(member, window, cx))
6508 .collect::<Vec<_>>(),
6509 flexes: Some(flexes.lock().clone()),
6510 },
6511 Member::Pane(pane_handle) => {
6512 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6513 }
6514 }
6515 }
6516
6517 fn build_serialized_docks(
6518 this: &Workspace,
6519 window: &mut Window,
6520 cx: &mut App,
6521 ) -> DockStructure {
6522 this.capture_dock_state(window, cx)
6523 }
6524
6525 match self.workspace_location(cx) {
6526 WorkspaceLocation::Location(location, paths) => {
6527 let breakpoints = self.project.update(cx, |project, cx| {
6528 project
6529 .breakpoint_store()
6530 .read(cx)
6531 .all_source_breakpoints(cx)
6532 });
6533 let user_toolchains = self
6534 .project
6535 .read(cx)
6536 .user_toolchains(cx)
6537 .unwrap_or_default();
6538
6539 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6540 let docks = build_serialized_docks(self, window, cx);
6541 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6542
6543 let serialized_workspace = SerializedWorkspace {
6544 id: database_id,
6545 location,
6546 paths,
6547 center_group,
6548 window_bounds,
6549 display: Default::default(),
6550 docks,
6551 centered_layout: self.centered_layout,
6552 session_id: self.session_id.clone(),
6553 breakpoints,
6554 window_id: Some(window.window_handle().window_id().as_u64()),
6555 user_toolchains,
6556 };
6557
6558 let db = WorkspaceDb::global(cx);
6559 window.spawn(cx, async move |_| {
6560 db.save_workspace(serialized_workspace).await;
6561 })
6562 }
6563 WorkspaceLocation::DetachFromSession => {
6564 let window_bounds = SerializedWindowBounds(window.window_bounds());
6565 let display = window.display(cx).and_then(|d| d.uuid().ok());
6566 // Save dock state for empty local workspaces
6567 let docks = build_serialized_docks(self, window, cx);
6568 let db = WorkspaceDb::global(cx);
6569 let kvp = db::kvp::KeyValueStore::global(cx);
6570 window.spawn(cx, async move |_| {
6571 db.set_window_open_status(
6572 database_id,
6573 window_bounds,
6574 display.unwrap_or_default(),
6575 )
6576 .await
6577 .log_err();
6578 db.set_session_id(database_id, None).await.log_err();
6579 persistence::write_default_dock_state(&kvp, docks)
6580 .await
6581 .log_err();
6582 })
6583 }
6584 WorkspaceLocation::None => {
6585 // Save dock state for empty non-local workspaces
6586 let docks = build_serialized_docks(self, window, cx);
6587 let kvp = db::kvp::KeyValueStore::global(cx);
6588 window.spawn(cx, async move |_| {
6589 persistence::write_default_dock_state(&kvp, docks)
6590 .await
6591 .log_err();
6592 })
6593 }
6594 }
6595 }
6596
6597 fn has_any_items_open(&self, cx: &App) -> bool {
6598 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6599 }
6600
6601 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6602 let paths = PathList::new(&self.root_paths(cx));
6603 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6604 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6605 } else if self.project.read(cx).is_local() {
6606 if !paths.is_empty() || self.has_any_items_open(cx) {
6607 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6608 } else {
6609 WorkspaceLocation::DetachFromSession
6610 }
6611 } else {
6612 WorkspaceLocation::None
6613 }
6614 }
6615
6616 fn update_history(&self, cx: &mut App) {
6617 let Some(id) = self.database_id() else {
6618 return;
6619 };
6620 if !self.project.read(cx).is_local() {
6621 return;
6622 }
6623 if let Some(manager) = HistoryManager::global(cx) {
6624 let paths = PathList::new(&self.root_paths(cx));
6625 manager.update(cx, |this, cx| {
6626 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6627 });
6628 }
6629 }
6630
6631 async fn serialize_items(
6632 this: &WeakEntity<Self>,
6633 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6634 cx: &mut AsyncWindowContext,
6635 ) -> Result<()> {
6636 const CHUNK_SIZE: usize = 200;
6637
6638 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6639
6640 while let Some(items_received) = serializable_items.next().await {
6641 let unique_items =
6642 items_received
6643 .into_iter()
6644 .fold(HashMap::default(), |mut acc, item| {
6645 acc.entry(item.item_id()).or_insert(item);
6646 acc
6647 });
6648
6649 // We use into_iter() here so that the references to the items are moved into
6650 // the tasks and not kept alive while we're sleeping.
6651 for (_, item) in unique_items.into_iter() {
6652 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6653 item.serialize(workspace, false, window, cx)
6654 }) {
6655 cx.background_spawn(async move { task.await.log_err() })
6656 .detach();
6657 }
6658 }
6659
6660 cx.background_executor()
6661 .timer(SERIALIZATION_THROTTLE_TIME)
6662 .await;
6663 }
6664
6665 Ok(())
6666 }
6667
6668 pub(crate) fn enqueue_item_serialization(
6669 &mut self,
6670 item: Box<dyn SerializableItemHandle>,
6671 ) -> Result<()> {
6672 self.serializable_items_tx
6673 .unbounded_send(item)
6674 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6675 }
6676
6677 pub(crate) fn load_workspace(
6678 serialized_workspace: SerializedWorkspace,
6679 paths_to_open: Vec<Option<ProjectPath>>,
6680 window: &mut Window,
6681 cx: &mut Context<Workspace>,
6682 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6683 cx.spawn_in(window, async move |workspace, cx| {
6684 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6685
6686 let mut center_group = None;
6687 let mut center_items = None;
6688
6689 // Traverse the splits tree and add to things
6690 if let Some((group, active_pane, items)) = serialized_workspace
6691 .center_group
6692 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6693 .await
6694 {
6695 center_items = Some(items);
6696 center_group = Some((group, active_pane))
6697 }
6698
6699 let mut items_by_project_path = HashMap::default();
6700 let mut item_ids_by_kind = HashMap::default();
6701 let mut all_deserialized_items = Vec::default();
6702 cx.update(|_, cx| {
6703 for item in center_items.unwrap_or_default().into_iter().flatten() {
6704 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6705 item_ids_by_kind
6706 .entry(serializable_item_handle.serialized_item_kind())
6707 .or_insert(Vec::new())
6708 .push(item.item_id().as_u64() as ItemId);
6709 }
6710
6711 if let Some(project_path) = item.project_path(cx) {
6712 items_by_project_path.insert(project_path, item.clone());
6713 }
6714 all_deserialized_items.push(item);
6715 }
6716 })?;
6717
6718 let opened_items = paths_to_open
6719 .into_iter()
6720 .map(|path_to_open| {
6721 path_to_open
6722 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6723 })
6724 .collect::<Vec<_>>();
6725
6726 // Remove old panes from workspace panes list
6727 workspace.update_in(cx, |workspace, window, cx| {
6728 if let Some((center_group, active_pane)) = center_group {
6729 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6730
6731 // Swap workspace center group
6732 workspace.center = PaneGroup::with_root(center_group);
6733 workspace.center.set_is_center(true);
6734 workspace.center.mark_positions(cx);
6735
6736 if let Some(active_pane) = active_pane {
6737 workspace.set_active_pane(&active_pane, window, cx);
6738 cx.focus_self(window);
6739 } else {
6740 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6741 }
6742 }
6743
6744 let docks = serialized_workspace.docks;
6745
6746 for (dock, serialized_dock) in [
6747 (&mut workspace.right_dock, docks.right),
6748 (&mut workspace.left_dock, docks.left),
6749 (&mut workspace.bottom_dock, docks.bottom),
6750 ]
6751 .iter_mut()
6752 {
6753 dock.update(cx, |dock, cx| {
6754 dock.serialized_dock = Some(serialized_dock.clone());
6755 dock.restore_state(window, cx);
6756 });
6757 }
6758
6759 cx.notify();
6760 })?;
6761
6762 let _ = project
6763 .update(cx, |project, cx| {
6764 project
6765 .breakpoint_store()
6766 .update(cx, |breakpoint_store, cx| {
6767 breakpoint_store
6768 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6769 })
6770 })
6771 .await;
6772
6773 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6774 // after loading the items, we might have different items and in order to avoid
6775 // the database filling up, we delete items that haven't been loaded now.
6776 //
6777 // The items that have been loaded, have been saved after they've been added to the workspace.
6778 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6779 item_ids_by_kind
6780 .into_iter()
6781 .map(|(item_kind, loaded_items)| {
6782 SerializableItemRegistry::cleanup(
6783 item_kind,
6784 serialized_workspace.id,
6785 loaded_items,
6786 window,
6787 cx,
6788 )
6789 .log_err()
6790 })
6791 .collect::<Vec<_>>()
6792 })?;
6793
6794 futures::future::join_all(clean_up_tasks).await;
6795
6796 workspace
6797 .update_in(cx, |workspace, window, cx| {
6798 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6799 workspace.serialize_workspace_internal(window, cx).detach();
6800
6801 // Ensure that we mark the window as edited if we did load dirty items
6802 workspace.update_window_edited(window, cx);
6803 })
6804 .ok();
6805
6806 Ok(opened_items)
6807 })
6808 }
6809
6810 pub fn key_context(&self, cx: &App) -> KeyContext {
6811 let mut context = KeyContext::new_with_defaults();
6812 context.add("Workspace");
6813 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6814 if let Some(status) = self
6815 .debugger_provider
6816 .as_ref()
6817 .and_then(|provider| provider.active_thread_state(cx))
6818 {
6819 match status {
6820 ThreadStatus::Running | ThreadStatus::Stepping => {
6821 context.add("debugger_running");
6822 }
6823 ThreadStatus::Stopped => context.add("debugger_stopped"),
6824 ThreadStatus::Exited | ThreadStatus::Ended => {}
6825 }
6826 }
6827
6828 if self.left_dock.read(cx).is_open() {
6829 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6830 context.set("left_dock", active_panel.panel_key());
6831 }
6832 }
6833
6834 if self.right_dock.read(cx).is_open() {
6835 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6836 context.set("right_dock", active_panel.panel_key());
6837 }
6838 }
6839
6840 if self.bottom_dock.read(cx).is_open() {
6841 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6842 context.set("bottom_dock", active_panel.panel_key());
6843 }
6844 }
6845
6846 context
6847 }
6848
6849 /// Multiworkspace uses this to add workspace action handling to itself
6850 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6851 self.add_workspace_actions_listeners(div, window, cx)
6852 .on_action(cx.listener(
6853 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6854 for action in &action_sequence.0 {
6855 window.dispatch_action(action.boxed_clone(), cx);
6856 }
6857 },
6858 ))
6859 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6860 .on_action(cx.listener(Self::close_all_items_and_panes))
6861 .on_action(cx.listener(Self::close_item_in_all_panes))
6862 .on_action(cx.listener(Self::save_all))
6863 .on_action(cx.listener(Self::send_keystrokes))
6864 .on_action(cx.listener(Self::add_folder_to_project))
6865 .on_action(cx.listener(Self::follow_next_collaborator))
6866 .on_action(cx.listener(Self::activate_pane_at_index))
6867 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6868 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6869 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6870 .on_action(cx.listener(Self::toggle_theme_mode))
6871 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6872 let pane = workspace.active_pane().clone();
6873 workspace.unfollow_in_pane(&pane, window, cx);
6874 }))
6875 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6876 workspace
6877 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6878 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6879 }))
6880 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6881 workspace
6882 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6883 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6884 }))
6885 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6886 workspace
6887 .save_active_item(SaveIntent::SaveAs, window, cx)
6888 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6889 }))
6890 .on_action(
6891 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6892 workspace.activate_previous_pane(window, cx)
6893 }),
6894 )
6895 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6896 workspace.activate_next_pane(window, cx)
6897 }))
6898 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6899 workspace.activate_last_pane(window, cx)
6900 }))
6901 .on_action(
6902 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6903 workspace.activate_next_window(cx)
6904 }),
6905 )
6906 .on_action(
6907 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6908 workspace.activate_previous_window(cx)
6909 }),
6910 )
6911 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6912 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6913 }))
6914 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6915 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6916 }))
6917 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6918 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6919 }))
6920 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6921 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6922 }))
6923 .on_action(cx.listener(
6924 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6925 workspace.move_item_to_pane_in_direction(action, window, cx)
6926 },
6927 ))
6928 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6929 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6930 }))
6931 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6932 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6933 }))
6934 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6935 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6936 }))
6937 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6938 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6939 }))
6940 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6941 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6942 SplitDirection::Down,
6943 SplitDirection::Up,
6944 SplitDirection::Right,
6945 SplitDirection::Left,
6946 ];
6947 for dir in DIRECTION_PRIORITY {
6948 if workspace.find_pane_in_direction(dir, cx).is_some() {
6949 workspace.swap_pane_in_direction(dir, cx);
6950 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6951 break;
6952 }
6953 }
6954 }))
6955 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6956 workspace.move_pane_to_border(SplitDirection::Left, cx)
6957 }))
6958 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6959 workspace.move_pane_to_border(SplitDirection::Right, cx)
6960 }))
6961 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6962 workspace.move_pane_to_border(SplitDirection::Up, cx)
6963 }))
6964 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6965 workspace.move_pane_to_border(SplitDirection::Down, cx)
6966 }))
6967 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6968 this.toggle_dock(DockPosition::Left, window, cx);
6969 }))
6970 .on_action(cx.listener(
6971 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6972 workspace.toggle_dock(DockPosition::Right, window, cx);
6973 },
6974 ))
6975 .on_action(cx.listener(
6976 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6977 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6978 },
6979 ))
6980 .on_action(cx.listener(
6981 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6982 if !workspace.close_active_dock(window, cx) {
6983 cx.propagate();
6984 }
6985 },
6986 ))
6987 .on_action(
6988 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6989 workspace.close_all_docks(window, cx);
6990 }),
6991 )
6992 .on_action(cx.listener(Self::toggle_all_docks))
6993 .on_action(cx.listener(
6994 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6995 workspace.clear_all_notifications(cx);
6996 },
6997 ))
6998 .on_action(cx.listener(
6999 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
7000 workspace.clear_navigation_history(window, cx);
7001 },
7002 ))
7003 .on_action(cx.listener(
7004 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
7005 if let Some((notification_id, _)) = workspace.notifications.pop() {
7006 workspace.suppress_notification(¬ification_id, cx);
7007 }
7008 },
7009 ))
7010 .on_action(cx.listener(
7011 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
7012 workspace.show_worktree_trust_security_modal(true, window, cx);
7013 },
7014 ))
7015 .on_action(
7016 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
7017 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
7018 trusted_worktrees.update(cx, |trusted_worktrees, _| {
7019 trusted_worktrees.clear_trusted_paths()
7020 });
7021 let db = WorkspaceDb::global(cx);
7022 cx.spawn(async move |_, cx| {
7023 if db.clear_trusted_worktrees().await.log_err().is_some() {
7024 cx.update(|cx| reload(cx));
7025 }
7026 })
7027 .detach();
7028 }
7029 }),
7030 )
7031 .on_action(cx.listener(
7032 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
7033 workspace.reopen_closed_item(window, cx).detach();
7034 },
7035 ))
7036 .on_action(cx.listener(
7037 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
7038 for dock in workspace.all_docks() {
7039 if dock.focus_handle(cx).contains_focused(window, cx) {
7040 let panel = dock.read(cx).active_panel().cloned();
7041 if let Some(panel) = panel {
7042 dock.update(cx, |dock, cx| {
7043 dock.set_panel_size_state(
7044 panel.as_ref(),
7045 dock::PanelSizeState::default(),
7046 cx,
7047 );
7048 });
7049 }
7050 return;
7051 }
7052 }
7053 },
7054 ))
7055 .on_action(cx.listener(
7056 |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
7057 for dock in workspace.all_docks() {
7058 let panel = dock.read(cx).visible_panel().cloned();
7059 if let Some(panel) = panel {
7060 dock.update(cx, |dock, cx| {
7061 dock.set_panel_size_state(
7062 panel.as_ref(),
7063 dock::PanelSizeState::default(),
7064 cx,
7065 );
7066 });
7067 }
7068 }
7069 },
7070 ))
7071 .on_action(cx.listener(
7072 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
7073 adjust_active_dock_size_by_px(
7074 px_with_ui_font_fallback(act.px, cx),
7075 workspace,
7076 window,
7077 cx,
7078 );
7079 },
7080 ))
7081 .on_action(cx.listener(
7082 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
7083 adjust_active_dock_size_by_px(
7084 px_with_ui_font_fallback(act.px, cx) * -1.,
7085 workspace,
7086 window,
7087 cx,
7088 );
7089 },
7090 ))
7091 .on_action(cx.listener(
7092 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
7093 adjust_open_docks_size_by_px(
7094 px_with_ui_font_fallback(act.px, cx),
7095 workspace,
7096 window,
7097 cx,
7098 );
7099 },
7100 ))
7101 .on_action(cx.listener(
7102 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
7103 adjust_open_docks_size_by_px(
7104 px_with_ui_font_fallback(act.px, cx) * -1.,
7105 workspace,
7106 window,
7107 cx,
7108 );
7109 },
7110 ))
7111 .on_action(cx.listener(Workspace::toggle_centered_layout))
7112 .on_action(cx.listener(
7113 |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
7114 if let Some(active_dock) = workspace.active_dock(window, cx) {
7115 let dock = active_dock.read(cx);
7116 if let Some(active_panel) = dock.active_panel() {
7117 if active_panel.pane(cx).is_none() {
7118 let mut recent_pane: Option<Entity<Pane>> = None;
7119 let mut recent_timestamp = 0;
7120 for pane_handle in workspace.panes() {
7121 let pane = pane_handle.read(cx);
7122 for entry in pane.activation_history() {
7123 if entry.timestamp > recent_timestamp {
7124 recent_timestamp = entry.timestamp;
7125 recent_pane = Some(pane_handle.clone());
7126 }
7127 }
7128 }
7129
7130 if let Some(pane) = recent_pane {
7131 let wrap_around = action.wrap_around;
7132 pane.update(cx, |pane, cx| {
7133 let current_index = pane.active_item_index();
7134 let items_len = pane.items_len();
7135 if items_len > 0 {
7136 let next_index = if current_index + 1 < items_len {
7137 current_index + 1
7138 } else if wrap_around {
7139 0
7140 } else {
7141 return;
7142 };
7143 pane.activate_item(
7144 next_index, false, false, window, cx,
7145 );
7146 }
7147 });
7148 return;
7149 }
7150 }
7151 }
7152 }
7153 cx.propagate();
7154 },
7155 ))
7156 .on_action(cx.listener(
7157 |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
7158 if let Some(active_dock) = workspace.active_dock(window, cx) {
7159 let dock = active_dock.read(cx);
7160 if let Some(active_panel) = dock.active_panel() {
7161 if active_panel.pane(cx).is_none() {
7162 let mut recent_pane: Option<Entity<Pane>> = None;
7163 let mut recent_timestamp = 0;
7164 for pane_handle in workspace.panes() {
7165 let pane = pane_handle.read(cx);
7166 for entry in pane.activation_history() {
7167 if entry.timestamp > recent_timestamp {
7168 recent_timestamp = entry.timestamp;
7169 recent_pane = Some(pane_handle.clone());
7170 }
7171 }
7172 }
7173
7174 if let Some(pane) = recent_pane {
7175 let wrap_around = action.wrap_around;
7176 pane.update(cx, |pane, cx| {
7177 let current_index = pane.active_item_index();
7178 let items_len = pane.items_len();
7179 if items_len > 0 {
7180 let prev_index = if current_index > 0 {
7181 current_index - 1
7182 } else if wrap_around {
7183 items_len.saturating_sub(1)
7184 } else {
7185 return;
7186 };
7187 pane.activate_item(
7188 prev_index, false, false, window, cx,
7189 );
7190 }
7191 });
7192 return;
7193 }
7194 }
7195 }
7196 }
7197 cx.propagate();
7198 },
7199 ))
7200 .on_action(cx.listener(
7201 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
7202 if let Some(active_dock) = workspace.active_dock(window, cx) {
7203 let dock = active_dock.read(cx);
7204 if let Some(active_panel) = dock.active_panel() {
7205 if active_panel.pane(cx).is_none() {
7206 let active_pane = workspace.active_pane().clone();
7207 active_pane.update(cx, |pane, cx| {
7208 pane.close_active_item(action, window, cx)
7209 .detach_and_log_err(cx);
7210 });
7211 return;
7212 }
7213 }
7214 }
7215 cx.propagate();
7216 },
7217 ))
7218 .on_action(
7219 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
7220 let pane = workspace.active_pane().clone();
7221 if let Some(item) = pane.read(cx).active_item() {
7222 item.toggle_read_only(window, cx);
7223 }
7224 }),
7225 )
7226 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
7227 workspace.focus_center_pane(window, cx);
7228 }))
7229 .on_action(cx.listener(Workspace::cancel))
7230 }
7231
7232 #[cfg(any(test, feature = "test-support"))]
7233 pub fn set_random_database_id(&mut self) {
7234 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
7235 }
7236
7237 #[cfg(any(test, feature = "test-support"))]
7238 pub(crate) fn test_new(
7239 project: Entity<Project>,
7240 window: &mut Window,
7241 cx: &mut Context<Self>,
7242 ) -> Self {
7243 use node_runtime::NodeRuntime;
7244 use session::Session;
7245
7246 let client = project.read(cx).client();
7247 let user_store = project.read(cx).user_store();
7248 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
7249 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
7250 window.activate_window();
7251 let app_state = Arc::new(AppState {
7252 languages: project.read(cx).languages().clone(),
7253 workspace_store,
7254 client,
7255 user_store,
7256 fs: project.read(cx).fs().clone(),
7257 build_window_options: |_, _| Default::default(),
7258 node_runtime: NodeRuntime::unavailable(),
7259 session,
7260 });
7261 let workspace = Self::new(Default::default(), project, app_state, window, cx);
7262 workspace
7263 .active_pane
7264 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
7265 workspace
7266 }
7267
7268 pub fn register_action<A: Action>(
7269 &mut self,
7270 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
7271 ) -> &mut Self {
7272 let callback = Arc::new(callback);
7273
7274 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
7275 let callback = callback.clone();
7276 div.on_action(cx.listener(move |workspace, event, window, cx| {
7277 (callback)(workspace, event, window, cx)
7278 }))
7279 }));
7280 self
7281 }
7282 pub fn register_action_renderer(
7283 &mut self,
7284 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
7285 ) -> &mut Self {
7286 self.workspace_actions.push(Box::new(callback));
7287 self
7288 }
7289
7290 fn add_workspace_actions_listeners(
7291 &self,
7292 mut div: Div,
7293 window: &mut Window,
7294 cx: &mut Context<Self>,
7295 ) -> Div {
7296 for action in self.workspace_actions.iter() {
7297 div = (action)(div, self, window, cx)
7298 }
7299 div
7300 }
7301
7302 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7303 self.modal_layer.read(cx).has_active_modal()
7304 }
7305
7306 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7307 self.modal_layer
7308 .read(cx)
7309 .is_active_modal_command_palette(cx)
7310 }
7311
7312 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7313 self.modal_layer.read(cx).active_modal()
7314 }
7315
7316 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7317 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7318 /// If no modal is active, the new modal will be shown.
7319 ///
7320 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7321 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7322 /// will not be shown.
7323 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7324 where
7325 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7326 {
7327 self.modal_layer.update(cx, |modal_layer, cx| {
7328 modal_layer.toggle_modal(window, cx, build)
7329 })
7330 }
7331
7332 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7333 self.modal_layer
7334 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7335 }
7336
7337 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7338 self.toast_layer
7339 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7340 }
7341
7342 pub fn toggle_centered_layout(
7343 &mut self,
7344 _: &ToggleCenteredLayout,
7345 _: &mut Window,
7346 cx: &mut Context<Self>,
7347 ) {
7348 self.centered_layout = !self.centered_layout;
7349 if let Some(database_id) = self.database_id() {
7350 let db = WorkspaceDb::global(cx);
7351 let centered_layout = self.centered_layout;
7352 cx.background_spawn(async move {
7353 db.set_centered_layout(database_id, centered_layout).await
7354 })
7355 .detach_and_log_err(cx);
7356 }
7357 cx.notify();
7358 }
7359
7360 fn adjust_padding(padding: Option<f32>) -> f32 {
7361 padding
7362 .unwrap_or(CenteredPaddingSettings::default().0)
7363 .clamp(
7364 CenteredPaddingSettings::MIN_PADDING,
7365 CenteredPaddingSettings::MAX_PADDING,
7366 )
7367 }
7368
7369 fn render_dock(
7370 &self,
7371 position: DockPosition,
7372 dock: &Entity<Dock>,
7373 window: &mut Window,
7374 cx: &mut App,
7375 ) -> Option<Div> {
7376 if self.zoomed_position == Some(position) {
7377 return None;
7378 }
7379
7380 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7381 let pane = panel.pane(cx)?;
7382 let follower_states = &self.follower_states;
7383 leader_border_for_pane(follower_states, &pane, window, cx)
7384 });
7385
7386 let mut container = div()
7387 .flex()
7388 .overflow_hidden()
7389 .flex_none()
7390 .child(dock.clone())
7391 .children(leader_border);
7392
7393 // Apply sizing only when the dock is open. When closed the dock is still
7394 // included in the element tree so its focus handle remains mounted — without
7395 // this, toggle_panel_focus cannot focus the panel when the dock is closed.
7396 let dock = dock.read(cx);
7397 if let Some(panel) = dock.visible_panel() {
7398 let size_state = dock.stored_panel_size_state(panel.as_ref());
7399 if position.axis() == Axis::Horizontal {
7400 let use_flexible = panel.has_flexible_size(window, cx);
7401 let flex_grow = if use_flexible {
7402 size_state
7403 .and_then(|state| state.flex)
7404 .or_else(|| self.default_dock_flex(position))
7405 } else {
7406 None
7407 };
7408 if let Some(grow) = flex_grow {
7409 let grow = grow.max(0.001);
7410 let style = container.style();
7411 style.flex_grow = Some(grow);
7412 style.flex_shrink = Some(1.0);
7413 style.flex_basis = Some(relative(0.).into());
7414 } else {
7415 let size = size_state
7416 .and_then(|state| state.size)
7417 .unwrap_or_else(|| panel.default_size(window, cx));
7418 container = container.w(size);
7419 }
7420 } else {
7421 let size = size_state
7422 .and_then(|state| state.size)
7423 .unwrap_or_else(|| panel.default_size(window, cx));
7424 container = container.h(size);
7425 }
7426 }
7427
7428 Some(container)
7429 }
7430
7431 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7432 window
7433 .root::<MultiWorkspace>()
7434 .flatten()
7435 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7436 }
7437
7438 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7439 self.zoomed.as_ref()
7440 }
7441
7442 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7443 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7444 return;
7445 };
7446 let windows = cx.windows();
7447 let next_window =
7448 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7449 || {
7450 windows
7451 .iter()
7452 .cycle()
7453 .skip_while(|window| window.window_id() != current_window_id)
7454 .nth(1)
7455 },
7456 );
7457
7458 if let Some(window) = next_window {
7459 window
7460 .update(cx, |_, window, _| window.activate_window())
7461 .ok();
7462 }
7463 }
7464
7465 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7466 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7467 return;
7468 };
7469 let windows = cx.windows();
7470 let prev_window =
7471 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7472 || {
7473 windows
7474 .iter()
7475 .rev()
7476 .cycle()
7477 .skip_while(|window| window.window_id() != current_window_id)
7478 .nth(1)
7479 },
7480 );
7481
7482 if let Some(window) = prev_window {
7483 window
7484 .update(cx, |_, window, _| window.activate_window())
7485 .ok();
7486 }
7487 }
7488
7489 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7490 if cx.stop_active_drag(window) {
7491 } else if let Some((notification_id, _)) = self.notifications.pop() {
7492 dismiss_app_notification(¬ification_id, cx);
7493 } else {
7494 cx.propagate();
7495 }
7496 }
7497
7498 fn resize_dock(
7499 &mut self,
7500 dock_pos: DockPosition,
7501 new_size: Pixels,
7502 window: &mut Window,
7503 cx: &mut Context<Self>,
7504 ) {
7505 match dock_pos {
7506 DockPosition::Left => self.resize_left_dock(new_size, window, cx),
7507 DockPosition::Right => self.resize_right_dock(new_size, window, cx),
7508 DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
7509 }
7510 }
7511
7512 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7513 let workspace_width = self.bounds.size.width;
7514 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7515
7516 self.right_dock.read_with(cx, |right_dock, cx| {
7517 let right_dock_size = right_dock
7518 .stored_active_panel_size(window, cx)
7519 .unwrap_or(Pixels::ZERO);
7520 if right_dock_size + size > workspace_width {
7521 size = workspace_width - right_dock_size
7522 }
7523 });
7524
7525 let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
7526 self.left_dock.update(cx, |left_dock, cx| {
7527 if WorkspaceSettings::get_global(cx)
7528 .resize_all_panels_in_dock
7529 .contains(&DockPosition::Left)
7530 {
7531 left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7532 } else {
7533 left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7534 }
7535 });
7536 }
7537
7538 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7539 let workspace_width = self.bounds.size.width;
7540 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7541 self.left_dock.read_with(cx, |left_dock, cx| {
7542 let left_dock_size = left_dock
7543 .stored_active_panel_size(window, cx)
7544 .unwrap_or(Pixels::ZERO);
7545 if left_dock_size + size > workspace_width {
7546 size = workspace_width - left_dock_size
7547 }
7548 });
7549 let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
7550 self.right_dock.update(cx, |right_dock, cx| {
7551 if WorkspaceSettings::get_global(cx)
7552 .resize_all_panels_in_dock
7553 .contains(&DockPosition::Right)
7554 {
7555 right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7556 } else {
7557 right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7558 }
7559 });
7560 }
7561
7562 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7563 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7564 self.bottom_dock.update(cx, |bottom_dock, cx| {
7565 if WorkspaceSettings::get_global(cx)
7566 .resize_all_panels_in_dock
7567 .contains(&DockPosition::Bottom)
7568 {
7569 bottom_dock.resize_all_panels(Some(size), None, window, cx);
7570 } else {
7571 bottom_dock.resize_active_panel(Some(size), None, window, cx);
7572 }
7573 });
7574 }
7575
7576 fn toggle_edit_predictions_all_files(
7577 &mut self,
7578 _: &ToggleEditPrediction,
7579 _window: &mut Window,
7580 cx: &mut Context<Self>,
7581 ) {
7582 let fs = self.project().read(cx).fs().clone();
7583 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7584 update_settings_file(fs, cx, move |file, _| {
7585 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7586 });
7587 }
7588
7589 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7590 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7591 let next_mode = match current_mode {
7592 Some(theme_settings::ThemeAppearanceMode::Light) => {
7593 theme_settings::ThemeAppearanceMode::Dark
7594 }
7595 Some(theme_settings::ThemeAppearanceMode::Dark) => {
7596 theme_settings::ThemeAppearanceMode::Light
7597 }
7598 Some(theme_settings::ThemeAppearanceMode::System) | None => {
7599 match cx.theme().appearance() {
7600 theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
7601 theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
7602 }
7603 }
7604 };
7605
7606 let fs = self.project().read(cx).fs().clone();
7607 settings::update_settings_file(fs, cx, move |settings, _cx| {
7608 theme_settings::set_mode(settings, next_mode);
7609 });
7610 }
7611
7612 pub fn show_worktree_trust_security_modal(
7613 &mut self,
7614 toggle: bool,
7615 window: &mut Window,
7616 cx: &mut Context<Self>,
7617 ) {
7618 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7619 if toggle {
7620 security_modal.update(cx, |security_modal, cx| {
7621 security_modal.dismiss(cx);
7622 })
7623 } else {
7624 security_modal.update(cx, |security_modal, cx| {
7625 security_modal.refresh_restricted_paths(cx);
7626 });
7627 }
7628 } else {
7629 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7630 .map(|trusted_worktrees| {
7631 trusted_worktrees
7632 .read(cx)
7633 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7634 })
7635 .unwrap_or(false);
7636 if has_restricted_worktrees {
7637 let project = self.project().read(cx);
7638 let remote_host = project
7639 .remote_connection_options(cx)
7640 .map(RemoteHostLocation::from);
7641 let worktree_store = project.worktree_store().downgrade();
7642 self.toggle_modal(window, cx, |_, cx| {
7643 SecurityModal::new(worktree_store, remote_host, cx)
7644 });
7645 }
7646 }
7647 }
7648}
7649
7650pub trait AnyActiveCall {
7651 fn entity(&self) -> AnyEntity;
7652 fn is_in_room(&self, _: &App) -> bool;
7653 fn room_id(&self, _: &App) -> Option<u64>;
7654 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7655 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7656 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7657 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7658 fn is_sharing_project(&self, _: &App) -> bool;
7659 fn has_remote_participants(&self, _: &App) -> bool;
7660 fn local_participant_is_guest(&self, _: &App) -> bool;
7661 fn client(&self, _: &App) -> Arc<Client>;
7662 fn share_on_join(&self, _: &App) -> bool;
7663 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7664 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7665 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7666 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7667 fn join_project(
7668 &self,
7669 _: u64,
7670 _: Arc<LanguageRegistry>,
7671 _: Arc<dyn Fs>,
7672 _: &mut App,
7673 ) -> Task<Result<Entity<Project>>>;
7674 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7675 fn subscribe(
7676 &self,
7677 _: &mut Window,
7678 _: &mut Context<Workspace>,
7679 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7680 ) -> Subscription;
7681 fn create_shared_screen(
7682 &self,
7683 _: PeerId,
7684 _: &Entity<Pane>,
7685 _: &mut Window,
7686 _: &mut App,
7687 ) -> Option<Entity<SharedScreen>>;
7688}
7689
7690#[derive(Clone)]
7691pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7692impl Global for GlobalAnyActiveCall {}
7693
7694impl GlobalAnyActiveCall {
7695 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7696 cx.try_global()
7697 }
7698
7699 pub(crate) fn global(cx: &App) -> &Self {
7700 cx.global()
7701 }
7702}
7703
7704pub fn merge_conflict_notification_id() -> NotificationId {
7705 struct MergeConflictNotification;
7706 NotificationId::unique::<MergeConflictNotification>()
7707}
7708
7709/// Workspace-local view of a remote participant's location.
7710#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7711pub enum ParticipantLocation {
7712 SharedProject { project_id: u64 },
7713 UnsharedProject,
7714 External,
7715}
7716
7717impl ParticipantLocation {
7718 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7719 match location
7720 .and_then(|l| l.variant)
7721 .context("participant location was not provided")?
7722 {
7723 proto::participant_location::Variant::SharedProject(project) => {
7724 Ok(Self::SharedProject {
7725 project_id: project.id,
7726 })
7727 }
7728 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7729 proto::participant_location::Variant::External(_) => Ok(Self::External),
7730 }
7731 }
7732}
7733/// Workspace-local view of a remote collaborator's state.
7734/// This is the subset of `call::RemoteParticipant` that workspace needs.
7735#[derive(Clone)]
7736pub struct RemoteCollaborator {
7737 pub user: Arc<User>,
7738 pub peer_id: PeerId,
7739 pub location: ParticipantLocation,
7740 pub participant_index: ParticipantIndex,
7741}
7742
7743pub enum ActiveCallEvent {
7744 ParticipantLocationChanged { participant_id: PeerId },
7745 RemoteVideoTracksChanged { participant_id: PeerId },
7746}
7747
7748fn leader_border_for_pane(
7749 follower_states: &HashMap<CollaboratorId, FollowerState>,
7750 pane: &Entity<Pane>,
7751 _: &Window,
7752 cx: &App,
7753) -> Option<Div> {
7754 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7755 if state.pane() == pane {
7756 Some((*leader_id, state))
7757 } else {
7758 None
7759 }
7760 })?;
7761
7762 let mut leader_color = match leader_id {
7763 CollaboratorId::PeerId(leader_peer_id) => {
7764 let leader = GlobalAnyActiveCall::try_global(cx)?
7765 .0
7766 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7767
7768 cx.theme()
7769 .players()
7770 .color_for_participant(leader.participant_index.0)
7771 .cursor
7772 }
7773 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7774 };
7775 leader_color.fade_out(0.3);
7776 Some(
7777 div()
7778 .absolute()
7779 .size_full()
7780 .left_0()
7781 .top_0()
7782 .border_2()
7783 .border_color(leader_color),
7784 )
7785}
7786
7787fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7788 ZED_WINDOW_POSITION
7789 .zip(*ZED_WINDOW_SIZE)
7790 .map(|(position, size)| Bounds {
7791 origin: position,
7792 size,
7793 })
7794}
7795
7796fn open_items(
7797 serialized_workspace: Option<SerializedWorkspace>,
7798 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7799 window: &mut Window,
7800 cx: &mut Context<Workspace>,
7801) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7802 let restored_items = serialized_workspace.map(|serialized_workspace| {
7803 Workspace::load_workspace(
7804 serialized_workspace,
7805 project_paths_to_open
7806 .iter()
7807 .map(|(_, project_path)| project_path)
7808 .cloned()
7809 .collect(),
7810 window,
7811 cx,
7812 )
7813 });
7814
7815 cx.spawn_in(window, async move |workspace, cx| {
7816 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7817
7818 if let Some(restored_items) = restored_items {
7819 let restored_items = restored_items.await?;
7820
7821 let restored_project_paths = restored_items
7822 .iter()
7823 .filter_map(|item| {
7824 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7825 .ok()
7826 .flatten()
7827 })
7828 .collect::<HashSet<_>>();
7829
7830 for restored_item in restored_items {
7831 opened_items.push(restored_item.map(Ok));
7832 }
7833
7834 project_paths_to_open
7835 .iter_mut()
7836 .for_each(|(_, project_path)| {
7837 if let Some(project_path_to_open) = project_path
7838 && restored_project_paths.contains(project_path_to_open)
7839 {
7840 *project_path = None;
7841 }
7842 });
7843 } else {
7844 for _ in 0..project_paths_to_open.len() {
7845 opened_items.push(None);
7846 }
7847 }
7848 assert!(opened_items.len() == project_paths_to_open.len());
7849
7850 let tasks =
7851 project_paths_to_open
7852 .into_iter()
7853 .enumerate()
7854 .map(|(ix, (abs_path, project_path))| {
7855 let workspace = workspace.clone();
7856 cx.spawn(async move |cx| {
7857 let file_project_path = project_path?;
7858 let abs_path_task = workspace.update(cx, |workspace, cx| {
7859 workspace.project().update(cx, |project, cx| {
7860 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7861 })
7862 });
7863
7864 // We only want to open file paths here. If one of the items
7865 // here is a directory, it was already opened further above
7866 // with a `find_or_create_worktree`.
7867 if let Ok(task) = abs_path_task
7868 && task.await.is_none_or(|p| p.is_file())
7869 {
7870 return Some((
7871 ix,
7872 workspace
7873 .update_in(cx, |workspace, window, cx| {
7874 workspace.open_path(
7875 file_project_path,
7876 None,
7877 true,
7878 window,
7879 cx,
7880 )
7881 })
7882 .log_err()?
7883 .await,
7884 ));
7885 }
7886 None
7887 })
7888 });
7889
7890 let tasks = tasks.collect::<Vec<_>>();
7891
7892 let tasks = futures::future::join_all(tasks);
7893 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7894 opened_items[ix] = Some(path_open_result);
7895 }
7896
7897 Ok(opened_items)
7898 })
7899}
7900
7901#[derive(Clone)]
7902enum ActivateInDirectionTarget {
7903 Pane(Entity<Pane>),
7904 Dock(Entity<Dock>),
7905 Sidebar(FocusHandle),
7906}
7907
7908fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7909 window
7910 .update(cx, |multi_workspace, _, cx| {
7911 let workspace = multi_workspace.workspace().clone();
7912 workspace.update(cx, |workspace, cx| {
7913 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7914 struct DatabaseFailedNotification;
7915
7916 workspace.show_notification(
7917 NotificationId::unique::<DatabaseFailedNotification>(),
7918 cx,
7919 |cx| {
7920 cx.new(|cx| {
7921 MessageNotification::new("Failed to load the database file.", cx)
7922 .primary_message("File an Issue")
7923 .primary_icon(IconName::Plus)
7924 .primary_on_click(|window, cx| {
7925 window.dispatch_action(Box::new(FileBugReport), cx)
7926 })
7927 })
7928 },
7929 );
7930 }
7931 });
7932 })
7933 .log_err();
7934}
7935
7936fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7937 if val == 0 {
7938 ThemeSettings::get_global(cx).ui_font_size(cx)
7939 } else {
7940 px(val as f32)
7941 }
7942}
7943
7944fn adjust_active_dock_size_by_px(
7945 px: Pixels,
7946 workspace: &mut Workspace,
7947 window: &mut Window,
7948 cx: &mut Context<Workspace>,
7949) {
7950 let Some(active_dock) = workspace
7951 .all_docks()
7952 .into_iter()
7953 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7954 else {
7955 return;
7956 };
7957 let dock = active_dock.read(cx);
7958 let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
7959 return;
7960 };
7961 workspace.resize_dock(dock.position(), panel_size + px, window, cx);
7962}
7963
7964fn adjust_open_docks_size_by_px(
7965 px: Pixels,
7966 workspace: &mut Workspace,
7967 window: &mut Window,
7968 cx: &mut Context<Workspace>,
7969) {
7970 let docks = workspace
7971 .all_docks()
7972 .into_iter()
7973 .filter_map(|dock_entity| {
7974 let dock = dock_entity.read(cx);
7975 if dock.is_open() {
7976 let dock_pos = dock.position();
7977 let panel_size = workspace.dock_size(&dock, window, cx)?;
7978 Some((dock_pos, panel_size + px))
7979 } else {
7980 None
7981 }
7982 })
7983 .collect::<Vec<_>>();
7984
7985 for (position, new_size) in docks {
7986 workspace.resize_dock(position, new_size, window, cx);
7987 }
7988}
7989
7990impl Focusable for Workspace {
7991 fn focus_handle(&self, cx: &App) -> FocusHandle {
7992 self.active_pane.focus_handle(cx)
7993 }
7994}
7995
7996#[derive(Clone)]
7997struct DraggedDock(DockPosition);
7998
7999impl Render for DraggedDock {
8000 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8001 gpui::Empty
8002 }
8003}
8004
8005impl Render for Workspace {
8006 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8007 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
8008 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
8009 log::info!("Rendered first frame");
8010 }
8011
8012 let centered_layout = self.centered_layout
8013 && self.center.panes().len() == 1
8014 && self.active_item(cx).is_some();
8015 let render_padding = |size| {
8016 (size > 0.0).then(|| {
8017 div()
8018 .h_full()
8019 .w(relative(size))
8020 .bg(cx.theme().colors().editor_background)
8021 .border_color(cx.theme().colors().pane_group_border)
8022 })
8023 };
8024 let paddings = if centered_layout {
8025 let settings = WorkspaceSettings::get_global(cx).centered_layout;
8026 (
8027 render_padding(Self::adjust_padding(
8028 settings.left_padding.map(|padding| padding.0),
8029 )),
8030 render_padding(Self::adjust_padding(
8031 settings.right_padding.map(|padding| padding.0),
8032 )),
8033 )
8034 } else {
8035 (None, None)
8036 };
8037 let ui_font = theme_settings::setup_ui_font(window, cx);
8038
8039 let theme = cx.theme().clone();
8040 let colors = theme.colors();
8041 let notification_entities = self
8042 .notifications
8043 .iter()
8044 .map(|(_, notification)| notification.entity_id())
8045 .collect::<Vec<_>>();
8046 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
8047
8048 div()
8049 .relative()
8050 .size_full()
8051 .flex()
8052 .flex_col()
8053 .font(ui_font)
8054 .gap_0()
8055 .justify_start()
8056 .items_start()
8057 .text_color(colors.text)
8058 .overflow_hidden()
8059 .children(self.titlebar_item.clone())
8060 .on_modifiers_changed(move |_, _, cx| {
8061 for &id in ¬ification_entities {
8062 cx.notify(id);
8063 }
8064 })
8065 .child(
8066 div()
8067 .size_full()
8068 .relative()
8069 .flex_1()
8070 .flex()
8071 .flex_col()
8072 .child(
8073 div()
8074 .id("workspace")
8075 .bg(colors.background)
8076 .relative()
8077 .flex_1()
8078 .w_full()
8079 .flex()
8080 .flex_col()
8081 .overflow_hidden()
8082 .border_t_1()
8083 .border_b_1()
8084 .border_color(colors.border)
8085 .child({
8086 let this = cx.entity();
8087 canvas(
8088 move |bounds, window, cx| {
8089 this.update(cx, |this, cx| {
8090 let bounds_changed = this.bounds != bounds;
8091 this.bounds = bounds;
8092
8093 if bounds_changed {
8094 this.left_dock.update(cx, |dock, cx| {
8095 dock.clamp_panel_size(
8096 bounds.size.width,
8097 window,
8098 cx,
8099 )
8100 });
8101
8102 this.right_dock.update(cx, |dock, cx| {
8103 dock.clamp_panel_size(
8104 bounds.size.width,
8105 window,
8106 cx,
8107 )
8108 });
8109
8110 this.bottom_dock.update(cx, |dock, cx| {
8111 dock.clamp_panel_size(
8112 bounds.size.height,
8113 window,
8114 cx,
8115 )
8116 });
8117 }
8118 })
8119 },
8120 |_, _, _, _| {},
8121 )
8122 .absolute()
8123 .size_full()
8124 })
8125 .when(self.zoomed.is_none(), |this| {
8126 this.on_drag_move(cx.listener(
8127 move |workspace,
8128 e: &DragMoveEvent<DraggedDock>,
8129 window,
8130 cx| {
8131 if workspace.previous_dock_drag_coordinates
8132 != Some(e.event.position)
8133 {
8134 workspace.previous_dock_drag_coordinates =
8135 Some(e.event.position);
8136
8137 match e.drag(cx).0 {
8138 DockPosition::Left => {
8139 workspace.resize_left_dock(
8140 e.event.position.x
8141 - workspace.bounds.left(),
8142 window,
8143 cx,
8144 );
8145 }
8146 DockPosition::Right => {
8147 workspace.resize_right_dock(
8148 workspace.bounds.right()
8149 - e.event.position.x,
8150 window,
8151 cx,
8152 );
8153 }
8154 DockPosition::Bottom => {
8155 workspace.resize_bottom_dock(
8156 workspace.bounds.bottom()
8157 - e.event.position.y,
8158 window,
8159 cx,
8160 );
8161 }
8162 };
8163 workspace.serialize_workspace(window, cx);
8164 }
8165 },
8166 ))
8167
8168 })
8169 .child({
8170 match bottom_dock_layout {
8171 BottomDockLayout::Full => div()
8172 .flex()
8173 .flex_col()
8174 .h_full()
8175 .child(
8176 div()
8177 .flex()
8178 .flex_row()
8179 .flex_1()
8180 .overflow_hidden()
8181 .children(self.render_dock(
8182 DockPosition::Left,
8183 &self.left_dock,
8184 window,
8185 cx,
8186 ))
8187
8188 .child(
8189 div()
8190 .flex()
8191 .flex_col()
8192 .flex_1()
8193 .overflow_hidden()
8194 .child(
8195 h_flex()
8196 .flex_1()
8197 .when_some(
8198 paddings.0,
8199 |this, p| {
8200 this.child(
8201 p.border_r_1(),
8202 )
8203 },
8204 )
8205 .child(self.center.render(
8206 self.zoomed.as_ref(),
8207 &PaneRenderContext {
8208 follower_states:
8209 &self.follower_states,
8210 active_call: self.active_call(),
8211 active_pane: &self.active_pane,
8212 app_state: &self.app_state,
8213 project: &self.project,
8214 workspace: &self.weak_self,
8215 },
8216 window,
8217 cx,
8218 ))
8219 .when_some(
8220 paddings.1,
8221 |this, p| {
8222 this.child(
8223 p.border_l_1(),
8224 )
8225 },
8226 ),
8227 ),
8228 )
8229
8230 .children(self.render_dock(
8231 DockPosition::Right,
8232 &self.right_dock,
8233 window,
8234 cx,
8235 )),
8236 )
8237 .child(div().w_full().children(self.render_dock(
8238 DockPosition::Bottom,
8239 &self.bottom_dock,
8240 window,
8241 cx
8242 ))),
8243
8244 BottomDockLayout::LeftAligned => div()
8245 .flex()
8246 .flex_row()
8247 .h_full()
8248 .child(
8249 div()
8250 .flex()
8251 .flex_col()
8252 .flex_1()
8253 .h_full()
8254 .child(
8255 div()
8256 .flex()
8257 .flex_row()
8258 .flex_1()
8259 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
8260
8261 .child(
8262 div()
8263 .flex()
8264 .flex_col()
8265 .flex_1()
8266 .overflow_hidden()
8267 .child(
8268 h_flex()
8269 .flex_1()
8270 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8271 .child(self.center.render(
8272 self.zoomed.as_ref(),
8273 &PaneRenderContext {
8274 follower_states:
8275 &self.follower_states,
8276 active_call: self.active_call(),
8277 active_pane: &self.active_pane,
8278 app_state: &self.app_state,
8279 project: &self.project,
8280 workspace: &self.weak_self,
8281 },
8282 window,
8283 cx,
8284 ))
8285 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8286 )
8287 )
8288
8289 )
8290 .child(
8291 div()
8292 .w_full()
8293 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8294 ),
8295 )
8296 .children(self.render_dock(
8297 DockPosition::Right,
8298 &self.right_dock,
8299 window,
8300 cx,
8301 )),
8302 BottomDockLayout::RightAligned => div()
8303 .flex()
8304 .flex_row()
8305 .h_full()
8306 .children(self.render_dock(
8307 DockPosition::Left,
8308 &self.left_dock,
8309 window,
8310 cx,
8311 ))
8312
8313 .child(
8314 div()
8315 .flex()
8316 .flex_col()
8317 .flex_1()
8318 .h_full()
8319 .child(
8320 div()
8321 .flex()
8322 .flex_row()
8323 .flex_1()
8324 .child(
8325 div()
8326 .flex()
8327 .flex_col()
8328 .flex_1()
8329 .overflow_hidden()
8330 .child(
8331 h_flex()
8332 .flex_1()
8333 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8334 .child(self.center.render(
8335 self.zoomed.as_ref(),
8336 &PaneRenderContext {
8337 follower_states:
8338 &self.follower_states,
8339 active_call: self.active_call(),
8340 active_pane: &self.active_pane,
8341 app_state: &self.app_state,
8342 project: &self.project,
8343 workspace: &self.weak_self,
8344 },
8345 window,
8346 cx,
8347 ))
8348 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8349 )
8350 )
8351
8352 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8353 )
8354 .child(
8355 div()
8356 .w_full()
8357 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8358 ),
8359 ),
8360 BottomDockLayout::Contained => div()
8361 .flex()
8362 .flex_row()
8363 .h_full()
8364 .children(self.render_dock(
8365 DockPosition::Left,
8366 &self.left_dock,
8367 window,
8368 cx,
8369 ))
8370
8371 .child(
8372 div()
8373 .flex()
8374 .flex_col()
8375 .flex_1()
8376 .overflow_hidden()
8377 .child(
8378 h_flex()
8379 .flex_1()
8380 .when_some(paddings.0, |this, p| {
8381 this.child(p.border_r_1())
8382 })
8383 .child(self.center.render(
8384 self.zoomed.as_ref(),
8385 &PaneRenderContext {
8386 follower_states:
8387 &self.follower_states,
8388 active_call: self.active_call(),
8389 active_pane: &self.active_pane,
8390 app_state: &self.app_state,
8391 project: &self.project,
8392 workspace: &self.weak_self,
8393 },
8394 window,
8395 cx,
8396 ))
8397 .when_some(paddings.1, |this, p| {
8398 this.child(p.border_l_1())
8399 }),
8400 )
8401 .children(self.render_dock(
8402 DockPosition::Bottom,
8403 &self.bottom_dock,
8404 window,
8405 cx,
8406 )),
8407 )
8408
8409 .children(self.render_dock(
8410 DockPosition::Right,
8411 &self.right_dock,
8412 window,
8413 cx,
8414 )),
8415 }
8416 })
8417 .children(self.zoomed.as_ref().and_then(|view| {
8418 let zoomed_view = view.upgrade()?;
8419 let div = div()
8420 .occlude()
8421 .absolute()
8422 .overflow_hidden()
8423 .border_color(colors.border)
8424 .bg(colors.background)
8425 .child(zoomed_view)
8426 .inset_0()
8427 .shadow_lg();
8428
8429 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8430 return Some(div);
8431 }
8432
8433 Some(match self.zoomed_position {
8434 Some(DockPosition::Left) => div.right_2().border_r_1(),
8435 Some(DockPosition::Right) => div.left_2().border_l_1(),
8436 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8437 None => {
8438 div.top_2().bottom_2().left_2().right_2().border_1()
8439 }
8440 })
8441 }))
8442 .children(self.render_notifications(window, cx)),
8443 )
8444 .when(self.status_bar_visible(cx), |parent| {
8445 parent.child(self.status_bar.clone())
8446 })
8447 .child(self.toast_layer.clone()),
8448 )
8449 }
8450}
8451
8452impl WorkspaceStore {
8453 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8454 Self {
8455 workspaces: Default::default(),
8456 _subscriptions: vec![
8457 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8458 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8459 ],
8460 client,
8461 }
8462 }
8463
8464 pub fn update_followers(
8465 &self,
8466 project_id: Option<u64>,
8467 update: proto::update_followers::Variant,
8468 cx: &App,
8469 ) -> Option<()> {
8470 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8471 let room_id = active_call.0.room_id(cx)?;
8472 self.client
8473 .send(proto::UpdateFollowers {
8474 room_id,
8475 project_id,
8476 variant: Some(update),
8477 })
8478 .log_err()
8479 }
8480
8481 pub async fn handle_follow(
8482 this: Entity<Self>,
8483 envelope: TypedEnvelope<proto::Follow>,
8484 mut cx: AsyncApp,
8485 ) -> Result<proto::FollowResponse> {
8486 this.update(&mut cx, |this, cx| {
8487 let follower = Follower {
8488 project_id: envelope.payload.project_id,
8489 peer_id: envelope.original_sender_id()?,
8490 };
8491
8492 let mut response = proto::FollowResponse::default();
8493
8494 this.workspaces.retain(|(window_handle, weak_workspace)| {
8495 let Some(workspace) = weak_workspace.upgrade() else {
8496 return false;
8497 };
8498 window_handle
8499 .update(cx, |_, window, cx| {
8500 workspace.update(cx, |workspace, cx| {
8501 let handler_response =
8502 workspace.handle_follow(follower.project_id, window, cx);
8503 if let Some(active_view) = handler_response.active_view
8504 && workspace.project.read(cx).remote_id() == follower.project_id
8505 {
8506 response.active_view = Some(active_view)
8507 }
8508 });
8509 })
8510 .is_ok()
8511 });
8512
8513 Ok(response)
8514 })
8515 }
8516
8517 async fn handle_update_followers(
8518 this: Entity<Self>,
8519 envelope: TypedEnvelope<proto::UpdateFollowers>,
8520 mut cx: AsyncApp,
8521 ) -> Result<()> {
8522 let leader_id = envelope.original_sender_id()?;
8523 let update = envelope.payload;
8524
8525 this.update(&mut cx, |this, cx| {
8526 this.workspaces.retain(|(window_handle, weak_workspace)| {
8527 let Some(workspace) = weak_workspace.upgrade() else {
8528 return false;
8529 };
8530 window_handle
8531 .update(cx, |_, window, cx| {
8532 workspace.update(cx, |workspace, cx| {
8533 let project_id = workspace.project.read(cx).remote_id();
8534 if update.project_id != project_id && update.project_id.is_some() {
8535 return;
8536 }
8537 workspace.handle_update_followers(
8538 leader_id,
8539 update.clone(),
8540 window,
8541 cx,
8542 );
8543 });
8544 })
8545 .is_ok()
8546 });
8547 Ok(())
8548 })
8549 }
8550
8551 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8552 self.workspaces.iter().map(|(_, weak)| weak)
8553 }
8554
8555 pub fn workspaces_with_windows(
8556 &self,
8557 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8558 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8559 }
8560}
8561
8562impl ViewId {
8563 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8564 Ok(Self {
8565 creator: message
8566 .creator
8567 .map(CollaboratorId::PeerId)
8568 .context("creator is missing")?,
8569 id: message.id,
8570 })
8571 }
8572
8573 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8574 if let CollaboratorId::PeerId(peer_id) = self.creator {
8575 Some(proto::ViewId {
8576 creator: Some(peer_id),
8577 id: self.id,
8578 })
8579 } else {
8580 None
8581 }
8582 }
8583}
8584
8585impl FollowerState {
8586 fn pane(&self) -> &Entity<Pane> {
8587 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8588 }
8589}
8590
8591pub trait WorkspaceHandle {
8592 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8593}
8594
8595impl WorkspaceHandle for Entity<Workspace> {
8596 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8597 self.read(cx)
8598 .worktrees(cx)
8599 .flat_map(|worktree| {
8600 let worktree_id = worktree.read(cx).id();
8601 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8602 worktree_id,
8603 path: f.path.clone(),
8604 })
8605 })
8606 .collect::<Vec<_>>()
8607 }
8608}
8609
8610pub async fn last_opened_workspace_location(
8611 db: &WorkspaceDb,
8612 fs: &dyn fs::Fs,
8613) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8614 db.last_workspace(fs)
8615 .await
8616 .log_err()
8617 .flatten()
8618 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8619}
8620
8621pub async fn last_session_workspace_locations(
8622 db: &WorkspaceDb,
8623 last_session_id: &str,
8624 last_session_window_stack: Option<Vec<WindowId>>,
8625 fs: &dyn fs::Fs,
8626) -> Option<Vec<SessionWorkspace>> {
8627 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8628 .await
8629 .log_err()
8630}
8631
8632pub struct MultiWorkspaceRestoreResult {
8633 pub window_handle: WindowHandle<MultiWorkspace>,
8634 pub errors: Vec<anyhow::Error>,
8635}
8636
8637pub async fn restore_multiworkspace(
8638 multi_workspace: SerializedMultiWorkspace,
8639 app_state: Arc<AppState>,
8640 cx: &mut AsyncApp,
8641) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8642 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
8643 let mut group_iter = workspaces.into_iter();
8644 let first = group_iter
8645 .next()
8646 .context("window group must not be empty")?;
8647
8648 let window_handle = if first.paths.is_empty() {
8649 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8650 .await?
8651 } else {
8652 let OpenResult { window, .. } = cx
8653 .update(|cx| {
8654 Workspace::new_local(
8655 first.paths.paths().to_vec(),
8656 app_state.clone(),
8657 None,
8658 None,
8659 None,
8660 OpenMode::Activate,
8661 cx,
8662 )
8663 })
8664 .await?;
8665 window
8666 };
8667
8668 let mut errors = Vec::new();
8669
8670 for session_workspace in group_iter {
8671 let error = if session_workspace.paths.is_empty() {
8672 cx.update(|cx| {
8673 open_workspace_by_id(
8674 session_workspace.workspace_id,
8675 app_state.clone(),
8676 Some(window_handle),
8677 cx,
8678 )
8679 })
8680 .await
8681 .err()
8682 } else {
8683 cx.update(|cx| {
8684 Workspace::new_local(
8685 session_workspace.paths.paths().to_vec(),
8686 app_state.clone(),
8687 Some(window_handle),
8688 None,
8689 None,
8690 OpenMode::Add,
8691 cx,
8692 )
8693 })
8694 .await
8695 .err()
8696 };
8697
8698 if let Some(error) = error {
8699 errors.push(error);
8700 }
8701 }
8702
8703 if let Some(target_id) = state.active_workspace_id {
8704 window_handle
8705 .update(cx, |multi_workspace, window, cx| {
8706 let target_index = multi_workspace
8707 .workspaces()
8708 .iter()
8709 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8710 let index = target_index.unwrap_or(0);
8711 if let Some(workspace) = multi_workspace.workspaces().get(index).cloned() {
8712 multi_workspace.activate(workspace, window, cx);
8713 }
8714 })
8715 .ok();
8716 } else {
8717 window_handle
8718 .update(cx, |multi_workspace, window, cx| {
8719 if let Some(workspace) = multi_workspace.workspaces().first().cloned() {
8720 multi_workspace.activate(workspace, window, cx);
8721 }
8722 })
8723 .ok();
8724 }
8725
8726 if !state.project_group_keys.is_empty() {
8727 window_handle
8728 .update(cx, |multi_workspace, _window, _cx| {
8729 for serialized_key in &state.project_group_keys {
8730 let paths = PathList::deserialize(&serialized_key.path_list);
8731 let host = match &serialized_key.location {
8732 SerializedWorkspaceLocation::Local => None,
8733 SerializedWorkspaceLocation::Remote(opts) => Some(opts.clone()),
8734 };
8735 let key = ProjectGroupKey::new(host, paths);
8736 multi_workspace.add_project_group_key(key);
8737 }
8738 })
8739 .ok();
8740 }
8741
8742 if state.sidebar_open {
8743 window_handle
8744 .update(cx, |multi_workspace, _, cx| {
8745 multi_workspace.open_sidebar(cx);
8746 })
8747 .ok();
8748 }
8749
8750 if let Some(sidebar_state) = &state.sidebar_state {
8751 let sidebar_state = sidebar_state.clone();
8752 window_handle
8753 .update(cx, |multi_workspace, window, cx| {
8754 if let Some(sidebar) = multi_workspace.sidebar() {
8755 sidebar.restore_serialized_state(&sidebar_state, window, cx);
8756 }
8757 multi_workspace.serialize(cx);
8758 })
8759 .ok();
8760 }
8761
8762 window_handle
8763 .update(cx, |_, window, _cx| {
8764 window.activate_window();
8765 })
8766 .ok();
8767
8768 Ok(MultiWorkspaceRestoreResult {
8769 window_handle,
8770 errors,
8771 })
8772}
8773
8774actions!(
8775 collab,
8776 [
8777 /// Opens the channel notes for the current call.
8778 ///
8779 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8780 /// channel in the collab panel.
8781 ///
8782 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8783 /// can be copied via "Copy link to section" in the context menu of the channel notes
8784 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8785 OpenChannelNotes,
8786 /// Mutes your microphone.
8787 Mute,
8788 /// Deafens yourself (mute both microphone and speakers).
8789 Deafen,
8790 /// Leaves the current call.
8791 LeaveCall,
8792 /// Shares the current project with collaborators.
8793 ShareProject,
8794 /// Shares your screen with collaborators.
8795 ScreenShare,
8796 /// Copies the current room name and session id for debugging purposes.
8797 CopyRoomId,
8798 ]
8799);
8800
8801/// Opens the channel notes for a specific channel by its ID.
8802#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8803#[action(namespace = collab)]
8804#[serde(deny_unknown_fields)]
8805pub struct OpenChannelNotesById {
8806 pub channel_id: u64,
8807}
8808
8809actions!(
8810 zed,
8811 [
8812 /// Opens the Zed log file.
8813 OpenLog,
8814 /// Reveals the Zed log file in the system file manager.
8815 RevealLogInFileManager
8816 ]
8817);
8818
8819async fn join_channel_internal(
8820 channel_id: ChannelId,
8821 app_state: &Arc<AppState>,
8822 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8823 requesting_workspace: Option<WeakEntity<Workspace>>,
8824 active_call: &dyn AnyActiveCall,
8825 cx: &mut AsyncApp,
8826) -> Result<bool> {
8827 let (should_prompt, already_in_channel) = cx.update(|cx| {
8828 if !active_call.is_in_room(cx) {
8829 return (false, false);
8830 }
8831
8832 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8833 let should_prompt = active_call.is_sharing_project(cx)
8834 && active_call.has_remote_participants(cx)
8835 && !already_in_channel;
8836 (should_prompt, already_in_channel)
8837 });
8838
8839 if already_in_channel {
8840 let task = cx.update(|cx| {
8841 if let Some((project, host)) = active_call.most_active_project(cx) {
8842 Some(join_in_room_project(project, host, app_state.clone(), cx))
8843 } else {
8844 None
8845 }
8846 });
8847 if let Some(task) = task {
8848 task.await?;
8849 }
8850 return anyhow::Ok(true);
8851 }
8852
8853 if should_prompt {
8854 if let Some(multi_workspace) = requesting_window {
8855 let answer = multi_workspace
8856 .update(cx, |_, window, cx| {
8857 window.prompt(
8858 PromptLevel::Warning,
8859 "Do you want to switch channels?",
8860 Some("Leaving this call will unshare your current project."),
8861 &["Yes, Join Channel", "Cancel"],
8862 cx,
8863 )
8864 })?
8865 .await;
8866
8867 if answer == Ok(1) {
8868 return Ok(false);
8869 }
8870 } else {
8871 return Ok(false);
8872 }
8873 }
8874
8875 let client = cx.update(|cx| active_call.client(cx));
8876
8877 let mut client_status = client.status();
8878
8879 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8880 'outer: loop {
8881 let Some(status) = client_status.recv().await else {
8882 anyhow::bail!("error connecting");
8883 };
8884
8885 match status {
8886 Status::Connecting
8887 | Status::Authenticating
8888 | Status::Authenticated
8889 | Status::Reconnecting
8890 | Status::Reauthenticating
8891 | Status::Reauthenticated => continue,
8892 Status::Connected { .. } => break 'outer,
8893 Status::SignedOut | Status::AuthenticationError => {
8894 return Err(ErrorCode::SignedOut.into());
8895 }
8896 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8897 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8898 return Err(ErrorCode::Disconnected.into());
8899 }
8900 }
8901 }
8902
8903 let joined = cx
8904 .update(|cx| active_call.join_channel(channel_id, cx))
8905 .await?;
8906
8907 if !joined {
8908 return anyhow::Ok(true);
8909 }
8910
8911 cx.update(|cx| active_call.room_update_completed(cx)).await;
8912
8913 let task = cx.update(|cx| {
8914 if let Some((project, host)) = active_call.most_active_project(cx) {
8915 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8916 }
8917
8918 // If you are the first to join a channel, see if you should share your project.
8919 if !active_call.has_remote_participants(cx)
8920 && !active_call.local_participant_is_guest(cx)
8921 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8922 {
8923 let project = workspace.update(cx, |workspace, cx| {
8924 let project = workspace.project.read(cx);
8925
8926 if !active_call.share_on_join(cx) {
8927 return None;
8928 }
8929
8930 if (project.is_local() || project.is_via_remote_server())
8931 && project.visible_worktrees(cx).any(|tree| {
8932 tree.read(cx)
8933 .root_entry()
8934 .is_some_and(|entry| entry.is_dir())
8935 })
8936 {
8937 Some(workspace.project.clone())
8938 } else {
8939 None
8940 }
8941 });
8942 if let Some(project) = project {
8943 let share_task = active_call.share_project(project, cx);
8944 return Some(cx.spawn(async move |_cx| -> Result<()> {
8945 share_task.await?;
8946 Ok(())
8947 }));
8948 }
8949 }
8950
8951 None
8952 });
8953 if let Some(task) = task {
8954 task.await?;
8955 return anyhow::Ok(true);
8956 }
8957 anyhow::Ok(false)
8958}
8959
8960pub fn join_channel(
8961 channel_id: ChannelId,
8962 app_state: Arc<AppState>,
8963 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8964 requesting_workspace: Option<WeakEntity<Workspace>>,
8965 cx: &mut App,
8966) -> Task<Result<()>> {
8967 let active_call = GlobalAnyActiveCall::global(cx).clone();
8968 cx.spawn(async move |cx| {
8969 let result = join_channel_internal(
8970 channel_id,
8971 &app_state,
8972 requesting_window,
8973 requesting_workspace,
8974 &*active_call.0,
8975 cx,
8976 )
8977 .await;
8978
8979 // join channel succeeded, and opened a window
8980 if matches!(result, Ok(true)) {
8981 return anyhow::Ok(());
8982 }
8983
8984 // find an existing workspace to focus and show call controls
8985 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8986 if active_window.is_none() {
8987 // no open workspaces, make one to show the error in (blergh)
8988 let OpenResult {
8989 window: window_handle,
8990 ..
8991 } = cx
8992 .update(|cx| {
8993 Workspace::new_local(
8994 vec![],
8995 app_state.clone(),
8996 requesting_window,
8997 None,
8998 None,
8999 OpenMode::Activate,
9000 cx,
9001 )
9002 })
9003 .await?;
9004
9005 window_handle
9006 .update(cx, |_, window, _cx| {
9007 window.activate_window();
9008 })
9009 .ok();
9010
9011 if result.is_ok() {
9012 cx.update(|cx| {
9013 cx.dispatch_action(&OpenChannelNotes);
9014 });
9015 }
9016
9017 active_window = Some(window_handle);
9018 }
9019
9020 if let Err(err) = result {
9021 log::error!("failed to join channel: {}", err);
9022 if let Some(active_window) = active_window {
9023 active_window
9024 .update(cx, |_, window, cx| {
9025 let detail: SharedString = match err.error_code() {
9026 ErrorCode::SignedOut => "Please sign in to continue.".into(),
9027 ErrorCode::UpgradeRequired => concat!(
9028 "Your are running an unsupported version of Zed. ",
9029 "Please update to continue."
9030 )
9031 .into(),
9032 ErrorCode::NoSuchChannel => concat!(
9033 "No matching channel was found. ",
9034 "Please check the link and try again."
9035 )
9036 .into(),
9037 ErrorCode::Forbidden => concat!(
9038 "This channel is private, and you do not have access. ",
9039 "Please ask someone to add you and try again."
9040 )
9041 .into(),
9042 ErrorCode::Disconnected => {
9043 "Please check your internet connection and try again.".into()
9044 }
9045 _ => format!("{}\n\nPlease try again.", err).into(),
9046 };
9047 window.prompt(
9048 PromptLevel::Critical,
9049 "Failed to join channel",
9050 Some(&detail),
9051 &["Ok"],
9052 cx,
9053 )
9054 })?
9055 .await
9056 .ok();
9057 }
9058 }
9059
9060 // return ok, we showed the error to the user.
9061 anyhow::Ok(())
9062 })
9063}
9064
9065pub async fn get_any_active_multi_workspace(
9066 app_state: Arc<AppState>,
9067 mut cx: AsyncApp,
9068) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
9069 // find an existing workspace to focus and show call controls
9070 let active_window = activate_any_workspace_window(&mut cx);
9071 if active_window.is_none() {
9072 cx.update(|cx| {
9073 Workspace::new_local(
9074 vec![],
9075 app_state.clone(),
9076 None,
9077 None,
9078 None,
9079 OpenMode::Activate,
9080 cx,
9081 )
9082 })
9083 .await?;
9084 }
9085 activate_any_workspace_window(&mut cx).context("could not open zed")
9086}
9087
9088fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
9089 cx.update(|cx| {
9090 if let Some(workspace_window) = cx
9091 .active_window()
9092 .and_then(|window| window.downcast::<MultiWorkspace>())
9093 {
9094 return Some(workspace_window);
9095 }
9096
9097 for window in cx.windows() {
9098 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
9099 workspace_window
9100 .update(cx, |_, window, _| window.activate_window())
9101 .ok();
9102 return Some(workspace_window);
9103 }
9104 }
9105 None
9106 })
9107}
9108
9109pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
9110 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
9111}
9112
9113pub fn workspace_windows_for_location(
9114 serialized_location: &SerializedWorkspaceLocation,
9115 cx: &App,
9116) -> Vec<WindowHandle<MultiWorkspace>> {
9117 cx.windows()
9118 .into_iter()
9119 .filter_map(|window| window.downcast::<MultiWorkspace>())
9120 .filter(|multi_workspace| {
9121 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
9122 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
9123 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
9124 }
9125 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
9126 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
9127 a.distro_name == b.distro_name
9128 }
9129 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
9130 a.container_id == b.container_id
9131 }
9132 #[cfg(any(test, feature = "test-support"))]
9133 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
9134 a.id == b.id
9135 }
9136 _ => false,
9137 };
9138
9139 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
9140 multi_workspace.workspaces().iter().any(|workspace| {
9141 match workspace.read(cx).workspace_location(cx) {
9142 WorkspaceLocation::Location(location, _) => {
9143 match (&location, serialized_location) {
9144 (
9145 SerializedWorkspaceLocation::Local,
9146 SerializedWorkspaceLocation::Local,
9147 ) => true,
9148 (
9149 SerializedWorkspaceLocation::Remote(a),
9150 SerializedWorkspaceLocation::Remote(b),
9151 ) => same_host(a, b),
9152 _ => false,
9153 }
9154 }
9155 _ => false,
9156 }
9157 })
9158 })
9159 })
9160 .collect()
9161}
9162
9163pub async fn find_existing_workspace(
9164 abs_paths: &[PathBuf],
9165 open_options: &OpenOptions,
9166 location: &SerializedWorkspaceLocation,
9167 cx: &mut AsyncApp,
9168) -> (
9169 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
9170 OpenVisible,
9171) {
9172 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
9173 let mut open_visible = OpenVisible::All;
9174 let mut best_match = None;
9175
9176 if open_options.open_new_workspace != Some(true) {
9177 cx.update(|cx| {
9178 for window in workspace_windows_for_location(location, cx) {
9179 if let Ok(multi_workspace) = window.read(cx) {
9180 for workspace in multi_workspace.workspaces() {
9181 let project = workspace.read(cx).project.read(cx);
9182 let m = project.visibility_for_paths(
9183 abs_paths,
9184 open_options.open_new_workspace == None,
9185 cx,
9186 );
9187 if m > best_match {
9188 existing = Some((window, workspace.clone()));
9189 best_match = m;
9190 } else if best_match.is_none()
9191 && open_options.open_new_workspace == Some(false)
9192 {
9193 existing = Some((window, workspace.clone()))
9194 }
9195 }
9196 }
9197 }
9198 });
9199
9200 let all_paths_are_files = existing
9201 .as_ref()
9202 .and_then(|(_, target_workspace)| {
9203 cx.update(|cx| {
9204 let workspace = target_workspace.read(cx);
9205 let project = workspace.project.read(cx);
9206 let path_style = workspace.path_style(cx);
9207 Some(!abs_paths.iter().any(|path| {
9208 let path = util::paths::SanitizedPath::new(path);
9209 project.worktrees(cx).any(|worktree| {
9210 let worktree = worktree.read(cx);
9211 let abs_path = worktree.abs_path();
9212 path_style
9213 .strip_prefix(path.as_ref(), abs_path.as_ref())
9214 .and_then(|rel| worktree.entry_for_path(&rel))
9215 .is_some_and(|e| e.is_dir())
9216 })
9217 }))
9218 })
9219 })
9220 .unwrap_or(false);
9221
9222 if open_options.open_new_workspace.is_none()
9223 && existing.is_some()
9224 && open_options.wait
9225 && all_paths_are_files
9226 {
9227 cx.update(|cx| {
9228 let windows = workspace_windows_for_location(location, cx);
9229 let window = cx
9230 .active_window()
9231 .and_then(|window| window.downcast::<MultiWorkspace>())
9232 .filter(|window| windows.contains(window))
9233 .or_else(|| windows.into_iter().next());
9234 if let Some(window) = window {
9235 if let Ok(multi_workspace) = window.read(cx) {
9236 let active_workspace = multi_workspace.workspace().clone();
9237 existing = Some((window, active_workspace));
9238 open_visible = OpenVisible::None;
9239 }
9240 }
9241 });
9242 }
9243 }
9244 (existing, open_visible)
9245}
9246
9247#[derive(Default, Clone)]
9248pub struct OpenOptions {
9249 pub visible: Option<OpenVisible>,
9250 pub focus: Option<bool>,
9251 pub open_new_workspace: Option<bool>,
9252 pub wait: bool,
9253 pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
9254 pub open_mode: OpenMode,
9255 pub env: Option<HashMap<String, String>>,
9256 pub open_in_dev_container: bool,
9257}
9258
9259/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
9260/// or [`Workspace::open_workspace_for_paths`].
9261pub struct OpenResult {
9262 pub window: WindowHandle<MultiWorkspace>,
9263 pub workspace: Entity<Workspace>,
9264 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
9265}
9266
9267/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
9268pub fn open_workspace_by_id(
9269 workspace_id: WorkspaceId,
9270 app_state: Arc<AppState>,
9271 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9272 cx: &mut App,
9273) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
9274 let project_handle = Project::local(
9275 app_state.client.clone(),
9276 app_state.node_runtime.clone(),
9277 app_state.user_store.clone(),
9278 app_state.languages.clone(),
9279 app_state.fs.clone(),
9280 None,
9281 project::LocalProjectFlags {
9282 init_worktree_trust: true,
9283 ..project::LocalProjectFlags::default()
9284 },
9285 cx,
9286 );
9287
9288 let db = WorkspaceDb::global(cx);
9289 let kvp = db::kvp::KeyValueStore::global(cx);
9290 cx.spawn(async move |cx| {
9291 let serialized_workspace = db
9292 .workspace_for_id(workspace_id)
9293 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
9294
9295 let centered_layout = serialized_workspace.centered_layout;
9296
9297 let (window, workspace) = if let Some(window) = requesting_window {
9298 let workspace = window.update(cx, |multi_workspace, window, cx| {
9299 let workspace = cx.new(|cx| {
9300 let mut workspace = Workspace::new(
9301 Some(workspace_id),
9302 project_handle.clone(),
9303 app_state.clone(),
9304 window,
9305 cx,
9306 );
9307 workspace.centered_layout = centered_layout;
9308 workspace
9309 });
9310 multi_workspace.add(workspace.clone(), &*window, cx);
9311 workspace
9312 })?;
9313 (window, workspace)
9314 } else {
9315 let window_bounds_override = window_bounds_env_override();
9316
9317 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
9318 (Some(WindowBounds::Windowed(bounds)), None)
9319 } else if let Some(display) = serialized_workspace.display
9320 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
9321 {
9322 (Some(bounds.0), Some(display))
9323 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
9324 (Some(bounds), Some(display))
9325 } else {
9326 (None, None)
9327 };
9328
9329 let options = cx.update(|cx| {
9330 let mut options = (app_state.build_window_options)(display, cx);
9331 options.window_bounds = window_bounds;
9332 options
9333 });
9334
9335 let window = cx.open_window(options, {
9336 let app_state = app_state.clone();
9337 let project_handle = project_handle.clone();
9338 move |window, cx| {
9339 let workspace = cx.new(|cx| {
9340 let mut workspace = Workspace::new(
9341 Some(workspace_id),
9342 project_handle,
9343 app_state,
9344 window,
9345 cx,
9346 );
9347 workspace.centered_layout = centered_layout;
9348 workspace
9349 });
9350 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9351 }
9352 })?;
9353
9354 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9355 multi_workspace.workspace().clone()
9356 })?;
9357
9358 (window, workspace)
9359 };
9360
9361 notify_if_database_failed(window, cx);
9362
9363 // Restore items from the serialized workspace
9364 window
9365 .update(cx, |_, window, cx| {
9366 workspace.update(cx, |_workspace, cx| {
9367 open_items(Some(serialized_workspace), vec![], window, cx)
9368 })
9369 })?
9370 .await?;
9371
9372 window.update(cx, |_, window, cx| {
9373 workspace.update(cx, |workspace, cx| {
9374 workspace.serialize_workspace(window, cx);
9375 });
9376 })?;
9377
9378 Ok(window)
9379 })
9380}
9381
9382#[allow(clippy::type_complexity)]
9383pub fn open_paths(
9384 abs_paths: &[PathBuf],
9385 app_state: Arc<AppState>,
9386 open_options: OpenOptions,
9387 cx: &mut App,
9388) -> Task<anyhow::Result<OpenResult>> {
9389 let abs_paths = abs_paths.to_vec();
9390 #[cfg(target_os = "windows")]
9391 let wsl_path = abs_paths
9392 .iter()
9393 .find_map(|p| util::paths::WslPath::from_path(p));
9394
9395 cx.spawn(async move |cx| {
9396 let (mut existing, mut open_visible) = find_existing_workspace(
9397 &abs_paths,
9398 &open_options,
9399 &SerializedWorkspaceLocation::Local,
9400 cx,
9401 )
9402 .await;
9403
9404 // Fallback: if no workspace contains the paths and all paths are files,
9405 // prefer an existing local workspace window (active window first).
9406 if open_options.open_new_workspace.is_none() && existing.is_none() {
9407 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9408 let all_metadatas = futures::future::join_all(all_paths)
9409 .await
9410 .into_iter()
9411 .filter_map(|result| result.ok().flatten())
9412 .collect::<Vec<_>>();
9413
9414 if all_metadatas.iter().all(|file| !file.is_dir) {
9415 cx.update(|cx| {
9416 let windows = workspace_windows_for_location(
9417 &SerializedWorkspaceLocation::Local,
9418 cx,
9419 );
9420 let window = cx
9421 .active_window()
9422 .and_then(|window| window.downcast::<MultiWorkspace>())
9423 .filter(|window| windows.contains(window))
9424 .or_else(|| windows.into_iter().next());
9425 if let Some(window) = window {
9426 if let Ok(multi_workspace) = window.read(cx) {
9427 let active_workspace = multi_workspace.workspace().clone();
9428 existing = Some((window, active_workspace));
9429 open_visible = OpenVisible::None;
9430 }
9431 }
9432 });
9433 }
9434 }
9435
9436 let open_in_dev_container = open_options.open_in_dev_container;
9437
9438 let result = if let Some((existing, target_workspace)) = existing {
9439 let open_task = existing
9440 .update(cx, |multi_workspace, window, cx| {
9441 window.activate_window();
9442 multi_workspace.activate(target_workspace.clone(), window, cx);
9443 target_workspace.update(cx, |workspace, cx| {
9444 if open_in_dev_container {
9445 workspace.set_open_in_dev_container(true);
9446 }
9447 workspace.open_paths(
9448 abs_paths,
9449 OpenOptions {
9450 visible: Some(open_visible),
9451 ..Default::default()
9452 },
9453 None,
9454 window,
9455 cx,
9456 )
9457 })
9458 })?
9459 .await;
9460
9461 _ = existing.update(cx, |multi_workspace, _, cx| {
9462 let workspace = multi_workspace.workspace().clone();
9463 workspace.update(cx, |workspace, cx| {
9464 for item in open_task.iter().flatten() {
9465 if let Err(e) = item {
9466 workspace.show_error(&e, cx);
9467 }
9468 }
9469 });
9470 });
9471
9472 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9473 } else {
9474 let init = if open_in_dev_container {
9475 Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {
9476 workspace.set_open_in_dev_container(true);
9477 }) as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>)
9478 } else {
9479 None
9480 };
9481 let result = cx
9482 .update(move |cx| {
9483 Workspace::new_local(
9484 abs_paths,
9485 app_state.clone(),
9486 open_options.requesting_window,
9487 open_options.env,
9488 init,
9489 open_options.open_mode,
9490 cx,
9491 )
9492 })
9493 .await;
9494
9495 if let Ok(ref result) = result {
9496 result.window
9497 .update(cx, |_, window, _cx| {
9498 window.activate_window();
9499 })
9500 .log_err();
9501 }
9502
9503 result
9504 };
9505
9506 #[cfg(target_os = "windows")]
9507 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9508 && let Ok(ref result) = result
9509 {
9510 result.window
9511 .update(cx, move |multi_workspace, _window, cx| {
9512 struct OpenInWsl;
9513 let workspace = multi_workspace.workspace().clone();
9514 workspace.update(cx, |workspace, cx| {
9515 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9516 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9517 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9518 cx.new(move |cx| {
9519 MessageNotification::new(msg, cx)
9520 .primary_message("Open in WSL")
9521 .primary_icon(IconName::FolderOpen)
9522 .primary_on_click(move |window, cx| {
9523 window.dispatch_action(Box::new(remote::OpenWslPath {
9524 distro: remote::WslConnectionOptions {
9525 distro_name: distro.clone(),
9526 user: None,
9527 },
9528 paths: vec![path.clone().into()],
9529 }), cx)
9530 })
9531 })
9532 });
9533 });
9534 })
9535 .unwrap();
9536 };
9537 result
9538 })
9539}
9540
9541pub fn open_new(
9542 open_options: OpenOptions,
9543 app_state: Arc<AppState>,
9544 cx: &mut App,
9545 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9546) -> Task<anyhow::Result<()>> {
9547 let addition = open_options.open_mode;
9548 let task = Workspace::new_local(
9549 Vec::new(),
9550 app_state,
9551 open_options.requesting_window,
9552 open_options.env,
9553 Some(Box::new(init)),
9554 addition,
9555 cx,
9556 );
9557 cx.spawn(async move |cx| {
9558 let OpenResult { window, .. } = task.await?;
9559 window
9560 .update(cx, |_, window, _cx| {
9561 window.activate_window();
9562 })
9563 .ok();
9564 Ok(())
9565 })
9566}
9567
9568pub fn create_and_open_local_file(
9569 path: &'static Path,
9570 window: &mut Window,
9571 cx: &mut Context<Workspace>,
9572 default_content: impl 'static + Send + FnOnce() -> Rope,
9573) -> Task<Result<Box<dyn ItemHandle>>> {
9574 cx.spawn_in(window, async move |workspace, cx| {
9575 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9576 if !fs.is_file(path).await {
9577 fs.create_file(path, Default::default()).await?;
9578 fs.save(path, &default_content(), Default::default())
9579 .await?;
9580 }
9581
9582 workspace
9583 .update_in(cx, |workspace, window, cx| {
9584 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9585 let path = workspace
9586 .project
9587 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9588 cx.spawn_in(window, async move |workspace, cx| {
9589 let path = path.await?;
9590
9591 let path = fs.canonicalize(&path).await.unwrap_or(path);
9592
9593 let mut items = workspace
9594 .update_in(cx, |workspace, window, cx| {
9595 workspace.open_paths(
9596 vec![path.to_path_buf()],
9597 OpenOptions {
9598 visible: Some(OpenVisible::None),
9599 ..Default::default()
9600 },
9601 None,
9602 window,
9603 cx,
9604 )
9605 })?
9606 .await;
9607 let item = items.pop().flatten();
9608 item.with_context(|| format!("path {path:?} is not a file"))?
9609 })
9610 })
9611 })?
9612 .await?
9613 .await
9614 })
9615}
9616
9617pub fn open_remote_project_with_new_connection(
9618 window: WindowHandle<MultiWorkspace>,
9619 remote_connection: Arc<dyn RemoteConnection>,
9620 cancel_rx: oneshot::Receiver<()>,
9621 delegate: Arc<dyn RemoteClientDelegate>,
9622 app_state: Arc<AppState>,
9623 paths: Vec<PathBuf>,
9624 cx: &mut App,
9625) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9626 cx.spawn(async move |cx| {
9627 let (workspace_id, serialized_workspace) =
9628 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9629 .await?;
9630
9631 let session = match cx
9632 .update(|cx| {
9633 remote::RemoteClient::new(
9634 ConnectionIdentifier::Workspace(workspace_id.0),
9635 remote_connection,
9636 cancel_rx,
9637 delegate,
9638 cx,
9639 )
9640 })
9641 .await?
9642 {
9643 Some(result) => result,
9644 None => return Ok(Vec::new()),
9645 };
9646
9647 let project = cx.update(|cx| {
9648 project::Project::remote(
9649 session,
9650 app_state.client.clone(),
9651 app_state.node_runtime.clone(),
9652 app_state.user_store.clone(),
9653 app_state.languages.clone(),
9654 app_state.fs.clone(),
9655 true,
9656 cx,
9657 )
9658 });
9659
9660 open_remote_project_inner(
9661 project,
9662 paths,
9663 workspace_id,
9664 serialized_workspace,
9665 app_state,
9666 window,
9667 cx,
9668 )
9669 .await
9670 })
9671}
9672
9673pub fn open_remote_project_with_existing_connection(
9674 connection_options: RemoteConnectionOptions,
9675 project: Entity<Project>,
9676 paths: Vec<PathBuf>,
9677 app_state: Arc<AppState>,
9678 window: WindowHandle<MultiWorkspace>,
9679 cx: &mut AsyncApp,
9680) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9681 cx.spawn(async move |cx| {
9682 let (workspace_id, serialized_workspace) =
9683 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9684
9685 open_remote_project_inner(
9686 project,
9687 paths,
9688 workspace_id,
9689 serialized_workspace,
9690 app_state,
9691 window,
9692 cx,
9693 )
9694 .await
9695 })
9696}
9697
9698async fn open_remote_project_inner(
9699 project: Entity<Project>,
9700 paths: Vec<PathBuf>,
9701 workspace_id: WorkspaceId,
9702 serialized_workspace: Option<SerializedWorkspace>,
9703 app_state: Arc<AppState>,
9704 window: WindowHandle<MultiWorkspace>,
9705 cx: &mut AsyncApp,
9706) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9707 let db = cx.update(|cx| WorkspaceDb::global(cx));
9708 let toolchains = db.toolchains(workspace_id).await?;
9709 for (toolchain, worktree_path, path) in toolchains {
9710 project
9711 .update(cx, |this, cx| {
9712 let Some(worktree_id) =
9713 this.find_worktree(&worktree_path, cx)
9714 .and_then(|(worktree, rel_path)| {
9715 if rel_path.is_empty() {
9716 Some(worktree.read(cx).id())
9717 } else {
9718 None
9719 }
9720 })
9721 else {
9722 return Task::ready(None);
9723 };
9724
9725 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9726 })
9727 .await;
9728 }
9729 let mut project_paths_to_open = vec![];
9730 let mut project_path_errors = vec![];
9731
9732 for path in paths {
9733 let result = cx
9734 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9735 .await;
9736 match result {
9737 Ok((_, project_path)) => {
9738 project_paths_to_open.push((path.clone(), Some(project_path)));
9739 }
9740 Err(error) => {
9741 project_path_errors.push(error);
9742 }
9743 };
9744 }
9745
9746 if project_paths_to_open.is_empty() {
9747 return Err(project_path_errors.pop().context("no paths given")?);
9748 }
9749
9750 let workspace = window.update(cx, |multi_workspace, window, cx| {
9751 telemetry::event!("SSH Project Opened");
9752
9753 let new_workspace = cx.new(|cx| {
9754 let mut workspace =
9755 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9756 workspace.update_history(cx);
9757
9758 if let Some(ref serialized) = serialized_workspace {
9759 workspace.centered_layout = serialized.centered_layout;
9760 }
9761
9762 workspace
9763 });
9764
9765 multi_workspace.activate(new_workspace.clone(), window, cx);
9766 new_workspace
9767 })?;
9768
9769 let items = window
9770 .update(cx, |_, window, cx| {
9771 window.activate_window();
9772 workspace.update(cx, |_workspace, cx| {
9773 open_items(serialized_workspace, project_paths_to_open, window, cx)
9774 })
9775 })?
9776 .await?;
9777
9778 workspace.update(cx, |workspace, cx| {
9779 for error in project_path_errors {
9780 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9781 if let Some(path) = error.error_tag("path") {
9782 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9783 }
9784 } else {
9785 workspace.show_error(&error, cx)
9786 }
9787 }
9788 });
9789
9790 Ok(items.into_iter().map(|item| item?.ok()).collect())
9791}
9792
9793fn deserialize_remote_project(
9794 connection_options: RemoteConnectionOptions,
9795 paths: Vec<PathBuf>,
9796 cx: &AsyncApp,
9797) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9798 let db = cx.update(|cx| WorkspaceDb::global(cx));
9799 cx.background_spawn(async move {
9800 let remote_connection_id = db
9801 .get_or_create_remote_connection(connection_options)
9802 .await?;
9803
9804 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9805
9806 let workspace_id = if let Some(workspace_id) =
9807 serialized_workspace.as_ref().map(|workspace| workspace.id)
9808 {
9809 workspace_id
9810 } else {
9811 db.next_id().await?
9812 };
9813
9814 Ok((workspace_id, serialized_workspace))
9815 })
9816}
9817
9818pub fn join_in_room_project(
9819 project_id: u64,
9820 follow_user_id: u64,
9821 app_state: Arc<AppState>,
9822 cx: &mut App,
9823) -> Task<Result<()>> {
9824 let windows = cx.windows();
9825 cx.spawn(async move |cx| {
9826 let existing_window_and_workspace: Option<(
9827 WindowHandle<MultiWorkspace>,
9828 Entity<Workspace>,
9829 )> = windows.into_iter().find_map(|window_handle| {
9830 window_handle
9831 .downcast::<MultiWorkspace>()
9832 .and_then(|window_handle| {
9833 window_handle
9834 .update(cx, |multi_workspace, _window, cx| {
9835 for workspace in multi_workspace.workspaces() {
9836 if workspace.read(cx).project().read(cx).remote_id()
9837 == Some(project_id)
9838 {
9839 return Some((window_handle, workspace.clone()));
9840 }
9841 }
9842 None
9843 })
9844 .unwrap_or(None)
9845 })
9846 });
9847
9848 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9849 existing_window_and_workspace
9850 {
9851 existing_window
9852 .update(cx, |multi_workspace, window, cx| {
9853 multi_workspace.activate(target_workspace, window, cx);
9854 })
9855 .ok();
9856 existing_window
9857 } else {
9858 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9859 let project = cx
9860 .update(|cx| {
9861 active_call.0.join_project(
9862 project_id,
9863 app_state.languages.clone(),
9864 app_state.fs.clone(),
9865 cx,
9866 )
9867 })
9868 .await?;
9869
9870 let window_bounds_override = window_bounds_env_override();
9871 cx.update(|cx| {
9872 let mut options = (app_state.build_window_options)(None, cx);
9873 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9874 cx.open_window(options, |window, cx| {
9875 let workspace = cx.new(|cx| {
9876 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9877 });
9878 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9879 })
9880 })?
9881 };
9882
9883 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9884 cx.activate(true);
9885 window.activate_window();
9886
9887 // We set the active workspace above, so this is the correct workspace.
9888 let workspace = multi_workspace.workspace().clone();
9889 workspace.update(cx, |workspace, cx| {
9890 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9891 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9892 .or_else(|| {
9893 // If we couldn't follow the given user, follow the host instead.
9894 let collaborator = workspace
9895 .project()
9896 .read(cx)
9897 .collaborators()
9898 .values()
9899 .find(|collaborator| collaborator.is_host)?;
9900 Some(collaborator.peer_id)
9901 });
9902
9903 if let Some(follow_peer_id) = follow_peer_id {
9904 workspace.follow(follow_peer_id, window, cx);
9905 }
9906 });
9907 })?;
9908
9909 anyhow::Ok(())
9910 })
9911}
9912
9913pub fn reload(cx: &mut App) {
9914 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9915 let mut workspace_windows = cx
9916 .windows()
9917 .into_iter()
9918 .filter_map(|window| window.downcast::<MultiWorkspace>())
9919 .collect::<Vec<_>>();
9920
9921 // If multiple windows have unsaved changes, and need a save prompt,
9922 // prompt in the active window before switching to a different window.
9923 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9924
9925 let mut prompt = None;
9926 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9927 prompt = window
9928 .update(cx, |_, window, cx| {
9929 window.prompt(
9930 PromptLevel::Info,
9931 "Are you sure you want to restart?",
9932 None,
9933 &["Restart", "Cancel"],
9934 cx,
9935 )
9936 })
9937 .ok();
9938 }
9939
9940 cx.spawn(async move |cx| {
9941 if let Some(prompt) = prompt {
9942 let answer = prompt.await?;
9943 if answer != 0 {
9944 return anyhow::Ok(());
9945 }
9946 }
9947
9948 // If the user cancels any save prompt, then keep the app open.
9949 for window in workspace_windows {
9950 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9951 let workspace = multi_workspace.workspace().clone();
9952 workspace.update(cx, |workspace, cx| {
9953 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9954 })
9955 }) && !should_close.await?
9956 {
9957 return anyhow::Ok(());
9958 }
9959 }
9960 cx.update(|cx| cx.restart());
9961 anyhow::Ok(())
9962 })
9963 .detach_and_log_err(cx);
9964}
9965
9966fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9967 let mut parts = value.split(',');
9968 let x: usize = parts.next()?.parse().ok()?;
9969 let y: usize = parts.next()?.parse().ok()?;
9970 Some(point(px(x as f32), px(y as f32)))
9971}
9972
9973fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9974 let mut parts = value.split(',');
9975 let width: usize = parts.next()?.parse().ok()?;
9976 let height: usize = parts.next()?.parse().ok()?;
9977 Some(size(px(width as f32), px(height as f32)))
9978}
9979
9980/// Add client-side decorations (rounded corners, shadows, resize handling) when
9981/// appropriate.
9982///
9983/// The `border_radius_tiling` parameter allows overriding which corners get
9984/// rounded, independently of the actual window tiling state. This is used
9985/// specifically for the workspace switcher sidebar: when the sidebar is open,
9986/// we want square corners on the left (so the sidebar appears flush with the
9987/// window edge) but we still need the shadow padding for proper visual
9988/// appearance. Unlike actual window tiling, this only affects border radius -
9989/// not padding or shadows.
9990pub fn client_side_decorations(
9991 element: impl IntoElement,
9992 window: &mut Window,
9993 cx: &mut App,
9994 border_radius_tiling: Tiling,
9995) -> Stateful<Div> {
9996 const BORDER_SIZE: Pixels = px(1.0);
9997 let decorations = window.window_decorations();
9998 let tiling = match decorations {
9999 Decorations::Server => Tiling::default(),
10000 Decorations::Client { tiling } => tiling,
10001 };
10002
10003 match decorations {
10004 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
10005 Decorations::Server => window.set_client_inset(px(0.0)),
10006 }
10007
10008 struct GlobalResizeEdge(ResizeEdge);
10009 impl Global for GlobalResizeEdge {}
10010
10011 div()
10012 .id("window-backdrop")
10013 .bg(transparent_black())
10014 .map(|div| match decorations {
10015 Decorations::Server => div,
10016 Decorations::Client { .. } => div
10017 .when(
10018 !(tiling.top
10019 || tiling.right
10020 || border_radius_tiling.top
10021 || border_radius_tiling.right),
10022 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10023 )
10024 .when(
10025 !(tiling.top
10026 || tiling.left
10027 || border_radius_tiling.top
10028 || border_radius_tiling.left),
10029 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10030 )
10031 .when(
10032 !(tiling.bottom
10033 || tiling.right
10034 || border_radius_tiling.bottom
10035 || border_radius_tiling.right),
10036 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10037 )
10038 .when(
10039 !(tiling.bottom
10040 || tiling.left
10041 || border_radius_tiling.bottom
10042 || border_radius_tiling.left),
10043 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10044 )
10045 .when(!tiling.top, |div| {
10046 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10047 })
10048 .when(!tiling.bottom, |div| {
10049 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10050 })
10051 .when(!tiling.left, |div| {
10052 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10053 })
10054 .when(!tiling.right, |div| {
10055 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10056 })
10057 .on_mouse_move(move |e, window, cx| {
10058 let size = window.window_bounds().get_bounds().size;
10059 let pos = e.position;
10060
10061 let new_edge =
10062 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10063
10064 let edge = cx.try_global::<GlobalResizeEdge>();
10065 if new_edge != edge.map(|edge| edge.0) {
10066 window
10067 .window_handle()
10068 .update(cx, |workspace, _, cx| {
10069 cx.notify(workspace.entity_id());
10070 })
10071 .ok();
10072 }
10073 })
10074 .on_mouse_down(MouseButton::Left, move |e, window, _| {
10075 let size = window.window_bounds().get_bounds().size;
10076 let pos = e.position;
10077
10078 let edge = match resize_edge(
10079 pos,
10080 theme::CLIENT_SIDE_DECORATION_SHADOW,
10081 size,
10082 tiling,
10083 ) {
10084 Some(value) => value,
10085 None => return,
10086 };
10087
10088 window.start_window_resize(edge);
10089 }),
10090 })
10091 .size_full()
10092 .child(
10093 div()
10094 .cursor(CursorStyle::Arrow)
10095 .map(|div| match decorations {
10096 Decorations::Server => div,
10097 Decorations::Client { .. } => div
10098 .border_color(cx.theme().colors().border)
10099 .when(
10100 !(tiling.top
10101 || tiling.right
10102 || border_radius_tiling.top
10103 || border_radius_tiling.right),
10104 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10105 )
10106 .when(
10107 !(tiling.top
10108 || tiling.left
10109 || border_radius_tiling.top
10110 || border_radius_tiling.left),
10111 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10112 )
10113 .when(
10114 !(tiling.bottom
10115 || tiling.right
10116 || border_radius_tiling.bottom
10117 || border_radius_tiling.right),
10118 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10119 )
10120 .when(
10121 !(tiling.bottom
10122 || tiling.left
10123 || border_radius_tiling.bottom
10124 || border_radius_tiling.left),
10125 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10126 )
10127 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10128 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10129 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10130 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10131 .when(!tiling.is_tiled(), |div| {
10132 div.shadow(vec![gpui::BoxShadow {
10133 color: Hsla {
10134 h: 0.,
10135 s: 0.,
10136 l: 0.,
10137 a: 0.4,
10138 },
10139 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10140 spread_radius: px(0.),
10141 offset: point(px(0.0), px(0.0)),
10142 }])
10143 }),
10144 })
10145 .on_mouse_move(|_e, _, cx| {
10146 cx.stop_propagation();
10147 })
10148 .size_full()
10149 .child(element),
10150 )
10151 .map(|div| match decorations {
10152 Decorations::Server => div,
10153 Decorations::Client { tiling, .. } => div.child(
10154 canvas(
10155 |_bounds, window, _| {
10156 window.insert_hitbox(
10157 Bounds::new(
10158 point(px(0.0), px(0.0)),
10159 window.window_bounds().get_bounds().size,
10160 ),
10161 HitboxBehavior::Normal,
10162 )
10163 },
10164 move |_bounds, hitbox, window, cx| {
10165 let mouse = window.mouse_position();
10166 let size = window.window_bounds().get_bounds().size;
10167 let Some(edge) =
10168 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10169 else {
10170 return;
10171 };
10172 cx.set_global(GlobalResizeEdge(edge));
10173 window.set_cursor_style(
10174 match edge {
10175 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10176 ResizeEdge::Left | ResizeEdge::Right => {
10177 CursorStyle::ResizeLeftRight
10178 }
10179 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10180 CursorStyle::ResizeUpLeftDownRight
10181 }
10182 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10183 CursorStyle::ResizeUpRightDownLeft
10184 }
10185 },
10186 &hitbox,
10187 );
10188 },
10189 )
10190 .size_full()
10191 .absolute(),
10192 ),
10193 })
10194}
10195
10196fn resize_edge(
10197 pos: Point<Pixels>,
10198 shadow_size: Pixels,
10199 window_size: Size<Pixels>,
10200 tiling: Tiling,
10201) -> Option<ResizeEdge> {
10202 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10203 if bounds.contains(&pos) {
10204 return None;
10205 }
10206
10207 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10208 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10209 if !tiling.top && top_left_bounds.contains(&pos) {
10210 return Some(ResizeEdge::TopLeft);
10211 }
10212
10213 let top_right_bounds = Bounds::new(
10214 Point::new(window_size.width - corner_size.width, px(0.)),
10215 corner_size,
10216 );
10217 if !tiling.top && top_right_bounds.contains(&pos) {
10218 return Some(ResizeEdge::TopRight);
10219 }
10220
10221 let bottom_left_bounds = Bounds::new(
10222 Point::new(px(0.), window_size.height - corner_size.height),
10223 corner_size,
10224 );
10225 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10226 return Some(ResizeEdge::BottomLeft);
10227 }
10228
10229 let bottom_right_bounds = Bounds::new(
10230 Point::new(
10231 window_size.width - corner_size.width,
10232 window_size.height - corner_size.height,
10233 ),
10234 corner_size,
10235 );
10236 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10237 return Some(ResizeEdge::BottomRight);
10238 }
10239
10240 if !tiling.top && pos.y < shadow_size {
10241 Some(ResizeEdge::Top)
10242 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10243 Some(ResizeEdge::Bottom)
10244 } else if !tiling.left && pos.x < shadow_size {
10245 Some(ResizeEdge::Left)
10246 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10247 Some(ResizeEdge::Right)
10248 } else {
10249 None
10250 }
10251}
10252
10253fn join_pane_into_active(
10254 active_pane: &Entity<Pane>,
10255 pane: &Entity<Pane>,
10256 window: &mut Window,
10257 cx: &mut App,
10258) {
10259 if pane == active_pane {
10260 } else if pane.read(cx).items_len() == 0 {
10261 pane.update(cx, |_, cx| {
10262 cx.emit(pane::Event::Remove {
10263 focus_on_pane: None,
10264 });
10265 })
10266 } else {
10267 move_all_items(pane, active_pane, window, cx);
10268 }
10269}
10270
10271fn move_all_items(
10272 from_pane: &Entity<Pane>,
10273 to_pane: &Entity<Pane>,
10274 window: &mut Window,
10275 cx: &mut App,
10276) {
10277 let destination_is_different = from_pane != to_pane;
10278 let mut moved_items = 0;
10279 for (item_ix, item_handle) in from_pane
10280 .read(cx)
10281 .items()
10282 .enumerate()
10283 .map(|(ix, item)| (ix, item.clone()))
10284 .collect::<Vec<_>>()
10285 {
10286 let ix = item_ix - moved_items;
10287 if destination_is_different {
10288 // Close item from previous pane
10289 from_pane.update(cx, |source, cx| {
10290 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10291 });
10292 moved_items += 1;
10293 }
10294
10295 // This automatically removes duplicate items in the pane
10296 to_pane.update(cx, |destination, cx| {
10297 destination.add_item(item_handle, true, true, None, window, cx);
10298 window.focus(&destination.focus_handle(cx), cx)
10299 });
10300 }
10301}
10302
10303pub fn move_item(
10304 source: &Entity<Pane>,
10305 destination: &Entity<Pane>,
10306 item_id_to_move: EntityId,
10307 destination_index: usize,
10308 activate: bool,
10309 window: &mut Window,
10310 cx: &mut App,
10311) {
10312 let Some((item_ix, item_handle)) = source
10313 .read(cx)
10314 .items()
10315 .enumerate()
10316 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10317 .map(|(ix, item)| (ix, item.clone()))
10318 else {
10319 // Tab was closed during drag
10320 return;
10321 };
10322
10323 if source != destination {
10324 // Close item from previous pane
10325 source.update(cx, |source, cx| {
10326 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10327 });
10328 }
10329
10330 // This automatically removes duplicate items in the pane
10331 destination.update(cx, |destination, cx| {
10332 destination.add_item_inner(
10333 item_handle,
10334 activate,
10335 activate,
10336 activate,
10337 Some(destination_index),
10338 window,
10339 cx,
10340 );
10341 if activate {
10342 window.focus(&destination.focus_handle(cx), cx)
10343 }
10344 });
10345}
10346
10347pub fn move_active_item(
10348 source: &Entity<Pane>,
10349 destination: &Entity<Pane>,
10350 focus_destination: bool,
10351 close_if_empty: bool,
10352 window: &mut Window,
10353 cx: &mut App,
10354) {
10355 if source == destination {
10356 return;
10357 }
10358 let Some(active_item) = source.read(cx).active_item() else {
10359 return;
10360 };
10361 source.update(cx, |source_pane, cx| {
10362 let item_id = active_item.item_id();
10363 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10364 destination.update(cx, |target_pane, cx| {
10365 target_pane.add_item(
10366 active_item,
10367 focus_destination,
10368 focus_destination,
10369 Some(target_pane.items_len()),
10370 window,
10371 cx,
10372 );
10373 });
10374 });
10375}
10376
10377pub fn clone_active_item(
10378 workspace_id: Option<WorkspaceId>,
10379 source: &Entity<Pane>,
10380 destination: &Entity<Pane>,
10381 focus_destination: bool,
10382 window: &mut Window,
10383 cx: &mut App,
10384) {
10385 if source == destination {
10386 return;
10387 }
10388 let Some(active_item) = source.read(cx).active_item() else {
10389 return;
10390 };
10391 if !active_item.can_split(cx) {
10392 return;
10393 }
10394 let destination = destination.downgrade();
10395 let task = active_item.clone_on_split(workspace_id, window, cx);
10396 window
10397 .spawn(cx, async move |cx| {
10398 let Some(clone) = task.await else {
10399 return;
10400 };
10401 destination
10402 .update_in(cx, |target_pane, window, cx| {
10403 target_pane.add_item(
10404 clone,
10405 focus_destination,
10406 focus_destination,
10407 Some(target_pane.items_len()),
10408 window,
10409 cx,
10410 );
10411 })
10412 .log_err();
10413 })
10414 .detach();
10415}
10416
10417#[derive(Debug)]
10418pub struct WorkspacePosition {
10419 pub window_bounds: Option<WindowBounds>,
10420 pub display: Option<Uuid>,
10421 pub centered_layout: bool,
10422}
10423
10424pub fn remote_workspace_position_from_db(
10425 connection_options: RemoteConnectionOptions,
10426 paths_to_open: &[PathBuf],
10427 cx: &App,
10428) -> Task<Result<WorkspacePosition>> {
10429 let paths = paths_to_open.to_vec();
10430 let db = WorkspaceDb::global(cx);
10431 let kvp = db::kvp::KeyValueStore::global(cx);
10432
10433 cx.background_spawn(async move {
10434 let remote_connection_id = db
10435 .get_or_create_remote_connection(connection_options)
10436 .await
10437 .context("fetching serialized ssh project")?;
10438 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10439
10440 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10441 (Some(WindowBounds::Windowed(bounds)), None)
10442 } else {
10443 let restorable_bounds = serialized_workspace
10444 .as_ref()
10445 .and_then(|workspace| {
10446 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10447 })
10448 .or_else(|| persistence::read_default_window_bounds(&kvp));
10449
10450 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10451 (Some(serialized_bounds), Some(serialized_display))
10452 } else {
10453 (None, None)
10454 }
10455 };
10456
10457 let centered_layout = serialized_workspace
10458 .as_ref()
10459 .map(|w| w.centered_layout)
10460 .unwrap_or(false);
10461
10462 Ok(WorkspacePosition {
10463 window_bounds,
10464 display,
10465 centered_layout,
10466 })
10467 })
10468}
10469
10470pub fn with_active_or_new_workspace(
10471 cx: &mut App,
10472 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10473) {
10474 match cx
10475 .active_window()
10476 .and_then(|w| w.downcast::<MultiWorkspace>())
10477 {
10478 Some(multi_workspace) => {
10479 cx.defer(move |cx| {
10480 multi_workspace
10481 .update(cx, |multi_workspace, window, cx| {
10482 let workspace = multi_workspace.workspace().clone();
10483 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10484 })
10485 .log_err();
10486 });
10487 }
10488 None => {
10489 let app_state = AppState::global(cx);
10490 open_new(
10491 OpenOptions::default(),
10492 app_state,
10493 cx,
10494 move |workspace, window, cx| f(workspace, window, cx),
10495 )
10496 .detach_and_log_err(cx);
10497 }
10498 }
10499}
10500
10501/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10502/// key. This migration path only runs once per panel per workspace.
10503fn load_legacy_panel_size(
10504 panel_key: &str,
10505 dock_position: DockPosition,
10506 workspace: &Workspace,
10507 cx: &mut App,
10508) -> Option<Pixels> {
10509 #[derive(Deserialize)]
10510 struct LegacyPanelState {
10511 #[serde(default)]
10512 width: Option<Pixels>,
10513 #[serde(default)]
10514 height: Option<Pixels>,
10515 }
10516
10517 let workspace_id = workspace
10518 .database_id()
10519 .map(|id| i64::from(id).to_string())
10520 .or_else(|| workspace.session_id())?;
10521
10522 let legacy_key = match panel_key {
10523 "ProjectPanel" => {
10524 format!("{}-{:?}", "ProjectPanel", workspace_id)
10525 }
10526 "OutlinePanel" => {
10527 format!("{}-{:?}", "OutlinePanel", workspace_id)
10528 }
10529 "GitPanel" => {
10530 format!("{}-{:?}", "GitPanel", workspace_id)
10531 }
10532 "TerminalPanel" => {
10533 format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10534 }
10535 _ => return None,
10536 };
10537
10538 let kvp = db::kvp::KeyValueStore::global(cx);
10539 let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10540 let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10541 let size = match dock_position {
10542 DockPosition::Bottom => state.height,
10543 DockPosition::Left | DockPosition::Right => state.width,
10544 }?;
10545
10546 cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10547 .detach_and_log_err(cx);
10548
10549 Some(size)
10550}
10551
10552#[cfg(test)]
10553mod tests {
10554 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10555
10556 use super::*;
10557 use crate::{
10558 dock::{PanelEvent, test::TestPanel},
10559 item::{
10560 ItemBufferKind, ItemEvent,
10561 test::{TestItem, TestProjectItem},
10562 },
10563 };
10564 use fs::FakeFs;
10565 use gpui::{
10566 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10567 UpdateGlobal, VisualTestContext, px,
10568 };
10569 use project::{Project, ProjectEntryId};
10570 use serde_json::json;
10571 use settings::SettingsStore;
10572 use util::path;
10573 use util::rel_path::rel_path;
10574
10575 #[gpui::test]
10576 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10577 init_test(cx);
10578
10579 let fs = FakeFs::new(cx.executor());
10580 let project = Project::test(fs, [], cx).await;
10581 let (workspace, cx) =
10582 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10583
10584 // Adding an item with no ambiguity renders the tab without detail.
10585 let item1 = cx.new(|cx| {
10586 let mut item = TestItem::new(cx);
10587 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10588 item
10589 });
10590 workspace.update_in(cx, |workspace, window, cx| {
10591 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10592 });
10593 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10594
10595 // Adding an item that creates ambiguity increases the level of detail on
10596 // both tabs.
10597 let item2 = cx.new_window_entity(|_window, cx| {
10598 let mut item = TestItem::new(cx);
10599 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10600 item
10601 });
10602 workspace.update_in(cx, |workspace, window, cx| {
10603 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10604 });
10605 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10606 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10607
10608 // Adding an item that creates ambiguity increases the level of detail only
10609 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10610 // we stop at the highest detail available.
10611 let item3 = cx.new(|cx| {
10612 let mut item = TestItem::new(cx);
10613 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10614 item
10615 });
10616 workspace.update_in(cx, |workspace, window, cx| {
10617 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10618 });
10619 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10620 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10621 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10622 }
10623
10624 #[gpui::test]
10625 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10626 init_test(cx);
10627
10628 let fs = FakeFs::new(cx.executor());
10629 fs.insert_tree(
10630 "/root1",
10631 json!({
10632 "one.txt": "",
10633 "two.txt": "",
10634 }),
10635 )
10636 .await;
10637 fs.insert_tree(
10638 "/root2",
10639 json!({
10640 "three.txt": "",
10641 }),
10642 )
10643 .await;
10644
10645 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10646 let (workspace, cx) =
10647 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10648 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10649 let worktree_id = project.update(cx, |project, cx| {
10650 project.worktrees(cx).next().unwrap().read(cx).id()
10651 });
10652
10653 let item1 = cx.new(|cx| {
10654 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10655 });
10656 let item2 = cx.new(|cx| {
10657 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10658 });
10659
10660 // Add an item to an empty pane
10661 workspace.update_in(cx, |workspace, window, cx| {
10662 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10663 });
10664 project.update(cx, |project, cx| {
10665 assert_eq!(
10666 project.active_entry(),
10667 project
10668 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10669 .map(|e| e.id)
10670 );
10671 });
10672 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10673
10674 // Add a second item to a non-empty pane
10675 workspace.update_in(cx, |workspace, window, cx| {
10676 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10677 });
10678 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10679 project.update(cx, |project, cx| {
10680 assert_eq!(
10681 project.active_entry(),
10682 project
10683 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10684 .map(|e| e.id)
10685 );
10686 });
10687
10688 // Close the active item
10689 pane.update_in(cx, |pane, window, cx| {
10690 pane.close_active_item(&Default::default(), window, cx)
10691 })
10692 .await
10693 .unwrap();
10694 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10695 project.update(cx, |project, cx| {
10696 assert_eq!(
10697 project.active_entry(),
10698 project
10699 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10700 .map(|e| e.id)
10701 );
10702 });
10703
10704 // Add a project folder
10705 project
10706 .update(cx, |project, cx| {
10707 project.find_or_create_worktree("root2", true, cx)
10708 })
10709 .await
10710 .unwrap();
10711 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10712
10713 // Remove a project folder
10714 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10715 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10716 }
10717
10718 #[gpui::test]
10719 async fn test_close_window(cx: &mut TestAppContext) {
10720 init_test(cx);
10721
10722 let fs = FakeFs::new(cx.executor());
10723 fs.insert_tree("/root", json!({ "one": "" })).await;
10724
10725 let project = Project::test(fs, ["root".as_ref()], cx).await;
10726 let (workspace, cx) =
10727 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10728
10729 // When there are no dirty items, there's nothing to do.
10730 let item1 = cx.new(TestItem::new);
10731 workspace.update_in(cx, |w, window, cx| {
10732 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10733 });
10734 let task = workspace.update_in(cx, |w, window, cx| {
10735 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10736 });
10737 assert!(task.await.unwrap());
10738
10739 // When there are dirty untitled items, prompt to save each one. If the user
10740 // cancels any prompt, then abort.
10741 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10742 let item3 = cx.new(|cx| {
10743 TestItem::new(cx)
10744 .with_dirty(true)
10745 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10746 });
10747 workspace.update_in(cx, |w, window, cx| {
10748 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10749 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10750 });
10751 let task = workspace.update_in(cx, |w, window, cx| {
10752 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10753 });
10754 cx.executor().run_until_parked();
10755 cx.simulate_prompt_answer("Cancel"); // cancel save all
10756 cx.executor().run_until_parked();
10757 assert!(!cx.has_pending_prompt());
10758 assert!(!task.await.unwrap());
10759 }
10760
10761 #[gpui::test]
10762 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10763 init_test(cx);
10764
10765 let fs = FakeFs::new(cx.executor());
10766 fs.insert_tree("/root", json!({ "one": "" })).await;
10767
10768 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10769 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10770 let multi_workspace_handle =
10771 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10772 cx.run_until_parked();
10773
10774 let workspace_a = multi_workspace_handle
10775 .read_with(cx, |mw, _| mw.workspace().clone())
10776 .unwrap();
10777
10778 let workspace_b = multi_workspace_handle
10779 .update(cx, |mw, window, cx| {
10780 mw.test_add_workspace(project_b, window, cx)
10781 })
10782 .unwrap();
10783
10784 // Activate workspace A
10785 multi_workspace_handle
10786 .update(cx, |mw, window, cx| {
10787 let workspace = mw.workspaces()[0].clone();
10788 mw.activate(workspace, window, cx);
10789 })
10790 .unwrap();
10791
10792 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10793
10794 // Workspace A has a clean item
10795 let item_a = cx.new(TestItem::new);
10796 workspace_a.update_in(cx, |w, window, cx| {
10797 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10798 });
10799
10800 // Workspace B has a dirty item
10801 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10802 workspace_b.update_in(cx, |w, window, cx| {
10803 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10804 });
10805
10806 // Verify workspace A is active
10807 multi_workspace_handle
10808 .read_with(cx, |mw, _| {
10809 assert_eq!(mw.active_workspace_index(), 0);
10810 })
10811 .unwrap();
10812
10813 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10814 multi_workspace_handle
10815 .update(cx, |mw, window, cx| {
10816 mw.close_window(&CloseWindow, window, cx);
10817 })
10818 .unwrap();
10819 cx.run_until_parked();
10820
10821 // Workspace B should now be active since it has dirty items that need attention
10822 multi_workspace_handle
10823 .read_with(cx, |mw, _| {
10824 assert_eq!(
10825 mw.active_workspace_index(),
10826 1,
10827 "workspace B should be activated when it prompts"
10828 );
10829 })
10830 .unwrap();
10831
10832 // User cancels the save prompt from workspace B
10833 cx.simulate_prompt_answer("Cancel");
10834 cx.run_until_parked();
10835
10836 // Window should still exist because workspace B's close was cancelled
10837 assert!(
10838 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10839 "window should still exist after cancelling one workspace's close"
10840 );
10841 }
10842
10843 #[gpui::test]
10844 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10845 init_test(cx);
10846
10847 // Register TestItem as a serializable item
10848 cx.update(|cx| {
10849 register_serializable_item::<TestItem>(cx);
10850 });
10851
10852 let fs = FakeFs::new(cx.executor());
10853 fs.insert_tree("/root", json!({ "one": "" })).await;
10854
10855 let project = Project::test(fs, ["root".as_ref()], cx).await;
10856 let (workspace, cx) =
10857 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10858
10859 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10860 let item1 = cx.new(|cx| {
10861 TestItem::new(cx)
10862 .with_dirty(true)
10863 .with_serialize(|| Some(Task::ready(Ok(()))))
10864 });
10865 let item2 = cx.new(|cx| {
10866 TestItem::new(cx)
10867 .with_dirty(true)
10868 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10869 .with_serialize(|| Some(Task::ready(Ok(()))))
10870 });
10871 workspace.update_in(cx, |w, window, cx| {
10872 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10873 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10874 });
10875 let task = workspace.update_in(cx, |w, window, cx| {
10876 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10877 });
10878 assert!(task.await.unwrap());
10879 }
10880
10881 #[gpui::test]
10882 async fn test_close_pane_items(cx: &mut TestAppContext) {
10883 init_test(cx);
10884
10885 let fs = FakeFs::new(cx.executor());
10886
10887 let project = Project::test(fs, None, cx).await;
10888 let (workspace, cx) =
10889 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10890
10891 let item1 = cx.new(|cx| {
10892 TestItem::new(cx)
10893 .with_dirty(true)
10894 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10895 });
10896 let item2 = cx.new(|cx| {
10897 TestItem::new(cx)
10898 .with_dirty(true)
10899 .with_conflict(true)
10900 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10901 });
10902 let item3 = cx.new(|cx| {
10903 TestItem::new(cx)
10904 .with_dirty(true)
10905 .with_conflict(true)
10906 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10907 });
10908 let item4 = cx.new(|cx| {
10909 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10910 let project_item = TestProjectItem::new_untitled(cx);
10911 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10912 project_item
10913 }])
10914 });
10915 let pane = workspace.update_in(cx, |workspace, window, cx| {
10916 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10917 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10918 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10919 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10920 workspace.active_pane().clone()
10921 });
10922
10923 let close_items = pane.update_in(cx, |pane, window, cx| {
10924 pane.activate_item(1, true, true, window, cx);
10925 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10926 let item1_id = item1.item_id();
10927 let item3_id = item3.item_id();
10928 let item4_id = item4.item_id();
10929 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10930 [item1_id, item3_id, item4_id].contains(&id)
10931 })
10932 });
10933 cx.executor().run_until_parked();
10934
10935 assert!(cx.has_pending_prompt());
10936 cx.simulate_prompt_answer("Save all");
10937
10938 cx.executor().run_until_parked();
10939
10940 // Item 1 is saved. There's a prompt to save item 3.
10941 pane.update(cx, |pane, cx| {
10942 assert_eq!(item1.read(cx).save_count, 1);
10943 assert_eq!(item1.read(cx).save_as_count, 0);
10944 assert_eq!(item1.read(cx).reload_count, 0);
10945 assert_eq!(pane.items_len(), 3);
10946 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10947 });
10948 assert!(cx.has_pending_prompt());
10949
10950 // Cancel saving item 3.
10951 cx.simulate_prompt_answer("Discard");
10952 cx.executor().run_until_parked();
10953
10954 // Item 3 is reloaded. There's a prompt to save item 4.
10955 pane.update(cx, |pane, cx| {
10956 assert_eq!(item3.read(cx).save_count, 0);
10957 assert_eq!(item3.read(cx).save_as_count, 0);
10958 assert_eq!(item3.read(cx).reload_count, 1);
10959 assert_eq!(pane.items_len(), 2);
10960 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10961 });
10962
10963 // There's a prompt for a path for item 4.
10964 cx.simulate_new_path_selection(|_| Some(Default::default()));
10965 close_items.await.unwrap();
10966
10967 // The requested items are closed.
10968 pane.update(cx, |pane, cx| {
10969 assert_eq!(item4.read(cx).save_count, 0);
10970 assert_eq!(item4.read(cx).save_as_count, 1);
10971 assert_eq!(item4.read(cx).reload_count, 0);
10972 assert_eq!(pane.items_len(), 1);
10973 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10974 });
10975 }
10976
10977 #[gpui::test]
10978 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10979 init_test(cx);
10980
10981 let fs = FakeFs::new(cx.executor());
10982 let project = Project::test(fs, [], cx).await;
10983 let (workspace, cx) =
10984 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10985
10986 // Create several workspace items with single project entries, and two
10987 // workspace items with multiple project entries.
10988 let single_entry_items = (0..=4)
10989 .map(|project_entry_id| {
10990 cx.new(|cx| {
10991 TestItem::new(cx)
10992 .with_dirty(true)
10993 .with_project_items(&[dirty_project_item(
10994 project_entry_id,
10995 &format!("{project_entry_id}.txt"),
10996 cx,
10997 )])
10998 })
10999 })
11000 .collect::<Vec<_>>();
11001 let item_2_3 = cx.new(|cx| {
11002 TestItem::new(cx)
11003 .with_dirty(true)
11004 .with_buffer_kind(ItemBufferKind::Multibuffer)
11005 .with_project_items(&[
11006 single_entry_items[2].read(cx).project_items[0].clone(),
11007 single_entry_items[3].read(cx).project_items[0].clone(),
11008 ])
11009 });
11010 let item_3_4 = cx.new(|cx| {
11011 TestItem::new(cx)
11012 .with_dirty(true)
11013 .with_buffer_kind(ItemBufferKind::Multibuffer)
11014 .with_project_items(&[
11015 single_entry_items[3].read(cx).project_items[0].clone(),
11016 single_entry_items[4].read(cx).project_items[0].clone(),
11017 ])
11018 });
11019
11020 // Create two panes that contain the following project entries:
11021 // left pane:
11022 // multi-entry items: (2, 3)
11023 // single-entry items: 0, 2, 3, 4
11024 // right pane:
11025 // single-entry items: 4, 1
11026 // multi-entry items: (3, 4)
11027 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11028 let left_pane = workspace.active_pane().clone();
11029 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11030 workspace.add_item_to_active_pane(
11031 single_entry_items[0].boxed_clone(),
11032 None,
11033 true,
11034 window,
11035 cx,
11036 );
11037 workspace.add_item_to_active_pane(
11038 single_entry_items[2].boxed_clone(),
11039 None,
11040 true,
11041 window,
11042 cx,
11043 );
11044 workspace.add_item_to_active_pane(
11045 single_entry_items[3].boxed_clone(),
11046 None,
11047 true,
11048 window,
11049 cx,
11050 );
11051 workspace.add_item_to_active_pane(
11052 single_entry_items[4].boxed_clone(),
11053 None,
11054 true,
11055 window,
11056 cx,
11057 );
11058
11059 let right_pane =
11060 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11061
11062 let boxed_clone = single_entry_items[1].boxed_clone();
11063 let right_pane = window.spawn(cx, async move |cx| {
11064 right_pane.await.inspect(|right_pane| {
11065 right_pane
11066 .update_in(cx, |pane, window, cx| {
11067 pane.add_item(boxed_clone, true, true, None, window, cx);
11068 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11069 })
11070 .unwrap();
11071 })
11072 });
11073
11074 (left_pane, right_pane)
11075 });
11076 let right_pane = right_pane.await.unwrap();
11077 cx.focus(&right_pane);
11078
11079 let close = right_pane.update_in(cx, |pane, window, cx| {
11080 pane.close_all_items(&CloseAllItems::default(), window, cx)
11081 .unwrap()
11082 });
11083 cx.executor().run_until_parked();
11084
11085 let msg = cx.pending_prompt().unwrap().0;
11086 assert!(msg.contains("1.txt"));
11087 assert!(!msg.contains("2.txt"));
11088 assert!(!msg.contains("3.txt"));
11089 assert!(!msg.contains("4.txt"));
11090
11091 // With best-effort close, cancelling item 1 keeps it open but items 4
11092 // and (3,4) still close since their entries exist in left pane.
11093 cx.simulate_prompt_answer("Cancel");
11094 close.await;
11095
11096 right_pane.read_with(cx, |pane, _| {
11097 assert_eq!(pane.items_len(), 1);
11098 });
11099
11100 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11101 left_pane
11102 .update_in(cx, |left_pane, window, cx| {
11103 left_pane.close_item_by_id(
11104 single_entry_items[3].entity_id(),
11105 SaveIntent::Skip,
11106 window,
11107 cx,
11108 )
11109 })
11110 .await
11111 .unwrap();
11112
11113 let close = left_pane.update_in(cx, |pane, window, cx| {
11114 pane.close_all_items(&CloseAllItems::default(), window, cx)
11115 .unwrap()
11116 });
11117 cx.executor().run_until_parked();
11118
11119 let details = cx.pending_prompt().unwrap().1;
11120 assert!(details.contains("0.txt"));
11121 assert!(details.contains("3.txt"));
11122 assert!(details.contains("4.txt"));
11123 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11124 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11125 // assert!(!details.contains("2.txt"));
11126
11127 cx.simulate_prompt_answer("Save all");
11128 cx.executor().run_until_parked();
11129 close.await;
11130
11131 left_pane.read_with(cx, |pane, _| {
11132 assert_eq!(pane.items_len(), 0);
11133 });
11134 }
11135
11136 #[gpui::test]
11137 async fn test_autosave(cx: &mut gpui::TestAppContext) {
11138 init_test(cx);
11139
11140 let fs = FakeFs::new(cx.executor());
11141 let project = Project::test(fs, [], cx).await;
11142 let (workspace, cx) =
11143 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11144 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11145
11146 let item = cx.new(|cx| {
11147 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11148 });
11149 let item_id = item.entity_id();
11150 workspace.update_in(cx, |workspace, window, cx| {
11151 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11152 });
11153
11154 // Autosave on window change.
11155 item.update(cx, |item, cx| {
11156 SettingsStore::update_global(cx, |settings, cx| {
11157 settings.update_user_settings(cx, |settings| {
11158 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11159 })
11160 });
11161 item.is_dirty = true;
11162 });
11163
11164 // Deactivating the window saves the file.
11165 cx.deactivate_window();
11166 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11167
11168 // Re-activating the window doesn't save the file.
11169 cx.update(|window, _| window.activate_window());
11170 cx.executor().run_until_parked();
11171 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11172
11173 // Autosave on focus change.
11174 item.update_in(cx, |item, window, cx| {
11175 cx.focus_self(window);
11176 SettingsStore::update_global(cx, |settings, cx| {
11177 settings.update_user_settings(cx, |settings| {
11178 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11179 })
11180 });
11181 item.is_dirty = true;
11182 });
11183 // Blurring the item saves the file.
11184 item.update_in(cx, |_, window, _| window.blur());
11185 cx.executor().run_until_parked();
11186 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11187
11188 // Deactivating the window still saves the file.
11189 item.update_in(cx, |item, window, cx| {
11190 cx.focus_self(window);
11191 item.is_dirty = true;
11192 });
11193 cx.deactivate_window();
11194 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11195
11196 // Autosave after delay.
11197 item.update(cx, |item, cx| {
11198 SettingsStore::update_global(cx, |settings, cx| {
11199 settings.update_user_settings(cx, |settings| {
11200 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11201 milliseconds: 500.into(),
11202 });
11203 })
11204 });
11205 item.is_dirty = true;
11206 cx.emit(ItemEvent::Edit);
11207 });
11208
11209 // Delay hasn't fully expired, so the file is still dirty and unsaved.
11210 cx.executor().advance_clock(Duration::from_millis(250));
11211 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11212
11213 // After delay expires, the file is saved.
11214 cx.executor().advance_clock(Duration::from_millis(250));
11215 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11216
11217 // Autosave after delay, should save earlier than delay if tab is closed
11218 item.update(cx, |item, cx| {
11219 item.is_dirty = true;
11220 cx.emit(ItemEvent::Edit);
11221 });
11222 cx.executor().advance_clock(Duration::from_millis(250));
11223 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11224
11225 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11226 pane.update_in(cx, |pane, window, cx| {
11227 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11228 })
11229 .await
11230 .unwrap();
11231 assert!(!cx.has_pending_prompt());
11232 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11233
11234 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11235 workspace.update_in(cx, |workspace, window, cx| {
11236 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11237 });
11238 item.update_in(cx, |item, _window, cx| {
11239 item.is_dirty = true;
11240 for project_item in &mut item.project_items {
11241 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11242 }
11243 });
11244 cx.run_until_parked();
11245 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11246
11247 // Autosave on focus change, ensuring closing the tab counts as such.
11248 item.update(cx, |item, cx| {
11249 SettingsStore::update_global(cx, |settings, cx| {
11250 settings.update_user_settings(cx, |settings| {
11251 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11252 })
11253 });
11254 item.is_dirty = true;
11255 for project_item in &mut item.project_items {
11256 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11257 }
11258 });
11259
11260 pane.update_in(cx, |pane, window, cx| {
11261 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11262 })
11263 .await
11264 .unwrap();
11265 assert!(!cx.has_pending_prompt());
11266 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11267
11268 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11269 workspace.update_in(cx, |workspace, window, cx| {
11270 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11271 });
11272 item.update_in(cx, |item, window, cx| {
11273 item.project_items[0].update(cx, |item, _| {
11274 item.entry_id = None;
11275 });
11276 item.is_dirty = true;
11277 window.blur();
11278 });
11279 cx.run_until_parked();
11280 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11281
11282 // Ensure autosave is prevented for deleted files also when closing the buffer.
11283 let _close_items = pane.update_in(cx, |pane, window, cx| {
11284 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11285 });
11286 cx.run_until_parked();
11287 assert!(cx.has_pending_prompt());
11288 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11289 }
11290
11291 #[gpui::test]
11292 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11293 init_test(cx);
11294
11295 let fs = FakeFs::new(cx.executor());
11296 let project = Project::test(fs, [], cx).await;
11297 let (workspace, cx) =
11298 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11299
11300 // Create a multibuffer-like item with two child focus handles,
11301 // simulating individual buffer editors within a multibuffer.
11302 let item = cx.new(|cx| {
11303 TestItem::new(cx)
11304 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11305 .with_child_focus_handles(2, cx)
11306 });
11307 workspace.update_in(cx, |workspace, window, cx| {
11308 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11309 });
11310
11311 // Set autosave to OnFocusChange and focus the first child handle,
11312 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11313 item.update_in(cx, |item, window, cx| {
11314 SettingsStore::update_global(cx, |settings, cx| {
11315 settings.update_user_settings(cx, |settings| {
11316 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11317 })
11318 });
11319 item.is_dirty = true;
11320 window.focus(&item.child_focus_handles[0], cx);
11321 });
11322 cx.executor().run_until_parked();
11323 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11324
11325 // Moving focus from one child to another within the same item should
11326 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11327 item.update_in(cx, |item, window, cx| {
11328 window.focus(&item.child_focus_handles[1], cx);
11329 });
11330 cx.executor().run_until_parked();
11331 item.read_with(cx, |item, _| {
11332 assert_eq!(
11333 item.save_count, 0,
11334 "Switching focus between children within the same item should not autosave"
11335 );
11336 });
11337
11338 // Blurring the item saves the file. This is the core regression scenario:
11339 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11340 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11341 // the leaf is always a child focus handle, so `on_blur` never detected
11342 // focus leaving the item.
11343 item.update_in(cx, |_, window, _| window.blur());
11344 cx.executor().run_until_parked();
11345 item.read_with(cx, |item, _| {
11346 assert_eq!(
11347 item.save_count, 1,
11348 "Blurring should trigger autosave when focus was on a child of the item"
11349 );
11350 });
11351
11352 // Deactivating the window should also trigger autosave when a child of
11353 // the multibuffer item currently owns focus.
11354 item.update_in(cx, |item, window, cx| {
11355 item.is_dirty = true;
11356 window.focus(&item.child_focus_handles[0], cx);
11357 });
11358 cx.executor().run_until_parked();
11359 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11360
11361 cx.deactivate_window();
11362 item.read_with(cx, |item, _| {
11363 assert_eq!(
11364 item.save_count, 2,
11365 "Deactivating window should trigger autosave when focus was on a child"
11366 );
11367 });
11368 }
11369
11370 #[gpui::test]
11371 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11372 init_test(cx);
11373
11374 let fs = FakeFs::new(cx.executor());
11375
11376 let project = Project::test(fs, [], cx).await;
11377 let (workspace, cx) =
11378 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11379
11380 let item = cx.new(|cx| {
11381 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11382 });
11383 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11384 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11385 let toolbar_notify_count = Rc::new(RefCell::new(0));
11386
11387 workspace.update_in(cx, |workspace, window, cx| {
11388 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11389 let toolbar_notification_count = toolbar_notify_count.clone();
11390 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11391 *toolbar_notification_count.borrow_mut() += 1
11392 })
11393 .detach();
11394 });
11395
11396 pane.read_with(cx, |pane, _| {
11397 assert!(!pane.can_navigate_backward());
11398 assert!(!pane.can_navigate_forward());
11399 });
11400
11401 item.update_in(cx, |item, _, cx| {
11402 item.set_state("one".to_string(), cx);
11403 });
11404
11405 // Toolbar must be notified to re-render the navigation buttons
11406 assert_eq!(*toolbar_notify_count.borrow(), 1);
11407
11408 pane.read_with(cx, |pane, _| {
11409 assert!(pane.can_navigate_backward());
11410 assert!(!pane.can_navigate_forward());
11411 });
11412
11413 workspace
11414 .update_in(cx, |workspace, window, cx| {
11415 workspace.go_back(pane.downgrade(), window, cx)
11416 })
11417 .await
11418 .unwrap();
11419
11420 assert_eq!(*toolbar_notify_count.borrow(), 2);
11421 pane.read_with(cx, |pane, _| {
11422 assert!(!pane.can_navigate_backward());
11423 assert!(pane.can_navigate_forward());
11424 });
11425 }
11426
11427 /// Tests that the navigation history deduplicates entries for the same item.
11428 ///
11429 /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11430 /// the navigation history deduplicates by keeping only the most recent visit to each item,
11431 /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11432 /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11433 /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11434 ///
11435 /// This behavior prevents the navigation history from growing unnecessarily large and provides
11436 /// a better user experience by eliminating redundant navigation steps when jumping between files.
11437 #[gpui::test]
11438 async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11439 init_test(cx);
11440
11441 let fs = FakeFs::new(cx.executor());
11442 let project = Project::test(fs, [], cx).await;
11443 let (workspace, cx) =
11444 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11445
11446 let item_a = cx.new(|cx| {
11447 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11448 });
11449 let item_b = cx.new(|cx| {
11450 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11451 });
11452 let item_c = cx.new(|cx| {
11453 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11454 });
11455
11456 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11457
11458 workspace.update_in(cx, |workspace, window, cx| {
11459 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11460 workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11461 workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11462 });
11463
11464 workspace.update_in(cx, |workspace, window, cx| {
11465 workspace.activate_item(&item_a, false, false, window, cx);
11466 });
11467 cx.run_until_parked();
11468
11469 workspace.update_in(cx, |workspace, window, cx| {
11470 workspace.activate_item(&item_b, false, false, window, cx);
11471 });
11472 cx.run_until_parked();
11473
11474 workspace.update_in(cx, |workspace, window, cx| {
11475 workspace.activate_item(&item_a, false, false, window, cx);
11476 });
11477 cx.run_until_parked();
11478
11479 workspace.update_in(cx, |workspace, window, cx| {
11480 workspace.activate_item(&item_b, false, false, window, cx);
11481 });
11482 cx.run_until_parked();
11483
11484 workspace.update_in(cx, |workspace, window, cx| {
11485 workspace.activate_item(&item_a, false, false, window, cx);
11486 });
11487 cx.run_until_parked();
11488
11489 workspace.update_in(cx, |workspace, window, cx| {
11490 workspace.activate_item(&item_b, false, false, window, cx);
11491 });
11492 cx.run_until_parked();
11493
11494 workspace.update_in(cx, |workspace, window, cx| {
11495 workspace.activate_item(&item_c, false, false, window, cx);
11496 });
11497 cx.run_until_parked();
11498
11499 let backward_count = pane.read_with(cx, |pane, cx| {
11500 let mut count = 0;
11501 pane.nav_history().for_each_entry(cx, &mut |_, _| {
11502 count += 1;
11503 });
11504 count
11505 });
11506 assert!(
11507 backward_count <= 4,
11508 "Should have at most 4 entries, got {}",
11509 backward_count
11510 );
11511
11512 workspace
11513 .update_in(cx, |workspace, window, cx| {
11514 workspace.go_back(pane.downgrade(), window, cx)
11515 })
11516 .await
11517 .unwrap();
11518
11519 let active_item = workspace.read_with(cx, |workspace, cx| {
11520 workspace.active_item(cx).unwrap().item_id()
11521 });
11522 assert_eq!(
11523 active_item,
11524 item_b.entity_id(),
11525 "After first go_back, should be at item B"
11526 );
11527
11528 workspace
11529 .update_in(cx, |workspace, window, cx| {
11530 workspace.go_back(pane.downgrade(), window, cx)
11531 })
11532 .await
11533 .unwrap();
11534
11535 let active_item = workspace.read_with(cx, |workspace, cx| {
11536 workspace.active_item(cx).unwrap().item_id()
11537 });
11538 assert_eq!(
11539 active_item,
11540 item_a.entity_id(),
11541 "After second go_back, should be at item A"
11542 );
11543
11544 pane.read_with(cx, |pane, _| {
11545 assert!(pane.can_navigate_forward(), "Should be able to go forward");
11546 });
11547 }
11548
11549 #[gpui::test]
11550 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11551 init_test(cx);
11552 let fs = FakeFs::new(cx.executor());
11553 let project = Project::test(fs, [], cx).await;
11554 let (multi_workspace, cx) =
11555 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11556 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11557
11558 workspace.update_in(cx, |workspace, window, cx| {
11559 let first_item = cx.new(|cx| {
11560 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11561 });
11562 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11563 workspace.split_pane(
11564 workspace.active_pane().clone(),
11565 SplitDirection::Right,
11566 window,
11567 cx,
11568 );
11569 workspace.split_pane(
11570 workspace.active_pane().clone(),
11571 SplitDirection::Right,
11572 window,
11573 cx,
11574 );
11575 });
11576
11577 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11578 let panes = workspace.center.panes();
11579 assert!(panes.len() >= 2);
11580 (
11581 panes.first().expect("at least one pane").entity_id(),
11582 panes.last().expect("at least one pane").entity_id(),
11583 )
11584 });
11585
11586 workspace.update_in(cx, |workspace, window, cx| {
11587 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11588 });
11589 workspace.update(cx, |workspace, _| {
11590 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11591 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11592 });
11593
11594 cx.dispatch_action(ActivateLastPane);
11595
11596 workspace.update(cx, |workspace, _| {
11597 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11598 });
11599 }
11600
11601 #[gpui::test]
11602 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11603 init_test(cx);
11604 let fs = FakeFs::new(cx.executor());
11605
11606 let project = Project::test(fs, [], cx).await;
11607 let (workspace, cx) =
11608 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11609
11610 let panel = workspace.update_in(cx, |workspace, window, cx| {
11611 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11612 workspace.add_panel(panel.clone(), window, cx);
11613
11614 workspace
11615 .right_dock()
11616 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11617
11618 panel
11619 });
11620
11621 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11622 pane.update_in(cx, |pane, window, cx| {
11623 let item = cx.new(TestItem::new);
11624 pane.add_item(Box::new(item), true, true, None, window, cx);
11625 });
11626
11627 // Transfer focus from center to panel
11628 workspace.update_in(cx, |workspace, window, cx| {
11629 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11630 });
11631
11632 workspace.update_in(cx, |workspace, window, cx| {
11633 assert!(workspace.right_dock().read(cx).is_open());
11634 assert!(!panel.is_zoomed(window, cx));
11635 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11636 });
11637
11638 // Transfer focus from panel to center
11639 workspace.update_in(cx, |workspace, window, cx| {
11640 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11641 });
11642
11643 workspace.update_in(cx, |workspace, window, cx| {
11644 assert!(workspace.right_dock().read(cx).is_open());
11645 assert!(!panel.is_zoomed(window, cx));
11646 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11647 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11648 });
11649
11650 // Close the dock
11651 workspace.update_in(cx, |workspace, window, cx| {
11652 workspace.toggle_dock(DockPosition::Right, window, cx);
11653 });
11654
11655 workspace.update_in(cx, |workspace, window, cx| {
11656 assert!(!workspace.right_dock().read(cx).is_open());
11657 assert!(!panel.is_zoomed(window, cx));
11658 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11659 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11660 });
11661
11662 // Open the dock
11663 workspace.update_in(cx, |workspace, window, cx| {
11664 workspace.toggle_dock(DockPosition::Right, window, cx);
11665 });
11666
11667 workspace.update_in(cx, |workspace, window, cx| {
11668 assert!(workspace.right_dock().read(cx).is_open());
11669 assert!(!panel.is_zoomed(window, cx));
11670 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11671 });
11672
11673 // Focus and zoom panel
11674 panel.update_in(cx, |panel, window, cx| {
11675 cx.focus_self(window);
11676 panel.set_zoomed(true, window, cx)
11677 });
11678
11679 workspace.update_in(cx, |workspace, window, cx| {
11680 assert!(workspace.right_dock().read(cx).is_open());
11681 assert!(panel.is_zoomed(window, cx));
11682 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11683 });
11684
11685 // Transfer focus to the center closes the dock
11686 workspace.update_in(cx, |workspace, window, cx| {
11687 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11688 });
11689
11690 workspace.update_in(cx, |workspace, window, cx| {
11691 assert!(!workspace.right_dock().read(cx).is_open());
11692 assert!(panel.is_zoomed(window, cx));
11693 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11694 });
11695
11696 // Transferring focus back to the panel keeps it zoomed
11697 workspace.update_in(cx, |workspace, window, cx| {
11698 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11699 });
11700
11701 workspace.update_in(cx, |workspace, window, cx| {
11702 assert!(workspace.right_dock().read(cx).is_open());
11703 assert!(panel.is_zoomed(window, cx));
11704 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11705 });
11706
11707 // Close the dock while it is zoomed
11708 workspace.update_in(cx, |workspace, window, cx| {
11709 workspace.toggle_dock(DockPosition::Right, window, cx)
11710 });
11711
11712 workspace.update_in(cx, |workspace, window, cx| {
11713 assert!(!workspace.right_dock().read(cx).is_open());
11714 assert!(panel.is_zoomed(window, cx));
11715 assert!(workspace.zoomed.is_none());
11716 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11717 });
11718
11719 // Opening the dock, when it's zoomed, retains focus
11720 workspace.update_in(cx, |workspace, window, cx| {
11721 workspace.toggle_dock(DockPosition::Right, window, cx)
11722 });
11723
11724 workspace.update_in(cx, |workspace, window, cx| {
11725 assert!(workspace.right_dock().read(cx).is_open());
11726 assert!(panel.is_zoomed(window, cx));
11727 assert!(workspace.zoomed.is_some());
11728 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11729 });
11730
11731 // Unzoom and close the panel, zoom the active pane.
11732 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11733 workspace.update_in(cx, |workspace, window, cx| {
11734 workspace.toggle_dock(DockPosition::Right, window, cx)
11735 });
11736 pane.update_in(cx, |pane, window, cx| {
11737 pane.toggle_zoom(&Default::default(), window, cx)
11738 });
11739
11740 // Opening a dock unzooms the pane.
11741 workspace.update_in(cx, |workspace, window, cx| {
11742 workspace.toggle_dock(DockPosition::Right, window, cx)
11743 });
11744 workspace.update_in(cx, |workspace, window, cx| {
11745 let pane = pane.read(cx);
11746 assert!(!pane.is_zoomed());
11747 assert!(!pane.focus_handle(cx).is_focused(window));
11748 assert!(workspace.right_dock().read(cx).is_open());
11749 assert!(workspace.zoomed.is_none());
11750 });
11751 }
11752
11753 #[gpui::test]
11754 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11755 init_test(cx);
11756 let fs = FakeFs::new(cx.executor());
11757
11758 let project = Project::test(fs, [], cx).await;
11759 let (workspace, cx) =
11760 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11761
11762 let panel = workspace.update_in(cx, |workspace, window, cx| {
11763 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11764 workspace.add_panel(panel.clone(), window, cx);
11765 panel
11766 });
11767
11768 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11769 pane.update_in(cx, |pane, window, cx| {
11770 let item = cx.new(TestItem::new);
11771 pane.add_item(Box::new(item), true, true, None, window, cx);
11772 });
11773
11774 // Enable close_panel_on_toggle
11775 cx.update_global(|store: &mut SettingsStore, cx| {
11776 store.update_user_settings(cx, |settings| {
11777 settings.workspace.close_panel_on_toggle = Some(true);
11778 });
11779 });
11780
11781 // Panel starts closed. Toggling should open and focus it.
11782 workspace.update_in(cx, |workspace, window, cx| {
11783 assert!(!workspace.right_dock().read(cx).is_open());
11784 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11785 });
11786
11787 workspace.update_in(cx, |workspace, window, cx| {
11788 assert!(
11789 workspace.right_dock().read(cx).is_open(),
11790 "Dock should be open after toggling from center"
11791 );
11792 assert!(
11793 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11794 "Panel should be focused after toggling from center"
11795 );
11796 });
11797
11798 // Panel is open and focused. Toggling should close the panel and
11799 // return focus to the center.
11800 workspace.update_in(cx, |workspace, window, cx| {
11801 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11802 });
11803
11804 workspace.update_in(cx, |workspace, window, cx| {
11805 assert!(
11806 !workspace.right_dock().read(cx).is_open(),
11807 "Dock should be closed after toggling from focused panel"
11808 );
11809 assert!(
11810 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11811 "Panel should not be focused after toggling from focused panel"
11812 );
11813 });
11814
11815 // Open the dock and focus something else so the panel is open but not
11816 // focused. Toggling should focus the panel (not close it).
11817 workspace.update_in(cx, |workspace, window, cx| {
11818 workspace
11819 .right_dock()
11820 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11821 window.focus(&pane.read(cx).focus_handle(cx), cx);
11822 });
11823
11824 workspace.update_in(cx, |workspace, window, cx| {
11825 assert!(workspace.right_dock().read(cx).is_open());
11826 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11827 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11828 });
11829
11830 workspace.update_in(cx, |workspace, window, cx| {
11831 assert!(
11832 workspace.right_dock().read(cx).is_open(),
11833 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11834 );
11835 assert!(
11836 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11837 "Panel should be focused after toggling an open-but-unfocused panel"
11838 );
11839 });
11840
11841 // Now disable the setting and verify the original behavior: toggling
11842 // from a focused panel moves focus to center but leaves the dock open.
11843 cx.update_global(|store: &mut SettingsStore, cx| {
11844 store.update_user_settings(cx, |settings| {
11845 settings.workspace.close_panel_on_toggle = Some(false);
11846 });
11847 });
11848
11849 workspace.update_in(cx, |workspace, window, cx| {
11850 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11851 });
11852
11853 workspace.update_in(cx, |workspace, window, cx| {
11854 assert!(
11855 workspace.right_dock().read(cx).is_open(),
11856 "Dock should remain open when setting is disabled"
11857 );
11858 assert!(
11859 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11860 "Panel should not be focused after toggling with setting disabled"
11861 );
11862 });
11863 }
11864
11865 #[gpui::test]
11866 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11867 init_test(cx);
11868 let fs = FakeFs::new(cx.executor());
11869
11870 let project = Project::test(fs, [], cx).await;
11871 let (workspace, cx) =
11872 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11873
11874 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11875 workspace.active_pane().clone()
11876 });
11877
11878 // Add an item to the pane so it can be zoomed
11879 workspace.update_in(cx, |workspace, window, cx| {
11880 let item = cx.new(TestItem::new);
11881 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11882 });
11883
11884 // Initially not zoomed
11885 workspace.update_in(cx, |workspace, _window, cx| {
11886 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11887 assert!(
11888 workspace.zoomed.is_none(),
11889 "Workspace should track no zoomed pane"
11890 );
11891 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11892 });
11893
11894 // Zoom In
11895 pane.update_in(cx, |pane, window, cx| {
11896 pane.zoom_in(&crate::ZoomIn, window, cx);
11897 });
11898
11899 workspace.update_in(cx, |workspace, window, cx| {
11900 assert!(
11901 pane.read(cx).is_zoomed(),
11902 "Pane should be zoomed after ZoomIn"
11903 );
11904 assert!(
11905 workspace.zoomed.is_some(),
11906 "Workspace should track the zoomed pane"
11907 );
11908 assert!(
11909 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11910 "ZoomIn should focus the pane"
11911 );
11912 });
11913
11914 // Zoom In again is a no-op
11915 pane.update_in(cx, |pane, window, cx| {
11916 pane.zoom_in(&crate::ZoomIn, window, cx);
11917 });
11918
11919 workspace.update_in(cx, |workspace, window, cx| {
11920 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11921 assert!(
11922 workspace.zoomed.is_some(),
11923 "Workspace still tracks zoomed pane"
11924 );
11925 assert!(
11926 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11927 "Pane remains focused after repeated ZoomIn"
11928 );
11929 });
11930
11931 // Zoom Out
11932 pane.update_in(cx, |pane, window, cx| {
11933 pane.zoom_out(&crate::ZoomOut, window, cx);
11934 });
11935
11936 workspace.update_in(cx, |workspace, _window, cx| {
11937 assert!(
11938 !pane.read(cx).is_zoomed(),
11939 "Pane should unzoom after ZoomOut"
11940 );
11941 assert!(
11942 workspace.zoomed.is_none(),
11943 "Workspace clears zoom tracking after ZoomOut"
11944 );
11945 });
11946
11947 // Zoom Out again is a no-op
11948 pane.update_in(cx, |pane, window, cx| {
11949 pane.zoom_out(&crate::ZoomOut, window, cx);
11950 });
11951
11952 workspace.update_in(cx, |workspace, _window, cx| {
11953 assert!(
11954 !pane.read(cx).is_zoomed(),
11955 "Second ZoomOut keeps pane unzoomed"
11956 );
11957 assert!(
11958 workspace.zoomed.is_none(),
11959 "Workspace remains without zoomed pane"
11960 );
11961 });
11962 }
11963
11964 #[gpui::test]
11965 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11966 init_test(cx);
11967 let fs = FakeFs::new(cx.executor());
11968
11969 let project = Project::test(fs, [], cx).await;
11970 let (workspace, cx) =
11971 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11972 workspace.update_in(cx, |workspace, window, cx| {
11973 // Open two docks
11974 let left_dock = workspace.dock_at_position(DockPosition::Left);
11975 let right_dock = workspace.dock_at_position(DockPosition::Right);
11976
11977 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11978 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11979
11980 assert!(left_dock.read(cx).is_open());
11981 assert!(right_dock.read(cx).is_open());
11982 });
11983
11984 workspace.update_in(cx, |workspace, window, cx| {
11985 // Toggle all docks - should close both
11986 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11987
11988 let left_dock = workspace.dock_at_position(DockPosition::Left);
11989 let right_dock = workspace.dock_at_position(DockPosition::Right);
11990 assert!(!left_dock.read(cx).is_open());
11991 assert!(!right_dock.read(cx).is_open());
11992 });
11993
11994 workspace.update_in(cx, |workspace, window, cx| {
11995 // Toggle again - should reopen both
11996 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11997
11998 let left_dock = workspace.dock_at_position(DockPosition::Left);
11999 let right_dock = workspace.dock_at_position(DockPosition::Right);
12000 assert!(left_dock.read(cx).is_open());
12001 assert!(right_dock.read(cx).is_open());
12002 });
12003 }
12004
12005 #[gpui::test]
12006 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
12007 init_test(cx);
12008 let fs = FakeFs::new(cx.executor());
12009
12010 let project = Project::test(fs, [], cx).await;
12011 let (workspace, cx) =
12012 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12013 workspace.update_in(cx, |workspace, window, cx| {
12014 // Open two docks
12015 let left_dock = workspace.dock_at_position(DockPosition::Left);
12016 let right_dock = workspace.dock_at_position(DockPosition::Right);
12017
12018 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12019 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12020
12021 assert!(left_dock.read(cx).is_open());
12022 assert!(right_dock.read(cx).is_open());
12023 });
12024
12025 workspace.update_in(cx, |workspace, window, cx| {
12026 // Close them manually
12027 workspace.toggle_dock(DockPosition::Left, window, cx);
12028 workspace.toggle_dock(DockPosition::Right, window, cx);
12029
12030 let left_dock = workspace.dock_at_position(DockPosition::Left);
12031 let right_dock = workspace.dock_at_position(DockPosition::Right);
12032 assert!(!left_dock.read(cx).is_open());
12033 assert!(!right_dock.read(cx).is_open());
12034 });
12035
12036 workspace.update_in(cx, |workspace, window, cx| {
12037 // Toggle all docks - only last closed (right dock) should reopen
12038 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12039
12040 let left_dock = workspace.dock_at_position(DockPosition::Left);
12041 let right_dock = workspace.dock_at_position(DockPosition::Right);
12042 assert!(!left_dock.read(cx).is_open());
12043 assert!(right_dock.read(cx).is_open());
12044 });
12045 }
12046
12047 #[gpui::test]
12048 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12049 init_test(cx);
12050 let fs = FakeFs::new(cx.executor());
12051 let project = Project::test(fs, [], cx).await;
12052 let (multi_workspace, cx) =
12053 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12054 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12055
12056 // Open two docks (left and right) with one panel each
12057 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12058 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12059 workspace.add_panel(left_panel.clone(), window, cx);
12060
12061 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12062 workspace.add_panel(right_panel.clone(), window, cx);
12063
12064 workspace.toggle_dock(DockPosition::Left, window, cx);
12065 workspace.toggle_dock(DockPosition::Right, window, cx);
12066
12067 // Verify initial state
12068 assert!(
12069 workspace.left_dock().read(cx).is_open(),
12070 "Left dock should be open"
12071 );
12072 assert_eq!(
12073 workspace
12074 .left_dock()
12075 .read(cx)
12076 .visible_panel()
12077 .unwrap()
12078 .panel_id(),
12079 left_panel.panel_id(),
12080 "Left panel should be visible in left dock"
12081 );
12082 assert!(
12083 workspace.right_dock().read(cx).is_open(),
12084 "Right dock should be open"
12085 );
12086 assert_eq!(
12087 workspace
12088 .right_dock()
12089 .read(cx)
12090 .visible_panel()
12091 .unwrap()
12092 .panel_id(),
12093 right_panel.panel_id(),
12094 "Right panel should be visible in right dock"
12095 );
12096 assert!(
12097 !workspace.bottom_dock().read(cx).is_open(),
12098 "Bottom dock should be closed"
12099 );
12100
12101 (left_panel, right_panel)
12102 });
12103
12104 // Focus the left panel and move it to the next position (bottom dock)
12105 workspace.update_in(cx, |workspace, window, cx| {
12106 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12107 assert!(
12108 left_panel.read(cx).focus_handle(cx).is_focused(window),
12109 "Left panel should be focused"
12110 );
12111 });
12112
12113 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12114
12115 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12116 workspace.update(cx, |workspace, cx| {
12117 assert!(
12118 !workspace.left_dock().read(cx).is_open(),
12119 "Left dock should be closed"
12120 );
12121 assert!(
12122 workspace.bottom_dock().read(cx).is_open(),
12123 "Bottom dock should now be open"
12124 );
12125 assert_eq!(
12126 left_panel.read(cx).position,
12127 DockPosition::Bottom,
12128 "Left panel should now be in the bottom dock"
12129 );
12130 assert_eq!(
12131 workspace
12132 .bottom_dock()
12133 .read(cx)
12134 .visible_panel()
12135 .unwrap()
12136 .panel_id(),
12137 left_panel.panel_id(),
12138 "Left panel should be the visible panel in the bottom dock"
12139 );
12140 });
12141
12142 // Toggle all docks off
12143 workspace.update_in(cx, |workspace, window, cx| {
12144 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12145 assert!(
12146 !workspace.left_dock().read(cx).is_open(),
12147 "Left dock should be closed"
12148 );
12149 assert!(
12150 !workspace.right_dock().read(cx).is_open(),
12151 "Right dock should be closed"
12152 );
12153 assert!(
12154 !workspace.bottom_dock().read(cx).is_open(),
12155 "Bottom dock should be closed"
12156 );
12157 });
12158
12159 // Toggle all docks back on and verify positions are restored
12160 workspace.update_in(cx, |workspace, window, cx| {
12161 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12162 assert!(
12163 !workspace.left_dock().read(cx).is_open(),
12164 "Left dock should remain closed"
12165 );
12166 assert!(
12167 workspace.right_dock().read(cx).is_open(),
12168 "Right dock should remain open"
12169 );
12170 assert!(
12171 workspace.bottom_dock().read(cx).is_open(),
12172 "Bottom dock should remain open"
12173 );
12174 assert_eq!(
12175 left_panel.read(cx).position,
12176 DockPosition::Bottom,
12177 "Left panel should remain in the bottom dock"
12178 );
12179 assert_eq!(
12180 right_panel.read(cx).position,
12181 DockPosition::Right,
12182 "Right panel should remain in the right dock"
12183 );
12184 assert_eq!(
12185 workspace
12186 .bottom_dock()
12187 .read(cx)
12188 .visible_panel()
12189 .unwrap()
12190 .panel_id(),
12191 left_panel.panel_id(),
12192 "Left panel should be the visible panel in the right dock"
12193 );
12194 });
12195 }
12196
12197 #[gpui::test]
12198 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12199 init_test(cx);
12200
12201 let fs = FakeFs::new(cx.executor());
12202
12203 let project = Project::test(fs, None, cx).await;
12204 let (workspace, cx) =
12205 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12206
12207 // Let's arrange the panes like this:
12208 //
12209 // +-----------------------+
12210 // | top |
12211 // +------+--------+-------+
12212 // | left | center | right |
12213 // +------+--------+-------+
12214 // | bottom |
12215 // +-----------------------+
12216
12217 let top_item = cx.new(|cx| {
12218 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12219 });
12220 let bottom_item = cx.new(|cx| {
12221 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12222 });
12223 let left_item = cx.new(|cx| {
12224 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12225 });
12226 let right_item = cx.new(|cx| {
12227 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12228 });
12229 let center_item = cx.new(|cx| {
12230 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12231 });
12232
12233 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12234 let top_pane_id = workspace.active_pane().entity_id();
12235 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12236 workspace.split_pane(
12237 workspace.active_pane().clone(),
12238 SplitDirection::Down,
12239 window,
12240 cx,
12241 );
12242 top_pane_id
12243 });
12244 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12245 let bottom_pane_id = workspace.active_pane().entity_id();
12246 workspace.add_item_to_active_pane(
12247 Box::new(bottom_item.clone()),
12248 None,
12249 false,
12250 window,
12251 cx,
12252 );
12253 workspace.split_pane(
12254 workspace.active_pane().clone(),
12255 SplitDirection::Up,
12256 window,
12257 cx,
12258 );
12259 bottom_pane_id
12260 });
12261 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12262 let left_pane_id = workspace.active_pane().entity_id();
12263 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12264 workspace.split_pane(
12265 workspace.active_pane().clone(),
12266 SplitDirection::Right,
12267 window,
12268 cx,
12269 );
12270 left_pane_id
12271 });
12272 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12273 let right_pane_id = workspace.active_pane().entity_id();
12274 workspace.add_item_to_active_pane(
12275 Box::new(right_item.clone()),
12276 None,
12277 false,
12278 window,
12279 cx,
12280 );
12281 workspace.split_pane(
12282 workspace.active_pane().clone(),
12283 SplitDirection::Left,
12284 window,
12285 cx,
12286 );
12287 right_pane_id
12288 });
12289 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12290 let center_pane_id = workspace.active_pane().entity_id();
12291 workspace.add_item_to_active_pane(
12292 Box::new(center_item.clone()),
12293 None,
12294 false,
12295 window,
12296 cx,
12297 );
12298 center_pane_id
12299 });
12300 cx.executor().run_until_parked();
12301
12302 workspace.update_in(cx, |workspace, window, cx| {
12303 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12304
12305 // Join into next from center pane into right
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!(right_pane_id, active_pane.entity_id());
12312 assert_eq!(2, 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
12318 // Join into next from right pane into bottom
12319 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12320 });
12321
12322 workspace.update_in(cx, |workspace, window, cx| {
12323 let active_pane = workspace.active_pane();
12324 assert_eq!(bottom_pane_id, active_pane.entity_id());
12325 assert_eq!(3, active_pane.read(cx).items_len());
12326 let item_ids_in_pane =
12327 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12328 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12329 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12330 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12331
12332 // Join into next from bottom pane into left
12333 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12334 });
12335
12336 workspace.update_in(cx, |workspace, window, cx| {
12337 let active_pane = workspace.active_pane();
12338 assert_eq!(left_pane_id, active_pane.entity_id());
12339 assert_eq!(4, active_pane.read(cx).items_len());
12340 let item_ids_in_pane =
12341 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12342 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12343 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12344 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12345 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12346
12347 // Join into next from left pane into top
12348 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12349 });
12350
12351 workspace.update_in(cx, |workspace, window, cx| {
12352 let active_pane = workspace.active_pane();
12353 assert_eq!(top_pane_id, active_pane.entity_id());
12354 assert_eq!(5, active_pane.read(cx).items_len());
12355 let item_ids_in_pane =
12356 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12357 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12358 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12359 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12360 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12361 assert!(item_ids_in_pane.contains(&top_item.item_id()));
12362
12363 // Single pane left: no-op
12364 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12365 });
12366
12367 workspace.update(cx, |workspace, _cx| {
12368 let active_pane = workspace.active_pane();
12369 assert_eq!(top_pane_id, active_pane.entity_id());
12370 });
12371 }
12372
12373 fn add_an_item_to_active_pane(
12374 cx: &mut VisualTestContext,
12375 workspace: &Entity<Workspace>,
12376 item_id: u64,
12377 ) -> Entity<TestItem> {
12378 let item = cx.new(|cx| {
12379 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12380 item_id,
12381 "item{item_id}.txt",
12382 cx,
12383 )])
12384 });
12385 workspace.update_in(cx, |workspace, window, cx| {
12386 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12387 });
12388 item
12389 }
12390
12391 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12392 workspace.update_in(cx, |workspace, window, cx| {
12393 workspace.split_pane(
12394 workspace.active_pane().clone(),
12395 SplitDirection::Right,
12396 window,
12397 cx,
12398 )
12399 })
12400 }
12401
12402 #[gpui::test]
12403 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12404 init_test(cx);
12405 let fs = FakeFs::new(cx.executor());
12406 let project = Project::test(fs, None, cx).await;
12407 let (workspace, cx) =
12408 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12409
12410 add_an_item_to_active_pane(cx, &workspace, 1);
12411 split_pane(cx, &workspace);
12412 add_an_item_to_active_pane(cx, &workspace, 2);
12413 split_pane(cx, &workspace); // empty pane
12414 split_pane(cx, &workspace);
12415 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12416
12417 cx.executor().run_until_parked();
12418
12419 workspace.update(cx, |workspace, cx| {
12420 let num_panes = workspace.panes().len();
12421 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12422 let active_item = workspace
12423 .active_pane()
12424 .read(cx)
12425 .active_item()
12426 .expect("item is in focus");
12427
12428 assert_eq!(num_panes, 4);
12429 assert_eq!(num_items_in_current_pane, 1);
12430 assert_eq!(active_item.item_id(), last_item.item_id());
12431 });
12432
12433 workspace.update_in(cx, |workspace, window, cx| {
12434 workspace.join_all_panes(window, cx);
12435 });
12436
12437 workspace.update(cx, |workspace, cx| {
12438 let num_panes = workspace.panes().len();
12439 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12440 let active_item = workspace
12441 .active_pane()
12442 .read(cx)
12443 .active_item()
12444 .expect("item is in focus");
12445
12446 assert_eq!(num_panes, 1);
12447 assert_eq!(num_items_in_current_pane, 3);
12448 assert_eq!(active_item.item_id(), last_item.item_id());
12449 });
12450 }
12451
12452 #[gpui::test]
12453 async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12454 init_test(cx);
12455 let fs = FakeFs::new(cx.executor());
12456
12457 let project = Project::test(fs, [], cx).await;
12458 let (multi_workspace, cx) =
12459 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12460 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12461
12462 workspace.update(cx, |workspace, _cx| {
12463 workspace.bounds.size.width = px(800.);
12464 });
12465
12466 workspace.update_in(cx, |workspace, window, cx| {
12467 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12468 workspace.add_panel(panel, window, cx);
12469 workspace.toggle_dock(DockPosition::Right, window, cx);
12470 });
12471
12472 let (panel, resized_width, ratio_basis_width) =
12473 workspace.update_in(cx, |workspace, window, cx| {
12474 let item = cx.new(|cx| {
12475 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12476 });
12477 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12478
12479 let dock = workspace.right_dock().read(cx);
12480 let workspace_width = workspace.bounds.size.width;
12481 let initial_width = workspace
12482 .dock_size(&dock, window, cx)
12483 .expect("flexible dock should have an initial width");
12484
12485 assert_eq!(initial_width, workspace_width / 2.);
12486
12487 workspace.resize_right_dock(px(300.), window, cx);
12488
12489 let dock = workspace.right_dock().read(cx);
12490 let resized_width = workspace
12491 .dock_size(&dock, window, cx)
12492 .expect("flexible dock should keep its resized width");
12493
12494 assert_eq!(resized_width, px(300.));
12495
12496 let panel = workspace
12497 .right_dock()
12498 .read(cx)
12499 .visible_panel()
12500 .expect("flexible dock should have a visible panel")
12501 .panel_id();
12502
12503 (panel, resized_width, workspace_width)
12504 });
12505
12506 workspace.update_in(cx, |workspace, window, cx| {
12507 workspace.toggle_dock(DockPosition::Right, window, cx);
12508 workspace.toggle_dock(DockPosition::Right, window, cx);
12509
12510 let dock = workspace.right_dock().read(cx);
12511 let reopened_width = workspace
12512 .dock_size(&dock, window, cx)
12513 .expect("flexible dock should restore when reopened");
12514
12515 assert_eq!(reopened_width, resized_width);
12516
12517 let right_dock = workspace.right_dock().read(cx);
12518 let flexible_panel = right_dock
12519 .visible_panel()
12520 .expect("flexible dock should still have a visible panel");
12521 assert_eq!(flexible_panel.panel_id(), panel);
12522 assert_eq!(
12523 right_dock
12524 .stored_panel_size_state(flexible_panel.as_ref())
12525 .and_then(|size_state| size_state.flex),
12526 Some(
12527 resized_width.to_f64() as f32
12528 / (workspace.bounds.size.width - resized_width).to_f64() as f32
12529 )
12530 );
12531 });
12532
12533 workspace.update_in(cx, |workspace, window, cx| {
12534 workspace.split_pane(
12535 workspace.active_pane().clone(),
12536 SplitDirection::Right,
12537 window,
12538 cx,
12539 );
12540
12541 let dock = workspace.right_dock().read(cx);
12542 let split_width = workspace
12543 .dock_size(&dock, window, cx)
12544 .expect("flexible dock should keep its user-resized proportion");
12545
12546 assert_eq!(split_width, px(300.));
12547
12548 workspace.bounds.size.width = px(1600.);
12549
12550 let dock = workspace.right_dock().read(cx);
12551 let resized_window_width = workspace
12552 .dock_size(&dock, window, cx)
12553 .expect("flexible dock should preserve proportional size on window resize");
12554
12555 assert_eq!(
12556 resized_window_width,
12557 workspace.bounds.size.width
12558 * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12559 );
12560 });
12561 }
12562
12563 #[gpui::test]
12564 async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12565 init_test(cx);
12566 let fs = FakeFs::new(cx.executor());
12567
12568 // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12569 {
12570 let project = Project::test(fs.clone(), [], cx).await;
12571 let (multi_workspace, cx) =
12572 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12573 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12574
12575 workspace.update(cx, |workspace, _cx| {
12576 workspace.set_random_database_id();
12577 workspace.bounds.size.width = px(800.);
12578 });
12579
12580 let panel = workspace.update_in(cx, |workspace, window, cx| {
12581 let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12582 workspace.add_panel(panel.clone(), window, cx);
12583 workspace.toggle_dock(DockPosition::Left, window, cx);
12584 panel
12585 });
12586
12587 workspace.update_in(cx, |workspace, window, cx| {
12588 workspace.resize_left_dock(px(350.), window, cx);
12589 });
12590
12591 cx.run_until_parked();
12592
12593 let persisted = workspace.read_with(cx, |workspace, cx| {
12594 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12595 });
12596 assert_eq!(
12597 persisted.and_then(|s| s.size),
12598 Some(px(350.)),
12599 "fixed-width panel size should be persisted to KVP"
12600 );
12601
12602 // Remove the panel and re-add a fresh instance with the same key.
12603 // The new instance should have its size state restored from KVP.
12604 workspace.update_in(cx, |workspace, window, cx| {
12605 workspace.remove_panel(&panel, window, cx);
12606 });
12607
12608 workspace.update_in(cx, |workspace, window, cx| {
12609 let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12610 workspace.add_panel(new_panel, window, cx);
12611
12612 let left_dock = workspace.left_dock().read(cx);
12613 let size_state = left_dock
12614 .panel::<TestPanel>()
12615 .and_then(|p| left_dock.stored_panel_size_state(&p));
12616 assert_eq!(
12617 size_state.and_then(|s| s.size),
12618 Some(px(350.)),
12619 "re-added fixed-width panel should restore persisted size from KVP"
12620 );
12621 });
12622 }
12623
12624 // Flexible panel: both pixel size and ratio are persisted and restored.
12625 {
12626 let project = Project::test(fs.clone(), [], cx).await;
12627 let (multi_workspace, cx) =
12628 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12629 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12630
12631 workspace.update(cx, |workspace, _cx| {
12632 workspace.set_random_database_id();
12633 workspace.bounds.size.width = px(800.);
12634 });
12635
12636 let panel = workspace.update_in(cx, |workspace, window, cx| {
12637 let item = cx.new(|cx| {
12638 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12639 });
12640 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12641
12642 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12643 workspace.add_panel(panel.clone(), window, cx);
12644 workspace.toggle_dock(DockPosition::Right, window, cx);
12645 panel
12646 });
12647
12648 workspace.update_in(cx, |workspace, window, cx| {
12649 workspace.resize_right_dock(px(300.), window, cx);
12650 });
12651
12652 cx.run_until_parked();
12653
12654 let persisted = workspace
12655 .read_with(cx, |workspace, cx| {
12656 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12657 })
12658 .expect("flexible panel state should be persisted to KVP");
12659 assert_eq!(
12660 persisted.size, None,
12661 "flexible panel should not persist a redundant pixel size"
12662 );
12663 let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12664
12665 // Remove the panel and re-add: both size and ratio should be restored.
12666 workspace.update_in(cx, |workspace, window, cx| {
12667 workspace.remove_panel(&panel, window, cx);
12668 });
12669
12670 workspace.update_in(cx, |workspace, window, cx| {
12671 let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12672 workspace.add_panel(new_panel, window, cx);
12673
12674 let right_dock = workspace.right_dock().read(cx);
12675 let size_state = right_dock
12676 .panel::<TestPanel>()
12677 .and_then(|p| right_dock.stored_panel_size_state(&p))
12678 .expect("re-added flexible panel should have restored size state from KVP");
12679 assert_eq!(
12680 size_state.size, None,
12681 "re-added flexible panel should not have a persisted pixel size"
12682 );
12683 assert_eq!(
12684 size_state.flex,
12685 Some(original_ratio),
12686 "re-added flexible panel should restore persisted flex"
12687 );
12688 });
12689 }
12690 }
12691
12692 #[gpui::test]
12693 async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12694 init_test(cx);
12695 let fs = FakeFs::new(cx.executor());
12696
12697 let project = Project::test(fs, [], cx).await;
12698 let (multi_workspace, cx) =
12699 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12700 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12701
12702 workspace.update(cx, |workspace, _cx| {
12703 workspace.bounds.size.width = px(900.);
12704 });
12705
12706 // Step 1: Add a tab to the center pane then open a flexible panel in the left
12707 // dock. With one full-width center pane the default ratio is 0.5, so the panel
12708 // and the center pane each take half the workspace width.
12709 workspace.update_in(cx, |workspace, window, cx| {
12710 let item = cx.new(|cx| {
12711 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12712 });
12713 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12714
12715 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12716 workspace.add_panel(panel, window, cx);
12717 workspace.toggle_dock(DockPosition::Left, window, cx);
12718
12719 let left_dock = workspace.left_dock().read(cx);
12720 let left_width = workspace
12721 .dock_size(&left_dock, window, cx)
12722 .expect("left dock should have an active panel");
12723
12724 assert_eq!(
12725 left_width,
12726 workspace.bounds.size.width / 2.,
12727 "flexible left panel should split evenly with the center pane"
12728 );
12729 });
12730
12731 // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12732 // change horizontal width fractions, so the flexible panel stays at the same
12733 // width as each half of the split.
12734 workspace.update_in(cx, |workspace, window, cx| {
12735 workspace.split_pane(
12736 workspace.active_pane().clone(),
12737 SplitDirection::Down,
12738 window,
12739 cx,
12740 );
12741
12742 let left_dock = workspace.left_dock().read(cx);
12743 let left_width = workspace
12744 .dock_size(&left_dock, window, cx)
12745 .expect("left dock should still have an active panel after vertical split");
12746
12747 assert_eq!(
12748 left_width,
12749 workspace.bounds.size.width / 2.,
12750 "flexible left panel width should match each vertically-split pane"
12751 );
12752 });
12753
12754 // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12755 // size reduces the available width, so the flexible left panel and the center
12756 // panes all shrink proportionally to accommodate it.
12757 workspace.update_in(cx, |workspace, window, cx| {
12758 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12759 workspace.add_panel(panel, window, cx);
12760 workspace.toggle_dock(DockPosition::Right, window, cx);
12761
12762 let right_dock = workspace.right_dock().read(cx);
12763 let right_width = workspace
12764 .dock_size(&right_dock, window, cx)
12765 .expect("right dock should have an active panel");
12766
12767 let left_dock = workspace.left_dock().read(cx);
12768 let left_width = workspace
12769 .dock_size(&left_dock, window, cx)
12770 .expect("left dock should still have an active panel");
12771
12772 let available_width = workspace.bounds.size.width - right_width;
12773 assert_eq!(
12774 left_width,
12775 available_width / 2.,
12776 "flexible left panel should shrink proportionally as the right dock takes space"
12777 );
12778 });
12779
12780 // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12781 // flex sizing and the workspace width is divided among left-flex, center
12782 // (implicit flex 1.0), and right-flex.
12783 workspace.update_in(cx, |workspace, window, cx| {
12784 let right_dock = workspace.right_dock().clone();
12785 let right_panel = right_dock
12786 .read(cx)
12787 .visible_panel()
12788 .expect("right dock should have a visible panel")
12789 .clone();
12790 workspace.toggle_dock_panel_flexible_size(
12791 &right_dock,
12792 right_panel.as_ref(),
12793 window,
12794 cx,
12795 );
12796
12797 let right_dock = right_dock.read(cx);
12798 let right_panel = right_dock
12799 .visible_panel()
12800 .expect("right dock should still have a visible panel");
12801 assert!(
12802 right_panel.has_flexible_size(window, cx),
12803 "right panel should now be flexible"
12804 );
12805
12806 let right_size_state = right_dock
12807 .stored_panel_size_state(right_panel.as_ref())
12808 .expect("right panel should have a stored size state after toggling");
12809 let right_flex = right_size_state
12810 .flex
12811 .expect("right panel should have a flex value after toggling");
12812
12813 let left_dock = workspace.left_dock().read(cx);
12814 let left_width = workspace
12815 .dock_size(&left_dock, window, cx)
12816 .expect("left dock should still have an active panel");
12817 let right_width = workspace
12818 .dock_size(&right_dock, window, cx)
12819 .expect("right dock should still have an active panel");
12820
12821 let left_flex = workspace
12822 .default_dock_flex(DockPosition::Left)
12823 .expect("left dock should have a default flex");
12824
12825 let total_flex = left_flex + 1.0 + right_flex;
12826 let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12827 let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12828 assert_eq!(
12829 left_width, expected_left,
12830 "flexible left panel should share workspace width via flex ratios"
12831 );
12832 assert_eq!(
12833 right_width, expected_right,
12834 "flexible right panel should share workspace width via flex ratios"
12835 );
12836 });
12837 }
12838
12839 struct TestModal(FocusHandle);
12840
12841 impl TestModal {
12842 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12843 Self(cx.focus_handle())
12844 }
12845 }
12846
12847 impl EventEmitter<DismissEvent> for TestModal {}
12848
12849 impl Focusable for TestModal {
12850 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12851 self.0.clone()
12852 }
12853 }
12854
12855 impl ModalView for TestModal {}
12856
12857 impl Render for TestModal {
12858 fn render(
12859 &mut self,
12860 _window: &mut Window,
12861 _cx: &mut Context<TestModal>,
12862 ) -> impl IntoElement {
12863 div().track_focus(&self.0)
12864 }
12865 }
12866
12867 #[gpui::test]
12868 async fn test_panels(cx: &mut gpui::TestAppContext) {
12869 init_test(cx);
12870 let fs = FakeFs::new(cx.executor());
12871
12872 let project = Project::test(fs, [], cx).await;
12873 let (multi_workspace, cx) =
12874 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12875 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12876
12877 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12878 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12879 workspace.add_panel(panel_1.clone(), window, cx);
12880 workspace.toggle_dock(DockPosition::Left, window, cx);
12881 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12882 workspace.add_panel(panel_2.clone(), window, cx);
12883 workspace.toggle_dock(DockPosition::Right, window, cx);
12884
12885 let left_dock = workspace.left_dock();
12886 assert_eq!(
12887 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12888 panel_1.panel_id()
12889 );
12890 assert_eq!(
12891 workspace.dock_size(&left_dock.read(cx), window, cx),
12892 Some(px(300.))
12893 );
12894
12895 workspace.resize_left_dock(px(1337.), window, cx);
12896 assert_eq!(
12897 workspace
12898 .right_dock()
12899 .read(cx)
12900 .visible_panel()
12901 .unwrap()
12902 .panel_id(),
12903 panel_2.panel_id(),
12904 );
12905
12906 (panel_1, panel_2)
12907 });
12908
12909 // Move panel_1 to the right
12910 panel_1.update_in(cx, |panel_1, window, cx| {
12911 panel_1.set_position(DockPosition::Right, window, cx)
12912 });
12913
12914 workspace.update_in(cx, |workspace, window, cx| {
12915 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12916 // Since it was the only panel on the left, the left dock should now be closed.
12917 assert!(!workspace.left_dock().read(cx).is_open());
12918 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12919 let right_dock = workspace.right_dock();
12920 assert_eq!(
12921 right_dock.read(cx).visible_panel().unwrap().panel_id(),
12922 panel_1.panel_id()
12923 );
12924 assert_eq!(
12925 right_dock
12926 .read(cx)
12927 .active_panel_size()
12928 .unwrap()
12929 .size
12930 .unwrap(),
12931 px(1337.)
12932 );
12933
12934 // Now we move panel_2 to the left
12935 panel_2.set_position(DockPosition::Left, window, cx);
12936 });
12937
12938 workspace.update(cx, |workspace, cx| {
12939 // Since panel_2 was not visible on the right, we don't open the left dock.
12940 assert!(!workspace.left_dock().read(cx).is_open());
12941 // And the right dock is unaffected in its displaying of panel_1
12942 assert!(workspace.right_dock().read(cx).is_open());
12943 assert_eq!(
12944 workspace
12945 .right_dock()
12946 .read(cx)
12947 .visible_panel()
12948 .unwrap()
12949 .panel_id(),
12950 panel_1.panel_id(),
12951 );
12952 });
12953
12954 // Move panel_1 back to the left
12955 panel_1.update_in(cx, |panel_1, window, cx| {
12956 panel_1.set_position(DockPosition::Left, window, cx)
12957 });
12958
12959 workspace.update_in(cx, |workspace, window, cx| {
12960 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12961 let left_dock = workspace.left_dock();
12962 assert!(left_dock.read(cx).is_open());
12963 assert_eq!(
12964 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12965 panel_1.panel_id()
12966 );
12967 assert_eq!(
12968 workspace.dock_size(&left_dock.read(cx), window, cx),
12969 Some(px(1337.))
12970 );
12971 // And the right dock should be closed as it no longer has any panels.
12972 assert!(!workspace.right_dock().read(cx).is_open());
12973
12974 // Now we move panel_1 to the bottom
12975 panel_1.set_position(DockPosition::Bottom, window, cx);
12976 });
12977
12978 workspace.update_in(cx, |workspace, window, cx| {
12979 // Since panel_1 was visible on the left, we close the left dock.
12980 assert!(!workspace.left_dock().read(cx).is_open());
12981 // The bottom dock is sized based on the panel's default size,
12982 // since the panel orientation changed from vertical to horizontal.
12983 let bottom_dock = workspace.bottom_dock();
12984 assert_eq!(
12985 workspace.dock_size(&bottom_dock.read(cx), window, cx),
12986 Some(px(300.))
12987 );
12988 // Close bottom dock and move panel_1 back to the left.
12989 bottom_dock.update(cx, |bottom_dock, cx| {
12990 bottom_dock.set_open(false, window, cx)
12991 });
12992 panel_1.set_position(DockPosition::Left, window, cx);
12993 });
12994
12995 // Emit activated event on panel 1
12996 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12997
12998 // Now the left dock is open and panel_1 is active and focused.
12999 workspace.update_in(cx, |workspace, window, cx| {
13000 let left_dock = workspace.left_dock();
13001 assert!(left_dock.read(cx).is_open());
13002 assert_eq!(
13003 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13004 panel_1.panel_id(),
13005 );
13006 assert!(panel_1.focus_handle(cx).is_focused(window));
13007 });
13008
13009 // Emit closed event on panel 2, which is not active
13010 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13011
13012 // Wo don't close the left dock, because panel_2 wasn't the active panel
13013 workspace.update(cx, |workspace, cx| {
13014 let left_dock = workspace.left_dock();
13015 assert!(left_dock.read(cx).is_open());
13016 assert_eq!(
13017 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13018 panel_1.panel_id(),
13019 );
13020 });
13021
13022 // Emitting a ZoomIn event shows the panel as zoomed.
13023 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
13024 workspace.read_with(cx, |workspace, _| {
13025 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13026 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13027 });
13028
13029 // Move panel to another dock while it is zoomed
13030 panel_1.update_in(cx, |panel, window, cx| {
13031 panel.set_position(DockPosition::Right, window, cx)
13032 });
13033 workspace.read_with(cx, |workspace, _| {
13034 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13035
13036 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13037 });
13038
13039 // This is a helper for getting a:
13040 // - valid focus on an element,
13041 // - that isn't a part of the panes and panels system of the Workspace,
13042 // - and doesn't trigger the 'on_focus_lost' API.
13043 let focus_other_view = {
13044 let workspace = workspace.clone();
13045 move |cx: &mut VisualTestContext| {
13046 workspace.update_in(cx, |workspace, window, cx| {
13047 if workspace.active_modal::<TestModal>(cx).is_some() {
13048 workspace.toggle_modal(window, cx, TestModal::new);
13049 workspace.toggle_modal(window, cx, TestModal::new);
13050 } else {
13051 workspace.toggle_modal(window, cx, TestModal::new);
13052 }
13053 })
13054 }
13055 };
13056
13057 // If focus is transferred to another view that's not a panel or another pane, we still show
13058 // the panel as zoomed.
13059 focus_other_view(cx);
13060 workspace.read_with(cx, |workspace, _| {
13061 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13062 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13063 });
13064
13065 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13066 workspace.update_in(cx, |_workspace, window, cx| {
13067 cx.focus_self(window);
13068 });
13069 workspace.read_with(cx, |workspace, _| {
13070 assert_eq!(workspace.zoomed, None);
13071 assert_eq!(workspace.zoomed_position, None);
13072 });
13073
13074 // If focus is transferred again to another view that's not a panel or a pane, we won't
13075 // show the panel as zoomed because it wasn't zoomed before.
13076 focus_other_view(cx);
13077 workspace.read_with(cx, |workspace, _| {
13078 assert_eq!(workspace.zoomed, None);
13079 assert_eq!(workspace.zoomed_position, None);
13080 });
13081
13082 // When the panel is activated, it is zoomed again.
13083 cx.dispatch_action(ToggleRightDock);
13084 workspace.read_with(cx, |workspace, _| {
13085 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13086 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13087 });
13088
13089 // Emitting a ZoomOut event unzooms the panel.
13090 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13091 workspace.read_with(cx, |workspace, _| {
13092 assert_eq!(workspace.zoomed, None);
13093 assert_eq!(workspace.zoomed_position, None);
13094 });
13095
13096 // Emit closed event on panel 1, which is active
13097 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13098
13099 // Now the left dock is closed, because panel_1 was the active panel
13100 workspace.update(cx, |workspace, cx| {
13101 let right_dock = workspace.right_dock();
13102 assert!(!right_dock.read(cx).is_open());
13103 });
13104 }
13105
13106 #[gpui::test]
13107 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13108 init_test(cx);
13109
13110 let fs = FakeFs::new(cx.background_executor.clone());
13111 let project = Project::test(fs, [], cx).await;
13112 let (workspace, cx) =
13113 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13114 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13115
13116 let dirty_regular_buffer = cx.new(|cx| {
13117 TestItem::new(cx)
13118 .with_dirty(true)
13119 .with_label("1.txt")
13120 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13121 });
13122 let dirty_regular_buffer_2 = cx.new(|cx| {
13123 TestItem::new(cx)
13124 .with_dirty(true)
13125 .with_label("2.txt")
13126 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13127 });
13128 let dirty_multi_buffer_with_both = cx.new(|cx| {
13129 TestItem::new(cx)
13130 .with_dirty(true)
13131 .with_buffer_kind(ItemBufferKind::Multibuffer)
13132 .with_label("Fake Project Search")
13133 .with_project_items(&[
13134 dirty_regular_buffer.read(cx).project_items[0].clone(),
13135 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13136 ])
13137 });
13138 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13139 workspace.update_in(cx, |workspace, window, cx| {
13140 workspace.add_item(
13141 pane.clone(),
13142 Box::new(dirty_regular_buffer.clone()),
13143 None,
13144 false,
13145 false,
13146 window,
13147 cx,
13148 );
13149 workspace.add_item(
13150 pane.clone(),
13151 Box::new(dirty_regular_buffer_2.clone()),
13152 None,
13153 false,
13154 false,
13155 window,
13156 cx,
13157 );
13158 workspace.add_item(
13159 pane.clone(),
13160 Box::new(dirty_multi_buffer_with_both.clone()),
13161 None,
13162 false,
13163 false,
13164 window,
13165 cx,
13166 );
13167 });
13168
13169 pane.update_in(cx, |pane, window, cx| {
13170 pane.activate_item(2, true, true, window, cx);
13171 assert_eq!(
13172 pane.active_item().unwrap().item_id(),
13173 multi_buffer_with_both_files_id,
13174 "Should select the multi buffer in the pane"
13175 );
13176 });
13177 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13178 pane.close_other_items(
13179 &CloseOtherItems {
13180 save_intent: Some(SaveIntent::Save),
13181 close_pinned: true,
13182 },
13183 None,
13184 window,
13185 cx,
13186 )
13187 });
13188 cx.background_executor.run_until_parked();
13189 assert!(!cx.has_pending_prompt());
13190 close_all_but_multi_buffer_task
13191 .await
13192 .expect("Closing all buffers but the multi buffer failed");
13193 pane.update(cx, |pane, cx| {
13194 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13195 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13196 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13197 assert_eq!(pane.items_len(), 1);
13198 assert_eq!(
13199 pane.active_item().unwrap().item_id(),
13200 multi_buffer_with_both_files_id,
13201 "Should have only the multi buffer left in the pane"
13202 );
13203 assert!(
13204 dirty_multi_buffer_with_both.read(cx).is_dirty,
13205 "The multi buffer containing the unsaved buffer should still be dirty"
13206 );
13207 });
13208
13209 dirty_regular_buffer.update(cx, |buffer, cx| {
13210 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13211 });
13212
13213 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13214 pane.close_active_item(
13215 &CloseActiveItem {
13216 save_intent: Some(SaveIntent::Close),
13217 close_pinned: false,
13218 },
13219 window,
13220 cx,
13221 )
13222 });
13223 cx.background_executor.run_until_parked();
13224 assert!(
13225 cx.has_pending_prompt(),
13226 "Dirty multi buffer should prompt a save dialog"
13227 );
13228 cx.simulate_prompt_answer("Save");
13229 cx.background_executor.run_until_parked();
13230 close_multi_buffer_task
13231 .await
13232 .expect("Closing the multi buffer failed");
13233 pane.update(cx, |pane, cx| {
13234 assert_eq!(
13235 dirty_multi_buffer_with_both.read(cx).save_count,
13236 1,
13237 "Multi buffer item should get be saved"
13238 );
13239 // Test impl does not save inner items, so we do not assert them
13240 assert_eq!(
13241 pane.items_len(),
13242 0,
13243 "No more items should be left in the pane"
13244 );
13245 assert!(pane.active_item().is_none());
13246 });
13247 }
13248
13249 #[gpui::test]
13250 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13251 cx: &mut TestAppContext,
13252 ) {
13253 init_test(cx);
13254
13255 let fs = FakeFs::new(cx.background_executor.clone());
13256 let project = Project::test(fs, [], cx).await;
13257 let (workspace, cx) =
13258 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13259 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13260
13261 let dirty_regular_buffer = cx.new(|cx| {
13262 TestItem::new(cx)
13263 .with_dirty(true)
13264 .with_label("1.txt")
13265 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13266 });
13267 let dirty_regular_buffer_2 = cx.new(|cx| {
13268 TestItem::new(cx)
13269 .with_dirty(true)
13270 .with_label("2.txt")
13271 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13272 });
13273 let clear_regular_buffer = cx.new(|cx| {
13274 TestItem::new(cx)
13275 .with_label("3.txt")
13276 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13277 });
13278
13279 let dirty_multi_buffer_with_both = cx.new(|cx| {
13280 TestItem::new(cx)
13281 .with_dirty(true)
13282 .with_buffer_kind(ItemBufferKind::Multibuffer)
13283 .with_label("Fake Project Search")
13284 .with_project_items(&[
13285 dirty_regular_buffer.read(cx).project_items[0].clone(),
13286 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13287 clear_regular_buffer.read(cx).project_items[0].clone(),
13288 ])
13289 });
13290 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13291 workspace.update_in(cx, |workspace, window, cx| {
13292 workspace.add_item(
13293 pane.clone(),
13294 Box::new(dirty_regular_buffer.clone()),
13295 None,
13296 false,
13297 false,
13298 window,
13299 cx,
13300 );
13301 workspace.add_item(
13302 pane.clone(),
13303 Box::new(dirty_multi_buffer_with_both.clone()),
13304 None,
13305 false,
13306 false,
13307 window,
13308 cx,
13309 );
13310 });
13311
13312 pane.update_in(cx, |pane, window, cx| {
13313 pane.activate_item(1, true, true, window, cx);
13314 assert_eq!(
13315 pane.active_item().unwrap().item_id(),
13316 multi_buffer_with_both_files_id,
13317 "Should select the multi buffer in the pane"
13318 );
13319 });
13320 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13321 pane.close_active_item(
13322 &CloseActiveItem {
13323 save_intent: None,
13324 close_pinned: false,
13325 },
13326 window,
13327 cx,
13328 )
13329 });
13330 cx.background_executor.run_until_parked();
13331 assert!(
13332 cx.has_pending_prompt(),
13333 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13334 );
13335 }
13336
13337 /// Tests that when `close_on_file_delete` is enabled, files are automatically
13338 /// closed when they are deleted from disk.
13339 #[gpui::test]
13340 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13341 init_test(cx);
13342
13343 // Enable the close_on_disk_deletion setting
13344 cx.update_global(|store: &mut SettingsStore, cx| {
13345 store.update_user_settings(cx, |settings| {
13346 settings.workspace.close_on_file_delete = Some(true);
13347 });
13348 });
13349
13350 let fs = FakeFs::new(cx.background_executor.clone());
13351 let project = Project::test(fs, [], cx).await;
13352 let (workspace, cx) =
13353 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13354 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13355
13356 // Create a test item that simulates a file
13357 let item = cx.new(|cx| {
13358 TestItem::new(cx)
13359 .with_label("test.txt")
13360 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13361 });
13362
13363 // Add item to workspace
13364 workspace.update_in(cx, |workspace, window, cx| {
13365 workspace.add_item(
13366 pane.clone(),
13367 Box::new(item.clone()),
13368 None,
13369 false,
13370 false,
13371 window,
13372 cx,
13373 );
13374 });
13375
13376 // Verify the item is in the pane
13377 pane.read_with(cx, |pane, _| {
13378 assert_eq!(pane.items().count(), 1);
13379 });
13380
13381 // Simulate file deletion by setting the item's deleted state
13382 item.update(cx, |item, _| {
13383 item.set_has_deleted_file(true);
13384 });
13385
13386 // Emit UpdateTab event to trigger the close behavior
13387 cx.run_until_parked();
13388 item.update(cx, |_, cx| {
13389 cx.emit(ItemEvent::UpdateTab);
13390 });
13391
13392 // Allow the close operation to complete
13393 cx.run_until_parked();
13394
13395 // Verify the item was automatically closed
13396 pane.read_with(cx, |pane, _| {
13397 assert_eq!(
13398 pane.items().count(),
13399 0,
13400 "Item should be automatically closed when file is deleted"
13401 );
13402 });
13403 }
13404
13405 /// Tests that when `close_on_file_delete` is disabled (default), files remain
13406 /// open with a strikethrough when they are deleted from disk.
13407 #[gpui::test]
13408 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13409 init_test(cx);
13410
13411 // Ensure close_on_disk_deletion is disabled (default)
13412 cx.update_global(|store: &mut SettingsStore, cx| {
13413 store.update_user_settings(cx, |settings| {
13414 settings.workspace.close_on_file_delete = Some(false);
13415 });
13416 });
13417
13418 let fs = FakeFs::new(cx.background_executor.clone());
13419 let project = Project::test(fs, [], cx).await;
13420 let (workspace, cx) =
13421 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13422 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13423
13424 // Create a test item that simulates a file
13425 let item = cx.new(|cx| {
13426 TestItem::new(cx)
13427 .with_label("test.txt")
13428 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13429 });
13430
13431 // Add item to workspace
13432 workspace.update_in(cx, |workspace, window, cx| {
13433 workspace.add_item(
13434 pane.clone(),
13435 Box::new(item.clone()),
13436 None,
13437 false,
13438 false,
13439 window,
13440 cx,
13441 );
13442 });
13443
13444 // Verify the item is in the pane
13445 pane.read_with(cx, |pane, _| {
13446 assert_eq!(pane.items().count(), 1);
13447 });
13448
13449 // Simulate file deletion
13450 item.update(cx, |item, _| {
13451 item.set_has_deleted_file(true);
13452 });
13453
13454 // Emit UpdateTab event
13455 cx.run_until_parked();
13456 item.update(cx, |_, cx| {
13457 cx.emit(ItemEvent::UpdateTab);
13458 });
13459
13460 // Allow any potential close operation to complete
13461 cx.run_until_parked();
13462
13463 // Verify the item remains open (with strikethrough)
13464 pane.read_with(cx, |pane, _| {
13465 assert_eq!(
13466 pane.items().count(),
13467 1,
13468 "Item should remain open when close_on_disk_deletion is disabled"
13469 );
13470 });
13471
13472 // Verify the item shows as deleted
13473 item.read_with(cx, |item, _| {
13474 assert!(
13475 item.has_deleted_file,
13476 "Item should be marked as having deleted file"
13477 );
13478 });
13479 }
13480
13481 /// Tests that dirty files are not automatically closed when deleted from disk,
13482 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13483 /// unsaved changes without being prompted.
13484 #[gpui::test]
13485 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13486 init_test(cx);
13487
13488 // Enable the close_on_file_delete setting
13489 cx.update_global(|store: &mut SettingsStore, cx| {
13490 store.update_user_settings(cx, |settings| {
13491 settings.workspace.close_on_file_delete = Some(true);
13492 });
13493 });
13494
13495 let fs = FakeFs::new(cx.background_executor.clone());
13496 let project = Project::test(fs, [], cx).await;
13497 let (workspace, cx) =
13498 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13499 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13500
13501 // Create a dirty test item
13502 let item = cx.new(|cx| {
13503 TestItem::new(cx)
13504 .with_dirty(true)
13505 .with_label("test.txt")
13506 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13507 });
13508
13509 // Add item to workspace
13510 workspace.update_in(cx, |workspace, window, cx| {
13511 workspace.add_item(
13512 pane.clone(),
13513 Box::new(item.clone()),
13514 None,
13515 false,
13516 false,
13517 window,
13518 cx,
13519 );
13520 });
13521
13522 // Simulate file deletion
13523 item.update(cx, |item, _| {
13524 item.set_has_deleted_file(true);
13525 });
13526
13527 // Emit UpdateTab event to trigger the close behavior
13528 cx.run_until_parked();
13529 item.update(cx, |_, cx| {
13530 cx.emit(ItemEvent::UpdateTab);
13531 });
13532
13533 // Allow any potential close operation to complete
13534 cx.run_until_parked();
13535
13536 // Verify the item remains open (dirty files are not auto-closed)
13537 pane.read_with(cx, |pane, _| {
13538 assert_eq!(
13539 pane.items().count(),
13540 1,
13541 "Dirty items should not be automatically closed even when file is deleted"
13542 );
13543 });
13544
13545 // Verify the item is marked as deleted and still dirty
13546 item.read_with(cx, |item, _| {
13547 assert!(
13548 item.has_deleted_file,
13549 "Item should be marked as having deleted file"
13550 );
13551 assert!(item.is_dirty, "Item should still be dirty");
13552 });
13553 }
13554
13555 /// Tests that navigation history is cleaned up when files are auto-closed
13556 /// due to deletion from disk.
13557 #[gpui::test]
13558 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13559 init_test(cx);
13560
13561 // Enable the close_on_file_delete setting
13562 cx.update_global(|store: &mut SettingsStore, cx| {
13563 store.update_user_settings(cx, |settings| {
13564 settings.workspace.close_on_file_delete = Some(true);
13565 });
13566 });
13567
13568 let fs = FakeFs::new(cx.background_executor.clone());
13569 let project = Project::test(fs, [], cx).await;
13570 let (workspace, cx) =
13571 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13572 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13573
13574 // Create test items
13575 let item1 = cx.new(|cx| {
13576 TestItem::new(cx)
13577 .with_label("test1.txt")
13578 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13579 });
13580 let item1_id = item1.item_id();
13581
13582 let item2 = cx.new(|cx| {
13583 TestItem::new(cx)
13584 .with_label("test2.txt")
13585 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13586 });
13587
13588 // Add items to workspace
13589 workspace.update_in(cx, |workspace, window, cx| {
13590 workspace.add_item(
13591 pane.clone(),
13592 Box::new(item1.clone()),
13593 None,
13594 false,
13595 false,
13596 window,
13597 cx,
13598 );
13599 workspace.add_item(
13600 pane.clone(),
13601 Box::new(item2.clone()),
13602 None,
13603 false,
13604 false,
13605 window,
13606 cx,
13607 );
13608 });
13609
13610 // Activate item1 to ensure it gets navigation entries
13611 pane.update_in(cx, |pane, window, cx| {
13612 pane.activate_item(0, true, true, window, cx);
13613 });
13614
13615 // Switch to item2 and back to create navigation history
13616 pane.update_in(cx, |pane, window, cx| {
13617 pane.activate_item(1, true, true, window, cx);
13618 });
13619 cx.run_until_parked();
13620
13621 pane.update_in(cx, |pane, window, cx| {
13622 pane.activate_item(0, true, true, window, cx);
13623 });
13624 cx.run_until_parked();
13625
13626 // Simulate file deletion for item1
13627 item1.update(cx, |item, _| {
13628 item.set_has_deleted_file(true);
13629 });
13630
13631 // Emit UpdateTab event to trigger the close behavior
13632 item1.update(cx, |_, cx| {
13633 cx.emit(ItemEvent::UpdateTab);
13634 });
13635 cx.run_until_parked();
13636
13637 // Verify item1 was closed
13638 pane.read_with(cx, |pane, _| {
13639 assert_eq!(
13640 pane.items().count(),
13641 1,
13642 "Should have 1 item remaining after auto-close"
13643 );
13644 });
13645
13646 // Check navigation history after close
13647 let has_item = pane.read_with(cx, |pane, cx| {
13648 let mut has_item = false;
13649 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13650 if entry.item.id() == item1_id {
13651 has_item = true;
13652 }
13653 });
13654 has_item
13655 });
13656
13657 assert!(
13658 !has_item,
13659 "Navigation history should not contain closed item entries"
13660 );
13661 }
13662
13663 #[gpui::test]
13664 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13665 cx: &mut TestAppContext,
13666 ) {
13667 init_test(cx);
13668
13669 let fs = FakeFs::new(cx.background_executor.clone());
13670 let project = Project::test(fs, [], cx).await;
13671 let (workspace, cx) =
13672 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13673 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13674
13675 let dirty_regular_buffer = cx.new(|cx| {
13676 TestItem::new(cx)
13677 .with_dirty(true)
13678 .with_label("1.txt")
13679 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13680 });
13681 let dirty_regular_buffer_2 = cx.new(|cx| {
13682 TestItem::new(cx)
13683 .with_dirty(true)
13684 .with_label("2.txt")
13685 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13686 });
13687 let clear_regular_buffer = cx.new(|cx| {
13688 TestItem::new(cx)
13689 .with_label("3.txt")
13690 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13691 });
13692
13693 let dirty_multi_buffer = cx.new(|cx| {
13694 TestItem::new(cx)
13695 .with_dirty(true)
13696 .with_buffer_kind(ItemBufferKind::Multibuffer)
13697 .with_label("Fake Project Search")
13698 .with_project_items(&[
13699 dirty_regular_buffer.read(cx).project_items[0].clone(),
13700 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13701 clear_regular_buffer.read(cx).project_items[0].clone(),
13702 ])
13703 });
13704 workspace.update_in(cx, |workspace, window, cx| {
13705 workspace.add_item(
13706 pane.clone(),
13707 Box::new(dirty_regular_buffer.clone()),
13708 None,
13709 false,
13710 false,
13711 window,
13712 cx,
13713 );
13714 workspace.add_item(
13715 pane.clone(),
13716 Box::new(dirty_regular_buffer_2.clone()),
13717 None,
13718 false,
13719 false,
13720 window,
13721 cx,
13722 );
13723 workspace.add_item(
13724 pane.clone(),
13725 Box::new(dirty_multi_buffer.clone()),
13726 None,
13727 false,
13728 false,
13729 window,
13730 cx,
13731 );
13732 });
13733
13734 pane.update_in(cx, |pane, window, cx| {
13735 pane.activate_item(2, true, true, window, cx);
13736 assert_eq!(
13737 pane.active_item().unwrap().item_id(),
13738 dirty_multi_buffer.item_id(),
13739 "Should select the multi buffer in the pane"
13740 );
13741 });
13742 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13743 pane.close_active_item(
13744 &CloseActiveItem {
13745 save_intent: None,
13746 close_pinned: false,
13747 },
13748 window,
13749 cx,
13750 )
13751 });
13752 cx.background_executor.run_until_parked();
13753 assert!(
13754 !cx.has_pending_prompt(),
13755 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13756 );
13757 close_multi_buffer_task
13758 .await
13759 .expect("Closing multi buffer failed");
13760 pane.update(cx, |pane, cx| {
13761 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13762 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13763 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13764 assert_eq!(
13765 pane.items()
13766 .map(|item| item.item_id())
13767 .sorted()
13768 .collect::<Vec<_>>(),
13769 vec![
13770 dirty_regular_buffer.item_id(),
13771 dirty_regular_buffer_2.item_id(),
13772 ],
13773 "Should have no multi buffer left in the pane"
13774 );
13775 assert!(dirty_regular_buffer.read(cx).is_dirty);
13776 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13777 });
13778 }
13779
13780 #[gpui::test]
13781 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13782 init_test(cx);
13783 let fs = FakeFs::new(cx.executor());
13784 let project = Project::test(fs, [], cx).await;
13785 let (multi_workspace, cx) =
13786 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13787 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13788
13789 // Add a new panel to the right dock, opening the dock and setting the
13790 // focus to the new panel.
13791 let panel = workspace.update_in(cx, |workspace, window, cx| {
13792 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13793 workspace.add_panel(panel.clone(), window, cx);
13794
13795 workspace
13796 .right_dock()
13797 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13798
13799 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13800
13801 panel
13802 });
13803
13804 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13805 // panel to the next valid position which, in this case, is the left
13806 // dock.
13807 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13808 workspace.update(cx, |workspace, cx| {
13809 assert!(workspace.left_dock().read(cx).is_open());
13810 assert_eq!(panel.read(cx).position, DockPosition::Left);
13811 });
13812
13813 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13814 // panel to the next valid position which, in this case, is the bottom
13815 // dock.
13816 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13817 workspace.update(cx, |workspace, cx| {
13818 assert!(workspace.bottom_dock().read(cx).is_open());
13819 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13820 });
13821
13822 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13823 // around moving the panel to its initial position, the right dock.
13824 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13825 workspace.update(cx, |workspace, cx| {
13826 assert!(workspace.right_dock().read(cx).is_open());
13827 assert_eq!(panel.read(cx).position, DockPosition::Right);
13828 });
13829
13830 // Remove focus from the panel, ensuring that, if the panel is not
13831 // focused, the `MoveFocusedPanelToNextPosition` action does not update
13832 // the panel's position, so the panel is still in the right dock.
13833 workspace.update_in(cx, |workspace, window, cx| {
13834 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13835 });
13836
13837 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13838 workspace.update(cx, |workspace, cx| {
13839 assert!(workspace.right_dock().read(cx).is_open());
13840 assert_eq!(panel.read(cx).position, DockPosition::Right);
13841 });
13842 }
13843
13844 #[gpui::test]
13845 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13846 init_test(cx);
13847
13848 let fs = FakeFs::new(cx.executor());
13849 let project = Project::test(fs, [], cx).await;
13850 let (workspace, cx) =
13851 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13852
13853 let item_1 = cx.new(|cx| {
13854 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13855 });
13856 workspace.update_in(cx, |workspace, window, cx| {
13857 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13858 workspace.move_item_to_pane_in_direction(
13859 &MoveItemToPaneInDirection {
13860 direction: SplitDirection::Right,
13861 focus: true,
13862 clone: false,
13863 },
13864 window,
13865 cx,
13866 );
13867 workspace.move_item_to_pane_at_index(
13868 &MoveItemToPane {
13869 destination: 3,
13870 focus: true,
13871 clone: false,
13872 },
13873 window,
13874 cx,
13875 );
13876
13877 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13878 assert_eq!(
13879 pane_items_paths(&workspace.active_pane, cx),
13880 vec!["first.txt".to_string()],
13881 "Single item was not moved anywhere"
13882 );
13883 });
13884
13885 let item_2 = cx.new(|cx| {
13886 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13887 });
13888 workspace.update_in(cx, |workspace, window, cx| {
13889 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13890 assert_eq!(
13891 pane_items_paths(&workspace.panes[0], cx),
13892 vec!["first.txt".to_string(), "second.txt".to_string()],
13893 );
13894 workspace.move_item_to_pane_in_direction(
13895 &MoveItemToPaneInDirection {
13896 direction: SplitDirection::Right,
13897 focus: true,
13898 clone: false,
13899 },
13900 window,
13901 cx,
13902 );
13903
13904 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13905 assert_eq!(
13906 pane_items_paths(&workspace.panes[0], cx),
13907 vec!["first.txt".to_string()],
13908 "After moving, one item should be left in the original pane"
13909 );
13910 assert_eq!(
13911 pane_items_paths(&workspace.panes[1], cx),
13912 vec!["second.txt".to_string()],
13913 "New item should have been moved to the new pane"
13914 );
13915 });
13916
13917 let item_3 = cx.new(|cx| {
13918 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13919 });
13920 workspace.update_in(cx, |workspace, window, cx| {
13921 let original_pane = workspace.panes[0].clone();
13922 workspace.set_active_pane(&original_pane, window, cx);
13923 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13924 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13925 assert_eq!(
13926 pane_items_paths(&workspace.active_pane, cx),
13927 vec!["first.txt".to_string(), "third.txt".to_string()],
13928 "New pane should be ready to move one item out"
13929 );
13930
13931 workspace.move_item_to_pane_at_index(
13932 &MoveItemToPane {
13933 destination: 3,
13934 focus: true,
13935 clone: false,
13936 },
13937 window,
13938 cx,
13939 );
13940 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13941 assert_eq!(
13942 pane_items_paths(&workspace.active_pane, cx),
13943 vec!["first.txt".to_string()],
13944 "After moving, one item should be left in the original pane"
13945 );
13946 assert_eq!(
13947 pane_items_paths(&workspace.panes[1], cx),
13948 vec!["second.txt".to_string()],
13949 "Previously created pane should be unchanged"
13950 );
13951 assert_eq!(
13952 pane_items_paths(&workspace.panes[2], cx),
13953 vec!["third.txt".to_string()],
13954 "New item should have been moved to the new pane"
13955 );
13956 });
13957 }
13958
13959 #[gpui::test]
13960 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13961 init_test(cx);
13962
13963 let fs = FakeFs::new(cx.executor());
13964 let project = Project::test(fs, [], cx).await;
13965 let (workspace, cx) =
13966 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13967
13968 let item_1 = cx.new(|cx| {
13969 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13970 });
13971 workspace.update_in(cx, |workspace, window, cx| {
13972 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13973 workspace.move_item_to_pane_in_direction(
13974 &MoveItemToPaneInDirection {
13975 direction: SplitDirection::Right,
13976 focus: true,
13977 clone: true,
13978 },
13979 window,
13980 cx,
13981 );
13982 });
13983 cx.run_until_parked();
13984 workspace.update_in(cx, |workspace, window, cx| {
13985 workspace.move_item_to_pane_at_index(
13986 &MoveItemToPane {
13987 destination: 3,
13988 focus: true,
13989 clone: true,
13990 },
13991 window,
13992 cx,
13993 );
13994 });
13995 cx.run_until_parked();
13996
13997 workspace.update(cx, |workspace, cx| {
13998 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13999 for pane in workspace.panes() {
14000 assert_eq!(
14001 pane_items_paths(pane, cx),
14002 vec!["first.txt".to_string()],
14003 "Single item exists in all panes"
14004 );
14005 }
14006 });
14007
14008 // verify that the active pane has been updated after waiting for the
14009 // pane focus event to fire and resolve
14010 workspace.read_with(cx, |workspace, _app| {
14011 assert_eq!(
14012 workspace.active_pane(),
14013 &workspace.panes[2],
14014 "The third pane should be the active one: {:?}",
14015 workspace.panes
14016 );
14017 })
14018 }
14019
14020 #[gpui::test]
14021 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
14022 init_test(cx);
14023
14024 let fs = FakeFs::new(cx.executor());
14025 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14026
14027 let project = Project::test(fs, ["root".as_ref()], cx).await;
14028 let (workspace, cx) =
14029 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14030
14031 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14032 // Add item to pane A with project path
14033 let item_a = cx.new(|cx| {
14034 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14035 });
14036 workspace.update_in(cx, |workspace, window, cx| {
14037 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14038 });
14039
14040 // Split to create pane B
14041 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14042 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14043 });
14044
14045 // Add item with SAME project path to pane B, and pin it
14046 let item_b = cx.new(|cx| {
14047 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14048 });
14049 pane_b.update_in(cx, |pane, window, cx| {
14050 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14051 pane.set_pinned_count(1);
14052 });
14053
14054 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14055 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14056
14057 // close_pinned: false should only close the unpinned copy
14058 workspace.update_in(cx, |workspace, window, cx| {
14059 workspace.close_item_in_all_panes(
14060 &CloseItemInAllPanes {
14061 save_intent: Some(SaveIntent::Close),
14062 close_pinned: false,
14063 },
14064 window,
14065 cx,
14066 )
14067 });
14068 cx.executor().run_until_parked();
14069
14070 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14071 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14072 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14073 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14074
14075 // Split again, seeing as closing the previous item also closed its
14076 // pane, so only pane remains, which does not allow us to properly test
14077 // that both items close when `close_pinned: true`.
14078 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14079 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14080 });
14081
14082 // Add an item with the same project path to pane C so that
14083 // close_item_in_all_panes can determine what to close across all panes
14084 // (it reads the active item from the active pane, and split_pane
14085 // creates an empty pane).
14086 let item_c = cx.new(|cx| {
14087 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14088 });
14089 pane_c.update_in(cx, |pane, window, cx| {
14090 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14091 });
14092
14093 // close_pinned: true should close the pinned copy too
14094 workspace.update_in(cx, |workspace, window, cx| {
14095 let panes_count = workspace.panes().len();
14096 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14097
14098 workspace.close_item_in_all_panes(
14099 &CloseItemInAllPanes {
14100 save_intent: Some(SaveIntent::Close),
14101 close_pinned: true,
14102 },
14103 window,
14104 cx,
14105 )
14106 });
14107 cx.executor().run_until_parked();
14108
14109 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14110 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14111 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14112 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14113 }
14114
14115 mod register_project_item_tests {
14116
14117 use super::*;
14118
14119 // View
14120 struct TestPngItemView {
14121 focus_handle: FocusHandle,
14122 }
14123 // Model
14124 struct TestPngItem {}
14125
14126 impl project::ProjectItem for TestPngItem {
14127 fn try_open(
14128 _project: &Entity<Project>,
14129 path: &ProjectPath,
14130 cx: &mut App,
14131 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14132 if path.path.extension().unwrap() == "png" {
14133 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14134 } else {
14135 None
14136 }
14137 }
14138
14139 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14140 None
14141 }
14142
14143 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14144 None
14145 }
14146
14147 fn is_dirty(&self) -> bool {
14148 false
14149 }
14150 }
14151
14152 impl Item for TestPngItemView {
14153 type Event = ();
14154 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14155 "".into()
14156 }
14157 }
14158 impl EventEmitter<()> for TestPngItemView {}
14159 impl Focusable for TestPngItemView {
14160 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14161 self.focus_handle.clone()
14162 }
14163 }
14164
14165 impl Render for TestPngItemView {
14166 fn render(
14167 &mut self,
14168 _window: &mut Window,
14169 _cx: &mut Context<Self>,
14170 ) -> impl IntoElement {
14171 Empty
14172 }
14173 }
14174
14175 impl ProjectItem for TestPngItemView {
14176 type Item = TestPngItem;
14177
14178 fn for_project_item(
14179 _project: Entity<Project>,
14180 _pane: Option<&Pane>,
14181 _item: Entity<Self::Item>,
14182 _: &mut Window,
14183 cx: &mut Context<Self>,
14184 ) -> Self
14185 where
14186 Self: Sized,
14187 {
14188 Self {
14189 focus_handle: cx.focus_handle(),
14190 }
14191 }
14192 }
14193
14194 // View
14195 struct TestIpynbItemView {
14196 focus_handle: FocusHandle,
14197 }
14198 // Model
14199 struct TestIpynbItem {}
14200
14201 impl project::ProjectItem for TestIpynbItem {
14202 fn try_open(
14203 _project: &Entity<Project>,
14204 path: &ProjectPath,
14205 cx: &mut App,
14206 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14207 if path.path.extension().unwrap() == "ipynb" {
14208 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14209 } else {
14210 None
14211 }
14212 }
14213
14214 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14215 None
14216 }
14217
14218 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14219 None
14220 }
14221
14222 fn is_dirty(&self) -> bool {
14223 false
14224 }
14225 }
14226
14227 impl Item for TestIpynbItemView {
14228 type Event = ();
14229 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14230 "".into()
14231 }
14232 }
14233 impl EventEmitter<()> for TestIpynbItemView {}
14234 impl Focusable for TestIpynbItemView {
14235 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14236 self.focus_handle.clone()
14237 }
14238 }
14239
14240 impl Render for TestIpynbItemView {
14241 fn render(
14242 &mut self,
14243 _window: &mut Window,
14244 _cx: &mut Context<Self>,
14245 ) -> impl IntoElement {
14246 Empty
14247 }
14248 }
14249
14250 impl ProjectItem for TestIpynbItemView {
14251 type Item = TestIpynbItem;
14252
14253 fn for_project_item(
14254 _project: Entity<Project>,
14255 _pane: Option<&Pane>,
14256 _item: Entity<Self::Item>,
14257 _: &mut Window,
14258 cx: &mut Context<Self>,
14259 ) -> Self
14260 where
14261 Self: Sized,
14262 {
14263 Self {
14264 focus_handle: cx.focus_handle(),
14265 }
14266 }
14267 }
14268
14269 struct TestAlternatePngItemView {
14270 focus_handle: FocusHandle,
14271 }
14272
14273 impl Item for TestAlternatePngItemView {
14274 type Event = ();
14275 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14276 "".into()
14277 }
14278 }
14279
14280 impl EventEmitter<()> for TestAlternatePngItemView {}
14281 impl Focusable for TestAlternatePngItemView {
14282 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14283 self.focus_handle.clone()
14284 }
14285 }
14286
14287 impl Render for TestAlternatePngItemView {
14288 fn render(
14289 &mut self,
14290 _window: &mut Window,
14291 _cx: &mut Context<Self>,
14292 ) -> impl IntoElement {
14293 Empty
14294 }
14295 }
14296
14297 impl ProjectItem for TestAlternatePngItemView {
14298 type Item = TestPngItem;
14299
14300 fn for_project_item(
14301 _project: Entity<Project>,
14302 _pane: Option<&Pane>,
14303 _item: Entity<Self::Item>,
14304 _: &mut Window,
14305 cx: &mut Context<Self>,
14306 ) -> Self
14307 where
14308 Self: Sized,
14309 {
14310 Self {
14311 focus_handle: cx.focus_handle(),
14312 }
14313 }
14314 }
14315
14316 #[gpui::test]
14317 async fn test_register_project_item(cx: &mut TestAppContext) {
14318 init_test(cx);
14319
14320 cx.update(|cx| {
14321 register_project_item::<TestPngItemView>(cx);
14322 register_project_item::<TestIpynbItemView>(cx);
14323 });
14324
14325 let fs = FakeFs::new(cx.executor());
14326 fs.insert_tree(
14327 "/root1",
14328 json!({
14329 "one.png": "BINARYDATAHERE",
14330 "two.ipynb": "{ totally a notebook }",
14331 "three.txt": "editing text, sure why not?"
14332 }),
14333 )
14334 .await;
14335
14336 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14337 let (workspace, cx) =
14338 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14339
14340 let worktree_id = project.update(cx, |project, cx| {
14341 project.worktrees(cx).next().unwrap().read(cx).id()
14342 });
14343
14344 let handle = workspace
14345 .update_in(cx, |workspace, window, cx| {
14346 let project_path = (worktree_id, rel_path("one.png"));
14347 workspace.open_path(project_path, None, true, window, cx)
14348 })
14349 .await
14350 .unwrap();
14351
14352 // Now we can check if the handle we got back errored or not
14353 assert_eq!(
14354 handle.to_any_view().entity_type(),
14355 TypeId::of::<TestPngItemView>()
14356 );
14357
14358 let handle = workspace
14359 .update_in(cx, |workspace, window, cx| {
14360 let project_path = (worktree_id, rel_path("two.ipynb"));
14361 workspace.open_path(project_path, None, true, window, cx)
14362 })
14363 .await
14364 .unwrap();
14365
14366 assert_eq!(
14367 handle.to_any_view().entity_type(),
14368 TypeId::of::<TestIpynbItemView>()
14369 );
14370
14371 let handle = workspace
14372 .update_in(cx, |workspace, window, cx| {
14373 let project_path = (worktree_id, rel_path("three.txt"));
14374 workspace.open_path(project_path, None, true, window, cx)
14375 })
14376 .await;
14377 assert!(handle.is_err());
14378 }
14379
14380 #[gpui::test]
14381 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14382 init_test(cx);
14383
14384 cx.update(|cx| {
14385 register_project_item::<TestPngItemView>(cx);
14386 register_project_item::<TestAlternatePngItemView>(cx);
14387 });
14388
14389 let fs = FakeFs::new(cx.executor());
14390 fs.insert_tree(
14391 "/root1",
14392 json!({
14393 "one.png": "BINARYDATAHERE",
14394 "two.ipynb": "{ totally a notebook }",
14395 "three.txt": "editing text, sure why not?"
14396 }),
14397 )
14398 .await;
14399 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14400 let (workspace, cx) =
14401 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14402 let worktree_id = project.update(cx, |project, cx| {
14403 project.worktrees(cx).next().unwrap().read(cx).id()
14404 });
14405
14406 let handle = workspace
14407 .update_in(cx, |workspace, window, cx| {
14408 let project_path = (worktree_id, rel_path("one.png"));
14409 workspace.open_path(project_path, None, true, window, cx)
14410 })
14411 .await
14412 .unwrap();
14413
14414 // This _must_ be the second item registered
14415 assert_eq!(
14416 handle.to_any_view().entity_type(),
14417 TypeId::of::<TestAlternatePngItemView>()
14418 );
14419
14420 let handle = workspace
14421 .update_in(cx, |workspace, window, cx| {
14422 let project_path = (worktree_id, rel_path("three.txt"));
14423 workspace.open_path(project_path, None, true, window, cx)
14424 })
14425 .await;
14426 assert!(handle.is_err());
14427 }
14428 }
14429
14430 #[gpui::test]
14431 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14432 init_test(cx);
14433
14434 let fs = FakeFs::new(cx.executor());
14435 let project = Project::test(fs, [], cx).await;
14436 let (workspace, _cx) =
14437 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14438
14439 // Test with status bar shown (default)
14440 workspace.read_with(cx, |workspace, cx| {
14441 let visible = workspace.status_bar_visible(cx);
14442 assert!(visible, "Status bar should be visible by default");
14443 });
14444
14445 // Test with status bar hidden
14446 cx.update_global(|store: &mut SettingsStore, cx| {
14447 store.update_user_settings(cx, |settings| {
14448 settings.status_bar.get_or_insert_default().show = Some(false);
14449 });
14450 });
14451
14452 workspace.read_with(cx, |workspace, cx| {
14453 let visible = workspace.status_bar_visible(cx);
14454 assert!(!visible, "Status bar should be hidden when show is false");
14455 });
14456
14457 // Test with status bar shown explicitly
14458 cx.update_global(|store: &mut SettingsStore, cx| {
14459 store.update_user_settings(cx, |settings| {
14460 settings.status_bar.get_or_insert_default().show = Some(true);
14461 });
14462 });
14463
14464 workspace.read_with(cx, |workspace, cx| {
14465 let visible = workspace.status_bar_visible(cx);
14466 assert!(visible, "Status bar should be visible when show is true");
14467 });
14468 }
14469
14470 #[gpui::test]
14471 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14472 init_test(cx);
14473
14474 let fs = FakeFs::new(cx.executor());
14475 let project = Project::test(fs, [], cx).await;
14476 let (multi_workspace, cx) =
14477 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14478 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14479 let panel = workspace.update_in(cx, |workspace, window, cx| {
14480 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14481 workspace.add_panel(panel.clone(), window, cx);
14482
14483 workspace
14484 .right_dock()
14485 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14486
14487 panel
14488 });
14489
14490 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14491 let item_a = cx.new(TestItem::new);
14492 let item_b = cx.new(TestItem::new);
14493 let item_a_id = item_a.entity_id();
14494 let item_b_id = item_b.entity_id();
14495
14496 pane.update_in(cx, |pane, window, cx| {
14497 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14498 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14499 });
14500
14501 pane.read_with(cx, |pane, _| {
14502 assert_eq!(pane.items_len(), 2);
14503 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14504 });
14505
14506 workspace.update_in(cx, |workspace, window, cx| {
14507 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14508 });
14509
14510 workspace.update_in(cx, |_, window, cx| {
14511 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14512 });
14513
14514 // Assert that the `pane::CloseActiveItem` action is handled at the
14515 // workspace level when one of the dock panels is focused and, in that
14516 // case, the center pane's active item is closed but the focus is not
14517 // moved.
14518 cx.dispatch_action(pane::CloseActiveItem::default());
14519 cx.run_until_parked();
14520
14521 pane.read_with(cx, |pane, _| {
14522 assert_eq!(pane.items_len(), 1);
14523 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14524 });
14525
14526 workspace.update_in(cx, |workspace, window, cx| {
14527 assert!(workspace.right_dock().read(cx).is_open());
14528 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14529 });
14530 }
14531
14532 #[gpui::test]
14533 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14534 init_test(cx);
14535 let fs = FakeFs::new(cx.executor());
14536
14537 let project_a = Project::test(fs.clone(), [], cx).await;
14538 let project_b = Project::test(fs, [], cx).await;
14539
14540 let multi_workspace_handle =
14541 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14542 cx.run_until_parked();
14543
14544 let workspace_a = multi_workspace_handle
14545 .read_with(cx, |mw, _| mw.workspace().clone())
14546 .unwrap();
14547
14548 let _workspace_b = multi_workspace_handle
14549 .update(cx, |mw, window, cx| {
14550 mw.test_add_workspace(project_b, window, cx)
14551 })
14552 .unwrap();
14553
14554 // Switch to workspace A
14555 multi_workspace_handle
14556 .update(cx, |mw, window, cx| {
14557 let workspace = mw.workspaces()[0].clone();
14558 mw.activate(workspace, window, cx);
14559 })
14560 .unwrap();
14561
14562 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14563
14564 // Add a panel to workspace A's right dock and open the dock
14565 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14566 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14567 workspace.add_panel(panel.clone(), window, cx);
14568 workspace
14569 .right_dock()
14570 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14571 panel
14572 });
14573
14574 // Focus the panel through the workspace (matching existing test pattern)
14575 workspace_a.update_in(cx, |workspace, window, cx| {
14576 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14577 });
14578
14579 // Zoom the panel
14580 panel.update_in(cx, |panel, window, cx| {
14581 panel.set_zoomed(true, window, cx);
14582 });
14583
14584 // Verify the panel is zoomed and the dock is open
14585 workspace_a.update_in(cx, |workspace, window, cx| {
14586 assert!(
14587 workspace.right_dock().read(cx).is_open(),
14588 "dock should be open before switch"
14589 );
14590 assert!(
14591 panel.is_zoomed(window, cx),
14592 "panel should be zoomed before switch"
14593 );
14594 assert!(
14595 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14596 "panel should be focused before switch"
14597 );
14598 });
14599
14600 // Switch to workspace B
14601 multi_workspace_handle
14602 .update(cx, |mw, window, cx| {
14603 let workspace = mw.workspaces()[1].clone();
14604 mw.activate(workspace, window, cx);
14605 })
14606 .unwrap();
14607 cx.run_until_parked();
14608
14609 // Switch back to workspace A
14610 multi_workspace_handle
14611 .update(cx, |mw, window, cx| {
14612 let workspace = mw.workspaces()[0].clone();
14613 mw.activate(workspace, window, cx);
14614 })
14615 .unwrap();
14616 cx.run_until_parked();
14617
14618 // Verify the panel is still zoomed and the dock is still open
14619 workspace_a.update_in(cx, |workspace, window, cx| {
14620 assert!(
14621 workspace.right_dock().read(cx).is_open(),
14622 "dock should still be open after switching back"
14623 );
14624 assert!(
14625 panel.is_zoomed(window, cx),
14626 "panel should still be zoomed after switching back"
14627 );
14628 });
14629 }
14630
14631 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14632 pane.read(cx)
14633 .items()
14634 .flat_map(|item| {
14635 item.project_paths(cx)
14636 .into_iter()
14637 .map(|path| path.path.display(PathStyle::local()).into_owned())
14638 })
14639 .collect()
14640 }
14641
14642 pub fn init_test(cx: &mut TestAppContext) {
14643 cx.update(|cx| {
14644 let settings_store = SettingsStore::test(cx);
14645 cx.set_global(settings_store);
14646 cx.set_global(db::AppDatabase::test_new());
14647 theme_settings::init(theme::LoadThemes::JustBase, cx);
14648 });
14649 }
14650
14651 #[gpui::test]
14652 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14653 use settings::{ThemeName, ThemeSelection};
14654 use theme::SystemAppearance;
14655 use zed_actions::theme::ToggleMode;
14656
14657 init_test(cx);
14658
14659 let fs = FakeFs::new(cx.executor());
14660 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14661
14662 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14663 .await;
14664
14665 // Build a test project and workspace view so the test can invoke
14666 // the workspace action handler the same way the UI would.
14667 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14668 let (workspace, cx) =
14669 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14670
14671 // Seed the settings file with a plain static light theme so the
14672 // first toggle always starts from a known persisted state.
14673 workspace.update_in(cx, |_workspace, _window, cx| {
14674 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14675 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14676 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14677 });
14678 });
14679 cx.executor().advance_clock(Duration::from_millis(200));
14680 cx.run_until_parked();
14681
14682 // Confirm the initial persisted settings contain the static theme
14683 // we just wrote before any toggling happens.
14684 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14685 assert!(settings_text.contains(r#""theme": "One Light""#));
14686
14687 // Toggle once. This should migrate the persisted theme settings
14688 // into light/dark slots and enable system mode.
14689 workspace.update_in(cx, |workspace, window, cx| {
14690 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14691 });
14692 cx.executor().advance_clock(Duration::from_millis(200));
14693 cx.run_until_parked();
14694
14695 // 1. Static -> Dynamic
14696 // this assertion checks theme changed from static to dynamic.
14697 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14698 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14699 assert_eq!(
14700 parsed["theme"],
14701 serde_json::json!({
14702 "mode": "system",
14703 "light": "One Light",
14704 "dark": "One Dark"
14705 })
14706 );
14707
14708 // 2. Toggle again, suppose it will change the mode to light
14709 workspace.update_in(cx, |workspace, window, cx| {
14710 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14711 });
14712 cx.executor().advance_clock(Duration::from_millis(200));
14713 cx.run_until_parked();
14714
14715 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14716 assert!(settings_text.contains(r#""mode": "light""#));
14717 }
14718
14719 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14720 let item = TestProjectItem::new(id, path, cx);
14721 item.update(cx, |item, _| {
14722 item.is_dirty = true;
14723 });
14724 item
14725 }
14726
14727 #[gpui::test]
14728 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14729 cx: &mut gpui::TestAppContext,
14730 ) {
14731 init_test(cx);
14732 let fs = FakeFs::new(cx.executor());
14733
14734 let project = Project::test(fs, [], cx).await;
14735 let (workspace, cx) =
14736 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14737
14738 let panel = workspace.update_in(cx, |workspace, window, cx| {
14739 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14740 workspace.add_panel(panel.clone(), window, cx);
14741 workspace
14742 .right_dock()
14743 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14744 panel
14745 });
14746
14747 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14748 pane.update_in(cx, |pane, window, cx| {
14749 let item = cx.new(TestItem::new);
14750 pane.add_item(Box::new(item), true, true, None, window, cx);
14751 });
14752
14753 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14754 // mirrors the real-world flow and avoids side effects from directly
14755 // focusing the panel while the center pane is active.
14756 workspace.update_in(cx, |workspace, window, cx| {
14757 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14758 });
14759
14760 panel.update_in(cx, |panel, window, cx| {
14761 panel.set_zoomed(true, window, cx);
14762 });
14763
14764 workspace.update_in(cx, |workspace, window, cx| {
14765 assert!(workspace.right_dock().read(cx).is_open());
14766 assert!(panel.is_zoomed(window, cx));
14767 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14768 });
14769
14770 // Simulate a spurious pane::Event::Focus on the center pane while the
14771 // panel still has focus. This mirrors what happens during macOS window
14772 // activation: the center pane fires a focus event even though actual
14773 // focus remains on the dock panel.
14774 pane.update_in(cx, |_, _, cx| {
14775 cx.emit(pane::Event::Focus);
14776 });
14777
14778 // The dock must remain open because the panel had focus at the time the
14779 // event was processed. Before the fix, dock_to_preserve was None for
14780 // panels that don't implement pane(), causing the dock to close.
14781 workspace.update_in(cx, |workspace, window, cx| {
14782 assert!(
14783 workspace.right_dock().read(cx).is_open(),
14784 "Dock should stay open when its zoomed panel (without pane()) still has focus"
14785 );
14786 assert!(panel.is_zoomed(window, cx));
14787 });
14788 }
14789
14790 #[gpui::test]
14791 async fn test_panels_stay_open_after_position_change_and_settings_update(
14792 cx: &mut gpui::TestAppContext,
14793 ) {
14794 init_test(cx);
14795 let fs = FakeFs::new(cx.executor());
14796 let project = Project::test(fs, [], cx).await;
14797 let (workspace, cx) =
14798 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14799
14800 // Add two panels to the left dock and open it.
14801 let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14802 let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14803 let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14804 workspace.add_panel(panel_a.clone(), window, cx);
14805 workspace.add_panel(panel_b.clone(), window, cx);
14806 workspace.left_dock().update(cx, |dock, cx| {
14807 dock.set_open(true, window, cx);
14808 dock.activate_panel(0, window, cx);
14809 });
14810 (panel_a, panel_b)
14811 });
14812
14813 workspace.update_in(cx, |workspace, _, cx| {
14814 assert!(workspace.left_dock().read(cx).is_open());
14815 });
14816
14817 // Simulate a feature flag changing default dock positions: both panels
14818 // move from Left to Right.
14819 workspace.update_in(cx, |_workspace, _window, cx| {
14820 panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14821 panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14822 cx.update_global::<SettingsStore, _>(|_, _| {});
14823 });
14824
14825 // Both panels should now be in the right dock.
14826 workspace.update_in(cx, |workspace, _, cx| {
14827 let right_dock = workspace.right_dock().read(cx);
14828 assert_eq!(right_dock.panels_len(), 2);
14829 });
14830
14831 // Open the right dock and activate panel_b (simulating the user
14832 // opening the panel after it moved).
14833 workspace.update_in(cx, |workspace, window, cx| {
14834 workspace.right_dock().update(cx, |dock, cx| {
14835 dock.set_open(true, window, cx);
14836 dock.activate_panel(1, window, cx);
14837 });
14838 });
14839
14840 // Now trigger another SettingsStore change
14841 workspace.update_in(cx, |_workspace, _window, cx| {
14842 cx.update_global::<SettingsStore, _>(|_, _| {});
14843 });
14844
14845 workspace.update_in(cx, |workspace, _, cx| {
14846 assert!(
14847 workspace.right_dock().read(cx).is_open(),
14848 "Right dock should still be open after a settings change"
14849 );
14850 assert_eq!(
14851 workspace.right_dock().read(cx).panels_len(),
14852 2,
14853 "Both panels should still be in the right dock"
14854 );
14855 });
14856 }
14857}