1pub mod active_file_name;
2pub mod dock;
3pub mod history_manager;
4pub mod invalid_item_view;
5pub mod item;
6mod modal_layer;
7mod multi_workspace;
8#[cfg(test)]
9mod multi_workspace_tests;
10pub mod notifications;
11pub mod pane;
12pub mod pane_group;
13pub mod path_list {
14 pub use util::path_list::{PathList, SerializedPathList};
15}
16mod persistence;
17pub mod searchable;
18mod security_modal;
19pub mod shared_screen;
20use db::smol::future::yield_now;
21pub use shared_screen::SharedScreen;
22pub mod focus_follows_mouse;
23mod status_bar;
24pub mod tasks;
25mod theme_preview;
26mod toast_layer;
27mod toolbar;
28pub mod welcome;
29mod workspace_settings;
30
31pub use crate::notifications::NotificationFrame;
32pub use dock::Panel;
33pub use multi_workspace::{
34 CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
35 MultiWorkspaceEvent, NextWorkspace, PreviousWorkspace, Sidebar, SidebarEvent, SidebarHandle,
36 SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar, sidebar_side_context_menu,
37};
38pub use path_list::{PathList, SerializedPathList};
39pub use toast_layer::{ToastAction, ToastLayer, ToastView};
40
41use anyhow::{Context as _, Result, anyhow};
42use client::{
43 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
44 proto::{self, ErrorCode, PanelId, PeerId},
45};
46use collections::{HashMap, HashSet, hash_map};
47use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
48use fs::Fs;
49use futures::{
50 Future, FutureExt, StreamExt,
51 channel::{
52 mpsc::{self, UnboundedReceiver, UnboundedSender},
53 oneshot,
54 },
55 future::{Shared, try_join_all},
56};
57use gpui::{
58 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
59 Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
60 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
61 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
62 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
63 WindowOptions, actions, canvas, point, relative, size, transparent_black,
64};
65pub use history_manager::*;
66pub use item::{
67 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
68 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
69};
70use itertools::Itertools;
71use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
72pub use modal_layer::*;
73use node_runtime::NodeRuntime;
74use notifications::{
75 DetachAndPromptErr, Notifications, dismiss_app_notification,
76 simple_message_notification::MessageNotification,
77};
78pub use pane::*;
79pub use pane_group::{
80 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
81 SplitDirection,
82};
83use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
84pub use persistence::{
85 WorkspaceDb, delete_unloaded_items,
86 model::{
87 DockStructure, ItemId, MultiWorkspaceState, SerializedMultiWorkspace,
88 SerializedWorkspaceLocation, SessionWorkspace,
89 },
90 read_serialized_multi_workspaces, resolve_worktree_workspaces,
91};
92use postage::stream::Stream;
93use project::{
94 DirectoryLister, Project, ProjectEntryId, ProjectGroupKey, ProjectPath, ResolvedPath, Worktree,
95 WorktreeId, WorktreeSettings,
96 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
97 project_settings::ProjectSettings,
98 toolchain_store::ToolchainStoreEvent,
99 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
100};
101use remote::{
102 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
103 remote_client::ConnectionIdentifier,
104};
105use schemars::JsonSchema;
106use serde::Deserialize;
107use session::AppSession;
108use settings::{
109 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
110};
111
112use sqlez::{
113 bindable::{Bind, Column, StaticColumnCount},
114 statement::Statement,
115};
116use status_bar::StatusBar;
117pub use status_bar::StatusItemView;
118use std::{
119 any::TypeId,
120 borrow::Cow,
121 cell::RefCell,
122 cmp,
123 collections::VecDeque,
124 env,
125 hash::Hash,
126 path::{Path, PathBuf},
127 process::ExitStatus,
128 rc::Rc,
129 sync::{
130 Arc, LazyLock,
131 atomic::{AtomicBool, AtomicUsize},
132 },
133 time::Duration,
134};
135use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
136use theme::{ActiveTheme, SystemAppearance};
137use theme_settings::ThemeSettings;
138pub use toolbar::{
139 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
140};
141pub use ui;
142use ui::{Window, prelude::*};
143use util::{
144 ResultExt, TryFutureExt,
145 paths::{PathStyle, SanitizedPath},
146 rel_path::RelPath,
147 serde::default_true,
148};
149use uuid::Uuid;
150pub use workspace_settings::{
151 AutosaveSetting, BottomDockLayout, FocusFollowsMouse, RestoreOnStartupBehavior,
152 StatusBarSettings, TabBarSettings, WorkspaceSettings,
153};
154use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
155
156use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::NotificationId};
157use crate::{
158 persistence::{
159 SerializedAxis,
160 model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
161 },
162 security_modal::SecurityModal,
163};
164
165pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
166
167static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
168 env::var("ZED_WINDOW_SIZE")
169 .ok()
170 .as_deref()
171 .and_then(parse_pixel_size_env_var)
172});
173
174static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
175 env::var("ZED_WINDOW_POSITION")
176 .ok()
177 .as_deref()
178 .and_then(parse_pixel_position_env_var)
179});
180
181pub trait TerminalProvider {
182 fn spawn(
183 &self,
184 task: SpawnInTerminal,
185 window: &mut Window,
186 cx: &mut App,
187 ) -> Task<Option<Result<ExitStatus>>>;
188}
189
190pub trait DebuggerProvider {
191 // `active_buffer` is used to resolve build task's name against language-specific tasks.
192 fn start_session(
193 &self,
194 definition: DebugScenario,
195 task_context: SharedTaskContext,
196 active_buffer: Option<Entity<Buffer>>,
197 worktree_id: Option<WorktreeId>,
198 window: &mut Window,
199 cx: &mut App,
200 );
201
202 fn spawn_task_or_modal(
203 &self,
204 workspace: &mut Workspace,
205 action: &Spawn,
206 window: &mut Window,
207 cx: &mut Context<Workspace>,
208 );
209
210 fn task_scheduled(&self, cx: &mut App);
211 fn debug_scenario_scheduled(&self, cx: &mut App);
212 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
213
214 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
215}
216
217/// Opens a file or directory.
218#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
219#[action(namespace = workspace)]
220pub struct Open {
221 /// When true, opens in a new window. When false, adds to the current
222 /// window as a new workspace (multi-workspace).
223 #[serde(default = "Open::default_create_new_window")]
224 pub create_new_window: bool,
225}
226
227impl Open {
228 pub const DEFAULT: Self = Self {
229 create_new_window: true,
230 };
231
232 /// Used by `#[serde(default)]` on the `create_new_window` field so that
233 /// the serde default and `Open::DEFAULT` stay in sync.
234 fn default_create_new_window() -> bool {
235 Self::DEFAULT.create_new_window
236 }
237}
238
239impl Default for Open {
240 fn default() -> Self {
241 Self::DEFAULT
242 }
243}
244
245actions!(
246 workspace,
247 [
248 /// Activates the next pane in the workspace.
249 ActivateNextPane,
250 /// Activates the previous pane in the workspace.
251 ActivatePreviousPane,
252 /// Activates the last pane in the workspace.
253 ActivateLastPane,
254 /// Switches to the next window.
255 ActivateNextWindow,
256 /// Switches to the previous window.
257 ActivatePreviousWindow,
258 /// Adds a folder to the current project.
259 AddFolderToProject,
260 /// Clears all notifications.
261 ClearAllNotifications,
262 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
263 ClearNavigationHistory,
264 /// Closes the active dock.
265 CloseActiveDock,
266 /// Closes all docks.
267 CloseAllDocks,
268 /// Toggles all docks.
269 ToggleAllDocks,
270 /// Closes the current window.
271 CloseWindow,
272 /// Closes the current project.
273 CloseProject,
274 /// Opens the feedback dialog.
275 Feedback,
276 /// Follows the next collaborator in the session.
277 FollowNextCollaborator,
278 /// Moves the focused panel to the next position.
279 MoveFocusedPanelToNextPosition,
280 /// Creates a new file.
281 NewFile,
282 /// Creates a new file in a vertical split.
283 NewFileSplitVertical,
284 /// Creates a new file in a horizontal split.
285 NewFileSplitHorizontal,
286 /// Opens a new search.
287 NewSearch,
288 /// Opens a new window.
289 NewWindow,
290 /// Opens multiple files.
291 OpenFiles,
292 /// Opens the current location in terminal.
293 OpenInTerminal,
294 /// Opens the component preview.
295 OpenComponentPreview,
296 /// Reloads the active item.
297 ReloadActiveItem,
298 /// Resets the active dock to its default size.
299 ResetActiveDockSize,
300 /// Resets all open docks to their default sizes.
301 ResetOpenDocksSize,
302 /// Reloads the application
303 Reload,
304 /// Saves the current file with a new name.
305 SaveAs,
306 /// Saves without formatting.
307 SaveWithoutFormat,
308 /// Shuts down all debug adapters.
309 ShutdownDebugAdapters,
310 /// Suppresses the current notification.
311 SuppressNotification,
312 /// Toggles the bottom dock.
313 ToggleBottomDock,
314 /// Toggles centered layout mode.
315 ToggleCenteredLayout,
316 /// Toggles edit prediction feature globally for all files.
317 ToggleEditPrediction,
318 /// Toggles the left dock.
319 ToggleLeftDock,
320 /// Toggles the right dock.
321 ToggleRightDock,
322 /// Toggles zoom on the active pane.
323 ToggleZoom,
324 /// Toggles read-only mode for the active item (if supported by that item).
325 ToggleReadOnlyFile,
326 /// Zooms in on the active pane.
327 ZoomIn,
328 /// Zooms out of the active pane.
329 ZoomOut,
330 /// If any worktrees are in restricted mode, shows a modal with possible actions.
331 /// If the modal is shown already, closes it without trusting any worktree.
332 ToggleWorktreeSecurity,
333 /// Clears all trusted worktrees, placing them in restricted mode on next open.
334 /// Requires restart to take effect on already opened projects.
335 ClearTrustedWorktrees,
336 /// Stops following a collaborator.
337 Unfollow,
338 /// Restores the banner.
339 RestoreBanner,
340 /// Toggles expansion of the selected item.
341 ToggleExpandItem,
342 ]
343);
344
345/// Activates a specific pane by its index.
346#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
347#[action(namespace = workspace)]
348pub struct ActivatePane(pub usize);
349
350/// Moves an item to a specific pane by index.
351#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
352#[action(namespace = workspace)]
353#[serde(deny_unknown_fields)]
354pub struct MoveItemToPane {
355 #[serde(default = "default_1")]
356 pub destination: usize,
357 #[serde(default = "default_true")]
358 pub focus: bool,
359 #[serde(default)]
360 pub clone: bool,
361}
362
363fn default_1() -> usize {
364 1
365}
366
367/// Moves an item to a pane in the specified direction.
368#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
369#[action(namespace = workspace)]
370#[serde(deny_unknown_fields)]
371pub struct MoveItemToPaneInDirection {
372 #[serde(default = "default_right")]
373 pub direction: SplitDirection,
374 #[serde(default = "default_true")]
375 pub focus: bool,
376 #[serde(default)]
377 pub clone: bool,
378}
379
380/// Creates a new file in a split of the desired direction.
381#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
382#[action(namespace = workspace)]
383#[serde(deny_unknown_fields)]
384pub struct NewFileSplit(pub SplitDirection);
385
386fn default_right() -> SplitDirection {
387 SplitDirection::Right
388}
389
390/// Saves all open files in the workspace.
391#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
392#[action(namespace = workspace)]
393#[serde(deny_unknown_fields)]
394pub struct SaveAll {
395 #[serde(default)]
396 pub save_intent: Option<SaveIntent>,
397}
398
399/// Saves the current file with the specified options.
400#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
401#[action(namespace = workspace)]
402#[serde(deny_unknown_fields)]
403pub struct Save {
404 #[serde(default)]
405 pub save_intent: Option<SaveIntent>,
406}
407
408/// Moves Focus to the central panes in the workspace.
409#[derive(Clone, Debug, PartialEq, Eq, Action)]
410#[action(namespace = workspace)]
411pub struct FocusCenterPane;
412
413/// Closes all items and panes in the workspace.
414#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
415#[action(namespace = workspace)]
416#[serde(deny_unknown_fields)]
417pub struct CloseAllItemsAndPanes {
418 #[serde(default)]
419 pub save_intent: Option<SaveIntent>,
420}
421
422/// Closes all inactive tabs and panes in the workspace.
423#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
424#[action(namespace = workspace)]
425#[serde(deny_unknown_fields)]
426pub struct CloseInactiveTabsAndPanes {
427 #[serde(default)]
428 pub save_intent: Option<SaveIntent>,
429}
430
431/// Closes the active item across all panes.
432#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
433#[action(namespace = workspace)]
434#[serde(deny_unknown_fields)]
435pub struct CloseItemInAllPanes {
436 #[serde(default)]
437 pub save_intent: Option<SaveIntent>,
438 #[serde(default)]
439 pub close_pinned: bool,
440}
441
442/// Sends a sequence of keystrokes to the active element.
443#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
444#[action(namespace = workspace)]
445pub struct SendKeystrokes(pub String);
446
447actions!(
448 project_symbols,
449 [
450 /// Toggles the project symbols search.
451 #[action(name = "Toggle")]
452 ToggleProjectSymbols
453 ]
454);
455
456/// Toggles the file finder interface.
457#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
458#[action(namespace = file_finder, name = "Toggle")]
459#[serde(deny_unknown_fields)]
460pub struct ToggleFileFinder {
461 #[serde(default)]
462 pub separate_history: bool,
463}
464
465/// Opens a new terminal in the center.
466#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
467#[action(namespace = workspace)]
468#[serde(deny_unknown_fields)]
469pub struct NewCenterTerminal {
470 /// If true, creates a local terminal even in remote projects.
471 #[serde(default)]
472 pub local: bool,
473}
474
475/// Opens a new terminal.
476#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
477#[action(namespace = workspace)]
478#[serde(deny_unknown_fields)]
479pub struct NewTerminal {
480 /// If true, creates a local terminal even in remote projects.
481 #[serde(default)]
482 pub local: bool,
483}
484
485/// Increases size of a currently focused dock by a given amount of pixels.
486#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
487#[action(namespace = workspace)]
488#[serde(deny_unknown_fields)]
489pub struct IncreaseActiveDockSize {
490 /// For 0px parameter, uses UI font size value.
491 #[serde(default)]
492 pub px: u32,
493}
494
495/// Decreases size of a currently focused dock by a given amount of pixels.
496#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
497#[action(namespace = workspace)]
498#[serde(deny_unknown_fields)]
499pub struct DecreaseActiveDockSize {
500 /// For 0px parameter, uses UI font size value.
501 #[serde(default)]
502 pub px: u32,
503}
504
505/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
506#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
507#[action(namespace = workspace)]
508#[serde(deny_unknown_fields)]
509pub struct IncreaseOpenDocksSize {
510 /// For 0px parameter, uses UI font size value.
511 #[serde(default)]
512 pub px: u32,
513}
514
515/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
516#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
517#[action(namespace = workspace)]
518#[serde(deny_unknown_fields)]
519pub struct DecreaseOpenDocksSize {
520 /// For 0px parameter, uses UI font size value.
521 #[serde(default)]
522 pub px: u32,
523}
524
525actions!(
526 workspace,
527 [
528 /// Activates the pane to the left.
529 ActivatePaneLeft,
530 /// Activates the pane to the right.
531 ActivatePaneRight,
532 /// Activates the pane above.
533 ActivatePaneUp,
534 /// Activates the pane below.
535 ActivatePaneDown,
536 /// Swaps the current pane with the one to the left.
537 SwapPaneLeft,
538 /// Swaps the current pane with the one to the right.
539 SwapPaneRight,
540 /// Swaps the current pane with the one above.
541 SwapPaneUp,
542 /// Swaps the current pane with the one below.
543 SwapPaneDown,
544 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
545 SwapPaneAdjacent,
546 /// Move the current pane to be at the far left.
547 MovePaneLeft,
548 /// Move the current pane to be at the far right.
549 MovePaneRight,
550 /// Move the current pane to be at the very top.
551 MovePaneUp,
552 /// Move the current pane to be at the very bottom.
553 MovePaneDown,
554 ]
555);
556
557#[derive(PartialEq, Eq, Debug)]
558pub enum CloseIntent {
559 /// Quit the program entirely.
560 Quit,
561 /// Close a window.
562 CloseWindow,
563 /// Replace the workspace in an existing window.
564 ReplaceWindow,
565}
566
567#[derive(Clone)]
568pub struct Toast {
569 id: NotificationId,
570 msg: Cow<'static, str>,
571 autohide: bool,
572 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
573}
574
575impl Toast {
576 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
577 Toast {
578 id,
579 msg: msg.into(),
580 on_click: None,
581 autohide: false,
582 }
583 }
584
585 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
586 where
587 M: Into<Cow<'static, str>>,
588 F: Fn(&mut Window, &mut App) + 'static,
589 {
590 self.on_click = Some((message.into(), Arc::new(on_click)));
591 self
592 }
593
594 pub fn autohide(mut self) -> Self {
595 self.autohide = true;
596 self
597 }
598}
599
600impl PartialEq for Toast {
601 fn eq(&self, other: &Self) -> bool {
602 self.id == other.id
603 && self.msg == other.msg
604 && self.on_click.is_some() == other.on_click.is_some()
605 }
606}
607
608/// Opens a new terminal with the specified working directory.
609#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
610#[action(namespace = workspace)]
611#[serde(deny_unknown_fields)]
612pub struct OpenTerminal {
613 pub working_directory: PathBuf,
614 /// If true, creates a local terminal even in remote projects.
615 #[serde(default)]
616 pub local: bool,
617}
618
619#[derive(
620 Clone,
621 Copy,
622 Debug,
623 Default,
624 Hash,
625 PartialEq,
626 Eq,
627 PartialOrd,
628 Ord,
629 serde::Serialize,
630 serde::Deserialize,
631)]
632pub struct WorkspaceId(i64);
633
634impl WorkspaceId {
635 pub fn from_i64(value: i64) -> Self {
636 Self(value)
637 }
638}
639
640impl StaticColumnCount for WorkspaceId {}
641impl Bind for WorkspaceId {
642 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
643 self.0.bind(statement, start_index)
644 }
645}
646impl Column for WorkspaceId {
647 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
648 i64::column(statement, start_index)
649 .map(|(i, next_index)| (Self(i), next_index))
650 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
651 }
652}
653impl From<WorkspaceId> for i64 {
654 fn from(val: WorkspaceId) -> Self {
655 val.0
656 }
657}
658
659fn prompt_and_open_paths(
660 app_state: Arc<AppState>,
661 options: PathPromptOptions,
662 create_new_window: bool,
663 cx: &mut App,
664) {
665 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
666 workspace_window
667 .update(cx, |multi_workspace, window, cx| {
668 let workspace = multi_workspace.workspace().clone();
669 workspace.update(cx, |workspace, cx| {
670 prompt_for_open_path_and_open(
671 workspace,
672 app_state,
673 options,
674 create_new_window,
675 window,
676 cx,
677 );
678 });
679 })
680 .ok();
681 } else {
682 let task = Workspace::new_local(
683 Vec::new(),
684 app_state.clone(),
685 None,
686 None,
687 None,
688 OpenMode::Activate,
689 cx,
690 );
691 cx.spawn(async move |cx| {
692 let OpenResult { window, .. } = task.await?;
693 window.update(cx, |multi_workspace, window, cx| {
694 window.activate_window();
695 let workspace = multi_workspace.workspace().clone();
696 workspace.update(cx, |workspace, cx| {
697 prompt_for_open_path_and_open(
698 workspace,
699 app_state,
700 options,
701 create_new_window,
702 window,
703 cx,
704 );
705 });
706 })?;
707 anyhow::Ok(())
708 })
709 .detach_and_log_err(cx);
710 }
711}
712
713pub fn prompt_for_open_path_and_open(
714 workspace: &mut Workspace,
715 app_state: Arc<AppState>,
716 options: PathPromptOptions,
717 create_new_window: bool,
718 window: &mut Window,
719 cx: &mut Context<Workspace>,
720) {
721 let paths = workspace.prompt_for_open_path(
722 options,
723 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
724 window,
725 cx,
726 );
727 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
728 cx.spawn_in(window, async move |this, cx| {
729 let Some(paths) = paths.await.log_err().flatten() else {
730 return;
731 };
732 if !create_new_window {
733 if let Some(handle) = multi_workspace_handle {
734 if let Some(task) = handle
735 .update(cx, |multi_workspace, window, cx| {
736 multi_workspace.open_project(paths, OpenMode::Activate, window, cx)
737 })
738 .log_err()
739 {
740 task.await.log_err();
741 }
742 return;
743 }
744 }
745 if let Some(task) = this
746 .update_in(cx, |this, window, cx| {
747 this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
748 })
749 .log_err()
750 {
751 task.await.log_err();
752 }
753 })
754 .detach();
755}
756
757pub fn init(app_state: Arc<AppState>, cx: &mut App) {
758 component::init();
759 theme_preview::init(cx);
760 toast_layer::init(cx);
761 history_manager::init(app_state.fs.clone(), cx);
762
763 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
764 .on_action(|_: &Reload, cx| reload(cx))
765 .on_action(|action: &Open, cx: &mut App| {
766 let app_state = AppState::global(cx);
767 prompt_and_open_paths(
768 app_state,
769 PathPromptOptions {
770 files: true,
771 directories: true,
772 multiple: true,
773 prompt: None,
774 },
775 action.create_new_window,
776 cx,
777 );
778 })
779 .on_action(|_: &OpenFiles, cx: &mut App| {
780 let directories = cx.can_select_mixed_files_and_dirs();
781 let app_state = AppState::global(cx);
782 prompt_and_open_paths(
783 app_state,
784 PathPromptOptions {
785 files: true,
786 directories,
787 multiple: true,
788 prompt: None,
789 },
790 true,
791 cx,
792 );
793 });
794}
795
796type BuildProjectItemFn =
797 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
798
799type BuildProjectItemForPathFn =
800 fn(
801 &Entity<Project>,
802 &ProjectPath,
803 &mut Window,
804 &mut App,
805 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
806
807#[derive(Clone, Default)]
808struct ProjectItemRegistry {
809 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
810 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
811}
812
813impl ProjectItemRegistry {
814 fn register<T: ProjectItem>(&mut self) {
815 self.build_project_item_fns_by_type.insert(
816 TypeId::of::<T::Item>(),
817 |item, project, pane, window, cx| {
818 let item = item.downcast().unwrap();
819 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
820 as Box<dyn ItemHandle>
821 },
822 );
823 self.build_project_item_for_path_fns
824 .push(|project, project_path, window, cx| {
825 let project_path = project_path.clone();
826 let is_file = project
827 .read(cx)
828 .entry_for_path(&project_path, cx)
829 .is_some_and(|entry| entry.is_file());
830 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
831 let is_local = project.read(cx).is_local();
832 let project_item =
833 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
834 let project = project.clone();
835 Some(window.spawn(cx, async move |cx| {
836 match project_item.await.with_context(|| {
837 format!(
838 "opening project path {:?}",
839 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
840 )
841 }) {
842 Ok(project_item) => {
843 let project_item = project_item;
844 let project_entry_id: Option<ProjectEntryId> =
845 project_item.read_with(cx, project::ProjectItem::entry_id);
846 let build_workspace_item = Box::new(
847 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
848 Box::new(cx.new(|cx| {
849 T::for_project_item(
850 project,
851 Some(pane),
852 project_item,
853 window,
854 cx,
855 )
856 })) as Box<dyn ItemHandle>
857 },
858 ) as Box<_>;
859 Ok((project_entry_id, build_workspace_item))
860 }
861 Err(e) => {
862 log::warn!("Failed to open a project item: {e:#}");
863 if e.error_code() == ErrorCode::Internal {
864 if let Some(abs_path) =
865 entry_abs_path.as_deref().filter(|_| is_file)
866 {
867 if let Some(broken_project_item_view) =
868 cx.update(|window, cx| {
869 T::for_broken_project_item(
870 abs_path, is_local, &e, window, cx,
871 )
872 })?
873 {
874 let build_workspace_item = Box::new(
875 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
876 cx.new(|_| broken_project_item_view).boxed_clone()
877 },
878 )
879 as Box<_>;
880 return Ok((None, build_workspace_item));
881 }
882 }
883 }
884 Err(e)
885 }
886 }
887 }))
888 });
889 }
890
891 fn open_path(
892 &self,
893 project: &Entity<Project>,
894 path: &ProjectPath,
895 window: &mut Window,
896 cx: &mut App,
897 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
898 let Some(open_project_item) = self
899 .build_project_item_for_path_fns
900 .iter()
901 .rev()
902 .find_map(|open_project_item| open_project_item(project, path, window, cx))
903 else {
904 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
905 };
906 open_project_item
907 }
908
909 fn build_item<T: project::ProjectItem>(
910 &self,
911 item: Entity<T>,
912 project: Entity<Project>,
913 pane: Option<&Pane>,
914 window: &mut Window,
915 cx: &mut App,
916 ) -> Option<Box<dyn ItemHandle>> {
917 let build = self
918 .build_project_item_fns_by_type
919 .get(&TypeId::of::<T>())?;
920 Some(build(item.into_any(), project, pane, window, cx))
921 }
922}
923
924type WorkspaceItemBuilder =
925 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
926
927impl Global for ProjectItemRegistry {}
928
929/// Registers a [ProjectItem] for the app. When opening a file, all the registered
930/// items will get a chance to open the file, starting from the project item that
931/// was added last.
932pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
933 cx.default_global::<ProjectItemRegistry>().register::<I>();
934}
935
936#[derive(Default)]
937pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
938
939struct FollowableViewDescriptor {
940 from_state_proto: fn(
941 Entity<Workspace>,
942 ViewId,
943 &mut Option<proto::view::Variant>,
944 &mut Window,
945 &mut App,
946 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
947 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
948}
949
950impl Global for FollowableViewRegistry {}
951
952impl FollowableViewRegistry {
953 pub fn register<I: FollowableItem>(cx: &mut App) {
954 cx.default_global::<Self>().0.insert(
955 TypeId::of::<I>(),
956 FollowableViewDescriptor {
957 from_state_proto: |workspace, id, state, window, cx| {
958 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
959 cx.foreground_executor()
960 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
961 })
962 },
963 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
964 },
965 );
966 }
967
968 pub fn from_state_proto(
969 workspace: Entity<Workspace>,
970 view_id: ViewId,
971 mut state: Option<proto::view::Variant>,
972 window: &mut Window,
973 cx: &mut App,
974 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
975 cx.update_default_global(|this: &mut Self, cx| {
976 this.0.values().find_map(|descriptor| {
977 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
978 })
979 })
980 }
981
982 pub fn to_followable_view(
983 view: impl Into<AnyView>,
984 cx: &App,
985 ) -> Option<Box<dyn FollowableItemHandle>> {
986 let this = cx.try_global::<Self>()?;
987 let view = view.into();
988 let descriptor = this.0.get(&view.entity_type())?;
989 Some((descriptor.to_followable_view)(&view))
990 }
991}
992
993#[derive(Copy, Clone)]
994struct SerializableItemDescriptor {
995 deserialize: fn(
996 Entity<Project>,
997 WeakEntity<Workspace>,
998 WorkspaceId,
999 ItemId,
1000 &mut Window,
1001 &mut Context<Pane>,
1002 ) -> Task<Result<Box<dyn ItemHandle>>>,
1003 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
1004 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
1005}
1006
1007#[derive(Default)]
1008struct SerializableItemRegistry {
1009 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
1010 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
1011}
1012
1013impl Global for SerializableItemRegistry {}
1014
1015impl SerializableItemRegistry {
1016 fn deserialize(
1017 item_kind: &str,
1018 project: Entity<Project>,
1019 workspace: WeakEntity<Workspace>,
1020 workspace_id: WorkspaceId,
1021 item_item: ItemId,
1022 window: &mut Window,
1023 cx: &mut Context<Pane>,
1024 ) -> Task<Result<Box<dyn ItemHandle>>> {
1025 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1026 return Task::ready(Err(anyhow!(
1027 "cannot deserialize {}, descriptor not found",
1028 item_kind
1029 )));
1030 };
1031
1032 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1033 }
1034
1035 fn cleanup(
1036 item_kind: &str,
1037 workspace_id: WorkspaceId,
1038 loaded_items: Vec<ItemId>,
1039 window: &mut Window,
1040 cx: &mut App,
1041 ) -> Task<Result<()>> {
1042 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1043 return Task::ready(Err(anyhow!(
1044 "cannot cleanup {}, descriptor not found",
1045 item_kind
1046 )));
1047 };
1048
1049 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1050 }
1051
1052 fn view_to_serializable_item_handle(
1053 view: AnyView,
1054 cx: &App,
1055 ) -> Option<Box<dyn SerializableItemHandle>> {
1056 let this = cx.try_global::<Self>()?;
1057 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1058 Some((descriptor.view_to_serializable_item)(view))
1059 }
1060
1061 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1062 let this = cx.try_global::<Self>()?;
1063 this.descriptors_by_kind.get(item_kind).copied()
1064 }
1065}
1066
1067pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1068 let serialized_item_kind = I::serialized_item_kind();
1069
1070 let registry = cx.default_global::<SerializableItemRegistry>();
1071 let descriptor = SerializableItemDescriptor {
1072 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1073 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1074 cx.foreground_executor()
1075 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1076 },
1077 cleanup: |workspace_id, loaded_items, window, cx| {
1078 I::cleanup(workspace_id, loaded_items, window, cx)
1079 },
1080 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1081 };
1082 registry
1083 .descriptors_by_kind
1084 .insert(Arc::from(serialized_item_kind), descriptor);
1085 registry
1086 .descriptors_by_type
1087 .insert(TypeId::of::<I>(), descriptor);
1088}
1089
1090pub struct AppState {
1091 pub languages: Arc<LanguageRegistry>,
1092 pub client: Arc<Client>,
1093 pub user_store: Entity<UserStore>,
1094 pub workspace_store: Entity<WorkspaceStore>,
1095 pub fs: Arc<dyn fs::Fs>,
1096 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1097 pub node_runtime: NodeRuntime,
1098 pub session: Entity<AppSession>,
1099}
1100
1101struct GlobalAppState(Arc<AppState>);
1102
1103impl Global for GlobalAppState {}
1104
1105pub struct WorkspaceStore {
1106 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1107 client: Arc<Client>,
1108 _subscriptions: Vec<client::Subscription>,
1109}
1110
1111#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1112pub enum CollaboratorId {
1113 PeerId(PeerId),
1114 Agent,
1115}
1116
1117impl From<PeerId> for CollaboratorId {
1118 fn from(peer_id: PeerId) -> Self {
1119 CollaboratorId::PeerId(peer_id)
1120 }
1121}
1122
1123impl From<&PeerId> for CollaboratorId {
1124 fn from(peer_id: &PeerId) -> Self {
1125 CollaboratorId::PeerId(*peer_id)
1126 }
1127}
1128
1129#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1130struct Follower {
1131 project_id: Option<u64>,
1132 peer_id: PeerId,
1133}
1134
1135impl AppState {
1136 #[track_caller]
1137 pub fn global(cx: &App) -> Arc<Self> {
1138 cx.global::<GlobalAppState>().0.clone()
1139 }
1140 pub fn try_global(cx: &App) -> Option<Arc<Self>> {
1141 cx.try_global::<GlobalAppState>()
1142 .map(|state| state.0.clone())
1143 }
1144 pub fn set_global(state: Arc<AppState>, cx: &mut App) {
1145 cx.set_global(GlobalAppState(state));
1146 }
1147
1148 #[cfg(any(test, feature = "test-support"))]
1149 pub fn test(cx: &mut App) -> Arc<Self> {
1150 use fs::Fs;
1151 use node_runtime::NodeRuntime;
1152 use session::Session;
1153 use settings::SettingsStore;
1154
1155 if !cx.has_global::<SettingsStore>() {
1156 let settings_store = SettingsStore::test(cx);
1157 cx.set_global(settings_store);
1158 }
1159
1160 let fs = fs::FakeFs::new(cx.background_executor().clone());
1161 <dyn Fs>::set_global(fs.clone(), cx);
1162 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1163 let clock = Arc::new(clock::FakeSystemClock::new());
1164 let http_client = http_client::FakeHttpClient::with_404_response();
1165 let client = Client::new(clock, http_client, cx);
1166 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1167 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1168 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1169
1170 theme_settings::init(theme::LoadThemes::JustBase, cx);
1171 client::init(&client, cx);
1172
1173 Arc::new(Self {
1174 client,
1175 fs,
1176 languages,
1177 user_store,
1178 workspace_store,
1179 node_runtime: NodeRuntime::unavailable(),
1180 build_window_options: |_, _| Default::default(),
1181 session,
1182 })
1183 }
1184}
1185
1186struct DelayedDebouncedEditAction {
1187 task: Option<Task<()>>,
1188 cancel_channel: Option<oneshot::Sender<()>>,
1189}
1190
1191impl DelayedDebouncedEditAction {
1192 fn new() -> DelayedDebouncedEditAction {
1193 DelayedDebouncedEditAction {
1194 task: None,
1195 cancel_channel: None,
1196 }
1197 }
1198
1199 fn fire_new<F>(
1200 &mut self,
1201 delay: Duration,
1202 window: &mut Window,
1203 cx: &mut Context<Workspace>,
1204 func: F,
1205 ) where
1206 F: 'static
1207 + Send
1208 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1209 {
1210 if let Some(channel) = self.cancel_channel.take() {
1211 _ = channel.send(());
1212 }
1213
1214 let (sender, mut receiver) = oneshot::channel::<()>();
1215 self.cancel_channel = Some(sender);
1216
1217 let previous_task = self.task.take();
1218 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1219 let mut timer = cx.background_executor().timer(delay).fuse();
1220 if let Some(previous_task) = previous_task {
1221 previous_task.await;
1222 }
1223
1224 futures::select_biased! {
1225 _ = receiver => return,
1226 _ = timer => {}
1227 }
1228
1229 if let Some(result) = workspace
1230 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1231 .log_err()
1232 {
1233 result.await.log_err();
1234 }
1235 }));
1236 }
1237}
1238
1239pub enum Event {
1240 PaneAdded(Entity<Pane>),
1241 PaneRemoved,
1242 ItemAdded {
1243 item: Box<dyn ItemHandle>,
1244 },
1245 ActiveItemChanged,
1246 ItemRemoved {
1247 item_id: EntityId,
1248 },
1249 UserSavedItem {
1250 pane: WeakEntity<Pane>,
1251 item: Box<dyn WeakItemHandle>,
1252 save_intent: SaveIntent,
1253 },
1254 ContactRequestedJoin(u64),
1255 WorkspaceCreated(WeakEntity<Workspace>),
1256 OpenBundledFile {
1257 text: Cow<'static, str>,
1258 title: &'static str,
1259 language: &'static str,
1260 },
1261 ZoomChanged,
1262 ModalOpened,
1263 Activate,
1264 PanelAdded(AnyView),
1265}
1266
1267#[derive(Debug, Clone)]
1268pub enum OpenVisible {
1269 All,
1270 None,
1271 OnlyFiles,
1272 OnlyDirectories,
1273}
1274
1275enum WorkspaceLocation {
1276 // Valid local paths or SSH project to serialize
1277 Location(SerializedWorkspaceLocation, PathList),
1278 // No valid location found hence clear session id
1279 DetachFromSession,
1280 // No valid location found to serialize
1281 None,
1282}
1283
1284type PromptForNewPath = Box<
1285 dyn Fn(
1286 &mut Workspace,
1287 DirectoryLister,
1288 Option<String>,
1289 &mut Window,
1290 &mut Context<Workspace>,
1291 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1292>;
1293
1294type PromptForOpenPath = Box<
1295 dyn Fn(
1296 &mut Workspace,
1297 DirectoryLister,
1298 &mut Window,
1299 &mut Context<Workspace>,
1300 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1301>;
1302
1303#[derive(Default)]
1304struct DispatchingKeystrokes {
1305 dispatched: HashSet<Vec<Keystroke>>,
1306 queue: VecDeque<Keystroke>,
1307 task: Option<Shared<Task<()>>>,
1308}
1309
1310/// Collects everything project-related for a certain window opened.
1311/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1312///
1313/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1314/// The `Workspace` owns everybody's state and serves as a default, "global context",
1315/// that can be used to register a global action to be triggered from any place in the window.
1316pub struct Workspace {
1317 weak_self: WeakEntity<Self>,
1318 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1319 zoomed: Option<AnyWeakView>,
1320 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1321 zoomed_position: Option<DockPosition>,
1322 center: PaneGroup,
1323 left_dock: Entity<Dock>,
1324 bottom_dock: Entity<Dock>,
1325 right_dock: Entity<Dock>,
1326 panes: Vec<Entity<Pane>>,
1327 active_worktree_override: Option<WorktreeId>,
1328 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1329 active_pane: Entity<Pane>,
1330 last_active_center_pane: Option<WeakEntity<Pane>>,
1331 last_active_view_id: Option<proto::ViewId>,
1332 status_bar: Entity<StatusBar>,
1333 pub(crate) modal_layer: Entity<ModalLayer>,
1334 toast_layer: Entity<ToastLayer>,
1335 titlebar_item: Option<AnyView>,
1336 notifications: Notifications,
1337 suppressed_notifications: HashSet<NotificationId>,
1338 project: Entity<Project>,
1339 follower_states: HashMap<CollaboratorId, FollowerState>,
1340 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1341 window_edited: bool,
1342 last_window_title: Option<String>,
1343 dirty_items: HashMap<EntityId, Subscription>,
1344 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1345 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1346 database_id: Option<WorkspaceId>,
1347 app_state: Arc<AppState>,
1348 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1349 _subscriptions: Vec<Subscription>,
1350 _apply_leader_updates: Task<Result<()>>,
1351 _observe_current_user: Task<Result<()>>,
1352 _schedule_serialize_workspace: Option<Task<()>>,
1353 _serialize_workspace_task: Option<Task<()>>,
1354 _schedule_serialize_ssh_paths: Option<Task<()>>,
1355 pane_history_timestamp: Arc<AtomicUsize>,
1356 bounds: Bounds<Pixels>,
1357 pub centered_layout: bool,
1358 bounds_save_task_queued: Option<Task<()>>,
1359 on_prompt_for_new_path: Option<PromptForNewPath>,
1360 on_prompt_for_open_path: Option<PromptForOpenPath>,
1361 terminal_provider: Option<Box<dyn TerminalProvider>>,
1362 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1363 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1364 _items_serializer: Task<Result<()>>,
1365 session_id: Option<String>,
1366 scheduled_tasks: Vec<Task<()>>,
1367 last_open_dock_positions: Vec<DockPosition>,
1368 removing: bool,
1369 open_in_dev_container: bool,
1370 _dev_container_task: Option<Task<Result<()>>>,
1371 _panels_task: Option<Task<Result<()>>>,
1372 sidebar_focus_handle: Option<FocusHandle>,
1373 multi_workspace: Option<WeakEntity<MultiWorkspace>>,
1374}
1375
1376impl EventEmitter<Event> for Workspace {}
1377
1378#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1379pub struct ViewId {
1380 pub creator: CollaboratorId,
1381 pub id: u64,
1382}
1383
1384pub struct FollowerState {
1385 center_pane: Entity<Pane>,
1386 dock_pane: Option<Entity<Pane>>,
1387 active_view_id: Option<ViewId>,
1388 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1389}
1390
1391struct FollowerView {
1392 view: Box<dyn FollowableItemHandle>,
1393 location: Option<proto::PanelId>,
1394}
1395
1396#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1397pub enum OpenMode {
1398 /// Open the workspace in a new window.
1399 NewWindow,
1400 /// Add to the window's multi workspace without activating it (used during deserialization).
1401 Add,
1402 /// Add to the window's multi workspace and activate it.
1403 #[default]
1404 Activate,
1405}
1406
1407impl Workspace {
1408 pub fn new(
1409 workspace_id: Option<WorkspaceId>,
1410 project: Entity<Project>,
1411 app_state: Arc<AppState>,
1412 window: &mut Window,
1413 cx: &mut Context<Self>,
1414 ) -> Self {
1415 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1416 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1417 if let TrustedWorktreesEvent::Trusted(..) = e {
1418 // Do not persist auto trusted worktrees
1419 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1420 worktrees_store.update(cx, |worktrees_store, cx| {
1421 worktrees_store.schedule_serialization(
1422 cx,
1423 |new_trusted_worktrees, cx| {
1424 let timeout =
1425 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1426 let db = WorkspaceDb::global(cx);
1427 cx.background_spawn(async move {
1428 timeout.await;
1429 db.save_trusted_worktrees(new_trusted_worktrees)
1430 .await
1431 .log_err();
1432 })
1433 },
1434 )
1435 });
1436 }
1437 }
1438 })
1439 .detach();
1440
1441 cx.observe_global::<SettingsStore>(|_, cx| {
1442 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1443 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1444 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1445 trusted_worktrees.auto_trust_all(cx);
1446 })
1447 }
1448 }
1449 })
1450 .detach();
1451 }
1452
1453 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1454 match event {
1455 project::Event::RemoteIdChanged(_) => {
1456 this.update_window_title(window, cx);
1457 }
1458
1459 project::Event::CollaboratorLeft(peer_id) => {
1460 this.collaborator_left(*peer_id, window, cx);
1461 }
1462
1463 &project::Event::WorktreeRemoved(_) => {
1464 this.update_window_title(window, cx);
1465 this.serialize_workspace(window, cx);
1466 this.update_history(cx);
1467 }
1468
1469 &project::Event::WorktreeAdded(id) => {
1470 this.update_window_title(window, cx);
1471 if this
1472 .project()
1473 .read(cx)
1474 .worktree_for_id(id, cx)
1475 .is_some_and(|wt| wt.read(cx).is_visible())
1476 {
1477 this.serialize_workspace(window, cx);
1478 this.update_history(cx);
1479 }
1480 }
1481 project::Event::WorktreeUpdatedEntries(..) => {
1482 this.update_window_title(window, cx);
1483 this.serialize_workspace(window, cx);
1484 }
1485
1486 project::Event::DisconnectedFromHost => {
1487 this.update_window_edited(window, cx);
1488 let leaders_to_unfollow =
1489 this.follower_states.keys().copied().collect::<Vec<_>>();
1490 for leader_id in leaders_to_unfollow {
1491 this.unfollow(leader_id, window, cx);
1492 }
1493 }
1494
1495 project::Event::DisconnectedFromRemote {
1496 server_not_running: _,
1497 } => {
1498 this.update_window_edited(window, cx);
1499 }
1500
1501 project::Event::Closed => {
1502 window.remove_window();
1503 }
1504
1505 project::Event::DeletedEntry(_, entry_id) => {
1506 for pane in this.panes.iter() {
1507 pane.update(cx, |pane, cx| {
1508 pane.handle_deleted_project_item(*entry_id, window, cx)
1509 });
1510 }
1511 }
1512
1513 project::Event::Toast {
1514 notification_id,
1515 message,
1516 link,
1517 } => this.show_notification(
1518 NotificationId::named(notification_id.clone()),
1519 cx,
1520 |cx| {
1521 let mut notification = MessageNotification::new(message.clone(), cx);
1522 if let Some(link) = link {
1523 notification = notification
1524 .more_info_message(link.label)
1525 .more_info_url(link.url);
1526 }
1527
1528 cx.new(|_| notification)
1529 },
1530 ),
1531
1532 project::Event::HideToast { notification_id } => {
1533 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1534 }
1535
1536 project::Event::LanguageServerPrompt(request) => {
1537 struct LanguageServerPrompt;
1538
1539 this.show_notification(
1540 NotificationId::composite::<LanguageServerPrompt>(request.id),
1541 cx,
1542 |cx| {
1543 cx.new(|cx| {
1544 notifications::LanguageServerPrompt::new(request.clone(), cx)
1545 })
1546 },
1547 );
1548 }
1549
1550 project::Event::AgentLocationChanged => {
1551 this.handle_agent_location_changed(window, cx)
1552 }
1553
1554 _ => {}
1555 }
1556 cx.notify()
1557 })
1558 .detach();
1559
1560 cx.subscribe_in(
1561 &project.read(cx).breakpoint_store(),
1562 window,
1563 |workspace, _, event, window, cx| match event {
1564 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1565 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1566 workspace.serialize_workspace(window, cx);
1567 }
1568 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1569 },
1570 )
1571 .detach();
1572 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1573 cx.subscribe_in(
1574 &toolchain_store,
1575 window,
1576 |workspace, _, event, window, cx| match event {
1577 ToolchainStoreEvent::CustomToolchainsModified => {
1578 workspace.serialize_workspace(window, cx);
1579 }
1580 _ => {}
1581 },
1582 )
1583 .detach();
1584 }
1585
1586 cx.on_focus_lost(window, |this, window, cx| {
1587 let focus_handle = this.focus_handle(cx);
1588 window.focus(&focus_handle, cx);
1589 })
1590 .detach();
1591
1592 let weak_handle = cx.entity().downgrade();
1593 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1594
1595 let center_pane = cx.new(|cx| {
1596 let mut center_pane = Pane::new(
1597 weak_handle.clone(),
1598 project.clone(),
1599 pane_history_timestamp.clone(),
1600 None,
1601 NewFile.boxed_clone(),
1602 true,
1603 window,
1604 cx,
1605 );
1606 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1607 center_pane.set_should_display_welcome_page(true);
1608 center_pane
1609 });
1610 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1611 .detach();
1612
1613 window.focus(¢er_pane.focus_handle(cx), cx);
1614
1615 cx.emit(Event::PaneAdded(center_pane.clone()));
1616
1617 let any_window_handle = window.window_handle();
1618 app_state.workspace_store.update(cx, |store, _| {
1619 store
1620 .workspaces
1621 .insert((any_window_handle, weak_handle.clone()));
1622 });
1623
1624 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1625 let mut connection_status = app_state.client.status();
1626 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1627 current_user.next().await;
1628 connection_status.next().await;
1629 let mut stream =
1630 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1631
1632 while stream.recv().await.is_some() {
1633 this.update(cx, |_, cx| cx.notify())?;
1634 }
1635 anyhow::Ok(())
1636 });
1637
1638 // All leader updates are enqueued and then processed in a single task, so
1639 // that each asynchronous operation can be run in order.
1640 let (leader_updates_tx, mut leader_updates_rx) =
1641 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1642 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1643 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1644 Self::process_leader_update(&this, leader_id, update, cx)
1645 .await
1646 .log_err();
1647 }
1648
1649 Ok(())
1650 });
1651
1652 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1653 let modal_layer = cx.new(|_| ModalLayer::new());
1654 let toast_layer = cx.new(|_| ToastLayer::new());
1655 cx.subscribe(
1656 &modal_layer,
1657 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1658 cx.emit(Event::ModalOpened);
1659 },
1660 )
1661 .detach();
1662
1663 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1664 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1665 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1666 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1667 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1668 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1669 let multi_workspace = window
1670 .root::<MultiWorkspace>()
1671 .flatten()
1672 .map(|mw| mw.downgrade());
1673 let status_bar = cx.new(|cx| {
1674 let mut status_bar =
1675 StatusBar::new(¢er_pane.clone(), multi_workspace.clone(), window, cx);
1676 status_bar.add_left_item(left_dock_buttons, window, cx);
1677 status_bar.add_right_item(right_dock_buttons, window, cx);
1678 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1679 status_bar
1680 });
1681
1682 let session_id = app_state.session.read(cx).id().to_owned();
1683
1684 let mut active_call = None;
1685 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1686 let subscriptions =
1687 vec![
1688 call.0
1689 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1690 ];
1691 active_call = Some((call, subscriptions));
1692 }
1693
1694 let (serializable_items_tx, serializable_items_rx) =
1695 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1696 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1697 Self::serialize_items(&this, serializable_items_rx, cx).await
1698 });
1699
1700 let subscriptions = vec![
1701 cx.observe_window_activation(window, Self::on_window_activation_changed),
1702 cx.observe_window_bounds(window, move |this, window, cx| {
1703 if this.bounds_save_task_queued.is_some() {
1704 return;
1705 }
1706 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1707 cx.background_executor()
1708 .timer(Duration::from_millis(100))
1709 .await;
1710 this.update_in(cx, |this, window, cx| {
1711 this.save_window_bounds(window, cx).detach();
1712 this.bounds_save_task_queued.take();
1713 })
1714 .ok();
1715 }));
1716 cx.notify();
1717 }),
1718 cx.observe_window_appearance(window, |_, window, cx| {
1719 let window_appearance = window.appearance();
1720
1721 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1722
1723 theme_settings::reload_theme(cx);
1724 theme_settings::reload_icon_theme(cx);
1725 }),
1726 cx.on_release({
1727 let weak_handle = weak_handle.clone();
1728 move |this, cx| {
1729 this.app_state.workspace_store.update(cx, move |store, _| {
1730 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1731 })
1732 }
1733 }),
1734 ];
1735
1736 cx.defer_in(window, move |this, window, cx| {
1737 this.update_window_title(window, cx);
1738 this.show_initial_notifications(cx);
1739 });
1740
1741 let mut center = PaneGroup::new(center_pane.clone());
1742 center.set_is_center(true);
1743 center.mark_positions(cx);
1744
1745 Workspace {
1746 weak_self: weak_handle.clone(),
1747 zoomed: None,
1748 zoomed_position: None,
1749 previous_dock_drag_coordinates: None,
1750 center,
1751 panes: vec![center_pane.clone()],
1752 panes_by_item: Default::default(),
1753 active_pane: center_pane.clone(),
1754 last_active_center_pane: Some(center_pane.downgrade()),
1755 last_active_view_id: None,
1756 status_bar,
1757 modal_layer,
1758 toast_layer,
1759 titlebar_item: None,
1760 active_worktree_override: None,
1761 notifications: Notifications::default(),
1762 suppressed_notifications: HashSet::default(),
1763 left_dock,
1764 bottom_dock,
1765 right_dock,
1766 _panels_task: None,
1767 project: project.clone(),
1768 follower_states: Default::default(),
1769 last_leaders_by_pane: Default::default(),
1770 dispatching_keystrokes: Default::default(),
1771 window_edited: false,
1772 last_window_title: None,
1773 dirty_items: Default::default(),
1774 active_call,
1775 database_id: workspace_id,
1776 app_state,
1777 _observe_current_user,
1778 _apply_leader_updates,
1779 _schedule_serialize_workspace: None,
1780 _serialize_workspace_task: None,
1781 _schedule_serialize_ssh_paths: None,
1782 leader_updates_tx,
1783 _subscriptions: subscriptions,
1784 pane_history_timestamp,
1785 workspace_actions: Default::default(),
1786 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1787 bounds: Default::default(),
1788 centered_layout: false,
1789 bounds_save_task_queued: None,
1790 on_prompt_for_new_path: None,
1791 on_prompt_for_open_path: None,
1792 terminal_provider: None,
1793 debugger_provider: None,
1794 serializable_items_tx,
1795 _items_serializer,
1796 session_id: Some(session_id),
1797
1798 scheduled_tasks: Vec::new(),
1799 last_open_dock_positions: Vec::new(),
1800 removing: false,
1801 sidebar_focus_handle: None,
1802 multi_workspace,
1803 open_in_dev_container: false,
1804 _dev_container_task: None,
1805 }
1806 }
1807
1808 pub fn new_local(
1809 abs_paths: Vec<PathBuf>,
1810 app_state: Arc<AppState>,
1811 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1812 env: Option<HashMap<String, String>>,
1813 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1814 open_mode: OpenMode,
1815 cx: &mut App,
1816 ) -> Task<anyhow::Result<OpenResult>> {
1817 let project_handle = Project::local(
1818 app_state.client.clone(),
1819 app_state.node_runtime.clone(),
1820 app_state.user_store.clone(),
1821 app_state.languages.clone(),
1822 app_state.fs.clone(),
1823 env,
1824 Default::default(),
1825 cx,
1826 );
1827
1828 let db = WorkspaceDb::global(cx);
1829 let kvp = db::kvp::KeyValueStore::global(cx);
1830 cx.spawn(async move |cx| {
1831 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1832 for path in abs_paths.into_iter() {
1833 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1834 paths_to_open.push(canonical)
1835 } else {
1836 paths_to_open.push(path)
1837 }
1838 }
1839
1840 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1841
1842 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1843 paths_to_open = paths.ordered_paths().cloned().collect();
1844 if !paths.is_lexicographically_ordered() {
1845 project_handle.update(cx, |project, cx| {
1846 project.set_worktrees_reordered(true, cx);
1847 });
1848 }
1849 }
1850
1851 // Get project paths for all of the abs_paths
1852 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1853 Vec::with_capacity(paths_to_open.len());
1854
1855 for path in paths_to_open.into_iter() {
1856 if let Some((_, project_entry)) = cx
1857 .update(|cx| {
1858 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1859 })
1860 .await
1861 .log_err()
1862 {
1863 project_paths.push((path, Some(project_entry)));
1864 } else {
1865 project_paths.push((path, None));
1866 }
1867 }
1868
1869 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1870 serialized_workspace.id
1871 } else {
1872 db.next_id().await.unwrap_or_else(|_| Default::default())
1873 };
1874
1875 let toolchains = db.toolchains(workspace_id).await?;
1876
1877 for (toolchain, worktree_path, path) in toolchains {
1878 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1879 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1880 this.find_worktree(&worktree_path, cx)
1881 .and_then(|(worktree, rel_path)| {
1882 if rel_path.is_empty() {
1883 Some(worktree.read(cx).id())
1884 } else {
1885 None
1886 }
1887 })
1888 }) else {
1889 // We did not find a worktree with a given path, but that's whatever.
1890 continue;
1891 };
1892 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1893 continue;
1894 }
1895
1896 project_handle
1897 .update(cx, |this, cx| {
1898 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1899 })
1900 .await;
1901 }
1902 if let Some(workspace) = serialized_workspace.as_ref() {
1903 project_handle.update(cx, |this, cx| {
1904 for (scope, toolchains) in &workspace.user_toolchains {
1905 for toolchain in toolchains {
1906 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1907 }
1908 }
1909 });
1910 }
1911
1912 let window_to_replace = match open_mode {
1913 OpenMode::NewWindow => None,
1914 _ => requesting_window,
1915 };
1916
1917 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1918 if let Some(window) = window_to_replace {
1919 let centered_layout = serialized_workspace
1920 .as_ref()
1921 .map(|w| w.centered_layout)
1922 .unwrap_or(false);
1923
1924 let workspace = window.update(cx, |multi_workspace, window, cx| {
1925 let workspace = cx.new(|cx| {
1926 let mut workspace = Workspace::new(
1927 Some(workspace_id),
1928 project_handle.clone(),
1929 app_state.clone(),
1930 window,
1931 cx,
1932 );
1933
1934 workspace.centered_layout = centered_layout;
1935
1936 // Call init callback to add items before window renders
1937 if let Some(init) = init {
1938 init(&mut workspace, window, cx);
1939 }
1940
1941 workspace
1942 });
1943 match open_mode {
1944 OpenMode::Activate => {
1945 multi_workspace.activate(workspace.clone(), window, cx);
1946 }
1947 OpenMode::Add => {
1948 multi_workspace.add(workspace.clone(), &*window, cx);
1949 }
1950 OpenMode::NewWindow => {
1951 unreachable!()
1952 }
1953 }
1954 workspace
1955 })?;
1956 (window, workspace)
1957 } else {
1958 let window_bounds_override = window_bounds_env_override();
1959
1960 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1961 (Some(WindowBounds::Windowed(bounds)), None)
1962 } else if let Some(workspace) = serialized_workspace.as_ref()
1963 && let Some(display) = workspace.display
1964 && let Some(bounds) = workspace.window_bounds.as_ref()
1965 {
1966 // Reopening an existing workspace - restore its saved bounds
1967 (Some(bounds.0), Some(display))
1968 } else if let Some((display, bounds)) =
1969 persistence::read_default_window_bounds(&kvp)
1970 {
1971 // New or empty workspace - use the last known window bounds
1972 (Some(bounds), Some(display))
1973 } else {
1974 // New window - let GPUI's default_bounds() handle cascading
1975 (None, None)
1976 };
1977
1978 // Use the serialized workspace to construct the new window
1979 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1980 options.window_bounds = window_bounds;
1981 let centered_layout = serialized_workspace
1982 .as_ref()
1983 .map(|w| w.centered_layout)
1984 .unwrap_or(false);
1985 let window = cx.open_window(options, {
1986 let app_state = app_state.clone();
1987 let project_handle = project_handle.clone();
1988 move |window, cx| {
1989 let workspace = cx.new(|cx| {
1990 let mut workspace = Workspace::new(
1991 Some(workspace_id),
1992 project_handle,
1993 app_state,
1994 window,
1995 cx,
1996 );
1997 workspace.centered_layout = centered_layout;
1998
1999 // Call init callback to add items before window renders
2000 if let Some(init) = init {
2001 init(&mut workspace, window, cx);
2002 }
2003
2004 workspace
2005 });
2006 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
2007 }
2008 })?;
2009 let workspace =
2010 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
2011 multi_workspace.workspace().clone()
2012 })?;
2013 (window, workspace)
2014 };
2015
2016 notify_if_database_failed(window, cx);
2017 // Check if this is an empty workspace (no paths to open)
2018 // An empty workspace is one where project_paths is empty
2019 let is_empty_workspace = project_paths.is_empty();
2020 // Check if serialized workspace has paths before it's moved
2021 let serialized_workspace_has_paths = serialized_workspace
2022 .as_ref()
2023 .map(|ws| !ws.paths.is_empty())
2024 .unwrap_or(false);
2025
2026 let opened_items = window
2027 .update(cx, |_, window, cx| {
2028 workspace.update(cx, |_workspace: &mut Workspace, cx| {
2029 open_items(serialized_workspace, project_paths, window, cx)
2030 })
2031 })?
2032 .await
2033 .unwrap_or_default();
2034
2035 // Restore default dock state for empty workspaces
2036 // Only restore if:
2037 // 1. This is an empty workspace (no paths), AND
2038 // 2. The serialized workspace either doesn't exist or has no paths
2039 if is_empty_workspace && !serialized_workspace_has_paths {
2040 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
2041 window
2042 .update(cx, |_, window, cx| {
2043 workspace.update(cx, |workspace, cx| {
2044 for (dock, serialized_dock) in [
2045 (&workspace.right_dock, &default_docks.right),
2046 (&workspace.left_dock, &default_docks.left),
2047 (&workspace.bottom_dock, &default_docks.bottom),
2048 ] {
2049 dock.update(cx, |dock, cx| {
2050 dock.serialized_dock = Some(serialized_dock.clone());
2051 dock.restore_state(window, cx);
2052 });
2053 }
2054 cx.notify();
2055 });
2056 })
2057 .log_err();
2058 }
2059 }
2060
2061 window
2062 .update(cx, |_, _window, cx| {
2063 workspace.update(cx, |this: &mut Workspace, cx| {
2064 this.update_history(cx);
2065 });
2066 })
2067 .log_err();
2068 Ok(OpenResult {
2069 window,
2070 workspace,
2071 opened_items,
2072 })
2073 })
2074 }
2075
2076 pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
2077 self.project.read(cx).project_group_key(cx)
2078 }
2079
2080 pub fn weak_handle(&self) -> WeakEntity<Self> {
2081 self.weak_self.clone()
2082 }
2083
2084 pub fn left_dock(&self) -> &Entity<Dock> {
2085 &self.left_dock
2086 }
2087
2088 pub fn bottom_dock(&self) -> &Entity<Dock> {
2089 &self.bottom_dock
2090 }
2091
2092 pub fn set_bottom_dock_layout(
2093 &mut self,
2094 layout: BottomDockLayout,
2095 window: &mut Window,
2096 cx: &mut Context<Self>,
2097 ) {
2098 let fs = self.project().read(cx).fs();
2099 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2100 content.workspace.bottom_dock_layout = Some(layout);
2101 });
2102
2103 cx.notify();
2104 self.serialize_workspace(window, cx);
2105 }
2106
2107 pub fn right_dock(&self) -> &Entity<Dock> {
2108 &self.right_dock
2109 }
2110
2111 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2112 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2113 }
2114
2115 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2116 let left_dock = self.left_dock.read(cx);
2117 let left_visible = left_dock.is_open();
2118 let left_active_panel = left_dock
2119 .active_panel()
2120 .map(|panel| panel.persistent_name().to_string());
2121 // `zoomed_position` is kept in sync with individual panel zoom state
2122 // by the dock code in `Dock::new` and `Dock::add_panel`.
2123 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2124
2125 let right_dock = self.right_dock.read(cx);
2126 let right_visible = right_dock.is_open();
2127 let right_active_panel = right_dock
2128 .active_panel()
2129 .map(|panel| panel.persistent_name().to_string());
2130 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2131
2132 let bottom_dock = self.bottom_dock.read(cx);
2133 let bottom_visible = bottom_dock.is_open();
2134 let bottom_active_panel = bottom_dock
2135 .active_panel()
2136 .map(|panel| panel.persistent_name().to_string());
2137 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2138
2139 DockStructure {
2140 left: DockData {
2141 visible: left_visible,
2142 active_panel: left_active_panel,
2143 zoom: left_dock_zoom,
2144 },
2145 right: DockData {
2146 visible: right_visible,
2147 active_panel: right_active_panel,
2148 zoom: right_dock_zoom,
2149 },
2150 bottom: DockData {
2151 visible: bottom_visible,
2152 active_panel: bottom_active_panel,
2153 zoom: bottom_dock_zoom,
2154 },
2155 }
2156 }
2157
2158 pub fn set_dock_structure(
2159 &self,
2160 docks: DockStructure,
2161 window: &mut Window,
2162 cx: &mut Context<Self>,
2163 ) {
2164 for (dock, data) in [
2165 (&self.left_dock, docks.left),
2166 (&self.bottom_dock, docks.bottom),
2167 (&self.right_dock, docks.right),
2168 ] {
2169 dock.update(cx, |dock, cx| {
2170 dock.serialized_dock = Some(data);
2171 dock.restore_state(window, cx);
2172 });
2173 }
2174 }
2175
2176 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2177 self.items(cx)
2178 .filter_map(|item| {
2179 let project_path = item.project_path(cx)?;
2180 self.project.read(cx).absolute_path(&project_path, cx)
2181 })
2182 .collect()
2183 }
2184
2185 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2186 match position {
2187 DockPosition::Left => &self.left_dock,
2188 DockPosition::Bottom => &self.bottom_dock,
2189 DockPosition::Right => &self.right_dock,
2190 }
2191 }
2192
2193 pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
2194 self.all_docks().into_iter().find_map(|dock| {
2195 let dock = dock.read(cx);
2196 dock.has_agent_panel(cx).then_some(dock.position())
2197 })
2198 }
2199
2200 pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
2201 self.all_docks().into_iter().find_map(|dock| {
2202 let dock = dock.read(cx);
2203 let panel = dock.panel::<T>()?;
2204 dock.stored_panel_size_state(&panel)
2205 })
2206 }
2207
2208 pub fn persisted_panel_size_state(
2209 &self,
2210 panel_key: &'static str,
2211 cx: &App,
2212 ) -> Option<dock::PanelSizeState> {
2213 dock::Dock::load_persisted_size_state(self, panel_key, cx)
2214 }
2215
2216 pub fn persist_panel_size_state(
2217 &self,
2218 panel_key: &str,
2219 size_state: dock::PanelSizeState,
2220 cx: &mut App,
2221 ) {
2222 let Some(workspace_id) = self
2223 .database_id()
2224 .map(|id| i64::from(id).to_string())
2225 .or(self.session_id())
2226 else {
2227 return;
2228 };
2229
2230 let kvp = db::kvp::KeyValueStore::global(cx);
2231 let panel_key = panel_key.to_string();
2232 cx.background_spawn(async move {
2233 let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
2234 scope
2235 .write(
2236 format!("{workspace_id}:{panel_key}"),
2237 serde_json::to_string(&size_state)?,
2238 )
2239 .await
2240 })
2241 .detach_and_log_err(cx);
2242 }
2243
2244 pub fn set_panel_size_state<T: Panel>(
2245 &mut self,
2246 size_state: dock::PanelSizeState,
2247 window: &mut Window,
2248 cx: &mut Context<Self>,
2249 ) -> bool {
2250 let Some(panel) = self.panel::<T>(cx) else {
2251 return false;
2252 };
2253
2254 let dock = self.dock_at_position(panel.position(window, cx));
2255 let did_set = dock.update(cx, |dock, cx| {
2256 dock.set_panel_size_state(&panel, size_state, cx)
2257 });
2258
2259 if did_set {
2260 self.persist_panel_size_state(T::panel_key(), size_state, cx);
2261 }
2262
2263 did_set
2264 }
2265
2266 pub fn toggle_dock_panel_flexible_size(
2267 &self,
2268 dock: &Entity<Dock>,
2269 panel: &dyn PanelHandle,
2270 window: &mut Window,
2271 cx: &mut App,
2272 ) {
2273 let position = dock.read(cx).position();
2274 let current_size = self.dock_size(&dock.read(cx), window, cx);
2275 let current_flex =
2276 current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
2277 dock.update(cx, |dock, cx| {
2278 dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
2279 });
2280 }
2281
2282 fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
2283 let panel = dock.active_panel()?;
2284 let size_state = dock
2285 .stored_panel_size_state(panel.as_ref())
2286 .unwrap_or_default();
2287 let position = dock.position();
2288
2289 let use_flex = panel.has_flexible_size(window, cx);
2290
2291 if position.axis() == Axis::Horizontal
2292 && use_flex
2293 && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
2294 {
2295 let workspace_width = self.bounds.size.width;
2296 if workspace_width <= Pixels::ZERO {
2297 return None;
2298 }
2299 let flex = flex.max(0.001);
2300 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2301 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2302 // Both docks are flex items sharing the full workspace width.
2303 let total_flex = flex + 1.0 + opposite_flex;
2304 return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
2305 } else {
2306 // Opposite dock is fixed-width; flex items share (W - fixed).
2307 let opposite_fixed = opposite
2308 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2309 .unwrap_or_default();
2310 let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
2311 return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
2312 }
2313 }
2314
2315 Some(
2316 size_state
2317 .size
2318 .unwrap_or_else(|| panel.default_size(window, cx)),
2319 )
2320 }
2321
2322 pub fn dock_flex_for_size(
2323 &self,
2324 position: DockPosition,
2325 size: Pixels,
2326 window: &Window,
2327 cx: &App,
2328 ) -> Option<f32> {
2329 if position.axis() != Axis::Horizontal {
2330 return None;
2331 }
2332
2333 let workspace_width = self.bounds.size.width;
2334 if workspace_width <= Pixels::ZERO {
2335 return None;
2336 }
2337
2338 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2339 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2340 let size = size.clamp(px(0.), workspace_width - px(1.));
2341 Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
2342 } else {
2343 let opposite_width = opposite
2344 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2345 .unwrap_or_default();
2346 let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
2347 let remaining = (available - size).max(px(1.));
2348 Some((size / remaining).max(0.0))
2349 }
2350 }
2351
2352 fn opposite_dock_panel_and_size_state(
2353 &self,
2354 position: DockPosition,
2355 window: &Window,
2356 cx: &App,
2357 ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
2358 let opposite_position = match position {
2359 DockPosition::Left => DockPosition::Right,
2360 DockPosition::Right => DockPosition::Left,
2361 DockPosition::Bottom => return None,
2362 };
2363
2364 let opposite_dock = self.dock_at_position(opposite_position).read(cx);
2365 let panel = opposite_dock.visible_panel()?;
2366 let mut size_state = opposite_dock
2367 .stored_panel_size_state(panel.as_ref())
2368 .unwrap_or_default();
2369 if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
2370 size_state.flex = self.default_dock_flex(opposite_position);
2371 }
2372 Some((panel.clone(), size_state))
2373 }
2374
2375 pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
2376 if position.axis() != Axis::Horizontal {
2377 return None;
2378 }
2379
2380 let pane = self.last_active_center_pane.clone()?.upgrade()?;
2381 Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
2382 }
2383
2384 pub fn is_edited(&self) -> bool {
2385 self.window_edited
2386 }
2387
2388 pub fn add_panel<T: Panel>(
2389 &mut self,
2390 panel: Entity<T>,
2391 window: &mut Window,
2392 cx: &mut Context<Self>,
2393 ) {
2394 let focus_handle = panel.panel_focus_handle(cx);
2395 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2396 .detach();
2397
2398 let dock_position = panel.position(window, cx);
2399 let dock = self.dock_at_position(dock_position);
2400 let any_panel = panel.to_any();
2401 let persisted_size_state =
2402 self.persisted_panel_size_state(T::panel_key(), cx)
2403 .or_else(|| {
2404 load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
2405 let state = dock::PanelSizeState {
2406 size: Some(size),
2407 flex: None,
2408 };
2409 self.persist_panel_size_state(T::panel_key(), state, cx);
2410 state
2411 })
2412 });
2413
2414 dock.update(cx, |dock, cx| {
2415 let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
2416 if let Some(size_state) = persisted_size_state {
2417 dock.set_panel_size_state(&panel, size_state, cx);
2418 }
2419 index
2420 });
2421
2422 cx.emit(Event::PanelAdded(any_panel));
2423 }
2424
2425 pub fn remove_panel<T: Panel>(
2426 &mut self,
2427 panel: &Entity<T>,
2428 window: &mut Window,
2429 cx: &mut Context<Self>,
2430 ) {
2431 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2432 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2433 }
2434 }
2435
2436 pub fn status_bar(&self) -> &Entity<StatusBar> {
2437 &self.status_bar
2438 }
2439
2440 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2441 self.sidebar_focus_handle = handle;
2442 }
2443
2444 pub fn status_bar_visible(&self, cx: &App) -> bool {
2445 StatusBarSettings::get_global(cx).show
2446 }
2447
2448 pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
2449 self.multi_workspace.as_ref()
2450 }
2451
2452 pub fn set_multi_workspace(
2453 &mut self,
2454 multi_workspace: WeakEntity<MultiWorkspace>,
2455 cx: &mut App,
2456 ) {
2457 self.status_bar.update(cx, |status_bar, cx| {
2458 status_bar.set_multi_workspace(multi_workspace.clone(), cx);
2459 });
2460 self.multi_workspace = Some(multi_workspace);
2461 }
2462
2463 pub fn app_state(&self) -> &Arc<AppState> {
2464 &self.app_state
2465 }
2466
2467 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2468 self._panels_task = Some(task);
2469 }
2470
2471 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2472 self._panels_task.take()
2473 }
2474
2475 pub fn user_store(&self) -> &Entity<UserStore> {
2476 &self.app_state.user_store
2477 }
2478
2479 pub fn project(&self) -> &Entity<Project> {
2480 &self.project
2481 }
2482
2483 pub fn path_style(&self, cx: &App) -> PathStyle {
2484 self.project.read(cx).path_style(cx)
2485 }
2486
2487 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2488 let mut history: HashMap<EntityId, usize> = HashMap::default();
2489
2490 for pane_handle in &self.panes {
2491 let pane = pane_handle.read(cx);
2492
2493 for entry in pane.activation_history() {
2494 history.insert(
2495 entry.entity_id,
2496 history
2497 .get(&entry.entity_id)
2498 .cloned()
2499 .unwrap_or(0)
2500 .max(entry.timestamp),
2501 );
2502 }
2503 }
2504
2505 history
2506 }
2507
2508 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2509 let mut recent_item: Option<Entity<T>> = None;
2510 let mut recent_timestamp = 0;
2511 for pane_handle in &self.panes {
2512 let pane = pane_handle.read(cx);
2513 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2514 pane.items().map(|item| (item.item_id(), item)).collect();
2515 for entry in pane.activation_history() {
2516 if entry.timestamp > recent_timestamp
2517 && let Some(&item) = item_map.get(&entry.entity_id)
2518 && let Some(typed_item) = item.act_as::<T>(cx)
2519 {
2520 recent_timestamp = entry.timestamp;
2521 recent_item = Some(typed_item);
2522 }
2523 }
2524 }
2525 recent_item
2526 }
2527
2528 pub fn recent_navigation_history_iter(
2529 &self,
2530 cx: &App,
2531 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2532 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2533 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2534
2535 for pane in &self.panes {
2536 let pane = pane.read(cx);
2537
2538 pane.nav_history()
2539 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2540 if let Some(fs_path) = &fs_path {
2541 abs_paths_opened
2542 .entry(fs_path.clone())
2543 .or_default()
2544 .insert(project_path.clone());
2545 }
2546 let timestamp = entry.timestamp;
2547 match history.entry(project_path) {
2548 hash_map::Entry::Occupied(mut entry) => {
2549 let (_, old_timestamp) = entry.get();
2550 if ×tamp > old_timestamp {
2551 entry.insert((fs_path, timestamp));
2552 }
2553 }
2554 hash_map::Entry::Vacant(entry) => {
2555 entry.insert((fs_path, timestamp));
2556 }
2557 }
2558 });
2559
2560 if let Some(item) = pane.active_item()
2561 && let Some(project_path) = item.project_path(cx)
2562 {
2563 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2564
2565 if let Some(fs_path) = &fs_path {
2566 abs_paths_opened
2567 .entry(fs_path.clone())
2568 .or_default()
2569 .insert(project_path.clone());
2570 }
2571
2572 history.insert(project_path, (fs_path, std::usize::MAX));
2573 }
2574 }
2575
2576 history
2577 .into_iter()
2578 .sorted_by_key(|(_, (_, order))| *order)
2579 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2580 .rev()
2581 .filter(move |(history_path, abs_path)| {
2582 let latest_project_path_opened = abs_path
2583 .as_ref()
2584 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2585 .and_then(|project_paths| {
2586 project_paths
2587 .iter()
2588 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2589 });
2590
2591 latest_project_path_opened.is_none_or(|path| path == history_path)
2592 })
2593 }
2594
2595 pub fn recent_navigation_history(
2596 &self,
2597 limit: Option<usize>,
2598 cx: &App,
2599 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2600 self.recent_navigation_history_iter(cx)
2601 .take(limit.unwrap_or(usize::MAX))
2602 .collect()
2603 }
2604
2605 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2606 for pane in &self.panes {
2607 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2608 }
2609 }
2610
2611 fn navigate_history(
2612 &mut self,
2613 pane: WeakEntity<Pane>,
2614 mode: NavigationMode,
2615 window: &mut Window,
2616 cx: &mut Context<Workspace>,
2617 ) -> Task<Result<()>> {
2618 self.navigate_history_impl(
2619 pane,
2620 mode,
2621 window,
2622 &mut |history, cx| history.pop(mode, cx),
2623 cx,
2624 )
2625 }
2626
2627 fn navigate_tag_history(
2628 &mut self,
2629 pane: WeakEntity<Pane>,
2630 mode: TagNavigationMode,
2631 window: &mut Window,
2632 cx: &mut Context<Workspace>,
2633 ) -> Task<Result<()>> {
2634 self.navigate_history_impl(
2635 pane,
2636 NavigationMode::Normal,
2637 window,
2638 &mut |history, _cx| history.pop_tag(mode),
2639 cx,
2640 )
2641 }
2642
2643 fn navigate_history_impl(
2644 &mut self,
2645 pane: WeakEntity<Pane>,
2646 mode: NavigationMode,
2647 window: &mut Window,
2648 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2649 cx: &mut Context<Workspace>,
2650 ) -> Task<Result<()>> {
2651 let to_load = if let Some(pane) = pane.upgrade() {
2652 pane.update(cx, |pane, cx| {
2653 window.focus(&pane.focus_handle(cx), cx);
2654 loop {
2655 // Retrieve the weak item handle from the history.
2656 let entry = cb(pane.nav_history_mut(), cx)?;
2657
2658 // If the item is still present in this pane, then activate it.
2659 if let Some(index) = entry
2660 .item
2661 .upgrade()
2662 .and_then(|v| pane.index_for_item(v.as_ref()))
2663 {
2664 let prev_active_item_index = pane.active_item_index();
2665 pane.nav_history_mut().set_mode(mode);
2666 pane.activate_item(index, true, true, window, cx);
2667 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2668
2669 let mut navigated = prev_active_item_index != pane.active_item_index();
2670 if let Some(data) = entry.data {
2671 navigated |= pane.active_item()?.navigate(data, window, cx);
2672 }
2673
2674 if navigated {
2675 break None;
2676 }
2677 } else {
2678 // If the item is no longer present in this pane, then retrieve its
2679 // path info in order to reopen it.
2680 break pane
2681 .nav_history()
2682 .path_for_item(entry.item.id())
2683 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2684 }
2685 }
2686 })
2687 } else {
2688 None
2689 };
2690
2691 if let Some((project_path, abs_path, entry)) = to_load {
2692 // If the item was no longer present, then load it again from its previous path, first try the local path
2693 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2694
2695 cx.spawn_in(window, async move |workspace, cx| {
2696 let open_by_project_path = open_by_project_path.await;
2697 let mut navigated = false;
2698 match open_by_project_path
2699 .with_context(|| format!("Navigating to {project_path:?}"))
2700 {
2701 Ok((project_entry_id, build_item)) => {
2702 let prev_active_item_id = pane.update(cx, |pane, _| {
2703 pane.nav_history_mut().set_mode(mode);
2704 pane.active_item().map(|p| p.item_id())
2705 })?;
2706
2707 pane.update_in(cx, |pane, window, cx| {
2708 let item = pane.open_item(
2709 project_entry_id,
2710 project_path,
2711 true,
2712 entry.is_preview,
2713 true,
2714 None,
2715 window, cx,
2716 build_item,
2717 );
2718 navigated |= Some(item.item_id()) != prev_active_item_id;
2719 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2720 if let Some(data) = entry.data {
2721 navigated |= item.navigate(data, window, cx);
2722 }
2723 })?;
2724 }
2725 Err(open_by_project_path_e) => {
2726 // Fall back to opening by abs path, in case an external file was opened and closed,
2727 // and its worktree is now dropped
2728 if let Some(abs_path) = abs_path {
2729 let prev_active_item_id = pane.update(cx, |pane, _| {
2730 pane.nav_history_mut().set_mode(mode);
2731 pane.active_item().map(|p| p.item_id())
2732 })?;
2733 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2734 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2735 })?;
2736 match open_by_abs_path
2737 .await
2738 .with_context(|| format!("Navigating to {abs_path:?}"))
2739 {
2740 Ok(item) => {
2741 pane.update_in(cx, |pane, window, cx| {
2742 navigated |= Some(item.item_id()) != prev_active_item_id;
2743 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2744 if let Some(data) = entry.data {
2745 navigated |= item.navigate(data, window, cx);
2746 }
2747 })?;
2748 }
2749 Err(open_by_abs_path_e) => {
2750 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2751 }
2752 }
2753 }
2754 }
2755 }
2756
2757 if !navigated {
2758 workspace
2759 .update_in(cx, |workspace, window, cx| {
2760 Self::navigate_history(workspace, pane, mode, window, cx)
2761 })?
2762 .await?;
2763 }
2764
2765 Ok(())
2766 })
2767 } else {
2768 Task::ready(Ok(()))
2769 }
2770 }
2771
2772 pub fn go_back(
2773 &mut self,
2774 pane: WeakEntity<Pane>,
2775 window: &mut Window,
2776 cx: &mut Context<Workspace>,
2777 ) -> Task<Result<()>> {
2778 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2779 }
2780
2781 pub fn go_forward(
2782 &mut self,
2783 pane: WeakEntity<Pane>,
2784 window: &mut Window,
2785 cx: &mut Context<Workspace>,
2786 ) -> Task<Result<()>> {
2787 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2788 }
2789
2790 pub fn reopen_closed_item(
2791 &mut self,
2792 window: &mut Window,
2793 cx: &mut Context<Workspace>,
2794 ) -> Task<Result<()>> {
2795 self.navigate_history(
2796 self.active_pane().downgrade(),
2797 NavigationMode::ReopeningClosedItem,
2798 window,
2799 cx,
2800 )
2801 }
2802
2803 pub fn client(&self) -> &Arc<Client> {
2804 &self.app_state.client
2805 }
2806
2807 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2808 self.titlebar_item = Some(item);
2809 cx.notify();
2810 }
2811
2812 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2813 self.on_prompt_for_new_path = Some(prompt)
2814 }
2815
2816 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2817 self.on_prompt_for_open_path = Some(prompt)
2818 }
2819
2820 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2821 self.terminal_provider = Some(Box::new(provider));
2822 }
2823
2824 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2825 self.debugger_provider = Some(Arc::new(provider));
2826 }
2827
2828 pub fn set_open_in_dev_container(&mut self, value: bool) {
2829 self.open_in_dev_container = value;
2830 }
2831
2832 pub fn open_in_dev_container(&self) -> bool {
2833 self.open_in_dev_container
2834 }
2835
2836 pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
2837 self._dev_container_task = Some(task);
2838 }
2839
2840 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2841 self.debugger_provider.clone()
2842 }
2843
2844 pub fn prompt_for_open_path(
2845 &mut self,
2846 path_prompt_options: PathPromptOptions,
2847 lister: DirectoryLister,
2848 window: &mut Window,
2849 cx: &mut Context<Self>,
2850 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2851 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2852 let prompt = self.on_prompt_for_open_path.take().unwrap();
2853 let rx = prompt(self, lister, window, cx);
2854 self.on_prompt_for_open_path = Some(prompt);
2855 rx
2856 } else {
2857 let (tx, rx) = oneshot::channel();
2858 let abs_path = cx.prompt_for_paths(path_prompt_options);
2859
2860 cx.spawn_in(window, async move |workspace, cx| {
2861 let Ok(result) = abs_path.await else {
2862 return Ok(());
2863 };
2864
2865 match result {
2866 Ok(result) => {
2867 tx.send(result).ok();
2868 }
2869 Err(err) => {
2870 let rx = workspace.update_in(cx, |workspace, window, cx| {
2871 workspace.show_portal_error(err.to_string(), cx);
2872 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2873 let rx = prompt(workspace, lister, window, cx);
2874 workspace.on_prompt_for_open_path = Some(prompt);
2875 rx
2876 })?;
2877 if let Ok(path) = rx.await {
2878 tx.send(path).ok();
2879 }
2880 }
2881 };
2882 anyhow::Ok(())
2883 })
2884 .detach();
2885
2886 rx
2887 }
2888 }
2889
2890 pub fn prompt_for_new_path(
2891 &mut self,
2892 lister: DirectoryLister,
2893 suggested_name: Option<String>,
2894 window: &mut Window,
2895 cx: &mut Context<Self>,
2896 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2897 if self.project.read(cx).is_via_collab()
2898 || self.project.read(cx).is_via_remote_server()
2899 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2900 {
2901 let prompt = self.on_prompt_for_new_path.take().unwrap();
2902 let rx = prompt(self, lister, suggested_name, window, cx);
2903 self.on_prompt_for_new_path = Some(prompt);
2904 return rx;
2905 }
2906
2907 let (tx, rx) = oneshot::channel();
2908 cx.spawn_in(window, async move |workspace, cx| {
2909 let abs_path = workspace.update(cx, |workspace, cx| {
2910 let relative_to = workspace
2911 .most_recent_active_path(cx)
2912 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2913 .or_else(|| {
2914 let project = workspace.project.read(cx);
2915 project.visible_worktrees(cx).find_map(|worktree| {
2916 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2917 })
2918 })
2919 .or_else(std::env::home_dir)
2920 .unwrap_or_else(|| PathBuf::from(""));
2921 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2922 })?;
2923 let abs_path = match abs_path.await? {
2924 Ok(path) => path,
2925 Err(err) => {
2926 let rx = workspace.update_in(cx, |workspace, window, cx| {
2927 workspace.show_portal_error(err.to_string(), cx);
2928
2929 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2930 let rx = prompt(workspace, lister, suggested_name, window, cx);
2931 workspace.on_prompt_for_new_path = Some(prompt);
2932 rx
2933 })?;
2934 if let Ok(path) = rx.await {
2935 tx.send(path).ok();
2936 }
2937 return anyhow::Ok(());
2938 }
2939 };
2940
2941 tx.send(abs_path.map(|path| vec![path])).ok();
2942 anyhow::Ok(())
2943 })
2944 .detach();
2945
2946 rx
2947 }
2948
2949 pub fn titlebar_item(&self) -> Option<AnyView> {
2950 self.titlebar_item.clone()
2951 }
2952
2953 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2954 /// When set, git-related operations should use this worktree instead of deriving
2955 /// the active worktree from the focused file.
2956 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2957 self.active_worktree_override
2958 }
2959
2960 pub fn set_active_worktree_override(
2961 &mut self,
2962 worktree_id: Option<WorktreeId>,
2963 cx: &mut Context<Self>,
2964 ) {
2965 self.active_worktree_override = worktree_id;
2966 cx.notify();
2967 }
2968
2969 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2970 self.active_worktree_override = None;
2971 cx.notify();
2972 }
2973
2974 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2975 ///
2976 /// If the given workspace has a local project, then it will be passed
2977 /// to the callback. Otherwise, a new empty window will be created.
2978 pub fn with_local_workspace<T, F>(
2979 &mut self,
2980 window: &mut Window,
2981 cx: &mut Context<Self>,
2982 callback: F,
2983 ) -> Task<Result<T>>
2984 where
2985 T: 'static,
2986 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2987 {
2988 if self.project.read(cx).is_local() {
2989 Task::ready(Ok(callback(self, window, cx)))
2990 } else {
2991 let env = self.project.read(cx).cli_environment(cx);
2992 let task = Self::new_local(
2993 Vec::new(),
2994 self.app_state.clone(),
2995 None,
2996 env,
2997 None,
2998 OpenMode::Activate,
2999 cx,
3000 );
3001 cx.spawn_in(window, async move |_vh, cx| {
3002 let OpenResult {
3003 window: multi_workspace_window,
3004 ..
3005 } = task.await?;
3006 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
3007 let workspace = multi_workspace.workspace().clone();
3008 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3009 })
3010 })
3011 }
3012 }
3013
3014 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
3015 ///
3016 /// If the given workspace has a local project, then it will be passed
3017 /// to the callback. Otherwise, a new empty window will be created.
3018 pub fn with_local_or_wsl_workspace<T, F>(
3019 &mut self,
3020 window: &mut Window,
3021 cx: &mut Context<Self>,
3022 callback: F,
3023 ) -> Task<Result<T>>
3024 where
3025 T: 'static,
3026 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
3027 {
3028 let project = self.project.read(cx);
3029 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
3030 Task::ready(Ok(callback(self, window, cx)))
3031 } else {
3032 let env = self.project.read(cx).cli_environment(cx);
3033 let task = Self::new_local(
3034 Vec::new(),
3035 self.app_state.clone(),
3036 None,
3037 env,
3038 None,
3039 OpenMode::Activate,
3040 cx,
3041 );
3042 cx.spawn_in(window, async move |_vh, cx| {
3043 let OpenResult {
3044 window: multi_workspace_window,
3045 ..
3046 } = task.await?;
3047 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
3048 let workspace = multi_workspace.workspace().clone();
3049 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3050 })
3051 })
3052 }
3053 }
3054
3055 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3056 self.project.read(cx).worktrees(cx)
3057 }
3058
3059 pub fn visible_worktrees<'a>(
3060 &self,
3061 cx: &'a App,
3062 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3063 self.project.read(cx).visible_worktrees(cx)
3064 }
3065
3066 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
3067 let futures = self
3068 .worktrees(cx)
3069 .filter_map(|worktree| worktree.read(cx).as_local())
3070 .map(|worktree| worktree.scan_complete())
3071 .collect::<Vec<_>>();
3072 async move {
3073 for future in futures {
3074 future.await;
3075 }
3076 }
3077 }
3078
3079 pub fn close_global(cx: &mut App) {
3080 cx.defer(|cx| {
3081 cx.windows().iter().find(|window| {
3082 window
3083 .update(cx, |_, window, _| {
3084 if window.is_window_active() {
3085 //This can only get called when the window's project connection has been lost
3086 //so we don't need to prompt the user for anything and instead just close the window
3087 window.remove_window();
3088 true
3089 } else {
3090 false
3091 }
3092 })
3093 .unwrap_or(false)
3094 });
3095 });
3096 }
3097
3098 pub fn move_focused_panel_to_next_position(
3099 &mut self,
3100 _: &MoveFocusedPanelToNextPosition,
3101 window: &mut Window,
3102 cx: &mut Context<Self>,
3103 ) {
3104 let docks = self.all_docks();
3105 let active_dock = docks
3106 .into_iter()
3107 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
3108
3109 if let Some(dock) = active_dock {
3110 dock.update(cx, |dock, cx| {
3111 let active_panel = dock
3112 .active_panel()
3113 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
3114
3115 if let Some(panel) = active_panel {
3116 panel.move_to_next_position(window, cx);
3117 }
3118 })
3119 }
3120 }
3121
3122 pub fn prepare_to_close(
3123 &mut self,
3124 close_intent: CloseIntent,
3125 window: &mut Window,
3126 cx: &mut Context<Self>,
3127 ) -> Task<Result<bool>> {
3128 let active_call = self.active_global_call();
3129
3130 cx.spawn_in(window, async move |this, cx| {
3131 this.update(cx, |this, _| {
3132 if close_intent == CloseIntent::CloseWindow {
3133 this.removing = true;
3134 }
3135 })?;
3136
3137 let workspace_count = cx.update(|_window, cx| {
3138 cx.windows()
3139 .iter()
3140 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
3141 .count()
3142 })?;
3143
3144 #[cfg(target_os = "macos")]
3145 let save_last_workspace = false;
3146
3147 // On Linux and Windows, closing the last window should restore the last workspace.
3148 #[cfg(not(target_os = "macos"))]
3149 let save_last_workspace = {
3150 let remaining_workspaces = cx.update(|_window, cx| {
3151 cx.windows()
3152 .iter()
3153 .filter_map(|window| window.downcast::<MultiWorkspace>())
3154 .filter_map(|multi_workspace| {
3155 multi_workspace
3156 .update(cx, |multi_workspace, _, cx| {
3157 multi_workspace.workspace().read(cx).removing
3158 })
3159 .ok()
3160 })
3161 .filter(|removing| !removing)
3162 .count()
3163 })?;
3164
3165 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
3166 };
3167
3168 if let Some(active_call) = active_call
3169 && workspace_count == 1
3170 && cx
3171 .update(|_window, cx| active_call.0.is_in_room(cx))
3172 .unwrap_or(false)
3173 {
3174 if close_intent == CloseIntent::CloseWindow {
3175 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
3176 let answer = cx.update(|window, cx| {
3177 window.prompt(
3178 PromptLevel::Warning,
3179 "Do you want to leave the current call?",
3180 None,
3181 &["Close window and hang up", "Cancel"],
3182 cx,
3183 )
3184 })?;
3185
3186 if answer.await.log_err() == Some(1) {
3187 return anyhow::Ok(false);
3188 } else {
3189 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
3190 task.await.log_err();
3191 }
3192 }
3193 }
3194 if close_intent == CloseIntent::ReplaceWindow {
3195 _ = cx.update(|_window, cx| {
3196 let multi_workspace = cx
3197 .windows()
3198 .iter()
3199 .filter_map(|window| window.downcast::<MultiWorkspace>())
3200 .next()
3201 .unwrap();
3202 let project = multi_workspace
3203 .read(cx)?
3204 .workspace()
3205 .read(cx)
3206 .project
3207 .clone();
3208 if project.read(cx).is_shared() {
3209 active_call.0.unshare_project(project, cx)?;
3210 }
3211 Ok::<_, anyhow::Error>(())
3212 });
3213 }
3214 }
3215
3216 let save_result = this
3217 .update_in(cx, |this, window, cx| {
3218 this.save_all_internal(SaveIntent::Close, window, cx)
3219 })?
3220 .await;
3221
3222 // If we're not quitting, but closing, we remove the workspace from
3223 // the current session.
3224 if close_intent != CloseIntent::Quit
3225 && !save_last_workspace
3226 && save_result.as_ref().is_ok_and(|&res| res)
3227 {
3228 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
3229 .await;
3230 }
3231
3232 save_result
3233 })
3234 }
3235
3236 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
3237 self.save_all_internal(
3238 action.save_intent.unwrap_or(SaveIntent::SaveAll),
3239 window,
3240 cx,
3241 )
3242 .detach_and_log_err(cx);
3243 }
3244
3245 fn send_keystrokes(
3246 &mut self,
3247 action: &SendKeystrokes,
3248 window: &mut Window,
3249 cx: &mut Context<Self>,
3250 ) {
3251 let keystrokes: Vec<Keystroke> = action
3252 .0
3253 .split(' ')
3254 .flat_map(|k| Keystroke::parse(k).log_err())
3255 .map(|k| {
3256 cx.keyboard_mapper()
3257 .map_key_equivalent(k, false)
3258 .inner()
3259 .clone()
3260 })
3261 .collect();
3262 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
3263 }
3264
3265 pub fn send_keystrokes_impl(
3266 &mut self,
3267 keystrokes: Vec<Keystroke>,
3268 window: &mut Window,
3269 cx: &mut Context<Self>,
3270 ) -> Shared<Task<()>> {
3271 let mut state = self.dispatching_keystrokes.borrow_mut();
3272 if !state.dispatched.insert(keystrokes.clone()) {
3273 cx.propagate();
3274 return state.task.clone().unwrap();
3275 }
3276
3277 state.queue.extend(keystrokes);
3278
3279 let keystrokes = self.dispatching_keystrokes.clone();
3280 if state.task.is_none() {
3281 state.task = Some(
3282 window
3283 .spawn(cx, async move |cx| {
3284 // limit to 100 keystrokes to avoid infinite recursion.
3285 for _ in 0..100 {
3286 let keystroke = {
3287 let mut state = keystrokes.borrow_mut();
3288 let Some(keystroke) = state.queue.pop_front() else {
3289 state.dispatched.clear();
3290 state.task.take();
3291 return;
3292 };
3293 keystroke
3294 };
3295 cx.update(|window, cx| {
3296 let focused = window.focused(cx);
3297 window.dispatch_keystroke(keystroke.clone(), cx);
3298 if window.focused(cx) != focused {
3299 // dispatch_keystroke may cause the focus to change.
3300 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3301 // And we need that to happen before the next keystroke to keep vim mode happy...
3302 // (Note that the tests always do this implicitly, so you must manually test with something like:
3303 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3304 // )
3305 window.draw(cx).clear();
3306 }
3307 })
3308 .ok();
3309
3310 // Yield between synthetic keystrokes so deferred focus and
3311 // other effects can settle before dispatching the next key.
3312 yield_now().await;
3313 }
3314
3315 *keystrokes.borrow_mut() = Default::default();
3316 log::error!("over 100 keystrokes passed to send_keystrokes");
3317 })
3318 .shared(),
3319 );
3320 }
3321 state.task.clone().unwrap()
3322 }
3323
3324 /// Prompts the user to save or discard each dirty item, returning
3325 /// `true` if they confirmed (saved/discarded everything) or `false`
3326 /// if they cancelled. Used before removing worktree roots during
3327 /// thread archival.
3328 pub fn prompt_to_save_or_discard_dirty_items(
3329 &mut self,
3330 window: &mut Window,
3331 cx: &mut Context<Self>,
3332 ) -> Task<Result<bool>> {
3333 self.save_all_internal(SaveIntent::Close, window, cx)
3334 }
3335
3336 fn save_all_internal(
3337 &mut self,
3338 mut save_intent: SaveIntent,
3339 window: &mut Window,
3340 cx: &mut Context<Self>,
3341 ) -> Task<Result<bool>> {
3342 if self.project.read(cx).is_disconnected(cx) {
3343 return Task::ready(Ok(true));
3344 }
3345 let dirty_items = self
3346 .panes
3347 .iter()
3348 .flat_map(|pane| {
3349 pane.read(cx).items().filter_map(|item| {
3350 if item.is_dirty(cx) {
3351 item.tab_content_text(0, cx);
3352 Some((pane.downgrade(), item.boxed_clone()))
3353 } else {
3354 None
3355 }
3356 })
3357 })
3358 .collect::<Vec<_>>();
3359
3360 let project = self.project.clone();
3361 cx.spawn_in(window, async move |workspace, cx| {
3362 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3363 let (serialize_tasks, remaining_dirty_items) =
3364 workspace.update_in(cx, |workspace, window, cx| {
3365 let mut remaining_dirty_items = Vec::new();
3366 let mut serialize_tasks = Vec::new();
3367 for (pane, item) in dirty_items {
3368 if let Some(task) = item
3369 .to_serializable_item_handle(cx)
3370 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3371 {
3372 serialize_tasks.push(task);
3373 } else {
3374 remaining_dirty_items.push((pane, item));
3375 }
3376 }
3377 (serialize_tasks, remaining_dirty_items)
3378 })?;
3379
3380 futures::future::try_join_all(serialize_tasks).await?;
3381
3382 if !remaining_dirty_items.is_empty() {
3383 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3384 }
3385
3386 if remaining_dirty_items.len() > 1 {
3387 let answer = workspace.update_in(cx, |_, window, cx| {
3388 let detail = Pane::file_names_for_prompt(
3389 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3390 cx,
3391 );
3392 window.prompt(
3393 PromptLevel::Warning,
3394 "Do you want to save all changes in the following files?",
3395 Some(&detail),
3396 &["Save all", "Discard all", "Cancel"],
3397 cx,
3398 )
3399 })?;
3400 match answer.await.log_err() {
3401 Some(0) => save_intent = SaveIntent::SaveAll,
3402 Some(1) => save_intent = SaveIntent::Skip,
3403 Some(2) => return Ok(false),
3404 _ => {}
3405 }
3406 }
3407
3408 remaining_dirty_items
3409 } else {
3410 dirty_items
3411 };
3412
3413 for (pane, item) in dirty_items {
3414 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3415 (
3416 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3417 item.project_entry_ids(cx),
3418 )
3419 })?;
3420 if (singleton || !project_entry_ids.is_empty())
3421 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3422 {
3423 return Ok(false);
3424 }
3425 }
3426 Ok(true)
3427 })
3428 }
3429
3430 pub fn open_workspace_for_paths(
3431 &mut self,
3432 // replace_current_window: bool,
3433 mut open_mode: OpenMode,
3434 paths: Vec<PathBuf>,
3435 window: &mut Window,
3436 cx: &mut Context<Self>,
3437 ) -> Task<Result<Entity<Workspace>>> {
3438 let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
3439 let is_remote = self.project.read(cx).is_via_collab();
3440 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3441 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3442
3443 let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
3444 if workspace_is_empty {
3445 open_mode = OpenMode::Activate;
3446 }
3447
3448 let app_state = self.app_state.clone();
3449
3450 cx.spawn(async move |_, cx| {
3451 let OpenResult { workspace, .. } = cx
3452 .update(|cx| {
3453 open_paths(
3454 &paths,
3455 app_state,
3456 OpenOptions {
3457 requesting_window,
3458 open_mode,
3459 ..Default::default()
3460 },
3461 cx,
3462 )
3463 })
3464 .await?;
3465 Ok(workspace)
3466 })
3467 }
3468
3469 #[allow(clippy::type_complexity)]
3470 pub fn open_paths(
3471 &mut self,
3472 mut abs_paths: Vec<PathBuf>,
3473 options: OpenOptions,
3474 pane: Option<WeakEntity<Pane>>,
3475 window: &mut Window,
3476 cx: &mut Context<Self>,
3477 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3478 let fs = self.app_state.fs.clone();
3479
3480 let caller_ordered_abs_paths = abs_paths.clone();
3481
3482 // Sort the paths to ensure we add worktrees for parents before their children.
3483 abs_paths.sort_unstable();
3484 cx.spawn_in(window, async move |this, cx| {
3485 let mut tasks = Vec::with_capacity(abs_paths.len());
3486
3487 for abs_path in &abs_paths {
3488 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3489 OpenVisible::All => Some(true),
3490 OpenVisible::None => Some(false),
3491 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3492 Some(Some(metadata)) => Some(!metadata.is_dir),
3493 Some(None) => Some(true),
3494 None => None,
3495 },
3496 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3497 Some(Some(metadata)) => Some(metadata.is_dir),
3498 Some(None) => Some(false),
3499 None => None,
3500 },
3501 };
3502 let project_path = match visible {
3503 Some(visible) => match this
3504 .update(cx, |this, cx| {
3505 Workspace::project_path_for_path(
3506 this.project.clone(),
3507 abs_path,
3508 visible,
3509 cx,
3510 )
3511 })
3512 .log_err()
3513 {
3514 Some(project_path) => project_path.await.log_err(),
3515 None => None,
3516 },
3517 None => None,
3518 };
3519
3520 let this = this.clone();
3521 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3522 let fs = fs.clone();
3523 let pane = pane.clone();
3524 let task = cx.spawn(async move |cx| {
3525 let (_worktree, project_path) = project_path?;
3526 if fs.is_dir(&abs_path).await {
3527 // Opening a directory should not race to update the active entry.
3528 // We'll select/reveal a deterministic final entry after all paths finish opening.
3529 None
3530 } else {
3531 Some(
3532 this.update_in(cx, |this, window, cx| {
3533 this.open_path(
3534 project_path,
3535 pane,
3536 options.focus.unwrap_or(true),
3537 window,
3538 cx,
3539 )
3540 })
3541 .ok()?
3542 .await,
3543 )
3544 }
3545 });
3546 tasks.push(task);
3547 }
3548
3549 let results = futures::future::join_all(tasks).await;
3550
3551 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3552 let mut winner: Option<(PathBuf, bool)> = None;
3553 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3554 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3555 if !metadata.is_dir {
3556 winner = Some((abs_path, false));
3557 break;
3558 }
3559 if winner.is_none() {
3560 winner = Some((abs_path, true));
3561 }
3562 } else if winner.is_none() {
3563 winner = Some((abs_path, false));
3564 }
3565 }
3566
3567 // Compute the winner entry id on the foreground thread and emit once, after all
3568 // paths finish opening. This avoids races between concurrently-opening paths
3569 // (directories in particular) and makes the resulting project panel selection
3570 // deterministic.
3571 if let Some((winner_abs_path, winner_is_dir)) = winner {
3572 'emit_winner: {
3573 let winner_abs_path: Arc<Path> =
3574 SanitizedPath::new(&winner_abs_path).as_path().into();
3575
3576 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3577 OpenVisible::All => true,
3578 OpenVisible::None => false,
3579 OpenVisible::OnlyFiles => !winner_is_dir,
3580 OpenVisible::OnlyDirectories => winner_is_dir,
3581 };
3582
3583 let Some(worktree_task) = this
3584 .update(cx, |workspace, cx| {
3585 workspace.project.update(cx, |project, cx| {
3586 project.find_or_create_worktree(
3587 winner_abs_path.as_ref(),
3588 visible,
3589 cx,
3590 )
3591 })
3592 })
3593 .ok()
3594 else {
3595 break 'emit_winner;
3596 };
3597
3598 let Ok((worktree, _)) = worktree_task.await else {
3599 break 'emit_winner;
3600 };
3601
3602 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3603 let worktree = worktree.read(cx);
3604 let worktree_abs_path = worktree.abs_path();
3605 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3606 worktree.root_entry()
3607 } else {
3608 winner_abs_path
3609 .strip_prefix(worktree_abs_path.as_ref())
3610 .ok()
3611 .and_then(|relative_path| {
3612 let relative_path =
3613 RelPath::new(relative_path, PathStyle::local())
3614 .log_err()?;
3615 worktree.entry_for_path(&relative_path)
3616 })
3617 }?;
3618 Some(entry.id)
3619 }) else {
3620 break 'emit_winner;
3621 };
3622
3623 this.update(cx, |workspace, cx| {
3624 workspace.project.update(cx, |_, cx| {
3625 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3626 });
3627 })
3628 .ok();
3629 }
3630 }
3631
3632 results
3633 })
3634 }
3635
3636 pub fn open_resolved_path(
3637 &mut self,
3638 path: ResolvedPath,
3639 window: &mut Window,
3640 cx: &mut Context<Self>,
3641 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3642 match path {
3643 ResolvedPath::ProjectPath { project_path, .. } => {
3644 self.open_path(project_path, None, true, window, cx)
3645 }
3646 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3647 PathBuf::from(path),
3648 OpenOptions {
3649 visible: Some(OpenVisible::None),
3650 ..Default::default()
3651 },
3652 window,
3653 cx,
3654 ),
3655 }
3656 }
3657
3658 pub fn absolute_path_of_worktree(
3659 &self,
3660 worktree_id: WorktreeId,
3661 cx: &mut Context<Self>,
3662 ) -> Option<PathBuf> {
3663 self.project
3664 .read(cx)
3665 .worktree_for_id(worktree_id, cx)
3666 // TODO: use `abs_path` or `root_dir`
3667 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3668 }
3669
3670 pub fn add_folder_to_project(
3671 &mut self,
3672 _: &AddFolderToProject,
3673 window: &mut Window,
3674 cx: &mut Context<Self>,
3675 ) {
3676 let project = self.project.read(cx);
3677 if project.is_via_collab() {
3678 self.show_error(
3679 &anyhow!("You cannot add folders to someone else's project"),
3680 cx,
3681 );
3682 return;
3683 }
3684 let paths = self.prompt_for_open_path(
3685 PathPromptOptions {
3686 files: false,
3687 directories: true,
3688 multiple: true,
3689 prompt: None,
3690 },
3691 DirectoryLister::Project(self.project.clone()),
3692 window,
3693 cx,
3694 );
3695 cx.spawn_in(window, async move |this, cx| {
3696 if let Some(paths) = paths.await.log_err().flatten() {
3697 let results = this
3698 .update_in(cx, |this, window, cx| {
3699 this.open_paths(
3700 paths,
3701 OpenOptions {
3702 visible: Some(OpenVisible::All),
3703 ..Default::default()
3704 },
3705 None,
3706 window,
3707 cx,
3708 )
3709 })?
3710 .await;
3711 for result in results.into_iter().flatten() {
3712 result.log_err();
3713 }
3714 }
3715 anyhow::Ok(())
3716 })
3717 .detach_and_log_err(cx);
3718 }
3719
3720 pub fn project_path_for_path(
3721 project: Entity<Project>,
3722 abs_path: &Path,
3723 visible: bool,
3724 cx: &mut App,
3725 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3726 let entry = project.update(cx, |project, cx| {
3727 project.find_or_create_worktree(abs_path, visible, cx)
3728 });
3729 cx.spawn(async move |cx| {
3730 let (worktree, path) = entry.await?;
3731 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3732 Ok((worktree, ProjectPath { worktree_id, path }))
3733 })
3734 }
3735
3736 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3737 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3738 }
3739
3740 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3741 self.items_of_type(cx).max_by_key(|item| item.item_id())
3742 }
3743
3744 pub fn items_of_type<'a, T: Item>(
3745 &'a self,
3746 cx: &'a App,
3747 ) -> impl 'a + Iterator<Item = Entity<T>> {
3748 self.panes
3749 .iter()
3750 .flat_map(|pane| pane.read(cx).items_of_type())
3751 }
3752
3753 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3754 self.active_pane().read(cx).active_item()
3755 }
3756
3757 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3758 let item = self.active_item(cx)?;
3759 item.to_any_view().downcast::<I>().ok()
3760 }
3761
3762 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3763 self.active_item(cx).and_then(|item| item.project_path(cx))
3764 }
3765
3766 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3767 self.recent_navigation_history_iter(cx)
3768 .filter_map(|(path, abs_path)| {
3769 let worktree = self
3770 .project
3771 .read(cx)
3772 .worktree_for_id(path.worktree_id, cx)?;
3773 if worktree.read(cx).is_visible() {
3774 abs_path
3775 } else {
3776 None
3777 }
3778 })
3779 .next()
3780 }
3781
3782 pub fn save_active_item(
3783 &mut self,
3784 save_intent: SaveIntent,
3785 window: &mut Window,
3786 cx: &mut App,
3787 ) -> Task<Result<()>> {
3788 let project = self.project.clone();
3789 let pane = self.active_pane();
3790 let item = pane.read(cx).active_item();
3791 let pane = pane.downgrade();
3792
3793 window.spawn(cx, async move |cx| {
3794 if let Some(item) = item {
3795 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3796 .await
3797 .map(|_| ())
3798 } else {
3799 Ok(())
3800 }
3801 })
3802 }
3803
3804 pub fn close_inactive_items_and_panes(
3805 &mut self,
3806 action: &CloseInactiveTabsAndPanes,
3807 window: &mut Window,
3808 cx: &mut Context<Self>,
3809 ) {
3810 if let Some(task) = self.close_all_internal(
3811 true,
3812 action.save_intent.unwrap_or(SaveIntent::Close),
3813 window,
3814 cx,
3815 ) {
3816 task.detach_and_log_err(cx)
3817 }
3818 }
3819
3820 pub fn close_all_items_and_panes(
3821 &mut self,
3822 action: &CloseAllItemsAndPanes,
3823 window: &mut Window,
3824 cx: &mut Context<Self>,
3825 ) {
3826 if let Some(task) = self.close_all_internal(
3827 false,
3828 action.save_intent.unwrap_or(SaveIntent::Close),
3829 window,
3830 cx,
3831 ) {
3832 task.detach_and_log_err(cx)
3833 }
3834 }
3835
3836 /// Closes the active item across all panes.
3837 pub fn close_item_in_all_panes(
3838 &mut self,
3839 action: &CloseItemInAllPanes,
3840 window: &mut Window,
3841 cx: &mut Context<Self>,
3842 ) {
3843 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3844 return;
3845 };
3846
3847 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3848 let close_pinned = action.close_pinned;
3849
3850 if let Some(project_path) = active_item.project_path(cx) {
3851 self.close_items_with_project_path(
3852 &project_path,
3853 save_intent,
3854 close_pinned,
3855 window,
3856 cx,
3857 );
3858 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3859 let item_id = active_item.item_id();
3860 self.active_pane().update(cx, |pane, cx| {
3861 pane.close_item_by_id(item_id, save_intent, window, cx)
3862 .detach_and_log_err(cx);
3863 });
3864 }
3865 }
3866
3867 /// Closes all items with the given project path across all panes.
3868 pub fn close_items_with_project_path(
3869 &mut self,
3870 project_path: &ProjectPath,
3871 save_intent: SaveIntent,
3872 close_pinned: bool,
3873 window: &mut Window,
3874 cx: &mut Context<Self>,
3875 ) {
3876 let panes = self.panes().to_vec();
3877 for pane in panes {
3878 pane.update(cx, |pane, cx| {
3879 pane.close_items_for_project_path(
3880 project_path,
3881 save_intent,
3882 close_pinned,
3883 window,
3884 cx,
3885 )
3886 .detach_and_log_err(cx);
3887 });
3888 }
3889 }
3890
3891 fn close_all_internal(
3892 &mut self,
3893 retain_active_pane: bool,
3894 save_intent: SaveIntent,
3895 window: &mut Window,
3896 cx: &mut Context<Self>,
3897 ) -> Option<Task<Result<()>>> {
3898 let current_pane = self.active_pane();
3899
3900 let mut tasks = Vec::new();
3901
3902 if retain_active_pane {
3903 let current_pane_close = current_pane.update(cx, |pane, cx| {
3904 pane.close_other_items(
3905 &CloseOtherItems {
3906 save_intent: None,
3907 close_pinned: false,
3908 },
3909 None,
3910 window,
3911 cx,
3912 )
3913 });
3914
3915 tasks.push(current_pane_close);
3916 }
3917
3918 for pane in self.panes() {
3919 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3920 continue;
3921 }
3922
3923 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3924 pane.close_all_items(
3925 &CloseAllItems {
3926 save_intent: Some(save_intent),
3927 close_pinned: false,
3928 },
3929 window,
3930 cx,
3931 )
3932 });
3933
3934 tasks.push(close_pane_items)
3935 }
3936
3937 if tasks.is_empty() {
3938 None
3939 } else {
3940 Some(cx.spawn_in(window, async move |_, _| {
3941 for task in tasks {
3942 task.await?
3943 }
3944 Ok(())
3945 }))
3946 }
3947 }
3948
3949 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3950 self.dock_at_position(position).read(cx).is_open()
3951 }
3952
3953 pub fn toggle_dock(
3954 &mut self,
3955 dock_side: DockPosition,
3956 window: &mut Window,
3957 cx: &mut Context<Self>,
3958 ) {
3959 let mut focus_center = false;
3960 let mut reveal_dock = false;
3961
3962 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3963 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3964
3965 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3966 telemetry::event!(
3967 "Panel Button Clicked",
3968 name = panel.persistent_name(),
3969 toggle_state = !was_visible
3970 );
3971 }
3972 if was_visible {
3973 self.save_open_dock_positions(cx);
3974 }
3975
3976 let dock = self.dock_at_position(dock_side);
3977 dock.update(cx, |dock, cx| {
3978 dock.set_open(!was_visible, window, cx);
3979
3980 if dock.active_panel().is_none() {
3981 let Some(panel_ix) = dock
3982 .first_enabled_panel_idx(cx)
3983 .log_with_level(log::Level::Info)
3984 else {
3985 return;
3986 };
3987 dock.activate_panel(panel_ix, window, cx);
3988 }
3989
3990 if let Some(active_panel) = dock.active_panel() {
3991 if was_visible {
3992 if active_panel
3993 .panel_focus_handle(cx)
3994 .contains_focused(window, cx)
3995 {
3996 focus_center = true;
3997 }
3998 } else {
3999 let focus_handle = &active_panel.panel_focus_handle(cx);
4000 window.focus(focus_handle, cx);
4001 reveal_dock = true;
4002 }
4003 }
4004 });
4005
4006 if reveal_dock {
4007 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
4008 }
4009
4010 if focus_center {
4011 self.active_pane
4012 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4013 }
4014
4015 cx.notify();
4016 self.serialize_workspace(window, cx);
4017 }
4018
4019 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
4020 self.all_docks().into_iter().find(|&dock| {
4021 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
4022 })
4023 }
4024
4025 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
4026 if let Some(dock) = self.active_dock(window, cx).cloned() {
4027 self.save_open_dock_positions(cx);
4028 dock.update(cx, |dock, cx| {
4029 dock.set_open(false, window, cx);
4030 });
4031 return true;
4032 }
4033 false
4034 }
4035
4036 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4037 self.save_open_dock_positions(cx);
4038 for dock in self.all_docks() {
4039 dock.update(cx, |dock, cx| {
4040 dock.set_open(false, window, cx);
4041 });
4042 }
4043
4044 cx.focus_self(window);
4045 cx.notify();
4046 self.serialize_workspace(window, cx);
4047 }
4048
4049 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
4050 self.all_docks()
4051 .into_iter()
4052 .filter_map(|dock| {
4053 let dock_ref = dock.read(cx);
4054 if dock_ref.is_open() {
4055 Some(dock_ref.position())
4056 } else {
4057 None
4058 }
4059 })
4060 .collect()
4061 }
4062
4063 /// Saves the positions of currently open docks.
4064 ///
4065 /// Updates `last_open_dock_positions` with positions of all currently open
4066 /// docks, to later be restored by the 'Toggle All Docks' action.
4067 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
4068 let open_dock_positions = self.get_open_dock_positions(cx);
4069 if !open_dock_positions.is_empty() {
4070 self.last_open_dock_positions = open_dock_positions;
4071 }
4072 }
4073
4074 /// Toggles all docks between open and closed states.
4075 ///
4076 /// If any docks are open, closes all and remembers their positions. If all
4077 /// docks are closed, restores the last remembered dock configuration.
4078 fn toggle_all_docks(
4079 &mut self,
4080 _: &ToggleAllDocks,
4081 window: &mut Window,
4082 cx: &mut Context<Self>,
4083 ) {
4084 let open_dock_positions = self.get_open_dock_positions(cx);
4085
4086 if !open_dock_positions.is_empty() {
4087 self.close_all_docks(window, cx);
4088 } else if !self.last_open_dock_positions.is_empty() {
4089 self.restore_last_open_docks(window, cx);
4090 }
4091 }
4092
4093 /// Reopens docks from the most recently remembered configuration.
4094 ///
4095 /// Opens all docks whose positions are stored in `last_open_dock_positions`
4096 /// and clears the stored positions.
4097 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4098 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
4099
4100 for position in positions_to_open {
4101 let dock = self.dock_at_position(position);
4102 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
4103 }
4104
4105 cx.focus_self(window);
4106 cx.notify();
4107 self.serialize_workspace(window, cx);
4108 }
4109
4110 /// Transfer focus to the panel of the given type.
4111 pub fn focus_panel<T: Panel>(
4112 &mut self,
4113 window: &mut Window,
4114 cx: &mut Context<Self>,
4115 ) -> Option<Entity<T>> {
4116 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
4117 panel.to_any().downcast().ok()
4118 }
4119
4120 /// Focus the panel of the given type if it isn't already focused. If it is
4121 /// already focused, then transfer focus back to the workspace center.
4122 /// When the `close_panel_on_toggle` setting is enabled, also closes the
4123 /// panel when transferring focus back to the center.
4124 pub fn toggle_panel_focus<T: Panel>(
4125 &mut self,
4126 window: &mut Window,
4127 cx: &mut Context<Self>,
4128 ) -> bool {
4129 let mut did_focus_panel = false;
4130 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
4131 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
4132 did_focus_panel
4133 });
4134
4135 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
4136 self.close_panel::<T>(window, cx);
4137 }
4138
4139 telemetry::event!(
4140 "Panel Button Clicked",
4141 name = T::persistent_name(),
4142 toggle_state = did_focus_panel
4143 );
4144
4145 did_focus_panel
4146 }
4147
4148 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4149 if let Some(item) = self.active_item(cx) {
4150 item.item_focus_handle(cx).focus(window, cx);
4151 } else {
4152 log::error!("Could not find a focus target when switching focus to the center panes",);
4153 }
4154 }
4155
4156 pub fn activate_panel_for_proto_id(
4157 &mut self,
4158 panel_id: PanelId,
4159 window: &mut Window,
4160 cx: &mut Context<Self>,
4161 ) -> Option<Arc<dyn PanelHandle>> {
4162 let mut panel = None;
4163 for dock in self.all_docks() {
4164 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
4165 panel = dock.update(cx, |dock, cx| {
4166 dock.activate_panel(panel_index, window, cx);
4167 dock.set_open(true, window, cx);
4168 dock.active_panel().cloned()
4169 });
4170 break;
4171 }
4172 }
4173
4174 if panel.is_some() {
4175 cx.notify();
4176 self.serialize_workspace(window, cx);
4177 }
4178
4179 panel
4180 }
4181
4182 /// Focus or unfocus the given panel type, depending on the given callback.
4183 fn focus_or_unfocus_panel<T: Panel>(
4184 &mut self,
4185 window: &mut Window,
4186 cx: &mut Context<Self>,
4187 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
4188 ) -> Option<Arc<dyn PanelHandle>> {
4189 let mut result_panel = None;
4190 let mut serialize = false;
4191 for dock in self.all_docks() {
4192 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4193 let mut focus_center = false;
4194 let panel = dock.update(cx, |dock, cx| {
4195 dock.activate_panel(panel_index, window, cx);
4196
4197 let panel = dock.active_panel().cloned();
4198 if let Some(panel) = panel.as_ref() {
4199 if should_focus(&**panel, window, cx) {
4200 dock.set_open(true, window, cx);
4201 panel.panel_focus_handle(cx).focus(window, cx);
4202 } else {
4203 focus_center = true;
4204 }
4205 }
4206 panel
4207 });
4208
4209 if focus_center {
4210 self.active_pane
4211 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4212 }
4213
4214 result_panel = panel;
4215 serialize = true;
4216 break;
4217 }
4218 }
4219
4220 if serialize {
4221 self.serialize_workspace(window, cx);
4222 }
4223
4224 cx.notify();
4225 result_panel
4226 }
4227
4228 /// Open the panel of the given type
4229 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4230 for dock in self.all_docks() {
4231 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4232 dock.update(cx, |dock, cx| {
4233 dock.activate_panel(panel_index, window, cx);
4234 dock.set_open(true, window, cx);
4235 });
4236 }
4237 }
4238 }
4239
4240 /// Open the panel of the given type, dismissing any zoomed items that
4241 /// would obscure it (e.g. a zoomed terminal).
4242 pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4243 let dock_position = self.all_docks().iter().find_map(|dock| {
4244 let dock = dock.read(cx);
4245 dock.panel_index_for_type::<T>().map(|_| dock.position())
4246 });
4247 self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
4248 self.open_panel::<T>(window, cx);
4249 }
4250
4251 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
4252 for dock in self.all_docks().iter() {
4253 dock.update(cx, |dock, cx| {
4254 if dock.panel::<T>().is_some() {
4255 dock.set_open(false, window, cx)
4256 }
4257 })
4258 }
4259 }
4260
4261 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
4262 self.all_docks()
4263 .iter()
4264 .find_map(|dock| dock.read(cx).panel::<T>())
4265 }
4266
4267 fn dismiss_zoomed_items_to_reveal(
4268 &mut self,
4269 dock_to_reveal: Option<DockPosition>,
4270 window: &mut Window,
4271 cx: &mut Context<Self>,
4272 ) {
4273 // If a center pane is zoomed, unzoom it.
4274 for pane in &self.panes {
4275 if pane != &self.active_pane || dock_to_reveal.is_some() {
4276 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4277 }
4278 }
4279
4280 // If another dock is zoomed, hide it.
4281 let mut focus_center = false;
4282 for dock in self.all_docks() {
4283 dock.update(cx, |dock, cx| {
4284 if Some(dock.position()) != dock_to_reveal
4285 && let Some(panel) = dock.active_panel()
4286 && panel.is_zoomed(window, cx)
4287 {
4288 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
4289 dock.set_open(false, window, cx);
4290 }
4291 });
4292 }
4293
4294 if focus_center {
4295 self.active_pane
4296 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4297 }
4298
4299 if self.zoomed_position != dock_to_reveal {
4300 self.zoomed = None;
4301 self.zoomed_position = None;
4302 cx.emit(Event::ZoomChanged);
4303 }
4304
4305 cx.notify();
4306 }
4307
4308 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4309 let pane = cx.new(|cx| {
4310 let mut pane = Pane::new(
4311 self.weak_handle(),
4312 self.project.clone(),
4313 self.pane_history_timestamp.clone(),
4314 None,
4315 NewFile.boxed_clone(),
4316 true,
4317 window,
4318 cx,
4319 );
4320 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4321 pane
4322 });
4323 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4324 .detach();
4325 self.panes.push(pane.clone());
4326
4327 window.focus(&pane.focus_handle(cx), cx);
4328
4329 cx.emit(Event::PaneAdded(pane.clone()));
4330 pane
4331 }
4332
4333 pub fn add_item_to_center(
4334 &mut self,
4335 item: Box<dyn ItemHandle>,
4336 window: &mut Window,
4337 cx: &mut Context<Self>,
4338 ) -> bool {
4339 if let Some(center_pane) = self.last_active_center_pane.clone() {
4340 if let Some(center_pane) = center_pane.upgrade() {
4341 center_pane.update(cx, |pane, cx| {
4342 pane.add_item(item, true, true, None, window, cx)
4343 });
4344 true
4345 } else {
4346 false
4347 }
4348 } else {
4349 false
4350 }
4351 }
4352
4353 pub fn add_item_to_active_pane(
4354 &mut self,
4355 item: Box<dyn ItemHandle>,
4356 destination_index: Option<usize>,
4357 focus_item: bool,
4358 window: &mut Window,
4359 cx: &mut App,
4360 ) {
4361 self.add_item(
4362 self.active_pane.clone(),
4363 item,
4364 destination_index,
4365 false,
4366 focus_item,
4367 window,
4368 cx,
4369 )
4370 }
4371
4372 pub fn add_item(
4373 &mut self,
4374 pane: Entity<Pane>,
4375 item: Box<dyn ItemHandle>,
4376 destination_index: Option<usize>,
4377 activate_pane: bool,
4378 focus_item: bool,
4379 window: &mut Window,
4380 cx: &mut App,
4381 ) {
4382 pane.update(cx, |pane, cx| {
4383 pane.add_item(
4384 item,
4385 activate_pane,
4386 focus_item,
4387 destination_index,
4388 window,
4389 cx,
4390 )
4391 });
4392 }
4393
4394 pub fn split_item(
4395 &mut self,
4396 split_direction: SplitDirection,
4397 item: Box<dyn ItemHandle>,
4398 window: &mut Window,
4399 cx: &mut Context<Self>,
4400 ) {
4401 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4402 self.add_item(new_pane, item, None, true, true, window, cx);
4403 }
4404
4405 pub fn open_abs_path(
4406 &mut self,
4407 abs_path: PathBuf,
4408 options: OpenOptions,
4409 window: &mut Window,
4410 cx: &mut Context<Self>,
4411 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4412 cx.spawn_in(window, async move |workspace, cx| {
4413 let open_paths_task_result = workspace
4414 .update_in(cx, |workspace, window, cx| {
4415 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4416 })
4417 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4418 .await;
4419 anyhow::ensure!(
4420 open_paths_task_result.len() == 1,
4421 "open abs path {abs_path:?} task returned incorrect number of results"
4422 );
4423 match open_paths_task_result
4424 .into_iter()
4425 .next()
4426 .expect("ensured single task result")
4427 {
4428 Some(open_result) => {
4429 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4430 }
4431 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4432 }
4433 })
4434 }
4435
4436 pub fn split_abs_path(
4437 &mut self,
4438 abs_path: PathBuf,
4439 visible: bool,
4440 window: &mut Window,
4441 cx: &mut Context<Self>,
4442 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4443 let project_path_task =
4444 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4445 cx.spawn_in(window, async move |this, cx| {
4446 let (_, path) = project_path_task.await?;
4447 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4448 .await
4449 })
4450 }
4451
4452 pub fn open_path(
4453 &mut self,
4454 path: impl Into<ProjectPath>,
4455 pane: Option<WeakEntity<Pane>>,
4456 focus_item: bool,
4457 window: &mut Window,
4458 cx: &mut App,
4459 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4460 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4461 }
4462
4463 pub fn open_path_preview(
4464 &mut self,
4465 path: impl Into<ProjectPath>,
4466 pane: Option<WeakEntity<Pane>>,
4467 focus_item: bool,
4468 allow_preview: bool,
4469 activate: bool,
4470 window: &mut Window,
4471 cx: &mut App,
4472 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4473 let pane = pane.unwrap_or_else(|| {
4474 self.last_active_center_pane.clone().unwrap_or_else(|| {
4475 self.panes
4476 .first()
4477 .expect("There must be an active pane")
4478 .downgrade()
4479 })
4480 });
4481
4482 let project_path = path.into();
4483 let task = self.load_path(project_path.clone(), window, cx);
4484 window.spawn(cx, async move |cx| {
4485 let (project_entry_id, build_item) = task.await?;
4486
4487 pane.update_in(cx, |pane, window, cx| {
4488 pane.open_item(
4489 project_entry_id,
4490 project_path,
4491 focus_item,
4492 allow_preview,
4493 activate,
4494 None,
4495 window,
4496 cx,
4497 build_item,
4498 )
4499 })
4500 })
4501 }
4502
4503 pub fn split_path(
4504 &mut self,
4505 path: impl Into<ProjectPath>,
4506 window: &mut Window,
4507 cx: &mut Context<Self>,
4508 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4509 self.split_path_preview(path, false, None, window, cx)
4510 }
4511
4512 pub fn split_path_preview(
4513 &mut self,
4514 path: impl Into<ProjectPath>,
4515 allow_preview: bool,
4516 split_direction: Option<SplitDirection>,
4517 window: &mut Window,
4518 cx: &mut Context<Self>,
4519 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4520 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4521 self.panes
4522 .first()
4523 .expect("There must be an active pane")
4524 .downgrade()
4525 });
4526
4527 if let Member::Pane(center_pane) = &self.center.root
4528 && center_pane.read(cx).items_len() == 0
4529 {
4530 return self.open_path(path, Some(pane), true, window, cx);
4531 }
4532
4533 let project_path = path.into();
4534 let task = self.load_path(project_path.clone(), window, cx);
4535 cx.spawn_in(window, async move |this, cx| {
4536 let (project_entry_id, build_item) = task.await?;
4537 this.update_in(cx, move |this, window, cx| -> Option<_> {
4538 let pane = pane.upgrade()?;
4539 let new_pane = this.split_pane(
4540 pane,
4541 split_direction.unwrap_or(SplitDirection::Right),
4542 window,
4543 cx,
4544 );
4545 new_pane.update(cx, |new_pane, cx| {
4546 Some(new_pane.open_item(
4547 project_entry_id,
4548 project_path,
4549 true,
4550 allow_preview,
4551 true,
4552 None,
4553 window,
4554 cx,
4555 build_item,
4556 ))
4557 })
4558 })
4559 .map(|option| option.context("pane was dropped"))?
4560 })
4561 }
4562
4563 fn load_path(
4564 &mut self,
4565 path: ProjectPath,
4566 window: &mut Window,
4567 cx: &mut App,
4568 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4569 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4570 registry.open_path(self.project(), &path, window, cx)
4571 }
4572
4573 pub fn find_project_item<T>(
4574 &self,
4575 pane: &Entity<Pane>,
4576 project_item: &Entity<T::Item>,
4577 cx: &App,
4578 ) -> Option<Entity<T>>
4579 where
4580 T: ProjectItem,
4581 {
4582 use project::ProjectItem as _;
4583 let project_item = project_item.read(cx);
4584 let entry_id = project_item.entry_id(cx);
4585 let project_path = project_item.project_path(cx);
4586
4587 let mut item = None;
4588 if let Some(entry_id) = entry_id {
4589 item = pane.read(cx).item_for_entry(entry_id, cx);
4590 }
4591 if item.is_none()
4592 && let Some(project_path) = project_path
4593 {
4594 item = pane.read(cx).item_for_path(project_path, cx);
4595 }
4596
4597 item.and_then(|item| item.downcast::<T>())
4598 }
4599
4600 pub fn is_project_item_open<T>(
4601 &self,
4602 pane: &Entity<Pane>,
4603 project_item: &Entity<T::Item>,
4604 cx: &App,
4605 ) -> bool
4606 where
4607 T: ProjectItem,
4608 {
4609 self.find_project_item::<T>(pane, project_item, cx)
4610 .is_some()
4611 }
4612
4613 pub fn open_project_item<T>(
4614 &mut self,
4615 pane: Entity<Pane>,
4616 project_item: Entity<T::Item>,
4617 activate_pane: bool,
4618 focus_item: bool,
4619 keep_old_preview: bool,
4620 allow_new_preview: bool,
4621 window: &mut Window,
4622 cx: &mut Context<Self>,
4623 ) -> Entity<T>
4624 where
4625 T: ProjectItem,
4626 {
4627 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4628
4629 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4630 if !keep_old_preview
4631 && let Some(old_id) = old_item_id
4632 && old_id != item.item_id()
4633 {
4634 // switching to a different item, so unpreview old active item
4635 pane.update(cx, |pane, _| {
4636 pane.unpreview_item_if_preview(old_id);
4637 });
4638 }
4639
4640 self.activate_item(&item, activate_pane, focus_item, window, cx);
4641 if !allow_new_preview {
4642 pane.update(cx, |pane, _| {
4643 pane.unpreview_item_if_preview(item.item_id());
4644 });
4645 }
4646 return item;
4647 }
4648
4649 let item = pane.update(cx, |pane, cx| {
4650 cx.new(|cx| {
4651 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4652 })
4653 });
4654 let mut destination_index = None;
4655 pane.update(cx, |pane, cx| {
4656 if !keep_old_preview && let Some(old_id) = old_item_id {
4657 pane.unpreview_item_if_preview(old_id);
4658 }
4659 if allow_new_preview {
4660 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4661 }
4662 });
4663
4664 self.add_item(
4665 pane,
4666 Box::new(item.clone()),
4667 destination_index,
4668 activate_pane,
4669 focus_item,
4670 window,
4671 cx,
4672 );
4673 item
4674 }
4675
4676 pub fn open_shared_screen(
4677 &mut self,
4678 peer_id: PeerId,
4679 window: &mut Window,
4680 cx: &mut Context<Self>,
4681 ) {
4682 if let Some(shared_screen) =
4683 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4684 {
4685 self.active_pane.update(cx, |pane, cx| {
4686 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4687 });
4688 }
4689 }
4690
4691 pub fn activate_item(
4692 &mut self,
4693 item: &dyn ItemHandle,
4694 activate_pane: bool,
4695 focus_item: bool,
4696 window: &mut Window,
4697 cx: &mut App,
4698 ) -> bool {
4699 let result = self.panes.iter().find_map(|pane| {
4700 pane.read(cx)
4701 .index_for_item(item)
4702 .map(|ix| (pane.clone(), ix))
4703 });
4704 if let Some((pane, ix)) = result {
4705 pane.update(cx, |pane, cx| {
4706 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4707 });
4708 true
4709 } else {
4710 false
4711 }
4712 }
4713
4714 fn activate_pane_at_index(
4715 &mut self,
4716 action: &ActivatePane,
4717 window: &mut Window,
4718 cx: &mut Context<Self>,
4719 ) {
4720 let panes = self.center.panes();
4721 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4722 window.focus(&pane.focus_handle(cx), cx);
4723 } else {
4724 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4725 .detach();
4726 }
4727 }
4728
4729 fn move_item_to_pane_at_index(
4730 &mut self,
4731 action: &MoveItemToPane,
4732 window: &mut Window,
4733 cx: &mut Context<Self>,
4734 ) {
4735 let panes = self.center.panes();
4736 let destination = match panes.get(action.destination) {
4737 Some(&destination) => destination.clone(),
4738 None => {
4739 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4740 return;
4741 }
4742 let direction = SplitDirection::Right;
4743 let split_off_pane = self
4744 .find_pane_in_direction(direction, cx)
4745 .unwrap_or_else(|| self.active_pane.clone());
4746 let new_pane = self.add_pane(window, cx);
4747 self.center.split(&split_off_pane, &new_pane, direction, cx);
4748 new_pane
4749 }
4750 };
4751
4752 if action.clone {
4753 if self
4754 .active_pane
4755 .read(cx)
4756 .active_item()
4757 .is_some_and(|item| item.can_split(cx))
4758 {
4759 clone_active_item(
4760 self.database_id(),
4761 &self.active_pane,
4762 &destination,
4763 action.focus,
4764 window,
4765 cx,
4766 );
4767 return;
4768 }
4769 }
4770 move_active_item(
4771 &self.active_pane,
4772 &destination,
4773 action.focus,
4774 true,
4775 window,
4776 cx,
4777 )
4778 }
4779
4780 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4781 let panes = self.center.panes();
4782 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4783 let next_ix = (ix + 1) % panes.len();
4784 let next_pane = panes[next_ix].clone();
4785 window.focus(&next_pane.focus_handle(cx), cx);
4786 }
4787 }
4788
4789 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4790 let panes = self.center.panes();
4791 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4792 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4793 let prev_pane = panes[prev_ix].clone();
4794 window.focus(&prev_pane.focus_handle(cx), cx);
4795 }
4796 }
4797
4798 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4799 let last_pane = self.center.last_pane();
4800 window.focus(&last_pane.focus_handle(cx), cx);
4801 }
4802
4803 pub fn activate_pane_in_direction(
4804 &mut self,
4805 direction: SplitDirection,
4806 window: &mut Window,
4807 cx: &mut App,
4808 ) {
4809 use ActivateInDirectionTarget as Target;
4810 enum Origin {
4811 Sidebar,
4812 LeftDock,
4813 RightDock,
4814 BottomDock,
4815 Center,
4816 }
4817
4818 let origin: Origin = if self
4819 .sidebar_focus_handle
4820 .as_ref()
4821 .is_some_and(|h| h.contains_focused(window, cx))
4822 {
4823 Origin::Sidebar
4824 } else {
4825 [
4826 (&self.left_dock, Origin::LeftDock),
4827 (&self.right_dock, Origin::RightDock),
4828 (&self.bottom_dock, Origin::BottomDock),
4829 ]
4830 .into_iter()
4831 .find_map(|(dock, origin)| {
4832 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4833 Some(origin)
4834 } else {
4835 None
4836 }
4837 })
4838 .unwrap_or(Origin::Center)
4839 };
4840
4841 let get_last_active_pane = || {
4842 let pane = self
4843 .last_active_center_pane
4844 .clone()
4845 .unwrap_or_else(|| {
4846 self.panes
4847 .first()
4848 .expect("There must be an active pane")
4849 .downgrade()
4850 })
4851 .upgrade()?;
4852 (pane.read(cx).items_len() != 0).then_some(pane)
4853 };
4854
4855 let try_dock =
4856 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4857
4858 let sidebar_target = self
4859 .sidebar_focus_handle
4860 .as_ref()
4861 .map(|h| Target::Sidebar(h.clone()));
4862
4863 let target = match (origin, direction) {
4864 // From the sidebar, only Right navigates into the workspace.
4865 (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
4866 .or_else(|| get_last_active_pane().map(Target::Pane))
4867 .or_else(|| try_dock(&self.bottom_dock))
4868 .or_else(|| try_dock(&self.right_dock)),
4869
4870 (Origin::Sidebar, _) => None,
4871
4872 // We're in the center, so we first try to go to a different pane,
4873 // otherwise try to go to a dock.
4874 (Origin::Center, direction) => {
4875 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4876 Some(Target::Pane(pane))
4877 } else {
4878 match direction {
4879 SplitDirection::Up => None,
4880 SplitDirection::Down => try_dock(&self.bottom_dock),
4881 SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
4882 SplitDirection::Right => try_dock(&self.right_dock),
4883 }
4884 }
4885 }
4886
4887 (Origin::LeftDock, SplitDirection::Right) => {
4888 if let Some(last_active_pane) = get_last_active_pane() {
4889 Some(Target::Pane(last_active_pane))
4890 } else {
4891 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4892 }
4893 }
4894
4895 (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
4896
4897 (Origin::LeftDock, SplitDirection::Down)
4898 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4899
4900 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4901 (Origin::BottomDock, SplitDirection::Left) => {
4902 try_dock(&self.left_dock).or(sidebar_target)
4903 }
4904 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4905
4906 (Origin::RightDock, SplitDirection::Left) => {
4907 if let Some(last_active_pane) = get_last_active_pane() {
4908 Some(Target::Pane(last_active_pane))
4909 } else {
4910 try_dock(&self.bottom_dock)
4911 .or_else(|| try_dock(&self.left_dock))
4912 .or(sidebar_target)
4913 }
4914 }
4915
4916 _ => None,
4917 };
4918
4919 match target {
4920 Some(ActivateInDirectionTarget::Pane(pane)) => {
4921 let pane = pane.read(cx);
4922 if let Some(item) = pane.active_item() {
4923 item.item_focus_handle(cx).focus(window, cx);
4924 } else {
4925 log::error!(
4926 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4927 );
4928 }
4929 }
4930 Some(ActivateInDirectionTarget::Dock(dock)) => {
4931 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4932 window.defer(cx, move |window, cx| {
4933 let dock = dock.read(cx);
4934 if let Some(panel) = dock.active_panel() {
4935 panel.panel_focus_handle(cx).focus(window, cx);
4936 } else {
4937 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4938 }
4939 })
4940 }
4941 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4942 focus_handle.focus(window, cx);
4943 }
4944 None => {}
4945 }
4946 }
4947
4948 pub fn move_item_to_pane_in_direction(
4949 &mut self,
4950 action: &MoveItemToPaneInDirection,
4951 window: &mut Window,
4952 cx: &mut Context<Self>,
4953 ) {
4954 let destination = match self.find_pane_in_direction(action.direction, cx) {
4955 Some(destination) => destination,
4956 None => {
4957 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4958 return;
4959 }
4960 let new_pane = self.add_pane(window, cx);
4961 self.center
4962 .split(&self.active_pane, &new_pane, action.direction, cx);
4963 new_pane
4964 }
4965 };
4966
4967 if action.clone {
4968 if self
4969 .active_pane
4970 .read(cx)
4971 .active_item()
4972 .is_some_and(|item| item.can_split(cx))
4973 {
4974 clone_active_item(
4975 self.database_id(),
4976 &self.active_pane,
4977 &destination,
4978 action.focus,
4979 window,
4980 cx,
4981 );
4982 return;
4983 }
4984 }
4985 move_active_item(
4986 &self.active_pane,
4987 &destination,
4988 action.focus,
4989 true,
4990 window,
4991 cx,
4992 );
4993 }
4994
4995 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4996 self.center.bounding_box_for_pane(pane)
4997 }
4998
4999 pub fn find_pane_in_direction(
5000 &mut self,
5001 direction: SplitDirection,
5002 cx: &App,
5003 ) -> Option<Entity<Pane>> {
5004 self.center
5005 .find_pane_in_direction(&self.active_pane, direction, cx)
5006 .cloned()
5007 }
5008
5009 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
5010 if let Some(to) = self.find_pane_in_direction(direction, cx) {
5011 self.center.swap(&self.active_pane, &to, cx);
5012 cx.notify();
5013 }
5014 }
5015
5016 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
5017 if self
5018 .center
5019 .move_to_border(&self.active_pane, direction, cx)
5020 .unwrap()
5021 {
5022 cx.notify();
5023 }
5024 }
5025
5026 pub fn resize_pane(
5027 &mut self,
5028 axis: gpui::Axis,
5029 amount: Pixels,
5030 window: &mut Window,
5031 cx: &mut Context<Self>,
5032 ) {
5033 let docks = self.all_docks();
5034 let active_dock = docks
5035 .into_iter()
5036 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
5037
5038 if let Some(dock_entity) = active_dock {
5039 let dock = dock_entity.read(cx);
5040 let Some(panel_size) = self.dock_size(&dock, window, cx) else {
5041 return;
5042 };
5043 match dock.position() {
5044 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
5045 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
5046 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
5047 }
5048 } else {
5049 self.center
5050 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
5051 }
5052 cx.notify();
5053 }
5054
5055 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
5056 self.center.reset_pane_sizes(cx);
5057 cx.notify();
5058 }
5059
5060 fn handle_pane_focused(
5061 &mut self,
5062 pane: Entity<Pane>,
5063 window: &mut Window,
5064 cx: &mut Context<Self>,
5065 ) {
5066 // This is explicitly hoisted out of the following check for pane identity as
5067 // terminal panel panes are not registered as a center panes.
5068 self.status_bar.update(cx, |status_bar, cx| {
5069 status_bar.set_active_pane(&pane, window, cx);
5070 });
5071 if self.active_pane != pane {
5072 self.set_active_pane(&pane, window, cx);
5073 }
5074
5075 if self.last_active_center_pane.is_none() {
5076 self.last_active_center_pane = Some(pane.downgrade());
5077 }
5078
5079 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
5080 // This prevents the dock from closing when focus events fire during window activation.
5081 // We also preserve any dock whose active panel itself has focus — this covers
5082 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
5083 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
5084 let dock_read = dock.read(cx);
5085 if let Some(panel) = dock_read.active_panel() {
5086 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
5087 || panel.panel_focus_handle(cx).contains_focused(window, cx)
5088 {
5089 return Some(dock_read.position());
5090 }
5091 }
5092 None
5093 });
5094
5095 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
5096 if pane.read(cx).is_zoomed() {
5097 self.zoomed = Some(pane.downgrade().into());
5098 } else {
5099 self.zoomed = None;
5100 }
5101 self.zoomed_position = None;
5102 cx.emit(Event::ZoomChanged);
5103 self.update_active_view_for_followers(window, cx);
5104 pane.update(cx, |pane, _| {
5105 pane.track_alternate_file_items();
5106 });
5107
5108 cx.notify();
5109 }
5110
5111 fn set_active_pane(
5112 &mut self,
5113 pane: &Entity<Pane>,
5114 window: &mut Window,
5115 cx: &mut Context<Self>,
5116 ) {
5117 self.active_pane = pane.clone();
5118 self.active_item_path_changed(true, window, cx);
5119 self.last_active_center_pane = Some(pane.downgrade());
5120 }
5121
5122 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5123 self.update_active_view_for_followers(window, cx);
5124 }
5125
5126 fn handle_pane_event(
5127 &mut self,
5128 pane: &Entity<Pane>,
5129 event: &pane::Event,
5130 window: &mut Window,
5131 cx: &mut Context<Self>,
5132 ) {
5133 let mut serialize_workspace = true;
5134 match event {
5135 pane::Event::AddItem { item } => {
5136 item.added_to_pane(self, pane.clone(), window, cx);
5137 cx.emit(Event::ItemAdded {
5138 item: item.boxed_clone(),
5139 });
5140 }
5141 pane::Event::Split { direction, mode } => {
5142 match mode {
5143 SplitMode::ClonePane => {
5144 self.split_and_clone(pane.clone(), *direction, window, cx)
5145 .detach();
5146 }
5147 SplitMode::EmptyPane => {
5148 self.split_pane(pane.clone(), *direction, window, cx);
5149 }
5150 SplitMode::MovePane => {
5151 self.split_and_move(pane.clone(), *direction, window, cx);
5152 }
5153 };
5154 }
5155 pane::Event::JoinIntoNext => {
5156 self.join_pane_into_next(pane.clone(), window, cx);
5157 }
5158 pane::Event::JoinAll => {
5159 self.join_all_panes(window, cx);
5160 }
5161 pane::Event::Remove { focus_on_pane } => {
5162 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
5163 }
5164 pane::Event::ActivateItem {
5165 local,
5166 focus_changed,
5167 } => {
5168 window.invalidate_character_coordinates();
5169
5170 pane.update(cx, |pane, _| {
5171 pane.track_alternate_file_items();
5172 });
5173 if *local {
5174 self.unfollow_in_pane(pane, window, cx);
5175 }
5176 serialize_workspace = *focus_changed || pane != self.active_pane();
5177 if pane == self.active_pane() {
5178 self.active_item_path_changed(*focus_changed, window, cx);
5179 self.update_active_view_for_followers(window, cx);
5180 } else if *local {
5181 self.set_active_pane(pane, window, cx);
5182 }
5183 }
5184 pane::Event::UserSavedItem { item, save_intent } => {
5185 cx.emit(Event::UserSavedItem {
5186 pane: pane.downgrade(),
5187 item: item.boxed_clone(),
5188 save_intent: *save_intent,
5189 });
5190 serialize_workspace = false;
5191 }
5192 pane::Event::ChangeItemTitle => {
5193 if *pane == self.active_pane {
5194 self.active_item_path_changed(false, window, cx);
5195 }
5196 serialize_workspace = false;
5197 }
5198 pane::Event::RemovedItem { item } => {
5199 cx.emit(Event::ActiveItemChanged);
5200 self.update_window_edited(window, cx);
5201 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
5202 && entry.get().entity_id() == pane.entity_id()
5203 {
5204 entry.remove();
5205 }
5206 cx.emit(Event::ItemRemoved {
5207 item_id: item.item_id(),
5208 });
5209 }
5210 pane::Event::Focus => {
5211 window.invalidate_character_coordinates();
5212 self.handle_pane_focused(pane.clone(), window, cx);
5213 }
5214 pane::Event::ZoomIn => {
5215 if *pane == self.active_pane {
5216 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
5217 if pane.read(cx).has_focus(window, cx) {
5218 self.zoomed = Some(pane.downgrade().into());
5219 self.zoomed_position = None;
5220 cx.emit(Event::ZoomChanged);
5221 }
5222 cx.notify();
5223 }
5224 }
5225 pane::Event::ZoomOut => {
5226 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
5227 if self.zoomed_position.is_none() {
5228 self.zoomed = None;
5229 cx.emit(Event::ZoomChanged);
5230 }
5231 cx.notify();
5232 }
5233 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
5234 }
5235
5236 if serialize_workspace {
5237 self.serialize_workspace(window, cx);
5238 }
5239 }
5240
5241 pub fn unfollow_in_pane(
5242 &mut self,
5243 pane: &Entity<Pane>,
5244 window: &mut Window,
5245 cx: &mut Context<Workspace>,
5246 ) -> Option<CollaboratorId> {
5247 let leader_id = self.leader_for_pane(pane)?;
5248 self.unfollow(leader_id, window, cx);
5249 Some(leader_id)
5250 }
5251
5252 pub fn split_pane(
5253 &mut self,
5254 pane_to_split: Entity<Pane>,
5255 split_direction: SplitDirection,
5256 window: &mut Window,
5257 cx: &mut Context<Self>,
5258 ) -> Entity<Pane> {
5259 let new_pane = self.add_pane(window, cx);
5260 self.center
5261 .split(&pane_to_split, &new_pane, split_direction, cx);
5262 cx.notify();
5263 new_pane
5264 }
5265
5266 pub fn split_and_move(
5267 &mut self,
5268 pane: Entity<Pane>,
5269 direction: SplitDirection,
5270 window: &mut Window,
5271 cx: &mut Context<Self>,
5272 ) {
5273 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
5274 return;
5275 };
5276 let new_pane = self.add_pane(window, cx);
5277 new_pane.update(cx, |pane, cx| {
5278 pane.add_item(item, true, true, None, window, cx)
5279 });
5280 self.center.split(&pane, &new_pane, direction, cx);
5281 cx.notify();
5282 }
5283
5284 pub fn split_and_clone(
5285 &mut self,
5286 pane: Entity<Pane>,
5287 direction: SplitDirection,
5288 window: &mut Window,
5289 cx: &mut Context<Self>,
5290 ) -> Task<Option<Entity<Pane>>> {
5291 let Some(item) = pane.read(cx).active_item() else {
5292 return Task::ready(None);
5293 };
5294 if !item.can_split(cx) {
5295 return Task::ready(None);
5296 }
5297 let task = item.clone_on_split(self.database_id(), window, cx);
5298 cx.spawn_in(window, async move |this, cx| {
5299 if let Some(clone) = task.await {
5300 this.update_in(cx, |this, window, cx| {
5301 let new_pane = this.add_pane(window, cx);
5302 let nav_history = pane.read(cx).fork_nav_history();
5303 new_pane.update(cx, |pane, cx| {
5304 pane.set_nav_history(nav_history, cx);
5305 pane.add_item(clone, true, true, None, window, cx)
5306 });
5307 this.center.split(&pane, &new_pane, direction, cx);
5308 cx.notify();
5309 new_pane
5310 })
5311 .ok()
5312 } else {
5313 None
5314 }
5315 })
5316 }
5317
5318 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5319 let active_item = self.active_pane.read(cx).active_item();
5320 for pane in &self.panes {
5321 join_pane_into_active(&self.active_pane, pane, window, cx);
5322 }
5323 if let Some(active_item) = active_item {
5324 self.activate_item(active_item.as_ref(), true, true, window, cx);
5325 }
5326 cx.notify();
5327 }
5328
5329 pub fn join_pane_into_next(
5330 &mut self,
5331 pane: Entity<Pane>,
5332 window: &mut Window,
5333 cx: &mut Context<Self>,
5334 ) {
5335 let next_pane = self
5336 .find_pane_in_direction(SplitDirection::Right, cx)
5337 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5338 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5339 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5340 let Some(next_pane) = next_pane else {
5341 return;
5342 };
5343 move_all_items(&pane, &next_pane, window, cx);
5344 cx.notify();
5345 }
5346
5347 fn remove_pane(
5348 &mut self,
5349 pane: Entity<Pane>,
5350 focus_on: Option<Entity<Pane>>,
5351 window: &mut Window,
5352 cx: &mut Context<Self>,
5353 ) {
5354 if self.center.remove(&pane, cx).unwrap() {
5355 self.force_remove_pane(&pane, &focus_on, window, cx);
5356 self.unfollow_in_pane(&pane, window, cx);
5357 self.last_leaders_by_pane.remove(&pane.downgrade());
5358 for removed_item in pane.read(cx).items() {
5359 self.panes_by_item.remove(&removed_item.item_id());
5360 }
5361
5362 cx.notify();
5363 } else {
5364 self.active_item_path_changed(true, window, cx);
5365 }
5366 cx.emit(Event::PaneRemoved);
5367 }
5368
5369 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5370 &mut self.panes
5371 }
5372
5373 pub fn panes(&self) -> &[Entity<Pane>] {
5374 &self.panes
5375 }
5376
5377 pub fn active_pane(&self) -> &Entity<Pane> {
5378 &self.active_pane
5379 }
5380
5381 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5382 for dock in self.all_docks() {
5383 if dock.focus_handle(cx).contains_focused(window, cx)
5384 && let Some(pane) = dock
5385 .read(cx)
5386 .active_panel()
5387 .and_then(|panel| panel.pane(cx))
5388 {
5389 return pane;
5390 }
5391 }
5392 self.active_pane().clone()
5393 }
5394
5395 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5396 self.find_pane_in_direction(SplitDirection::Right, cx)
5397 .unwrap_or_else(|| {
5398 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5399 })
5400 }
5401
5402 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5403 self.pane_for_item_id(handle.item_id())
5404 }
5405
5406 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5407 let weak_pane = self.panes_by_item.get(&item_id)?;
5408 weak_pane.upgrade()
5409 }
5410
5411 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5412 self.panes
5413 .iter()
5414 .find(|pane| pane.entity_id() == entity_id)
5415 .cloned()
5416 }
5417
5418 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5419 self.follower_states.retain(|leader_id, state| {
5420 if *leader_id == CollaboratorId::PeerId(peer_id) {
5421 for item in state.items_by_leader_view_id.values() {
5422 item.view.set_leader_id(None, window, cx);
5423 }
5424 false
5425 } else {
5426 true
5427 }
5428 });
5429 cx.notify();
5430 }
5431
5432 pub fn start_following(
5433 &mut self,
5434 leader_id: impl Into<CollaboratorId>,
5435 window: &mut Window,
5436 cx: &mut Context<Self>,
5437 ) -> Option<Task<Result<()>>> {
5438 let leader_id = leader_id.into();
5439 let pane = self.active_pane().clone();
5440
5441 self.last_leaders_by_pane
5442 .insert(pane.downgrade(), leader_id);
5443 self.unfollow(leader_id, window, cx);
5444 self.unfollow_in_pane(&pane, window, cx);
5445 self.follower_states.insert(
5446 leader_id,
5447 FollowerState {
5448 center_pane: pane.clone(),
5449 dock_pane: None,
5450 active_view_id: None,
5451 items_by_leader_view_id: Default::default(),
5452 },
5453 );
5454 cx.notify();
5455
5456 match leader_id {
5457 CollaboratorId::PeerId(leader_peer_id) => {
5458 let room_id = self.active_call()?.room_id(cx)?;
5459 let project_id = self.project.read(cx).remote_id();
5460 let request = self.app_state.client.request(proto::Follow {
5461 room_id,
5462 project_id,
5463 leader_id: Some(leader_peer_id),
5464 });
5465
5466 Some(cx.spawn_in(window, async move |this, cx| {
5467 let response = request.await?;
5468 this.update(cx, |this, _| {
5469 let state = this
5470 .follower_states
5471 .get_mut(&leader_id)
5472 .context("following interrupted")?;
5473 state.active_view_id = response
5474 .active_view
5475 .as_ref()
5476 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5477 anyhow::Ok(())
5478 })??;
5479 if let Some(view) = response.active_view {
5480 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5481 }
5482 this.update_in(cx, |this, window, cx| {
5483 this.leader_updated(leader_id, window, cx)
5484 })?;
5485 Ok(())
5486 }))
5487 }
5488 CollaboratorId::Agent => {
5489 self.leader_updated(leader_id, window, cx)?;
5490 Some(Task::ready(Ok(())))
5491 }
5492 }
5493 }
5494
5495 pub fn follow_next_collaborator(
5496 &mut self,
5497 _: &FollowNextCollaborator,
5498 window: &mut Window,
5499 cx: &mut Context<Self>,
5500 ) {
5501 let collaborators = self.project.read(cx).collaborators();
5502 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5503 let mut collaborators = collaborators.keys().copied();
5504 for peer_id in collaborators.by_ref() {
5505 if CollaboratorId::PeerId(peer_id) == leader_id {
5506 break;
5507 }
5508 }
5509 collaborators.next().map(CollaboratorId::PeerId)
5510 } else if let Some(last_leader_id) =
5511 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5512 {
5513 match last_leader_id {
5514 CollaboratorId::PeerId(peer_id) => {
5515 if collaborators.contains_key(peer_id) {
5516 Some(*last_leader_id)
5517 } else {
5518 None
5519 }
5520 }
5521 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5522 }
5523 } else {
5524 None
5525 };
5526
5527 let pane = self.active_pane.clone();
5528 let Some(leader_id) = next_leader_id.or_else(|| {
5529 Some(CollaboratorId::PeerId(
5530 collaborators.keys().copied().next()?,
5531 ))
5532 }) else {
5533 return;
5534 };
5535 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5536 return;
5537 }
5538 if let Some(task) = self.start_following(leader_id, window, cx) {
5539 task.detach_and_log_err(cx)
5540 }
5541 }
5542
5543 pub fn follow(
5544 &mut self,
5545 leader_id: impl Into<CollaboratorId>,
5546 window: &mut Window,
5547 cx: &mut Context<Self>,
5548 ) {
5549 let leader_id = leader_id.into();
5550
5551 if let CollaboratorId::PeerId(peer_id) = leader_id {
5552 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5553 return;
5554 };
5555 let Some(remote_participant) =
5556 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5557 else {
5558 return;
5559 };
5560
5561 let project = self.project.read(cx);
5562
5563 let other_project_id = match remote_participant.location {
5564 ParticipantLocation::External => None,
5565 ParticipantLocation::UnsharedProject => None,
5566 ParticipantLocation::SharedProject { project_id } => {
5567 if Some(project_id) == project.remote_id() {
5568 None
5569 } else {
5570 Some(project_id)
5571 }
5572 }
5573 };
5574
5575 // if they are active in another project, follow there.
5576 if let Some(project_id) = other_project_id {
5577 let app_state = self.app_state.clone();
5578 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5579 .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
5580 Some(format!("{error:#}"))
5581 });
5582 }
5583 }
5584
5585 // if you're already following, find the right pane and focus it.
5586 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5587 window.focus(&follower_state.pane().focus_handle(cx), cx);
5588
5589 return;
5590 }
5591
5592 // Otherwise, follow.
5593 if let Some(task) = self.start_following(leader_id, window, cx) {
5594 task.detach_and_log_err(cx)
5595 }
5596 }
5597
5598 pub fn unfollow(
5599 &mut self,
5600 leader_id: impl Into<CollaboratorId>,
5601 window: &mut Window,
5602 cx: &mut Context<Self>,
5603 ) -> Option<()> {
5604 cx.notify();
5605
5606 let leader_id = leader_id.into();
5607 let state = self.follower_states.remove(&leader_id)?;
5608 for (_, item) in state.items_by_leader_view_id {
5609 item.view.set_leader_id(None, window, cx);
5610 }
5611
5612 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5613 let project_id = self.project.read(cx).remote_id();
5614 let room_id = self.active_call()?.room_id(cx)?;
5615 self.app_state
5616 .client
5617 .send(proto::Unfollow {
5618 room_id,
5619 project_id,
5620 leader_id: Some(leader_peer_id),
5621 })
5622 .log_err();
5623 }
5624
5625 Some(())
5626 }
5627
5628 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5629 self.follower_states.contains_key(&id.into())
5630 }
5631
5632 fn active_item_path_changed(
5633 &mut self,
5634 focus_changed: bool,
5635 window: &mut Window,
5636 cx: &mut Context<Self>,
5637 ) {
5638 cx.emit(Event::ActiveItemChanged);
5639 let active_entry = self.active_project_path(cx);
5640 self.project.update(cx, |project, cx| {
5641 project.set_active_path(active_entry.clone(), cx)
5642 });
5643
5644 if focus_changed && let Some(project_path) = &active_entry {
5645 let git_store_entity = self.project.read(cx).git_store().clone();
5646 git_store_entity.update(cx, |git_store, cx| {
5647 git_store.set_active_repo_for_path(project_path, cx);
5648 });
5649 }
5650
5651 self.update_window_title(window, cx);
5652 }
5653
5654 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5655 let project = self.project().read(cx);
5656 let mut title = String::new();
5657
5658 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5659 let name = {
5660 let settings_location = SettingsLocation {
5661 worktree_id: worktree.read(cx).id(),
5662 path: RelPath::empty(),
5663 };
5664
5665 let settings = WorktreeSettings::get(Some(settings_location), cx);
5666 match &settings.project_name {
5667 Some(name) => name.as_str(),
5668 None => worktree.read(cx).root_name_str(),
5669 }
5670 };
5671 if i > 0 {
5672 title.push_str(", ");
5673 }
5674 title.push_str(name);
5675 }
5676
5677 if title.is_empty() {
5678 title = "empty project".to_string();
5679 }
5680
5681 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5682 let filename = path.path.file_name().or_else(|| {
5683 Some(
5684 project
5685 .worktree_for_id(path.worktree_id, cx)?
5686 .read(cx)
5687 .root_name_str(),
5688 )
5689 });
5690
5691 if let Some(filename) = filename {
5692 title.push_str(" — ");
5693 title.push_str(filename.as_ref());
5694 }
5695 }
5696
5697 if project.is_via_collab() {
5698 title.push_str(" ↙");
5699 } else if project.is_shared() {
5700 title.push_str(" ↗");
5701 }
5702
5703 if let Some(last_title) = self.last_window_title.as_ref()
5704 && &title == last_title
5705 {
5706 return;
5707 }
5708 window.set_window_title(&title);
5709 SystemWindowTabController::update_tab_title(
5710 cx,
5711 window.window_handle().window_id(),
5712 SharedString::from(&title),
5713 );
5714 self.last_window_title = Some(title);
5715 }
5716
5717 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5718 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5719 if is_edited != self.window_edited {
5720 self.window_edited = is_edited;
5721 window.set_window_edited(self.window_edited)
5722 }
5723 }
5724
5725 fn update_item_dirty_state(
5726 &mut self,
5727 item: &dyn ItemHandle,
5728 window: &mut Window,
5729 cx: &mut App,
5730 ) {
5731 let is_dirty = item.is_dirty(cx);
5732 let item_id = item.item_id();
5733 let was_dirty = self.dirty_items.contains_key(&item_id);
5734 if is_dirty == was_dirty {
5735 return;
5736 }
5737 if was_dirty {
5738 self.dirty_items.remove(&item_id);
5739 self.update_window_edited(window, cx);
5740 return;
5741 }
5742
5743 let workspace = self.weak_handle();
5744 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5745 return;
5746 };
5747 let on_release_callback = Box::new(move |cx: &mut App| {
5748 window_handle
5749 .update(cx, |_, window, cx| {
5750 workspace
5751 .update(cx, |workspace, cx| {
5752 workspace.dirty_items.remove(&item_id);
5753 workspace.update_window_edited(window, cx)
5754 })
5755 .ok();
5756 })
5757 .ok();
5758 });
5759
5760 let s = item.on_release(cx, on_release_callback);
5761 self.dirty_items.insert(item_id, s);
5762 self.update_window_edited(window, cx);
5763 }
5764
5765 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5766 if self.notifications.is_empty() {
5767 None
5768 } else {
5769 Some(
5770 div()
5771 .absolute()
5772 .right_3()
5773 .bottom_3()
5774 .w_112()
5775 .h_full()
5776 .flex()
5777 .flex_col()
5778 .justify_end()
5779 .gap_2()
5780 .children(
5781 self.notifications
5782 .iter()
5783 .map(|(_, notification)| notification.clone().into_any()),
5784 ),
5785 )
5786 }
5787 }
5788
5789 // RPC handlers
5790
5791 fn active_view_for_follower(
5792 &self,
5793 follower_project_id: Option<u64>,
5794 window: &mut Window,
5795 cx: &mut Context<Self>,
5796 ) -> Option<proto::View> {
5797 let (item, panel_id) = self.active_item_for_followers(window, cx);
5798 let item = item?;
5799 let leader_id = self
5800 .pane_for(&*item)
5801 .and_then(|pane| self.leader_for_pane(&pane));
5802 let leader_peer_id = match leader_id {
5803 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5804 Some(CollaboratorId::Agent) | None => None,
5805 };
5806
5807 let item_handle = item.to_followable_item_handle(cx)?;
5808 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5809 let variant = item_handle.to_state_proto(window, cx)?;
5810
5811 if item_handle.is_project_item(window, cx)
5812 && (follower_project_id.is_none()
5813 || follower_project_id != self.project.read(cx).remote_id())
5814 {
5815 return None;
5816 }
5817
5818 Some(proto::View {
5819 id: id.to_proto(),
5820 leader_id: leader_peer_id,
5821 variant: Some(variant),
5822 panel_id: panel_id.map(|id| id as i32),
5823 })
5824 }
5825
5826 fn handle_follow(
5827 &mut self,
5828 follower_project_id: Option<u64>,
5829 window: &mut Window,
5830 cx: &mut Context<Self>,
5831 ) -> proto::FollowResponse {
5832 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5833
5834 cx.notify();
5835 proto::FollowResponse {
5836 views: active_view.iter().cloned().collect(),
5837 active_view,
5838 }
5839 }
5840
5841 fn handle_update_followers(
5842 &mut self,
5843 leader_id: PeerId,
5844 message: proto::UpdateFollowers,
5845 _window: &mut Window,
5846 _cx: &mut Context<Self>,
5847 ) {
5848 self.leader_updates_tx
5849 .unbounded_send((leader_id, message))
5850 .ok();
5851 }
5852
5853 async fn process_leader_update(
5854 this: &WeakEntity<Self>,
5855 leader_id: PeerId,
5856 update: proto::UpdateFollowers,
5857 cx: &mut AsyncWindowContext,
5858 ) -> Result<()> {
5859 match update.variant.context("invalid update")? {
5860 proto::update_followers::Variant::CreateView(view) => {
5861 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5862 let should_add_view = this.update(cx, |this, _| {
5863 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5864 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5865 } else {
5866 anyhow::Ok(false)
5867 }
5868 })??;
5869
5870 if should_add_view {
5871 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5872 }
5873 }
5874 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5875 let should_add_view = this.update(cx, |this, _| {
5876 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5877 state.active_view_id = update_active_view
5878 .view
5879 .as_ref()
5880 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5881
5882 if state.active_view_id.is_some_and(|view_id| {
5883 !state.items_by_leader_view_id.contains_key(&view_id)
5884 }) {
5885 anyhow::Ok(true)
5886 } else {
5887 anyhow::Ok(false)
5888 }
5889 } else {
5890 anyhow::Ok(false)
5891 }
5892 })??;
5893
5894 if should_add_view && let Some(view) = update_active_view.view {
5895 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5896 }
5897 }
5898 proto::update_followers::Variant::UpdateView(update_view) => {
5899 let variant = update_view.variant.context("missing update view variant")?;
5900 let id = update_view.id.context("missing update view id")?;
5901 let mut tasks = Vec::new();
5902 this.update_in(cx, |this, window, cx| {
5903 let project = this.project.clone();
5904 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5905 let view_id = ViewId::from_proto(id.clone())?;
5906 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5907 tasks.push(item.view.apply_update_proto(
5908 &project,
5909 variant.clone(),
5910 window,
5911 cx,
5912 ));
5913 }
5914 }
5915 anyhow::Ok(())
5916 })??;
5917 try_join_all(tasks).await.log_err();
5918 }
5919 }
5920 this.update_in(cx, |this, window, cx| {
5921 this.leader_updated(leader_id, window, cx)
5922 })?;
5923 Ok(())
5924 }
5925
5926 async fn add_view_from_leader(
5927 this: WeakEntity<Self>,
5928 leader_id: PeerId,
5929 view: &proto::View,
5930 cx: &mut AsyncWindowContext,
5931 ) -> Result<()> {
5932 let this = this.upgrade().context("workspace dropped")?;
5933
5934 let Some(id) = view.id.clone() else {
5935 anyhow::bail!("no id for view");
5936 };
5937 let id = ViewId::from_proto(id)?;
5938 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5939
5940 let pane = this.update(cx, |this, _cx| {
5941 let state = this
5942 .follower_states
5943 .get(&leader_id.into())
5944 .context("stopped following")?;
5945 anyhow::Ok(state.pane().clone())
5946 })?;
5947 let existing_item = pane.update_in(cx, |pane, window, cx| {
5948 let client = this.read(cx).client().clone();
5949 pane.items().find_map(|item| {
5950 let item = item.to_followable_item_handle(cx)?;
5951 if item.remote_id(&client, window, cx) == Some(id) {
5952 Some(item)
5953 } else {
5954 None
5955 }
5956 })
5957 })?;
5958 let item = if let Some(existing_item) = existing_item {
5959 existing_item
5960 } else {
5961 let variant = view.variant.clone();
5962 anyhow::ensure!(variant.is_some(), "missing view variant");
5963
5964 let task = cx.update(|window, cx| {
5965 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5966 })?;
5967
5968 let Some(task) = task else {
5969 anyhow::bail!(
5970 "failed to construct view from leader (maybe from a different version of zed?)"
5971 );
5972 };
5973
5974 let mut new_item = task.await?;
5975 pane.update_in(cx, |pane, window, cx| {
5976 let mut item_to_remove = None;
5977 for (ix, item) in pane.items().enumerate() {
5978 if let Some(item) = item.to_followable_item_handle(cx) {
5979 match new_item.dedup(item.as_ref(), window, cx) {
5980 Some(item::Dedup::KeepExisting) => {
5981 new_item =
5982 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5983 break;
5984 }
5985 Some(item::Dedup::ReplaceExisting) => {
5986 item_to_remove = Some((ix, item.item_id()));
5987 break;
5988 }
5989 None => {}
5990 }
5991 }
5992 }
5993
5994 if let Some((ix, id)) = item_to_remove {
5995 pane.remove_item(id, false, false, window, cx);
5996 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5997 }
5998 })?;
5999
6000 new_item
6001 };
6002
6003 this.update_in(cx, |this, window, cx| {
6004 let state = this.follower_states.get_mut(&leader_id.into())?;
6005 item.set_leader_id(Some(leader_id.into()), window, cx);
6006 state.items_by_leader_view_id.insert(
6007 id,
6008 FollowerView {
6009 view: item,
6010 location: panel_id,
6011 },
6012 );
6013
6014 Some(())
6015 })
6016 .context("no follower state")?;
6017
6018 Ok(())
6019 }
6020
6021 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6022 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
6023 return;
6024 };
6025
6026 if let Some(agent_location) = self.project.read(cx).agent_location() {
6027 let buffer_entity_id = agent_location.buffer.entity_id();
6028 let view_id = ViewId {
6029 creator: CollaboratorId::Agent,
6030 id: buffer_entity_id.as_u64(),
6031 };
6032 follower_state.active_view_id = Some(view_id);
6033
6034 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
6035 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
6036 hash_map::Entry::Vacant(entry) => {
6037 let existing_view =
6038 follower_state
6039 .center_pane
6040 .read(cx)
6041 .items()
6042 .find_map(|item| {
6043 let item = item.to_followable_item_handle(cx)?;
6044 if item.buffer_kind(cx) == ItemBufferKind::Singleton
6045 && item.project_item_model_ids(cx).as_slice()
6046 == [buffer_entity_id]
6047 {
6048 Some(item)
6049 } else {
6050 None
6051 }
6052 });
6053 let view = existing_view.or_else(|| {
6054 agent_location.buffer.upgrade().and_then(|buffer| {
6055 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
6056 registry.build_item(buffer, self.project.clone(), None, window, cx)
6057 })?
6058 .to_followable_item_handle(cx)
6059 })
6060 });
6061
6062 view.map(|view| {
6063 entry.insert(FollowerView {
6064 view,
6065 location: None,
6066 })
6067 })
6068 }
6069 };
6070
6071 if let Some(item) = item {
6072 item.view
6073 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
6074 item.view
6075 .update_agent_location(agent_location.position, window, cx);
6076 }
6077 } else {
6078 follower_state.active_view_id = None;
6079 }
6080
6081 self.leader_updated(CollaboratorId::Agent, window, cx);
6082 }
6083
6084 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
6085 let mut is_project_item = true;
6086 let mut update = proto::UpdateActiveView::default();
6087 if window.is_window_active() {
6088 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
6089
6090 if let Some(item) = active_item
6091 && item.item_focus_handle(cx).contains_focused(window, cx)
6092 {
6093 let leader_id = self
6094 .pane_for(&*item)
6095 .and_then(|pane| self.leader_for_pane(&pane));
6096 let leader_peer_id = match leader_id {
6097 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
6098 Some(CollaboratorId::Agent) | None => None,
6099 };
6100
6101 if let Some(item) = item.to_followable_item_handle(cx) {
6102 let id = item
6103 .remote_id(&self.app_state.client, window, cx)
6104 .map(|id| id.to_proto());
6105
6106 if let Some(id) = id
6107 && let Some(variant) = item.to_state_proto(window, cx)
6108 {
6109 let view = Some(proto::View {
6110 id,
6111 leader_id: leader_peer_id,
6112 variant: Some(variant),
6113 panel_id: panel_id.map(|id| id as i32),
6114 });
6115
6116 is_project_item = item.is_project_item(window, cx);
6117 update = proto::UpdateActiveView { view };
6118 };
6119 }
6120 }
6121 }
6122
6123 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
6124 if active_view_id != self.last_active_view_id.as_ref() {
6125 self.last_active_view_id = active_view_id.cloned();
6126 self.update_followers(
6127 is_project_item,
6128 proto::update_followers::Variant::UpdateActiveView(update),
6129 window,
6130 cx,
6131 );
6132 }
6133 }
6134
6135 fn active_item_for_followers(
6136 &self,
6137 window: &mut Window,
6138 cx: &mut App,
6139 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
6140 let mut active_item = None;
6141 let mut panel_id = None;
6142 for dock in self.all_docks() {
6143 if dock.focus_handle(cx).contains_focused(window, cx)
6144 && let Some(panel) = dock.read(cx).active_panel()
6145 && let Some(pane) = panel.pane(cx)
6146 && let Some(item) = pane.read(cx).active_item()
6147 {
6148 active_item = Some(item);
6149 panel_id = panel.remote_id();
6150 break;
6151 }
6152 }
6153
6154 if active_item.is_none() {
6155 active_item = self.active_pane().read(cx).active_item();
6156 }
6157 (active_item, panel_id)
6158 }
6159
6160 fn update_followers(
6161 &self,
6162 project_only: bool,
6163 update: proto::update_followers::Variant,
6164 _: &mut Window,
6165 cx: &mut App,
6166 ) -> Option<()> {
6167 // If this update only applies to for followers in the current project,
6168 // then skip it unless this project is shared. If it applies to all
6169 // followers, regardless of project, then set `project_id` to none,
6170 // indicating that it goes to all followers.
6171 let project_id = if project_only {
6172 Some(self.project.read(cx).remote_id()?)
6173 } else {
6174 None
6175 };
6176 self.app_state().workspace_store.update(cx, |store, cx| {
6177 store.update_followers(project_id, update, cx)
6178 })
6179 }
6180
6181 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
6182 self.follower_states.iter().find_map(|(leader_id, state)| {
6183 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
6184 Some(*leader_id)
6185 } else {
6186 None
6187 }
6188 })
6189 }
6190
6191 fn leader_updated(
6192 &mut self,
6193 leader_id: impl Into<CollaboratorId>,
6194 window: &mut Window,
6195 cx: &mut Context<Self>,
6196 ) -> Option<Box<dyn ItemHandle>> {
6197 cx.notify();
6198
6199 let leader_id = leader_id.into();
6200 let (panel_id, item) = match leader_id {
6201 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
6202 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
6203 };
6204
6205 let state = self.follower_states.get(&leader_id)?;
6206 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
6207 let pane;
6208 if let Some(panel_id) = panel_id {
6209 pane = self
6210 .activate_panel_for_proto_id(panel_id, window, cx)?
6211 .pane(cx)?;
6212 let state = self.follower_states.get_mut(&leader_id)?;
6213 state.dock_pane = Some(pane.clone());
6214 } else {
6215 pane = state.center_pane.clone();
6216 let state = self.follower_states.get_mut(&leader_id)?;
6217 if let Some(dock_pane) = state.dock_pane.take() {
6218 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
6219 }
6220 }
6221
6222 pane.update(cx, |pane, cx| {
6223 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
6224 if let Some(index) = pane.index_for_item(item.as_ref()) {
6225 pane.activate_item(index, false, false, window, cx);
6226 } else {
6227 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
6228 }
6229
6230 if focus_active_item {
6231 pane.focus_active_item(window, cx)
6232 }
6233 });
6234
6235 Some(item)
6236 }
6237
6238 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
6239 let state = self.follower_states.get(&CollaboratorId::Agent)?;
6240 let active_view_id = state.active_view_id?;
6241 Some(
6242 state
6243 .items_by_leader_view_id
6244 .get(&active_view_id)?
6245 .view
6246 .boxed_clone(),
6247 )
6248 }
6249
6250 fn active_item_for_peer(
6251 &self,
6252 peer_id: PeerId,
6253 window: &mut Window,
6254 cx: &mut Context<Self>,
6255 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
6256 let call = self.active_call()?;
6257 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
6258 let leader_in_this_app;
6259 let leader_in_this_project;
6260 match participant.location {
6261 ParticipantLocation::SharedProject { project_id } => {
6262 leader_in_this_app = true;
6263 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
6264 }
6265 ParticipantLocation::UnsharedProject => {
6266 leader_in_this_app = true;
6267 leader_in_this_project = false;
6268 }
6269 ParticipantLocation::External => {
6270 leader_in_this_app = false;
6271 leader_in_this_project = false;
6272 }
6273 };
6274 let state = self.follower_states.get(&peer_id.into())?;
6275 let mut item_to_activate = None;
6276 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
6277 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
6278 && (leader_in_this_project || !item.view.is_project_item(window, cx))
6279 {
6280 item_to_activate = Some((item.location, item.view.boxed_clone()));
6281 }
6282 } else if let Some(shared_screen) =
6283 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
6284 {
6285 item_to_activate = Some((None, Box::new(shared_screen)));
6286 }
6287 item_to_activate
6288 }
6289
6290 fn shared_screen_for_peer(
6291 &self,
6292 peer_id: PeerId,
6293 pane: &Entity<Pane>,
6294 window: &mut Window,
6295 cx: &mut App,
6296 ) -> Option<Entity<SharedScreen>> {
6297 self.active_call()?
6298 .create_shared_screen(peer_id, pane, window, cx)
6299 }
6300
6301 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6302 if window.is_window_active() {
6303 self.update_active_view_for_followers(window, cx);
6304
6305 if let Some(database_id) = self.database_id {
6306 let db = WorkspaceDb::global(cx);
6307 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6308 .detach();
6309 }
6310 } else {
6311 for pane in &self.panes {
6312 pane.update(cx, |pane, cx| {
6313 if let Some(item) = pane.active_item() {
6314 item.workspace_deactivated(window, cx);
6315 }
6316 for item in pane.items() {
6317 if matches!(
6318 item.workspace_settings(cx).autosave,
6319 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6320 ) {
6321 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6322 .detach_and_log_err(cx);
6323 }
6324 }
6325 });
6326 }
6327 }
6328 }
6329
6330 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6331 self.active_call.as_ref().map(|(call, _)| &*call.0)
6332 }
6333
6334 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6335 self.active_call.as_ref().map(|(call, _)| call.clone())
6336 }
6337
6338 fn on_active_call_event(
6339 &mut self,
6340 event: &ActiveCallEvent,
6341 window: &mut Window,
6342 cx: &mut Context<Self>,
6343 ) {
6344 match event {
6345 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6346 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6347 self.leader_updated(participant_id, window, cx);
6348 }
6349 }
6350 }
6351
6352 pub fn database_id(&self) -> Option<WorkspaceId> {
6353 self.database_id
6354 }
6355
6356 #[cfg(any(test, feature = "test-support"))]
6357 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6358 self.database_id = Some(id);
6359 }
6360
6361 pub fn session_id(&self) -> Option<String> {
6362 self.session_id.clone()
6363 }
6364
6365 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6366 let Some(display) = window.display(cx) else {
6367 return Task::ready(());
6368 };
6369 let Ok(display_uuid) = display.uuid() else {
6370 return Task::ready(());
6371 };
6372
6373 let window_bounds = window.inner_window_bounds();
6374 let database_id = self.database_id;
6375 let has_paths = !self.root_paths(cx).is_empty();
6376 let db = WorkspaceDb::global(cx);
6377 let kvp = db::kvp::KeyValueStore::global(cx);
6378
6379 cx.background_executor().spawn(async move {
6380 if !has_paths {
6381 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6382 .await
6383 .log_err();
6384 }
6385 if let Some(database_id) = database_id {
6386 db.set_window_open_status(
6387 database_id,
6388 SerializedWindowBounds(window_bounds),
6389 display_uuid,
6390 )
6391 .await
6392 .log_err();
6393 } else {
6394 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6395 .await
6396 .log_err();
6397 }
6398 })
6399 }
6400
6401 /// Bypass the 200ms serialization throttle and write workspace state to
6402 /// the DB immediately. Returns a task the caller can await to ensure the
6403 /// write completes. Used by the quit handler so the most recent state
6404 /// isn't lost to a pending throttle timer when the process exits.
6405 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6406 self._schedule_serialize_workspace.take();
6407 self._serialize_workspace_task.take();
6408 self.bounds_save_task_queued.take();
6409
6410 let bounds_task = self.save_window_bounds(window, cx);
6411 let serialize_task = self.serialize_workspace_internal(window, cx);
6412 cx.spawn(async move |_| {
6413 bounds_task.await;
6414 serialize_task.await;
6415 })
6416 }
6417
6418 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6419 let project = self.project().read(cx);
6420 project
6421 .visible_worktrees(cx)
6422 .map(|worktree| worktree.read(cx).abs_path())
6423 .collect::<Vec<_>>()
6424 }
6425
6426 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6427 match member {
6428 Member::Axis(PaneAxis { members, .. }) => {
6429 for child in members.iter() {
6430 self.remove_panes(child.clone(), window, cx)
6431 }
6432 }
6433 Member::Pane(pane) => {
6434 self.force_remove_pane(&pane, &None, window, cx);
6435 }
6436 }
6437 }
6438
6439 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6440 self.session_id.take();
6441 self.serialize_workspace_internal(window, cx)
6442 }
6443
6444 fn force_remove_pane(
6445 &mut self,
6446 pane: &Entity<Pane>,
6447 focus_on: &Option<Entity<Pane>>,
6448 window: &mut Window,
6449 cx: &mut Context<Workspace>,
6450 ) {
6451 self.panes.retain(|p| p != pane);
6452 if let Some(focus_on) = focus_on {
6453 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6454 } else if self.active_pane() == pane {
6455 self.panes
6456 .last()
6457 .unwrap()
6458 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6459 }
6460 if self.last_active_center_pane == Some(pane.downgrade()) {
6461 self.last_active_center_pane = None;
6462 }
6463 cx.notify();
6464 }
6465
6466 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6467 if self._schedule_serialize_workspace.is_none() {
6468 self._schedule_serialize_workspace =
6469 Some(cx.spawn_in(window, async move |this, cx| {
6470 cx.background_executor()
6471 .timer(SERIALIZATION_THROTTLE_TIME)
6472 .await;
6473 this.update_in(cx, |this, window, cx| {
6474 this._serialize_workspace_task =
6475 Some(this.serialize_workspace_internal(window, cx));
6476 this._schedule_serialize_workspace.take();
6477 })
6478 .log_err();
6479 }));
6480 }
6481 }
6482
6483 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6484 let Some(database_id) = self.database_id() else {
6485 return Task::ready(());
6486 };
6487
6488 fn serialize_pane_handle(
6489 pane_handle: &Entity<Pane>,
6490 window: &mut Window,
6491 cx: &mut App,
6492 ) -> SerializedPane {
6493 let (items, active, pinned_count) = {
6494 let pane = pane_handle.read(cx);
6495 let active_item_id = pane.active_item().map(|item| item.item_id());
6496 (
6497 pane.items()
6498 .filter_map(|handle| {
6499 let handle = handle.to_serializable_item_handle(cx)?;
6500
6501 Some(SerializedItem {
6502 kind: Arc::from(handle.serialized_item_kind()),
6503 item_id: handle.item_id().as_u64(),
6504 active: Some(handle.item_id()) == active_item_id,
6505 preview: pane.is_active_preview_item(handle.item_id()),
6506 })
6507 })
6508 .collect::<Vec<_>>(),
6509 pane.has_focus(window, cx),
6510 pane.pinned_count(),
6511 )
6512 };
6513
6514 SerializedPane::new(items, active, pinned_count)
6515 }
6516
6517 fn build_serialized_pane_group(
6518 pane_group: &Member,
6519 window: &mut Window,
6520 cx: &mut App,
6521 ) -> SerializedPaneGroup {
6522 match pane_group {
6523 Member::Axis(PaneAxis {
6524 axis,
6525 members,
6526 flexes,
6527 bounding_boxes: _,
6528 }) => SerializedPaneGroup::Group {
6529 axis: SerializedAxis(*axis),
6530 children: members
6531 .iter()
6532 .map(|member| build_serialized_pane_group(member, window, cx))
6533 .collect::<Vec<_>>(),
6534 flexes: Some(flexes.lock().clone()),
6535 },
6536 Member::Pane(pane_handle) => {
6537 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6538 }
6539 }
6540 }
6541
6542 fn build_serialized_docks(
6543 this: &Workspace,
6544 window: &mut Window,
6545 cx: &mut App,
6546 ) -> DockStructure {
6547 this.capture_dock_state(window, cx)
6548 }
6549
6550 match self.workspace_location(cx) {
6551 WorkspaceLocation::Location(location, paths) => {
6552 let breakpoints = self.project.update(cx, |project, cx| {
6553 project
6554 .breakpoint_store()
6555 .read(cx)
6556 .all_source_breakpoints(cx)
6557 });
6558 let user_toolchains = self
6559 .project
6560 .read(cx)
6561 .user_toolchains(cx)
6562 .unwrap_or_default();
6563
6564 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6565 let docks = build_serialized_docks(self, window, cx);
6566 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6567
6568 let serialized_workspace = SerializedWorkspace {
6569 id: database_id,
6570 location,
6571 paths,
6572 center_group,
6573 window_bounds,
6574 display: Default::default(),
6575 docks,
6576 centered_layout: self.centered_layout,
6577 session_id: self.session_id.clone(),
6578 breakpoints,
6579 window_id: Some(window.window_handle().window_id().as_u64()),
6580 user_toolchains,
6581 };
6582
6583 let db = WorkspaceDb::global(cx);
6584 window.spawn(cx, async move |_| {
6585 db.save_workspace(serialized_workspace).await;
6586 })
6587 }
6588 WorkspaceLocation::DetachFromSession => {
6589 let window_bounds = SerializedWindowBounds(window.window_bounds());
6590 let display = window.display(cx).and_then(|d| d.uuid().ok());
6591 // Save dock state for empty local workspaces
6592 let docks = build_serialized_docks(self, window, cx);
6593 let db = WorkspaceDb::global(cx);
6594 let kvp = db::kvp::KeyValueStore::global(cx);
6595 window.spawn(cx, async move |_| {
6596 db.set_window_open_status(
6597 database_id,
6598 window_bounds,
6599 display.unwrap_or_default(),
6600 )
6601 .await
6602 .log_err();
6603 db.set_session_id(database_id, None).await.log_err();
6604 persistence::write_default_dock_state(&kvp, docks)
6605 .await
6606 .log_err();
6607 })
6608 }
6609 WorkspaceLocation::None => {
6610 // Save dock state for empty non-local workspaces
6611 let docks = build_serialized_docks(self, window, cx);
6612 let kvp = db::kvp::KeyValueStore::global(cx);
6613 window.spawn(cx, async move |_| {
6614 persistence::write_default_dock_state(&kvp, docks)
6615 .await
6616 .log_err();
6617 })
6618 }
6619 }
6620 }
6621
6622 fn has_any_items_open(&self, cx: &App) -> bool {
6623 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6624 }
6625
6626 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6627 let paths = PathList::new(&self.root_paths(cx));
6628 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6629 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6630 } else if self.project.read(cx).is_local() {
6631 if !paths.is_empty() || self.has_any_items_open(cx) {
6632 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6633 } else {
6634 WorkspaceLocation::DetachFromSession
6635 }
6636 } else {
6637 WorkspaceLocation::None
6638 }
6639 }
6640
6641 fn update_history(&self, cx: &mut App) {
6642 let Some(id) = self.database_id() else {
6643 return;
6644 };
6645 if !self.project.read(cx).is_local() {
6646 return;
6647 }
6648 if let Some(manager) = HistoryManager::global(cx) {
6649 let paths = PathList::new(&self.root_paths(cx));
6650 manager.update(cx, |this, cx| {
6651 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6652 });
6653 }
6654 }
6655
6656 async fn serialize_items(
6657 this: &WeakEntity<Self>,
6658 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6659 cx: &mut AsyncWindowContext,
6660 ) -> Result<()> {
6661 const CHUNK_SIZE: usize = 200;
6662
6663 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6664
6665 while let Some(items_received) = serializable_items.next().await {
6666 let unique_items =
6667 items_received
6668 .into_iter()
6669 .fold(HashMap::default(), |mut acc, item| {
6670 acc.entry(item.item_id()).or_insert(item);
6671 acc
6672 });
6673
6674 // We use into_iter() here so that the references to the items are moved into
6675 // the tasks and not kept alive while we're sleeping.
6676 for (_, item) in unique_items.into_iter() {
6677 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6678 item.serialize(workspace, false, window, cx)
6679 }) {
6680 cx.background_spawn(async move { task.await.log_err() })
6681 .detach();
6682 }
6683 }
6684
6685 cx.background_executor()
6686 .timer(SERIALIZATION_THROTTLE_TIME)
6687 .await;
6688 }
6689
6690 Ok(())
6691 }
6692
6693 pub(crate) fn enqueue_item_serialization(
6694 &mut self,
6695 item: Box<dyn SerializableItemHandle>,
6696 ) -> Result<()> {
6697 self.serializable_items_tx
6698 .unbounded_send(item)
6699 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6700 }
6701
6702 pub(crate) fn load_workspace(
6703 serialized_workspace: SerializedWorkspace,
6704 paths_to_open: Vec<Option<ProjectPath>>,
6705 window: &mut Window,
6706 cx: &mut Context<Workspace>,
6707 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6708 cx.spawn_in(window, async move |workspace, cx| {
6709 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6710
6711 let mut center_group = None;
6712 let mut center_items = None;
6713
6714 // Traverse the splits tree and add to things
6715 if let Some((group, active_pane, items)) = serialized_workspace
6716 .center_group
6717 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6718 .await
6719 {
6720 center_items = Some(items);
6721 center_group = Some((group, active_pane))
6722 }
6723
6724 let mut items_by_project_path = HashMap::default();
6725 let mut item_ids_by_kind = HashMap::default();
6726 let mut all_deserialized_items = Vec::default();
6727 cx.update(|_, cx| {
6728 for item in center_items.unwrap_or_default().into_iter().flatten() {
6729 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6730 item_ids_by_kind
6731 .entry(serializable_item_handle.serialized_item_kind())
6732 .or_insert(Vec::new())
6733 .push(item.item_id().as_u64() as ItemId);
6734 }
6735
6736 if let Some(project_path) = item.project_path(cx) {
6737 items_by_project_path.insert(project_path, item.clone());
6738 }
6739 all_deserialized_items.push(item);
6740 }
6741 })?;
6742
6743 let opened_items = paths_to_open
6744 .into_iter()
6745 .map(|path_to_open| {
6746 path_to_open
6747 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6748 })
6749 .collect::<Vec<_>>();
6750
6751 // Remove old panes from workspace panes list
6752 workspace.update_in(cx, |workspace, window, cx| {
6753 if let Some((center_group, active_pane)) = center_group {
6754 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6755
6756 // Swap workspace center group
6757 workspace.center = PaneGroup::with_root(center_group);
6758 workspace.center.set_is_center(true);
6759 workspace.center.mark_positions(cx);
6760
6761 if let Some(active_pane) = active_pane {
6762 workspace.set_active_pane(&active_pane, window, cx);
6763 cx.focus_self(window);
6764 } else {
6765 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6766 }
6767 }
6768
6769 let docks = serialized_workspace.docks;
6770
6771 for (dock, serialized_dock) in [
6772 (&mut workspace.right_dock, docks.right),
6773 (&mut workspace.left_dock, docks.left),
6774 (&mut workspace.bottom_dock, docks.bottom),
6775 ]
6776 .iter_mut()
6777 {
6778 dock.update(cx, |dock, cx| {
6779 dock.serialized_dock = Some(serialized_dock.clone());
6780 dock.restore_state(window, cx);
6781 });
6782 }
6783
6784 cx.notify();
6785 })?;
6786
6787 let _ = project
6788 .update(cx, |project, cx| {
6789 project
6790 .breakpoint_store()
6791 .update(cx, |breakpoint_store, cx| {
6792 breakpoint_store
6793 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6794 })
6795 })
6796 .await;
6797
6798 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6799 // after loading the items, we might have different items and in order to avoid
6800 // the database filling up, we delete items that haven't been loaded now.
6801 //
6802 // The items that have been loaded, have been saved after they've been added to the workspace.
6803 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6804 item_ids_by_kind
6805 .into_iter()
6806 .map(|(item_kind, loaded_items)| {
6807 SerializableItemRegistry::cleanup(
6808 item_kind,
6809 serialized_workspace.id,
6810 loaded_items,
6811 window,
6812 cx,
6813 )
6814 .log_err()
6815 })
6816 .collect::<Vec<_>>()
6817 })?;
6818
6819 futures::future::join_all(clean_up_tasks).await;
6820
6821 workspace
6822 .update_in(cx, |workspace, window, cx| {
6823 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6824 workspace.serialize_workspace_internal(window, cx).detach();
6825
6826 // Ensure that we mark the window as edited if we did load dirty items
6827 workspace.update_window_edited(window, cx);
6828 })
6829 .ok();
6830
6831 Ok(opened_items)
6832 })
6833 }
6834
6835 pub fn key_context(&self, cx: &App) -> KeyContext {
6836 let mut context = KeyContext::new_with_defaults();
6837 context.add("Workspace");
6838 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6839 if let Some(status) = self
6840 .debugger_provider
6841 .as_ref()
6842 .and_then(|provider| provider.active_thread_state(cx))
6843 {
6844 match status {
6845 ThreadStatus::Running | ThreadStatus::Stepping => {
6846 context.add("debugger_running");
6847 }
6848 ThreadStatus::Stopped => context.add("debugger_stopped"),
6849 ThreadStatus::Exited | ThreadStatus::Ended => {}
6850 }
6851 }
6852
6853 if self.left_dock.read(cx).is_open() {
6854 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6855 context.set("left_dock", active_panel.panel_key());
6856 }
6857 }
6858
6859 if self.right_dock.read(cx).is_open() {
6860 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6861 context.set("right_dock", active_panel.panel_key());
6862 }
6863 }
6864
6865 if self.bottom_dock.read(cx).is_open() {
6866 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6867 context.set("bottom_dock", active_panel.panel_key());
6868 }
6869 }
6870
6871 context
6872 }
6873
6874 /// Multiworkspace uses this to add workspace action handling to itself
6875 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6876 self.add_workspace_actions_listeners(div, window, cx)
6877 .on_action(cx.listener(
6878 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6879 for action in &action_sequence.0 {
6880 window.dispatch_action(action.boxed_clone(), cx);
6881 }
6882 },
6883 ))
6884 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6885 .on_action(cx.listener(Self::close_all_items_and_panes))
6886 .on_action(cx.listener(Self::close_item_in_all_panes))
6887 .on_action(cx.listener(Self::save_all))
6888 .on_action(cx.listener(Self::send_keystrokes))
6889 .on_action(cx.listener(Self::add_folder_to_project))
6890 .on_action(cx.listener(Self::follow_next_collaborator))
6891 .on_action(cx.listener(Self::activate_pane_at_index))
6892 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6893 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6894 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6895 .on_action(cx.listener(Self::toggle_theme_mode))
6896 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6897 let pane = workspace.active_pane().clone();
6898 workspace.unfollow_in_pane(&pane, window, cx);
6899 }))
6900 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6901 workspace
6902 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6903 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6904 }))
6905 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6906 workspace
6907 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6908 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6909 }))
6910 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6911 workspace
6912 .save_active_item(SaveIntent::SaveAs, window, cx)
6913 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6914 }))
6915 .on_action(
6916 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6917 workspace.activate_previous_pane(window, cx)
6918 }),
6919 )
6920 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6921 workspace.activate_next_pane(window, cx)
6922 }))
6923 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6924 workspace.activate_last_pane(window, cx)
6925 }))
6926 .on_action(
6927 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6928 workspace.activate_next_window(cx)
6929 }),
6930 )
6931 .on_action(
6932 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6933 workspace.activate_previous_window(cx)
6934 }),
6935 )
6936 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6937 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6938 }))
6939 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6940 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6941 }))
6942 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6943 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6944 }))
6945 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6946 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6947 }))
6948 .on_action(cx.listener(
6949 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6950 workspace.move_item_to_pane_in_direction(action, window, cx)
6951 },
6952 ))
6953 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6954 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6955 }))
6956 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6957 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6958 }))
6959 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6960 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6961 }))
6962 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6963 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6964 }))
6965 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6966 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6967 SplitDirection::Down,
6968 SplitDirection::Up,
6969 SplitDirection::Right,
6970 SplitDirection::Left,
6971 ];
6972 for dir in DIRECTION_PRIORITY {
6973 if workspace.find_pane_in_direction(dir, cx).is_some() {
6974 workspace.swap_pane_in_direction(dir, cx);
6975 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6976 break;
6977 }
6978 }
6979 }))
6980 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6981 workspace.move_pane_to_border(SplitDirection::Left, cx)
6982 }))
6983 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6984 workspace.move_pane_to_border(SplitDirection::Right, cx)
6985 }))
6986 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6987 workspace.move_pane_to_border(SplitDirection::Up, cx)
6988 }))
6989 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6990 workspace.move_pane_to_border(SplitDirection::Down, cx)
6991 }))
6992 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6993 this.toggle_dock(DockPosition::Left, window, cx);
6994 }))
6995 .on_action(cx.listener(
6996 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6997 workspace.toggle_dock(DockPosition::Right, window, cx);
6998 },
6999 ))
7000 .on_action(cx.listener(
7001 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
7002 workspace.toggle_dock(DockPosition::Bottom, window, cx);
7003 },
7004 ))
7005 .on_action(cx.listener(
7006 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
7007 if !workspace.close_active_dock(window, cx) {
7008 cx.propagate();
7009 }
7010 },
7011 ))
7012 .on_action(
7013 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
7014 workspace.close_all_docks(window, cx);
7015 }),
7016 )
7017 .on_action(cx.listener(Self::toggle_all_docks))
7018 .on_action(cx.listener(
7019 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
7020 workspace.clear_all_notifications(cx);
7021 },
7022 ))
7023 .on_action(cx.listener(
7024 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
7025 workspace.clear_navigation_history(window, cx);
7026 },
7027 ))
7028 .on_action(cx.listener(
7029 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
7030 if let Some((notification_id, _)) = workspace.notifications.pop() {
7031 workspace.suppress_notification(¬ification_id, cx);
7032 }
7033 },
7034 ))
7035 .on_action(cx.listener(
7036 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
7037 workspace.show_worktree_trust_security_modal(true, window, cx);
7038 },
7039 ))
7040 .on_action(
7041 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
7042 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
7043 trusted_worktrees.update(cx, |trusted_worktrees, _| {
7044 trusted_worktrees.clear_trusted_paths()
7045 });
7046 let db = WorkspaceDb::global(cx);
7047 cx.spawn(async move |_, cx| {
7048 if db.clear_trusted_worktrees().await.log_err().is_some() {
7049 cx.update(|cx| reload(cx));
7050 }
7051 })
7052 .detach();
7053 }
7054 }),
7055 )
7056 .on_action(cx.listener(
7057 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
7058 workspace.reopen_closed_item(window, cx).detach();
7059 },
7060 ))
7061 .on_action(cx.listener(
7062 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
7063 for dock in workspace.all_docks() {
7064 if dock.focus_handle(cx).contains_focused(window, cx) {
7065 let panel = dock.read(cx).active_panel().cloned();
7066 if let Some(panel) = panel {
7067 dock.update(cx, |dock, cx| {
7068 dock.set_panel_size_state(
7069 panel.as_ref(),
7070 dock::PanelSizeState::default(),
7071 cx,
7072 );
7073 });
7074 }
7075 return;
7076 }
7077 }
7078 },
7079 ))
7080 .on_action(cx.listener(
7081 |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
7082 for dock in workspace.all_docks() {
7083 let panel = dock.read(cx).visible_panel().cloned();
7084 if let Some(panel) = panel {
7085 dock.update(cx, |dock, cx| {
7086 dock.set_panel_size_state(
7087 panel.as_ref(),
7088 dock::PanelSizeState::default(),
7089 cx,
7090 );
7091 });
7092 }
7093 }
7094 },
7095 ))
7096 .on_action(cx.listener(
7097 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
7098 adjust_active_dock_size_by_px(
7099 px_with_ui_font_fallback(act.px, cx),
7100 workspace,
7101 window,
7102 cx,
7103 );
7104 },
7105 ))
7106 .on_action(cx.listener(
7107 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
7108 adjust_active_dock_size_by_px(
7109 px_with_ui_font_fallback(act.px, cx) * -1.,
7110 workspace,
7111 window,
7112 cx,
7113 );
7114 },
7115 ))
7116 .on_action(cx.listener(
7117 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
7118 adjust_open_docks_size_by_px(
7119 px_with_ui_font_fallback(act.px, cx),
7120 workspace,
7121 window,
7122 cx,
7123 );
7124 },
7125 ))
7126 .on_action(cx.listener(
7127 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
7128 adjust_open_docks_size_by_px(
7129 px_with_ui_font_fallback(act.px, cx) * -1.,
7130 workspace,
7131 window,
7132 cx,
7133 );
7134 },
7135 ))
7136 .on_action(cx.listener(Workspace::toggle_centered_layout))
7137 .on_action(cx.listener(
7138 |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
7139 if let Some(active_dock) = workspace.active_dock(window, cx) {
7140 let dock = active_dock.read(cx);
7141 if let Some(active_panel) = dock.active_panel() {
7142 if active_panel.pane(cx).is_none() {
7143 let mut recent_pane: Option<Entity<Pane>> = None;
7144 let mut recent_timestamp = 0;
7145 for pane_handle in workspace.panes() {
7146 let pane = pane_handle.read(cx);
7147 for entry in pane.activation_history() {
7148 if entry.timestamp > recent_timestamp {
7149 recent_timestamp = entry.timestamp;
7150 recent_pane = Some(pane_handle.clone());
7151 }
7152 }
7153 }
7154
7155 if let Some(pane) = recent_pane {
7156 let wrap_around = action.wrap_around;
7157 pane.update(cx, |pane, cx| {
7158 let current_index = pane.active_item_index();
7159 let items_len = pane.items_len();
7160 if items_len > 0 {
7161 let next_index = if current_index + 1 < items_len {
7162 current_index + 1
7163 } else if wrap_around {
7164 0
7165 } else {
7166 return;
7167 };
7168 pane.activate_item(
7169 next_index, false, false, window, cx,
7170 );
7171 }
7172 });
7173 return;
7174 }
7175 }
7176 }
7177 }
7178 cx.propagate();
7179 },
7180 ))
7181 .on_action(cx.listener(
7182 |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
7183 if let Some(active_dock) = workspace.active_dock(window, cx) {
7184 let dock = active_dock.read(cx);
7185 if let Some(active_panel) = dock.active_panel() {
7186 if active_panel.pane(cx).is_none() {
7187 let mut recent_pane: Option<Entity<Pane>> = None;
7188 let mut recent_timestamp = 0;
7189 for pane_handle in workspace.panes() {
7190 let pane = pane_handle.read(cx);
7191 for entry in pane.activation_history() {
7192 if entry.timestamp > recent_timestamp {
7193 recent_timestamp = entry.timestamp;
7194 recent_pane = Some(pane_handle.clone());
7195 }
7196 }
7197 }
7198
7199 if let Some(pane) = recent_pane {
7200 let wrap_around = action.wrap_around;
7201 pane.update(cx, |pane, cx| {
7202 let current_index = pane.active_item_index();
7203 let items_len = pane.items_len();
7204 if items_len > 0 {
7205 let prev_index = if current_index > 0 {
7206 current_index - 1
7207 } else if wrap_around {
7208 items_len.saturating_sub(1)
7209 } else {
7210 return;
7211 };
7212 pane.activate_item(
7213 prev_index, false, false, window, cx,
7214 );
7215 }
7216 });
7217 return;
7218 }
7219 }
7220 }
7221 }
7222 cx.propagate();
7223 },
7224 ))
7225 .on_action(cx.listener(
7226 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
7227 if let Some(active_dock) = workspace.active_dock(window, cx) {
7228 let dock = active_dock.read(cx);
7229 if let Some(active_panel) = dock.active_panel() {
7230 if active_panel.pane(cx).is_none() {
7231 let active_pane = workspace.active_pane().clone();
7232 active_pane.update(cx, |pane, cx| {
7233 pane.close_active_item(action, window, cx)
7234 .detach_and_log_err(cx);
7235 });
7236 return;
7237 }
7238 }
7239 }
7240 cx.propagate();
7241 },
7242 ))
7243 .on_action(
7244 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
7245 let pane = workspace.active_pane().clone();
7246 if let Some(item) = pane.read(cx).active_item() {
7247 item.toggle_read_only(window, cx);
7248 }
7249 }),
7250 )
7251 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
7252 workspace.focus_center_pane(window, cx);
7253 }))
7254 .on_action(cx.listener(Workspace::cancel))
7255 }
7256
7257 #[cfg(any(test, feature = "test-support"))]
7258 pub fn set_random_database_id(&mut self) {
7259 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
7260 }
7261
7262 #[cfg(any(test, feature = "test-support"))]
7263 pub(crate) fn test_new(
7264 project: Entity<Project>,
7265 window: &mut Window,
7266 cx: &mut Context<Self>,
7267 ) -> Self {
7268 use node_runtime::NodeRuntime;
7269 use session::Session;
7270
7271 let client = project.read(cx).client();
7272 let user_store = project.read(cx).user_store();
7273 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
7274 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
7275 window.activate_window();
7276 let app_state = Arc::new(AppState {
7277 languages: project.read(cx).languages().clone(),
7278 workspace_store,
7279 client,
7280 user_store,
7281 fs: project.read(cx).fs().clone(),
7282 build_window_options: |_, _| Default::default(),
7283 node_runtime: NodeRuntime::unavailable(),
7284 session,
7285 });
7286 let workspace = Self::new(Default::default(), project, app_state, window, cx);
7287 workspace
7288 .active_pane
7289 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
7290 workspace
7291 }
7292
7293 pub fn register_action<A: Action>(
7294 &mut self,
7295 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
7296 ) -> &mut Self {
7297 let callback = Arc::new(callback);
7298
7299 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
7300 let callback = callback.clone();
7301 div.on_action(cx.listener(move |workspace, event, window, cx| {
7302 (callback)(workspace, event, window, cx)
7303 }))
7304 }));
7305 self
7306 }
7307 pub fn register_action_renderer(
7308 &mut self,
7309 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
7310 ) -> &mut Self {
7311 self.workspace_actions.push(Box::new(callback));
7312 self
7313 }
7314
7315 fn add_workspace_actions_listeners(
7316 &self,
7317 mut div: Div,
7318 window: &mut Window,
7319 cx: &mut Context<Self>,
7320 ) -> Div {
7321 for action in self.workspace_actions.iter() {
7322 div = (action)(div, self, window, cx)
7323 }
7324 div
7325 }
7326
7327 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7328 self.modal_layer.read(cx).has_active_modal()
7329 }
7330
7331 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7332 self.modal_layer
7333 .read(cx)
7334 .is_active_modal_command_palette(cx)
7335 }
7336
7337 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7338 self.modal_layer.read(cx).active_modal()
7339 }
7340
7341 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7342 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7343 /// If no modal is active, the new modal will be shown.
7344 ///
7345 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7346 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7347 /// will not be shown.
7348 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7349 where
7350 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7351 {
7352 self.modal_layer.update(cx, |modal_layer, cx| {
7353 modal_layer.toggle_modal(window, cx, build)
7354 })
7355 }
7356
7357 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7358 self.modal_layer
7359 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7360 }
7361
7362 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7363 self.toast_layer
7364 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7365 }
7366
7367 pub fn toggle_centered_layout(
7368 &mut self,
7369 _: &ToggleCenteredLayout,
7370 _: &mut Window,
7371 cx: &mut Context<Self>,
7372 ) {
7373 self.centered_layout = !self.centered_layout;
7374 if let Some(database_id) = self.database_id() {
7375 let db = WorkspaceDb::global(cx);
7376 let centered_layout = self.centered_layout;
7377 cx.background_spawn(async move {
7378 db.set_centered_layout(database_id, centered_layout).await
7379 })
7380 .detach_and_log_err(cx);
7381 }
7382 cx.notify();
7383 }
7384
7385 fn adjust_padding(padding: Option<f32>) -> f32 {
7386 padding
7387 .unwrap_or(CenteredPaddingSettings::default().0)
7388 .clamp(
7389 CenteredPaddingSettings::MIN_PADDING,
7390 CenteredPaddingSettings::MAX_PADDING,
7391 )
7392 }
7393
7394 fn render_dock(
7395 &self,
7396 position: DockPosition,
7397 dock: &Entity<Dock>,
7398 window: &mut Window,
7399 cx: &mut App,
7400 ) -> Option<Div> {
7401 if self.zoomed_position == Some(position) {
7402 return None;
7403 }
7404
7405 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7406 let pane = panel.pane(cx)?;
7407 let follower_states = &self.follower_states;
7408 leader_border_for_pane(follower_states, &pane, window, cx)
7409 });
7410
7411 let mut container = div()
7412 .flex()
7413 .overflow_hidden()
7414 .flex_none()
7415 .child(dock.clone())
7416 .children(leader_border);
7417
7418 // Apply sizing only when the dock is open. When closed the dock is still
7419 // included in the element tree so its focus handle remains mounted — without
7420 // this, toggle_panel_focus cannot focus the panel when the dock is closed.
7421 let dock = dock.read(cx);
7422 if let Some(panel) = dock.visible_panel() {
7423 let size_state = dock.stored_panel_size_state(panel.as_ref());
7424 if position.axis() == Axis::Horizontal {
7425 let use_flexible = panel.has_flexible_size(window, cx);
7426 let flex_grow = if use_flexible {
7427 size_state
7428 .and_then(|state| state.flex)
7429 .or_else(|| self.default_dock_flex(position))
7430 } else {
7431 None
7432 };
7433 if let Some(grow) = flex_grow {
7434 let grow = grow.max(0.001);
7435 let style = container.style();
7436 style.flex_grow = Some(grow);
7437 style.flex_shrink = Some(1.0);
7438 style.flex_basis = Some(relative(0.).into());
7439 } else {
7440 let size = size_state
7441 .and_then(|state| state.size)
7442 .unwrap_or_else(|| panel.default_size(window, cx));
7443 container = container.w(size);
7444 }
7445 } else {
7446 let size = size_state
7447 .and_then(|state| state.size)
7448 .unwrap_or_else(|| panel.default_size(window, cx));
7449 container = container.h(size);
7450 }
7451 }
7452
7453 Some(container)
7454 }
7455
7456 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7457 window
7458 .root::<MultiWorkspace>()
7459 .flatten()
7460 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7461 }
7462
7463 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7464 self.zoomed.as_ref()
7465 }
7466
7467 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7468 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7469 return;
7470 };
7471 let windows = cx.windows();
7472 let next_window =
7473 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7474 || {
7475 windows
7476 .iter()
7477 .cycle()
7478 .skip_while(|window| window.window_id() != current_window_id)
7479 .nth(1)
7480 },
7481 );
7482
7483 if let Some(window) = next_window {
7484 window
7485 .update(cx, |_, window, _| window.activate_window())
7486 .ok();
7487 }
7488 }
7489
7490 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7491 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7492 return;
7493 };
7494 let windows = cx.windows();
7495 let prev_window =
7496 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7497 || {
7498 windows
7499 .iter()
7500 .rev()
7501 .cycle()
7502 .skip_while(|window| window.window_id() != current_window_id)
7503 .nth(1)
7504 },
7505 );
7506
7507 if let Some(window) = prev_window {
7508 window
7509 .update(cx, |_, window, _| window.activate_window())
7510 .ok();
7511 }
7512 }
7513
7514 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7515 if cx.stop_active_drag(window) {
7516 } else if let Some((notification_id, _)) = self.notifications.pop() {
7517 dismiss_app_notification(¬ification_id, cx);
7518 } else {
7519 cx.propagate();
7520 }
7521 }
7522
7523 fn resize_dock(
7524 &mut self,
7525 dock_pos: DockPosition,
7526 new_size: Pixels,
7527 window: &mut Window,
7528 cx: &mut Context<Self>,
7529 ) {
7530 match dock_pos {
7531 DockPosition::Left => self.resize_left_dock(new_size, window, cx),
7532 DockPosition::Right => self.resize_right_dock(new_size, window, cx),
7533 DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
7534 }
7535 }
7536
7537 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7538 let workspace_width = self.bounds.size.width;
7539 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7540
7541 self.right_dock.read_with(cx, |right_dock, cx| {
7542 let right_dock_size = right_dock
7543 .stored_active_panel_size(window, cx)
7544 .unwrap_or(Pixels::ZERO);
7545 if right_dock_size + size > workspace_width {
7546 size = workspace_width - right_dock_size
7547 }
7548 });
7549
7550 let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
7551 self.left_dock.update(cx, |left_dock, cx| {
7552 if WorkspaceSettings::get_global(cx)
7553 .resize_all_panels_in_dock
7554 .contains(&DockPosition::Left)
7555 {
7556 left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7557 } else {
7558 left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7559 }
7560 });
7561 }
7562
7563 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7564 let workspace_width = self.bounds.size.width;
7565 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7566 self.left_dock.read_with(cx, |left_dock, cx| {
7567 let left_dock_size = left_dock
7568 .stored_active_panel_size(window, cx)
7569 .unwrap_or(Pixels::ZERO);
7570 if left_dock_size + size > workspace_width {
7571 size = workspace_width - left_dock_size
7572 }
7573 });
7574 let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
7575 self.right_dock.update(cx, |right_dock, cx| {
7576 if WorkspaceSettings::get_global(cx)
7577 .resize_all_panels_in_dock
7578 .contains(&DockPosition::Right)
7579 {
7580 right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7581 } else {
7582 right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7583 }
7584 });
7585 }
7586
7587 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7588 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7589 self.bottom_dock.update(cx, |bottom_dock, cx| {
7590 if WorkspaceSettings::get_global(cx)
7591 .resize_all_panels_in_dock
7592 .contains(&DockPosition::Bottom)
7593 {
7594 bottom_dock.resize_all_panels(Some(size), None, window, cx);
7595 } else {
7596 bottom_dock.resize_active_panel(Some(size), None, window, cx);
7597 }
7598 });
7599 }
7600
7601 fn toggle_edit_predictions_all_files(
7602 &mut self,
7603 _: &ToggleEditPrediction,
7604 _window: &mut Window,
7605 cx: &mut Context<Self>,
7606 ) {
7607 let fs = self.project().read(cx).fs().clone();
7608 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7609 update_settings_file(fs, cx, move |file, _| {
7610 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7611 });
7612 }
7613
7614 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7615 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7616 let next_mode = match current_mode {
7617 Some(theme_settings::ThemeAppearanceMode::Light) => {
7618 theme_settings::ThemeAppearanceMode::Dark
7619 }
7620 Some(theme_settings::ThemeAppearanceMode::Dark) => {
7621 theme_settings::ThemeAppearanceMode::Light
7622 }
7623 Some(theme_settings::ThemeAppearanceMode::System) | None => {
7624 match cx.theme().appearance() {
7625 theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
7626 theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
7627 }
7628 }
7629 };
7630
7631 let fs = self.project().read(cx).fs().clone();
7632 settings::update_settings_file(fs, cx, move |settings, _cx| {
7633 theme_settings::set_mode(settings, next_mode);
7634 });
7635 }
7636
7637 pub fn show_worktree_trust_security_modal(
7638 &mut self,
7639 toggle: bool,
7640 window: &mut Window,
7641 cx: &mut Context<Self>,
7642 ) {
7643 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7644 if toggle {
7645 security_modal.update(cx, |security_modal, cx| {
7646 security_modal.dismiss(cx);
7647 })
7648 } else {
7649 security_modal.update(cx, |security_modal, cx| {
7650 security_modal.refresh_restricted_paths(cx);
7651 });
7652 }
7653 } else {
7654 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7655 .map(|trusted_worktrees| {
7656 trusted_worktrees
7657 .read(cx)
7658 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7659 })
7660 .unwrap_or(false);
7661 if has_restricted_worktrees {
7662 let project = self.project().read(cx);
7663 let remote_host = project
7664 .remote_connection_options(cx)
7665 .map(RemoteHostLocation::from);
7666 let worktree_store = project.worktree_store().downgrade();
7667 self.toggle_modal(window, cx, |_, cx| {
7668 SecurityModal::new(worktree_store, remote_host, cx)
7669 });
7670 }
7671 }
7672 }
7673}
7674
7675pub trait AnyActiveCall {
7676 fn entity(&self) -> AnyEntity;
7677 fn is_in_room(&self, _: &App) -> bool;
7678 fn room_id(&self, _: &App) -> Option<u64>;
7679 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7680 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7681 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7682 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7683 fn is_sharing_project(&self, _: &App) -> bool;
7684 fn has_remote_participants(&self, _: &App) -> bool;
7685 fn local_participant_is_guest(&self, _: &App) -> bool;
7686 fn client(&self, _: &App) -> Arc<Client>;
7687 fn share_on_join(&self, _: &App) -> bool;
7688 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7689 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7690 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7691 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7692 fn join_project(
7693 &self,
7694 _: u64,
7695 _: Arc<LanguageRegistry>,
7696 _: Arc<dyn Fs>,
7697 _: &mut App,
7698 ) -> Task<Result<Entity<Project>>>;
7699 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7700 fn subscribe(
7701 &self,
7702 _: &mut Window,
7703 _: &mut Context<Workspace>,
7704 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7705 ) -> Subscription;
7706 fn create_shared_screen(
7707 &self,
7708 _: PeerId,
7709 _: &Entity<Pane>,
7710 _: &mut Window,
7711 _: &mut App,
7712 ) -> Option<Entity<SharedScreen>>;
7713}
7714
7715#[derive(Clone)]
7716pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7717impl Global for GlobalAnyActiveCall {}
7718
7719impl GlobalAnyActiveCall {
7720 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7721 cx.try_global()
7722 }
7723
7724 pub(crate) fn global(cx: &App) -> &Self {
7725 cx.global()
7726 }
7727}
7728
7729/// Workspace-local view of a remote participant's location.
7730#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7731pub enum ParticipantLocation {
7732 SharedProject { project_id: u64 },
7733 UnsharedProject,
7734 External,
7735}
7736
7737impl ParticipantLocation {
7738 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7739 match location
7740 .and_then(|l| l.variant)
7741 .context("participant location was not provided")?
7742 {
7743 proto::participant_location::Variant::SharedProject(project) => {
7744 Ok(Self::SharedProject {
7745 project_id: project.id,
7746 })
7747 }
7748 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7749 proto::participant_location::Variant::External(_) => Ok(Self::External),
7750 }
7751 }
7752}
7753/// Workspace-local view of a remote collaborator's state.
7754/// This is the subset of `call::RemoteParticipant` that workspace needs.
7755#[derive(Clone)]
7756pub struct RemoteCollaborator {
7757 pub user: Arc<User>,
7758 pub peer_id: PeerId,
7759 pub location: ParticipantLocation,
7760 pub participant_index: ParticipantIndex,
7761}
7762
7763pub enum ActiveCallEvent {
7764 ParticipantLocationChanged { participant_id: PeerId },
7765 RemoteVideoTracksChanged { participant_id: PeerId },
7766}
7767
7768fn leader_border_for_pane(
7769 follower_states: &HashMap<CollaboratorId, FollowerState>,
7770 pane: &Entity<Pane>,
7771 _: &Window,
7772 cx: &App,
7773) -> Option<Div> {
7774 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7775 if state.pane() == pane {
7776 Some((*leader_id, state))
7777 } else {
7778 None
7779 }
7780 })?;
7781
7782 let mut leader_color = match leader_id {
7783 CollaboratorId::PeerId(leader_peer_id) => {
7784 let leader = GlobalAnyActiveCall::try_global(cx)?
7785 .0
7786 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7787
7788 cx.theme()
7789 .players()
7790 .color_for_participant(leader.participant_index.0)
7791 .cursor
7792 }
7793 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7794 };
7795 leader_color.fade_out(0.3);
7796 Some(
7797 div()
7798 .absolute()
7799 .size_full()
7800 .left_0()
7801 .top_0()
7802 .border_2()
7803 .border_color(leader_color),
7804 )
7805}
7806
7807fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7808 ZED_WINDOW_POSITION
7809 .zip(*ZED_WINDOW_SIZE)
7810 .map(|(position, size)| Bounds {
7811 origin: position,
7812 size,
7813 })
7814}
7815
7816fn open_items(
7817 serialized_workspace: Option<SerializedWorkspace>,
7818 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7819 window: &mut Window,
7820 cx: &mut Context<Workspace>,
7821) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7822 let restored_items = serialized_workspace.map(|serialized_workspace| {
7823 Workspace::load_workspace(
7824 serialized_workspace,
7825 project_paths_to_open
7826 .iter()
7827 .map(|(_, project_path)| project_path)
7828 .cloned()
7829 .collect(),
7830 window,
7831 cx,
7832 )
7833 });
7834
7835 cx.spawn_in(window, async move |workspace, cx| {
7836 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7837
7838 if let Some(restored_items) = restored_items {
7839 let restored_items = restored_items.await?;
7840
7841 let restored_project_paths = restored_items
7842 .iter()
7843 .filter_map(|item| {
7844 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7845 .ok()
7846 .flatten()
7847 })
7848 .collect::<HashSet<_>>();
7849
7850 for restored_item in restored_items {
7851 opened_items.push(restored_item.map(Ok));
7852 }
7853
7854 project_paths_to_open
7855 .iter_mut()
7856 .for_each(|(_, project_path)| {
7857 if let Some(project_path_to_open) = project_path
7858 && restored_project_paths.contains(project_path_to_open)
7859 {
7860 *project_path = None;
7861 }
7862 });
7863 } else {
7864 for _ in 0..project_paths_to_open.len() {
7865 opened_items.push(None);
7866 }
7867 }
7868 assert!(opened_items.len() == project_paths_to_open.len());
7869
7870 let tasks =
7871 project_paths_to_open
7872 .into_iter()
7873 .enumerate()
7874 .map(|(ix, (abs_path, project_path))| {
7875 let workspace = workspace.clone();
7876 cx.spawn(async move |cx| {
7877 let file_project_path = project_path?;
7878 let abs_path_task = workspace.update(cx, |workspace, cx| {
7879 workspace.project().update(cx, |project, cx| {
7880 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7881 })
7882 });
7883
7884 // We only want to open file paths here. If one of the items
7885 // here is a directory, it was already opened further above
7886 // with a `find_or_create_worktree`.
7887 if let Ok(task) = abs_path_task
7888 && task.await.is_none_or(|p| p.is_file())
7889 {
7890 return Some((
7891 ix,
7892 workspace
7893 .update_in(cx, |workspace, window, cx| {
7894 workspace.open_path(
7895 file_project_path,
7896 None,
7897 true,
7898 window,
7899 cx,
7900 )
7901 })
7902 .log_err()?
7903 .await,
7904 ));
7905 }
7906 None
7907 })
7908 });
7909
7910 let tasks = tasks.collect::<Vec<_>>();
7911
7912 let tasks = futures::future::join_all(tasks);
7913 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7914 opened_items[ix] = Some(path_open_result);
7915 }
7916
7917 Ok(opened_items)
7918 })
7919}
7920
7921#[derive(Clone)]
7922enum ActivateInDirectionTarget {
7923 Pane(Entity<Pane>),
7924 Dock(Entity<Dock>),
7925 Sidebar(FocusHandle),
7926}
7927
7928fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7929 window
7930 .update(cx, |multi_workspace, _, cx| {
7931 let workspace = multi_workspace.workspace().clone();
7932 workspace.update(cx, |workspace, cx| {
7933 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7934 struct DatabaseFailedNotification;
7935
7936 workspace.show_notification(
7937 NotificationId::unique::<DatabaseFailedNotification>(),
7938 cx,
7939 |cx| {
7940 cx.new(|cx| {
7941 MessageNotification::new("Failed to load the database file.", cx)
7942 .primary_message("File an Issue")
7943 .primary_icon(IconName::Plus)
7944 .primary_on_click(|window, cx| {
7945 window.dispatch_action(Box::new(FileBugReport), cx)
7946 })
7947 })
7948 },
7949 );
7950 }
7951 });
7952 })
7953 .log_err();
7954}
7955
7956fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7957 if val == 0 {
7958 ThemeSettings::get_global(cx).ui_font_size(cx)
7959 } else {
7960 px(val as f32)
7961 }
7962}
7963
7964fn adjust_active_dock_size_by_px(
7965 px: Pixels,
7966 workspace: &mut Workspace,
7967 window: &mut Window,
7968 cx: &mut Context<Workspace>,
7969) {
7970 let Some(active_dock) = workspace
7971 .all_docks()
7972 .into_iter()
7973 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7974 else {
7975 return;
7976 };
7977 let dock = active_dock.read(cx);
7978 let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
7979 return;
7980 };
7981 workspace.resize_dock(dock.position(), panel_size + px, window, cx);
7982}
7983
7984fn adjust_open_docks_size_by_px(
7985 px: Pixels,
7986 workspace: &mut Workspace,
7987 window: &mut Window,
7988 cx: &mut Context<Workspace>,
7989) {
7990 let docks = workspace
7991 .all_docks()
7992 .into_iter()
7993 .filter_map(|dock_entity| {
7994 let dock = dock_entity.read(cx);
7995 if dock.is_open() {
7996 let dock_pos = dock.position();
7997 let panel_size = workspace.dock_size(&dock, window, cx)?;
7998 Some((dock_pos, panel_size + px))
7999 } else {
8000 None
8001 }
8002 })
8003 .collect::<Vec<_>>();
8004
8005 for (position, new_size) in docks {
8006 workspace.resize_dock(position, new_size, window, cx);
8007 }
8008}
8009
8010impl Focusable for Workspace {
8011 fn focus_handle(&self, cx: &App) -> FocusHandle {
8012 self.active_pane.focus_handle(cx)
8013 }
8014}
8015
8016#[derive(Clone)]
8017struct DraggedDock(DockPosition);
8018
8019impl Render for DraggedDock {
8020 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8021 gpui::Empty
8022 }
8023}
8024
8025impl Render for Workspace {
8026 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8027 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
8028 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
8029 log::info!("Rendered first frame");
8030 }
8031
8032 let centered_layout = self.centered_layout
8033 && self.center.panes().len() == 1
8034 && self.active_item(cx).is_some();
8035 let render_padding = |size| {
8036 (size > 0.0).then(|| {
8037 div()
8038 .h_full()
8039 .w(relative(size))
8040 .bg(cx.theme().colors().editor_background)
8041 .border_color(cx.theme().colors().pane_group_border)
8042 })
8043 };
8044 let paddings = if centered_layout {
8045 let settings = WorkspaceSettings::get_global(cx).centered_layout;
8046 (
8047 render_padding(Self::adjust_padding(
8048 settings.left_padding.map(|padding| padding.0),
8049 )),
8050 render_padding(Self::adjust_padding(
8051 settings.right_padding.map(|padding| padding.0),
8052 )),
8053 )
8054 } else {
8055 (None, None)
8056 };
8057 let ui_font = theme_settings::setup_ui_font(window, cx);
8058
8059 let theme = cx.theme().clone();
8060 let colors = theme.colors();
8061 let notification_entities = self
8062 .notifications
8063 .iter()
8064 .map(|(_, notification)| notification.entity_id())
8065 .collect::<Vec<_>>();
8066 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
8067
8068 div()
8069 .relative()
8070 .size_full()
8071 .flex()
8072 .flex_col()
8073 .font(ui_font)
8074 .gap_0()
8075 .justify_start()
8076 .items_start()
8077 .text_color(colors.text)
8078 .overflow_hidden()
8079 .children(self.titlebar_item.clone())
8080 .on_modifiers_changed(move |_, _, cx| {
8081 for &id in ¬ification_entities {
8082 cx.notify(id);
8083 }
8084 })
8085 .child(
8086 div()
8087 .size_full()
8088 .relative()
8089 .flex_1()
8090 .flex()
8091 .flex_col()
8092 .child(
8093 div()
8094 .id("workspace")
8095 .bg(colors.background)
8096 .relative()
8097 .flex_1()
8098 .w_full()
8099 .flex()
8100 .flex_col()
8101 .overflow_hidden()
8102 .border_t_1()
8103 .border_b_1()
8104 .border_color(colors.border)
8105 .child({
8106 let this = cx.entity();
8107 canvas(
8108 move |bounds, window, cx| {
8109 this.update(cx, |this, cx| {
8110 let bounds_changed = this.bounds != bounds;
8111 this.bounds = bounds;
8112
8113 if bounds_changed {
8114 this.left_dock.update(cx, |dock, cx| {
8115 dock.clamp_panel_size(
8116 bounds.size.width,
8117 window,
8118 cx,
8119 )
8120 });
8121
8122 this.right_dock.update(cx, |dock, cx| {
8123 dock.clamp_panel_size(
8124 bounds.size.width,
8125 window,
8126 cx,
8127 )
8128 });
8129
8130 this.bottom_dock.update(cx, |dock, cx| {
8131 dock.clamp_panel_size(
8132 bounds.size.height,
8133 window,
8134 cx,
8135 )
8136 });
8137 }
8138 })
8139 },
8140 |_, _, _, _| {},
8141 )
8142 .absolute()
8143 .size_full()
8144 })
8145 .when(self.zoomed.is_none(), |this| {
8146 this.on_drag_move(cx.listener(
8147 move |workspace,
8148 e: &DragMoveEvent<DraggedDock>,
8149 window,
8150 cx| {
8151 if workspace.previous_dock_drag_coordinates
8152 != Some(e.event.position)
8153 {
8154 workspace.previous_dock_drag_coordinates =
8155 Some(e.event.position);
8156
8157 match e.drag(cx).0 {
8158 DockPosition::Left => {
8159 workspace.resize_left_dock(
8160 e.event.position.x
8161 - workspace.bounds.left(),
8162 window,
8163 cx,
8164 );
8165 }
8166 DockPosition::Right => {
8167 workspace.resize_right_dock(
8168 workspace.bounds.right()
8169 - e.event.position.x,
8170 window,
8171 cx,
8172 );
8173 }
8174 DockPosition::Bottom => {
8175 workspace.resize_bottom_dock(
8176 workspace.bounds.bottom()
8177 - e.event.position.y,
8178 window,
8179 cx,
8180 );
8181 }
8182 };
8183 workspace.serialize_workspace(window, cx);
8184 }
8185 },
8186 ))
8187
8188 })
8189 .child({
8190 match bottom_dock_layout {
8191 BottomDockLayout::Full => div()
8192 .flex()
8193 .flex_col()
8194 .h_full()
8195 .child(
8196 div()
8197 .flex()
8198 .flex_row()
8199 .flex_1()
8200 .overflow_hidden()
8201 .children(self.render_dock(
8202 DockPosition::Left,
8203 &self.left_dock,
8204 window,
8205 cx,
8206 ))
8207
8208 .child(
8209 div()
8210 .flex()
8211 .flex_col()
8212 .flex_1()
8213 .overflow_hidden()
8214 .child(
8215 h_flex()
8216 .flex_1()
8217 .when_some(
8218 paddings.0,
8219 |this, p| {
8220 this.child(
8221 p.border_r_1(),
8222 )
8223 },
8224 )
8225 .child(self.center.render(
8226 self.zoomed.as_ref(),
8227 &PaneRenderContext {
8228 follower_states:
8229 &self.follower_states,
8230 active_call: self.active_call(),
8231 active_pane: &self.active_pane,
8232 app_state: &self.app_state,
8233 project: &self.project,
8234 workspace: &self.weak_self,
8235 },
8236 window,
8237 cx,
8238 ))
8239 .when_some(
8240 paddings.1,
8241 |this, p| {
8242 this.child(
8243 p.border_l_1(),
8244 )
8245 },
8246 ),
8247 ),
8248 )
8249
8250 .children(self.render_dock(
8251 DockPosition::Right,
8252 &self.right_dock,
8253 window,
8254 cx,
8255 )),
8256 )
8257 .child(div().w_full().children(self.render_dock(
8258 DockPosition::Bottom,
8259 &self.bottom_dock,
8260 window,
8261 cx
8262 ))),
8263
8264 BottomDockLayout::LeftAligned => div()
8265 .flex()
8266 .flex_row()
8267 .h_full()
8268 .child(
8269 div()
8270 .flex()
8271 .flex_col()
8272 .flex_1()
8273 .h_full()
8274 .child(
8275 div()
8276 .flex()
8277 .flex_row()
8278 .flex_1()
8279 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
8280
8281 .child(
8282 div()
8283 .flex()
8284 .flex_col()
8285 .flex_1()
8286 .overflow_hidden()
8287 .child(
8288 h_flex()
8289 .flex_1()
8290 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8291 .child(self.center.render(
8292 self.zoomed.as_ref(),
8293 &PaneRenderContext {
8294 follower_states:
8295 &self.follower_states,
8296 active_call: self.active_call(),
8297 active_pane: &self.active_pane,
8298 app_state: &self.app_state,
8299 project: &self.project,
8300 workspace: &self.weak_self,
8301 },
8302 window,
8303 cx,
8304 ))
8305 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8306 )
8307 )
8308
8309 )
8310 .child(
8311 div()
8312 .w_full()
8313 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8314 ),
8315 )
8316 .children(self.render_dock(
8317 DockPosition::Right,
8318 &self.right_dock,
8319 window,
8320 cx,
8321 )),
8322 BottomDockLayout::RightAligned => div()
8323 .flex()
8324 .flex_row()
8325 .h_full()
8326 .children(self.render_dock(
8327 DockPosition::Left,
8328 &self.left_dock,
8329 window,
8330 cx,
8331 ))
8332
8333 .child(
8334 div()
8335 .flex()
8336 .flex_col()
8337 .flex_1()
8338 .h_full()
8339 .child(
8340 div()
8341 .flex()
8342 .flex_row()
8343 .flex_1()
8344 .child(
8345 div()
8346 .flex()
8347 .flex_col()
8348 .flex_1()
8349 .overflow_hidden()
8350 .child(
8351 h_flex()
8352 .flex_1()
8353 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8354 .child(self.center.render(
8355 self.zoomed.as_ref(),
8356 &PaneRenderContext {
8357 follower_states:
8358 &self.follower_states,
8359 active_call: self.active_call(),
8360 active_pane: &self.active_pane,
8361 app_state: &self.app_state,
8362 project: &self.project,
8363 workspace: &self.weak_self,
8364 },
8365 window,
8366 cx,
8367 ))
8368 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8369 )
8370 )
8371
8372 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8373 )
8374 .child(
8375 div()
8376 .w_full()
8377 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8378 ),
8379 ),
8380 BottomDockLayout::Contained => div()
8381 .flex()
8382 .flex_row()
8383 .h_full()
8384 .children(self.render_dock(
8385 DockPosition::Left,
8386 &self.left_dock,
8387 window,
8388 cx,
8389 ))
8390
8391 .child(
8392 div()
8393 .flex()
8394 .flex_col()
8395 .flex_1()
8396 .overflow_hidden()
8397 .child(
8398 h_flex()
8399 .flex_1()
8400 .when_some(paddings.0, |this, p| {
8401 this.child(p.border_r_1())
8402 })
8403 .child(self.center.render(
8404 self.zoomed.as_ref(),
8405 &PaneRenderContext {
8406 follower_states:
8407 &self.follower_states,
8408 active_call: self.active_call(),
8409 active_pane: &self.active_pane,
8410 app_state: &self.app_state,
8411 project: &self.project,
8412 workspace: &self.weak_self,
8413 },
8414 window,
8415 cx,
8416 ))
8417 .when_some(paddings.1, |this, p| {
8418 this.child(p.border_l_1())
8419 }),
8420 )
8421 .children(self.render_dock(
8422 DockPosition::Bottom,
8423 &self.bottom_dock,
8424 window,
8425 cx,
8426 )),
8427 )
8428
8429 .children(self.render_dock(
8430 DockPosition::Right,
8431 &self.right_dock,
8432 window,
8433 cx,
8434 )),
8435 }
8436 })
8437 .children(self.zoomed.as_ref().and_then(|view| {
8438 let zoomed_view = view.upgrade()?;
8439 let div = div()
8440 .occlude()
8441 .absolute()
8442 .overflow_hidden()
8443 .border_color(colors.border)
8444 .bg(colors.background)
8445 .child(zoomed_view)
8446 .inset_0()
8447 .shadow_lg();
8448
8449 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8450 return Some(div);
8451 }
8452
8453 Some(match self.zoomed_position {
8454 Some(DockPosition::Left) => div.right_2().border_r_1(),
8455 Some(DockPosition::Right) => div.left_2().border_l_1(),
8456 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8457 None => {
8458 div.top_2().bottom_2().left_2().right_2().border_1()
8459 }
8460 })
8461 }))
8462 .children(self.render_notifications(window, cx)),
8463 )
8464 .when(self.status_bar_visible(cx), |parent| {
8465 parent.child(self.status_bar.clone())
8466 })
8467 .child(self.toast_layer.clone()),
8468 )
8469 }
8470}
8471
8472impl WorkspaceStore {
8473 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8474 Self {
8475 workspaces: Default::default(),
8476 _subscriptions: vec![
8477 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8478 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8479 ],
8480 client,
8481 }
8482 }
8483
8484 pub fn update_followers(
8485 &self,
8486 project_id: Option<u64>,
8487 update: proto::update_followers::Variant,
8488 cx: &App,
8489 ) -> Option<()> {
8490 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8491 let room_id = active_call.0.room_id(cx)?;
8492 self.client
8493 .send(proto::UpdateFollowers {
8494 room_id,
8495 project_id,
8496 variant: Some(update),
8497 })
8498 .log_err()
8499 }
8500
8501 pub async fn handle_follow(
8502 this: Entity<Self>,
8503 envelope: TypedEnvelope<proto::Follow>,
8504 mut cx: AsyncApp,
8505 ) -> Result<proto::FollowResponse> {
8506 this.update(&mut cx, |this, cx| {
8507 let follower = Follower {
8508 project_id: envelope.payload.project_id,
8509 peer_id: envelope.original_sender_id()?,
8510 };
8511
8512 let mut response = proto::FollowResponse::default();
8513
8514 this.workspaces.retain(|(window_handle, weak_workspace)| {
8515 let Some(workspace) = weak_workspace.upgrade() else {
8516 return false;
8517 };
8518 window_handle
8519 .update(cx, |_, window, cx| {
8520 workspace.update(cx, |workspace, cx| {
8521 let handler_response =
8522 workspace.handle_follow(follower.project_id, window, cx);
8523 if let Some(active_view) = handler_response.active_view
8524 && workspace.project.read(cx).remote_id() == follower.project_id
8525 {
8526 response.active_view = Some(active_view)
8527 }
8528 });
8529 })
8530 .is_ok()
8531 });
8532
8533 Ok(response)
8534 })
8535 }
8536
8537 async fn handle_update_followers(
8538 this: Entity<Self>,
8539 envelope: TypedEnvelope<proto::UpdateFollowers>,
8540 mut cx: AsyncApp,
8541 ) -> Result<()> {
8542 let leader_id = envelope.original_sender_id()?;
8543 let update = envelope.payload;
8544
8545 this.update(&mut cx, |this, cx| {
8546 this.workspaces.retain(|(window_handle, weak_workspace)| {
8547 let Some(workspace) = weak_workspace.upgrade() else {
8548 return false;
8549 };
8550 window_handle
8551 .update(cx, |_, window, cx| {
8552 workspace.update(cx, |workspace, cx| {
8553 let project_id = workspace.project.read(cx).remote_id();
8554 if update.project_id != project_id && update.project_id.is_some() {
8555 return;
8556 }
8557 workspace.handle_update_followers(
8558 leader_id,
8559 update.clone(),
8560 window,
8561 cx,
8562 );
8563 });
8564 })
8565 .is_ok()
8566 });
8567 Ok(())
8568 })
8569 }
8570
8571 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8572 self.workspaces.iter().map(|(_, weak)| weak)
8573 }
8574
8575 pub fn workspaces_with_windows(
8576 &self,
8577 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8578 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8579 }
8580}
8581
8582impl ViewId {
8583 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8584 Ok(Self {
8585 creator: message
8586 .creator
8587 .map(CollaboratorId::PeerId)
8588 .context("creator is missing")?,
8589 id: message.id,
8590 })
8591 }
8592
8593 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8594 if let CollaboratorId::PeerId(peer_id) = self.creator {
8595 Some(proto::ViewId {
8596 creator: Some(peer_id),
8597 id: self.id,
8598 })
8599 } else {
8600 None
8601 }
8602 }
8603}
8604
8605impl FollowerState {
8606 fn pane(&self) -> &Entity<Pane> {
8607 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8608 }
8609}
8610
8611pub trait WorkspaceHandle {
8612 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8613}
8614
8615impl WorkspaceHandle for Entity<Workspace> {
8616 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8617 self.read(cx)
8618 .worktrees(cx)
8619 .flat_map(|worktree| {
8620 let worktree_id = worktree.read(cx).id();
8621 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8622 worktree_id,
8623 path: f.path.clone(),
8624 })
8625 })
8626 .collect::<Vec<_>>()
8627 }
8628}
8629
8630pub async fn last_opened_workspace_location(
8631 db: &WorkspaceDb,
8632 fs: &dyn fs::Fs,
8633) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8634 db.last_workspace(fs)
8635 .await
8636 .log_err()
8637 .flatten()
8638 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8639}
8640
8641pub async fn last_session_workspace_locations(
8642 db: &WorkspaceDb,
8643 last_session_id: &str,
8644 last_session_window_stack: Option<Vec<WindowId>>,
8645 fs: &dyn fs::Fs,
8646) -> Option<Vec<SessionWorkspace>> {
8647 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8648 .await
8649 .log_err()
8650}
8651
8652pub async fn restore_multiworkspace(
8653 multi_workspace: SerializedMultiWorkspace,
8654 app_state: Arc<AppState>,
8655 cx: &mut AsyncApp,
8656) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8657 let SerializedMultiWorkspace {
8658 active_workspace,
8659 state,
8660 } = multi_workspace;
8661 let MultiWorkspaceState {
8662 sidebar_open,
8663 project_group_keys,
8664 sidebar_state,
8665 ..
8666 } = state;
8667
8668 let window_handle = if active_workspace.paths.is_empty() {
8669 cx.update(|cx| {
8670 open_workspace_by_id(active_workspace.workspace_id, app_state.clone(), None, cx)
8671 })
8672 .await?
8673 } else {
8674 let OpenResult { window, .. } = cx
8675 .update(|cx| {
8676 Workspace::new_local(
8677 active_workspace.paths.paths().to_vec(),
8678 app_state.clone(),
8679 None,
8680 None,
8681 None,
8682 OpenMode::Activate,
8683 cx,
8684 )
8685 })
8686 .await?;
8687 window
8688 };
8689
8690 if !project_group_keys.is_empty() {
8691 let restored_keys: Vec<ProjectGroupKey> =
8692 project_group_keys.into_iter().map(Into::into).collect();
8693 window_handle
8694 .update(cx, |multi_workspace, _window, _cx| {
8695 multi_workspace.restore_project_group_keys(restored_keys);
8696 })
8697 .ok();
8698 }
8699
8700 if sidebar_open {
8701 window_handle
8702 .update(cx, |multi_workspace, _, cx| {
8703 multi_workspace.open_sidebar(cx);
8704 })
8705 .ok();
8706 }
8707
8708 if let Some(sidebar_state) = sidebar_state {
8709 window_handle
8710 .update(cx, |multi_workspace, window, cx| {
8711 if let Some(sidebar) = multi_workspace.sidebar() {
8712 sidebar.restore_serialized_state(&sidebar_state, window, cx);
8713 }
8714 multi_workspace.serialize(cx);
8715 })
8716 .ok();
8717 }
8718
8719 window_handle
8720 .update(cx, |_, window, _cx| {
8721 window.activate_window();
8722 })
8723 .ok();
8724
8725 Ok(window_handle)
8726}
8727
8728actions!(
8729 collab,
8730 [
8731 /// Opens the channel notes for the current call.
8732 ///
8733 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8734 /// channel in the collab panel.
8735 ///
8736 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8737 /// can be copied via "Copy link to section" in the context menu of the channel notes
8738 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8739 OpenChannelNotes,
8740 /// Mutes your microphone.
8741 Mute,
8742 /// Deafens yourself (mute both microphone and speakers).
8743 Deafen,
8744 /// Leaves the current call.
8745 LeaveCall,
8746 /// Shares the current project with collaborators.
8747 ShareProject,
8748 /// Shares your screen with collaborators.
8749 ScreenShare,
8750 /// Copies the current room name and session id for debugging purposes.
8751 CopyRoomId,
8752 ]
8753);
8754
8755/// Opens the channel notes for a specific channel by its ID.
8756#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8757#[action(namespace = collab)]
8758#[serde(deny_unknown_fields)]
8759pub struct OpenChannelNotesById {
8760 pub channel_id: u64,
8761}
8762
8763actions!(
8764 zed,
8765 [
8766 /// Opens the Zed log file.
8767 OpenLog,
8768 /// Reveals the Zed log file in the system file manager.
8769 RevealLogInFileManager
8770 ]
8771);
8772
8773async fn join_channel_internal(
8774 channel_id: ChannelId,
8775 app_state: &Arc<AppState>,
8776 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8777 requesting_workspace: Option<WeakEntity<Workspace>>,
8778 active_call: &dyn AnyActiveCall,
8779 cx: &mut AsyncApp,
8780) -> Result<bool> {
8781 let (should_prompt, already_in_channel) = cx.update(|cx| {
8782 if !active_call.is_in_room(cx) {
8783 return (false, false);
8784 }
8785
8786 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8787 let should_prompt = active_call.is_sharing_project(cx)
8788 && active_call.has_remote_participants(cx)
8789 && !already_in_channel;
8790 (should_prompt, already_in_channel)
8791 });
8792
8793 if already_in_channel {
8794 let task = cx.update(|cx| {
8795 if let Some((project, host)) = active_call.most_active_project(cx) {
8796 Some(join_in_room_project(project, host, app_state.clone(), cx))
8797 } else {
8798 None
8799 }
8800 });
8801 if let Some(task) = task {
8802 task.await?;
8803 }
8804 return anyhow::Ok(true);
8805 }
8806
8807 if should_prompt {
8808 if let Some(multi_workspace) = requesting_window {
8809 let answer = multi_workspace
8810 .update(cx, |_, window, cx| {
8811 window.prompt(
8812 PromptLevel::Warning,
8813 "Do you want to switch channels?",
8814 Some("Leaving this call will unshare your current project."),
8815 &["Yes, Join Channel", "Cancel"],
8816 cx,
8817 )
8818 })?
8819 .await;
8820
8821 if answer == Ok(1) {
8822 return Ok(false);
8823 }
8824 } else {
8825 return Ok(false);
8826 }
8827 }
8828
8829 let client = cx.update(|cx| active_call.client(cx));
8830
8831 let mut client_status = client.status();
8832
8833 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8834 'outer: loop {
8835 let Some(status) = client_status.recv().await else {
8836 anyhow::bail!("error connecting");
8837 };
8838
8839 match status {
8840 Status::Connecting
8841 | Status::Authenticating
8842 | Status::Authenticated
8843 | Status::Reconnecting
8844 | Status::Reauthenticating
8845 | Status::Reauthenticated => continue,
8846 Status::Connected { .. } => break 'outer,
8847 Status::SignedOut | Status::AuthenticationError => {
8848 return Err(ErrorCode::SignedOut.into());
8849 }
8850 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8851 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8852 return Err(ErrorCode::Disconnected.into());
8853 }
8854 }
8855 }
8856
8857 let joined = cx
8858 .update(|cx| active_call.join_channel(channel_id, cx))
8859 .await?;
8860
8861 if !joined {
8862 return anyhow::Ok(true);
8863 }
8864
8865 cx.update(|cx| active_call.room_update_completed(cx)).await;
8866
8867 let task = cx.update(|cx| {
8868 if let Some((project, host)) = active_call.most_active_project(cx) {
8869 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8870 }
8871
8872 // If you are the first to join a channel, see if you should share your project.
8873 if !active_call.has_remote_participants(cx)
8874 && !active_call.local_participant_is_guest(cx)
8875 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8876 {
8877 let project = workspace.update(cx, |workspace, cx| {
8878 let project = workspace.project.read(cx);
8879
8880 if !active_call.share_on_join(cx) {
8881 return None;
8882 }
8883
8884 if (project.is_local() || project.is_via_remote_server())
8885 && project.visible_worktrees(cx).any(|tree| {
8886 tree.read(cx)
8887 .root_entry()
8888 .is_some_and(|entry| entry.is_dir())
8889 })
8890 {
8891 Some(workspace.project.clone())
8892 } else {
8893 None
8894 }
8895 });
8896 if let Some(project) = project {
8897 let share_task = active_call.share_project(project, cx);
8898 return Some(cx.spawn(async move |_cx| -> Result<()> {
8899 share_task.await?;
8900 Ok(())
8901 }));
8902 }
8903 }
8904
8905 None
8906 });
8907 if let Some(task) = task {
8908 task.await?;
8909 return anyhow::Ok(true);
8910 }
8911 anyhow::Ok(false)
8912}
8913
8914pub fn join_channel(
8915 channel_id: ChannelId,
8916 app_state: Arc<AppState>,
8917 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8918 requesting_workspace: Option<WeakEntity<Workspace>>,
8919 cx: &mut App,
8920) -> Task<Result<()>> {
8921 let active_call = GlobalAnyActiveCall::global(cx).clone();
8922 cx.spawn(async move |cx| {
8923 let result = join_channel_internal(
8924 channel_id,
8925 &app_state,
8926 requesting_window,
8927 requesting_workspace,
8928 &*active_call.0,
8929 cx,
8930 )
8931 .await;
8932
8933 // join channel succeeded, and opened a window
8934 if matches!(result, Ok(true)) {
8935 return anyhow::Ok(());
8936 }
8937
8938 // find an existing workspace to focus and show call controls
8939 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8940 if active_window.is_none() {
8941 // no open workspaces, make one to show the error in (blergh)
8942 let OpenResult {
8943 window: window_handle,
8944 ..
8945 } = cx
8946 .update(|cx| {
8947 Workspace::new_local(
8948 vec![],
8949 app_state.clone(),
8950 requesting_window,
8951 None,
8952 None,
8953 OpenMode::Activate,
8954 cx,
8955 )
8956 })
8957 .await?;
8958
8959 window_handle
8960 .update(cx, |_, window, _cx| {
8961 window.activate_window();
8962 })
8963 .ok();
8964
8965 if result.is_ok() {
8966 cx.update(|cx| {
8967 cx.dispatch_action(&OpenChannelNotes);
8968 });
8969 }
8970
8971 active_window = Some(window_handle);
8972 }
8973
8974 if let Err(err) = result {
8975 log::error!("failed to join channel: {}", err);
8976 if let Some(active_window) = active_window {
8977 active_window
8978 .update(cx, |_, window, cx| {
8979 let detail: SharedString = match err.error_code() {
8980 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8981 ErrorCode::UpgradeRequired => concat!(
8982 "Your are running an unsupported version of Zed. ",
8983 "Please update to continue."
8984 )
8985 .into(),
8986 ErrorCode::NoSuchChannel => concat!(
8987 "No matching channel was found. ",
8988 "Please check the link and try again."
8989 )
8990 .into(),
8991 ErrorCode::Forbidden => concat!(
8992 "This channel is private, and you do not have access. ",
8993 "Please ask someone to add you and try again."
8994 )
8995 .into(),
8996 ErrorCode::Disconnected => {
8997 "Please check your internet connection and try again.".into()
8998 }
8999 _ => format!("{}\n\nPlease try again.", err).into(),
9000 };
9001 window.prompt(
9002 PromptLevel::Critical,
9003 "Failed to join channel",
9004 Some(&detail),
9005 &["Ok"],
9006 cx,
9007 )
9008 })?
9009 .await
9010 .ok();
9011 }
9012 }
9013
9014 // return ok, we showed the error to the user.
9015 anyhow::Ok(())
9016 })
9017}
9018
9019pub async fn get_any_active_multi_workspace(
9020 app_state: Arc<AppState>,
9021 mut cx: AsyncApp,
9022) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
9023 // find an existing workspace to focus and show call controls
9024 let active_window = activate_any_workspace_window(&mut cx);
9025 if active_window.is_none() {
9026 cx.update(|cx| {
9027 Workspace::new_local(
9028 vec![],
9029 app_state.clone(),
9030 None,
9031 None,
9032 None,
9033 OpenMode::Activate,
9034 cx,
9035 )
9036 })
9037 .await?;
9038 }
9039 activate_any_workspace_window(&mut cx).context("could not open zed")
9040}
9041
9042fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
9043 cx.update(|cx| {
9044 if let Some(workspace_window) = cx
9045 .active_window()
9046 .and_then(|window| window.downcast::<MultiWorkspace>())
9047 {
9048 return Some(workspace_window);
9049 }
9050
9051 for window in cx.windows() {
9052 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
9053 workspace_window
9054 .update(cx, |_, window, _| window.activate_window())
9055 .ok();
9056 return Some(workspace_window);
9057 }
9058 }
9059 None
9060 })
9061}
9062
9063pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
9064 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
9065}
9066
9067pub fn workspace_windows_for_location(
9068 serialized_location: &SerializedWorkspaceLocation,
9069 cx: &App,
9070) -> Vec<WindowHandle<MultiWorkspace>> {
9071 cx.windows()
9072 .into_iter()
9073 .filter_map(|window| window.downcast::<MultiWorkspace>())
9074 .filter(|multi_workspace| {
9075 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
9076 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
9077 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
9078 }
9079 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
9080 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
9081 a.distro_name == b.distro_name
9082 }
9083 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
9084 a.container_id == b.container_id
9085 }
9086 #[cfg(any(test, feature = "test-support"))]
9087 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
9088 a.id == b.id
9089 }
9090 _ => false,
9091 };
9092
9093 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
9094 multi_workspace.workspaces().iter().any(|workspace| {
9095 match workspace.read(cx).workspace_location(cx) {
9096 WorkspaceLocation::Location(location, _) => {
9097 match (&location, serialized_location) {
9098 (
9099 SerializedWorkspaceLocation::Local,
9100 SerializedWorkspaceLocation::Local,
9101 ) => true,
9102 (
9103 SerializedWorkspaceLocation::Remote(a),
9104 SerializedWorkspaceLocation::Remote(b),
9105 ) => same_host(a, b),
9106 _ => false,
9107 }
9108 }
9109 _ => false,
9110 }
9111 })
9112 })
9113 })
9114 .collect()
9115}
9116
9117pub async fn find_existing_workspace(
9118 abs_paths: &[PathBuf],
9119 open_options: &OpenOptions,
9120 location: &SerializedWorkspaceLocation,
9121 cx: &mut AsyncApp,
9122) -> (
9123 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
9124 OpenVisible,
9125) {
9126 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
9127 let mut open_visible = OpenVisible::All;
9128 let mut best_match = None;
9129
9130 if open_options.open_new_workspace != Some(true) {
9131 cx.update(|cx| {
9132 for window in workspace_windows_for_location(location, cx) {
9133 if let Ok(multi_workspace) = window.read(cx) {
9134 for workspace in multi_workspace.workspaces() {
9135 let project = workspace.read(cx).project.read(cx);
9136 let m = project.visibility_for_paths(
9137 abs_paths,
9138 open_options.open_new_workspace == None,
9139 cx,
9140 );
9141 if m > best_match {
9142 existing = Some((window, workspace.clone()));
9143 best_match = m;
9144 } else if best_match.is_none()
9145 && open_options.open_new_workspace == Some(false)
9146 {
9147 existing = Some((window, workspace.clone()))
9148 }
9149 }
9150 }
9151 }
9152 });
9153
9154 let all_paths_are_files = existing
9155 .as_ref()
9156 .and_then(|(_, target_workspace)| {
9157 cx.update(|cx| {
9158 let workspace = target_workspace.read(cx);
9159 let project = workspace.project.read(cx);
9160 let path_style = workspace.path_style(cx);
9161 Some(!abs_paths.iter().any(|path| {
9162 let path = util::paths::SanitizedPath::new(path);
9163 project.worktrees(cx).any(|worktree| {
9164 let worktree = worktree.read(cx);
9165 let abs_path = worktree.abs_path();
9166 path_style
9167 .strip_prefix(path.as_ref(), abs_path.as_ref())
9168 .and_then(|rel| worktree.entry_for_path(&rel))
9169 .is_some_and(|e| e.is_dir())
9170 })
9171 }))
9172 })
9173 })
9174 .unwrap_or(false);
9175
9176 if open_options.open_new_workspace.is_none()
9177 && existing.is_some()
9178 && open_options.wait
9179 && all_paths_are_files
9180 {
9181 cx.update(|cx| {
9182 let windows = workspace_windows_for_location(location, cx);
9183 let window = cx
9184 .active_window()
9185 .and_then(|window| window.downcast::<MultiWorkspace>())
9186 .filter(|window| windows.contains(window))
9187 .or_else(|| windows.into_iter().next());
9188 if let Some(window) = window {
9189 if let Ok(multi_workspace) = window.read(cx) {
9190 let active_workspace = multi_workspace.workspace().clone();
9191 existing = Some((window, active_workspace));
9192 open_visible = OpenVisible::None;
9193 }
9194 }
9195 });
9196 }
9197 }
9198 (existing, open_visible)
9199}
9200
9201#[derive(Default, Clone)]
9202pub struct OpenOptions {
9203 pub visible: Option<OpenVisible>,
9204 pub focus: Option<bool>,
9205 pub open_new_workspace: Option<bool>,
9206 pub wait: bool,
9207 pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
9208 pub open_mode: OpenMode,
9209 pub env: Option<HashMap<String, String>>,
9210 pub open_in_dev_container: bool,
9211}
9212
9213/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
9214/// or [`Workspace::open_workspace_for_paths`].
9215pub struct OpenResult {
9216 pub window: WindowHandle<MultiWorkspace>,
9217 pub workspace: Entity<Workspace>,
9218 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
9219}
9220
9221/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
9222pub fn open_workspace_by_id(
9223 workspace_id: WorkspaceId,
9224 app_state: Arc<AppState>,
9225 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9226 cx: &mut App,
9227) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
9228 let project_handle = Project::local(
9229 app_state.client.clone(),
9230 app_state.node_runtime.clone(),
9231 app_state.user_store.clone(),
9232 app_state.languages.clone(),
9233 app_state.fs.clone(),
9234 None,
9235 project::LocalProjectFlags {
9236 init_worktree_trust: true,
9237 ..project::LocalProjectFlags::default()
9238 },
9239 cx,
9240 );
9241
9242 let db = WorkspaceDb::global(cx);
9243 let kvp = db::kvp::KeyValueStore::global(cx);
9244 cx.spawn(async move |cx| {
9245 let serialized_workspace = db
9246 .workspace_for_id(workspace_id)
9247 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
9248
9249 let centered_layout = serialized_workspace.centered_layout;
9250
9251 let (window, workspace) = if let Some(window) = requesting_window {
9252 let workspace = window.update(cx, |multi_workspace, window, cx| {
9253 let workspace = cx.new(|cx| {
9254 let mut workspace = Workspace::new(
9255 Some(workspace_id),
9256 project_handle.clone(),
9257 app_state.clone(),
9258 window,
9259 cx,
9260 );
9261 workspace.centered_layout = centered_layout;
9262 workspace
9263 });
9264 multi_workspace.add(workspace.clone(), &*window, cx);
9265 workspace
9266 })?;
9267 (window, workspace)
9268 } else {
9269 let window_bounds_override = window_bounds_env_override();
9270
9271 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
9272 (Some(WindowBounds::Windowed(bounds)), None)
9273 } else if let Some(display) = serialized_workspace.display
9274 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
9275 {
9276 (Some(bounds.0), Some(display))
9277 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
9278 (Some(bounds), Some(display))
9279 } else {
9280 (None, None)
9281 };
9282
9283 let options = cx.update(|cx| {
9284 let mut options = (app_state.build_window_options)(display, cx);
9285 options.window_bounds = window_bounds;
9286 options
9287 });
9288
9289 let window = cx.open_window(options, {
9290 let app_state = app_state.clone();
9291 let project_handle = project_handle.clone();
9292 move |window, cx| {
9293 let workspace = cx.new(|cx| {
9294 let mut workspace = Workspace::new(
9295 Some(workspace_id),
9296 project_handle,
9297 app_state,
9298 window,
9299 cx,
9300 );
9301 workspace.centered_layout = centered_layout;
9302 workspace
9303 });
9304 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9305 }
9306 })?;
9307
9308 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9309 multi_workspace.workspace().clone()
9310 })?;
9311
9312 (window, workspace)
9313 };
9314
9315 notify_if_database_failed(window, cx);
9316
9317 // Restore items from the serialized workspace
9318 window
9319 .update(cx, |_, window, cx| {
9320 workspace.update(cx, |_workspace, cx| {
9321 open_items(Some(serialized_workspace), vec![], window, cx)
9322 })
9323 })?
9324 .await?;
9325
9326 window.update(cx, |_, window, cx| {
9327 workspace.update(cx, |workspace, cx| {
9328 workspace.serialize_workspace(window, cx);
9329 });
9330 })?;
9331
9332 Ok(window)
9333 })
9334}
9335
9336#[allow(clippy::type_complexity)]
9337pub fn open_paths(
9338 abs_paths: &[PathBuf],
9339 app_state: Arc<AppState>,
9340 mut open_options: OpenOptions,
9341 cx: &mut App,
9342) -> Task<anyhow::Result<OpenResult>> {
9343 let abs_paths = abs_paths.to_vec();
9344 #[cfg(target_os = "windows")]
9345 let wsl_path = abs_paths
9346 .iter()
9347 .find_map(|p| util::paths::WslPath::from_path(p));
9348
9349 cx.spawn(async move |cx| {
9350 let (mut existing, mut open_visible) = find_existing_workspace(
9351 &abs_paths,
9352 &open_options,
9353 &SerializedWorkspaceLocation::Local,
9354 cx,
9355 )
9356 .await;
9357
9358 // Fallback: if no workspace contains the paths and all paths are files,
9359 // prefer an existing local workspace window (active window first).
9360 if open_options.open_new_workspace.is_none() && existing.is_none() {
9361 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9362 let all_metadatas = futures::future::join_all(all_paths)
9363 .await
9364 .into_iter()
9365 .filter_map(|result| result.ok().flatten());
9366
9367 if all_metadatas.into_iter().all(|file| !file.is_dir) {
9368 cx.update(|cx| {
9369 let windows = workspace_windows_for_location(
9370 &SerializedWorkspaceLocation::Local,
9371 cx,
9372 );
9373 let window = cx
9374 .active_window()
9375 .and_then(|window| window.downcast::<MultiWorkspace>())
9376 .filter(|window| windows.contains(window))
9377 .or_else(|| windows.into_iter().next());
9378 if let Some(window) = window {
9379 if let Ok(multi_workspace) = window.read(cx) {
9380 let active_workspace = multi_workspace.workspace().clone();
9381 existing = Some((window, active_workspace));
9382 open_visible = OpenVisible::None;
9383 }
9384 }
9385 });
9386 }
9387 }
9388
9389 // Fallback for directories: when no flag is specified and no existing
9390 // workspace matched, add the directory as a new workspace in the
9391 // active window's MultiWorkspace (instead of opening a new window).
9392 if open_options.open_new_workspace.is_none() && existing.is_none() {
9393 let target_window = cx.update(|cx| {
9394 let windows = workspace_windows_for_location(
9395 &SerializedWorkspaceLocation::Local,
9396 cx,
9397 );
9398 let window = cx
9399 .active_window()
9400 .and_then(|window| window.downcast::<MultiWorkspace>())
9401 .filter(|window| windows.contains(window))
9402 .or_else(|| windows.into_iter().next());
9403 window.filter(|window| {
9404 window.read(cx).is_ok_and(|mw| mw.multi_workspace_enabled(cx))
9405 })
9406 });
9407
9408 if let Some(window) = target_window {
9409 open_options.requesting_window = Some(window);
9410 window
9411 .update(cx, |multi_workspace, _, cx| {
9412 multi_workspace.open_sidebar(cx);
9413 })
9414 .log_err();
9415 }
9416 }
9417
9418 let open_in_dev_container = open_options.open_in_dev_container;
9419
9420 let result = if let Some((existing, target_workspace)) = existing {
9421 let open_task = existing
9422 .update(cx, |multi_workspace, window, cx| {
9423 window.activate_window();
9424 multi_workspace.activate(target_workspace.clone(), window, cx);
9425 target_workspace.update(cx, |workspace, cx| {
9426 if open_in_dev_container {
9427 workspace.set_open_in_dev_container(true);
9428 }
9429 workspace.open_paths(
9430 abs_paths,
9431 OpenOptions {
9432 visible: Some(open_visible),
9433 ..Default::default()
9434 },
9435 None,
9436 window,
9437 cx,
9438 )
9439 })
9440 })?
9441 .await;
9442
9443 _ = existing.update(cx, |multi_workspace, _, cx| {
9444 let workspace = multi_workspace.workspace().clone();
9445 workspace.update(cx, |workspace, cx| {
9446 for item in open_task.iter().flatten() {
9447 if let Err(e) = item {
9448 workspace.show_error(&e, cx);
9449 }
9450 }
9451 });
9452 });
9453
9454 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9455 } else {
9456 let init = if open_in_dev_container {
9457 Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {
9458 workspace.set_open_in_dev_container(true);
9459 }) as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>)
9460 } else {
9461 None
9462 };
9463 let result = cx
9464 .update(move |cx| {
9465 Workspace::new_local(
9466 abs_paths,
9467 app_state.clone(),
9468 open_options.requesting_window,
9469 open_options.env,
9470 init,
9471 open_options.open_mode,
9472 cx,
9473 )
9474 })
9475 .await;
9476
9477 if let Ok(ref result) = result {
9478 result.window
9479 .update(cx, |_, window, _cx| {
9480 window.activate_window();
9481 })
9482 .log_err();
9483 }
9484
9485 result
9486 };
9487
9488 #[cfg(target_os = "windows")]
9489 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9490 && let Ok(ref result) = result
9491 {
9492 result.window
9493 .update(cx, move |multi_workspace, _window, cx| {
9494 struct OpenInWsl;
9495 let workspace = multi_workspace.workspace().clone();
9496 workspace.update(cx, |workspace, cx| {
9497 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9498 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9499 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9500 cx.new(move |cx| {
9501 MessageNotification::new(msg, cx)
9502 .primary_message("Open in WSL")
9503 .primary_icon(IconName::FolderOpen)
9504 .primary_on_click(move |window, cx| {
9505 window.dispatch_action(Box::new(remote::OpenWslPath {
9506 distro: remote::WslConnectionOptions {
9507 distro_name: distro.clone(),
9508 user: None,
9509 },
9510 paths: vec![path.clone().into()],
9511 }), cx)
9512 })
9513 })
9514 });
9515 });
9516 })
9517 .unwrap();
9518 };
9519 result
9520 })
9521}
9522
9523pub fn open_new(
9524 open_options: OpenOptions,
9525 app_state: Arc<AppState>,
9526 cx: &mut App,
9527 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9528) -> Task<anyhow::Result<()>> {
9529 let addition = open_options.open_mode;
9530 let task = Workspace::new_local(
9531 Vec::new(),
9532 app_state,
9533 open_options.requesting_window,
9534 open_options.env,
9535 Some(Box::new(init)),
9536 addition,
9537 cx,
9538 );
9539 cx.spawn(async move |cx| {
9540 let OpenResult { window, .. } = task.await?;
9541 window
9542 .update(cx, |_, window, _cx| {
9543 window.activate_window();
9544 })
9545 .ok();
9546 Ok(())
9547 })
9548}
9549
9550pub fn create_and_open_local_file(
9551 path: &'static Path,
9552 window: &mut Window,
9553 cx: &mut Context<Workspace>,
9554 default_content: impl 'static + Send + FnOnce() -> Rope,
9555) -> Task<Result<Box<dyn ItemHandle>>> {
9556 cx.spawn_in(window, async move |workspace, cx| {
9557 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9558 if !fs.is_file(path).await {
9559 fs.create_file(path, Default::default()).await?;
9560 fs.save(path, &default_content(), Default::default())
9561 .await?;
9562 }
9563
9564 workspace
9565 .update_in(cx, |workspace, window, cx| {
9566 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9567 let path = workspace
9568 .project
9569 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9570 cx.spawn_in(window, async move |workspace, cx| {
9571 let path = path.await?;
9572
9573 let path = fs.canonicalize(&path).await.unwrap_or(path);
9574
9575 let mut items = workspace
9576 .update_in(cx, |workspace, window, cx| {
9577 workspace.open_paths(
9578 vec![path.to_path_buf()],
9579 OpenOptions {
9580 visible: Some(OpenVisible::None),
9581 ..Default::default()
9582 },
9583 None,
9584 window,
9585 cx,
9586 )
9587 })?
9588 .await;
9589 let item = items.pop().flatten();
9590 item.with_context(|| format!("path {path:?} is not a file"))?
9591 })
9592 })
9593 })?
9594 .await?
9595 .await
9596 })
9597}
9598
9599pub fn open_remote_project_with_new_connection(
9600 window: WindowHandle<MultiWorkspace>,
9601 remote_connection: Arc<dyn RemoteConnection>,
9602 cancel_rx: oneshot::Receiver<()>,
9603 delegate: Arc<dyn RemoteClientDelegate>,
9604 app_state: Arc<AppState>,
9605 paths: Vec<PathBuf>,
9606 cx: &mut App,
9607) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9608 cx.spawn(async move |cx| {
9609 let (workspace_id, serialized_workspace) =
9610 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9611 .await?;
9612
9613 let session = match cx
9614 .update(|cx| {
9615 remote::RemoteClient::new(
9616 ConnectionIdentifier::Workspace(workspace_id.0),
9617 remote_connection,
9618 cancel_rx,
9619 delegate,
9620 cx,
9621 )
9622 })
9623 .await?
9624 {
9625 Some(result) => result,
9626 None => return Ok(Vec::new()),
9627 };
9628
9629 let project = cx.update(|cx| {
9630 project::Project::remote(
9631 session,
9632 app_state.client.clone(),
9633 app_state.node_runtime.clone(),
9634 app_state.user_store.clone(),
9635 app_state.languages.clone(),
9636 app_state.fs.clone(),
9637 true,
9638 cx,
9639 )
9640 });
9641
9642 open_remote_project_inner(
9643 project,
9644 paths,
9645 workspace_id,
9646 serialized_workspace,
9647 app_state,
9648 window,
9649 cx,
9650 )
9651 .await
9652 })
9653}
9654
9655pub fn open_remote_project_with_existing_connection(
9656 connection_options: RemoteConnectionOptions,
9657 project: Entity<Project>,
9658 paths: Vec<PathBuf>,
9659 app_state: Arc<AppState>,
9660 window: WindowHandle<MultiWorkspace>,
9661 cx: &mut AsyncApp,
9662) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9663 cx.spawn(async move |cx| {
9664 let (workspace_id, serialized_workspace) =
9665 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9666
9667 open_remote_project_inner(
9668 project,
9669 paths,
9670 workspace_id,
9671 serialized_workspace,
9672 app_state,
9673 window,
9674 cx,
9675 )
9676 .await
9677 })
9678}
9679
9680async fn open_remote_project_inner(
9681 project: Entity<Project>,
9682 paths: Vec<PathBuf>,
9683 workspace_id: WorkspaceId,
9684 serialized_workspace: Option<SerializedWorkspace>,
9685 app_state: Arc<AppState>,
9686 window: WindowHandle<MultiWorkspace>,
9687 cx: &mut AsyncApp,
9688) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9689 let db = cx.update(|cx| WorkspaceDb::global(cx));
9690 let toolchains = db.toolchains(workspace_id).await?;
9691 for (toolchain, worktree_path, path) in toolchains {
9692 project
9693 .update(cx, |this, cx| {
9694 let Some(worktree_id) =
9695 this.find_worktree(&worktree_path, cx)
9696 .and_then(|(worktree, rel_path)| {
9697 if rel_path.is_empty() {
9698 Some(worktree.read(cx).id())
9699 } else {
9700 None
9701 }
9702 })
9703 else {
9704 return Task::ready(None);
9705 };
9706
9707 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9708 })
9709 .await;
9710 }
9711 let mut project_paths_to_open = vec![];
9712 let mut project_path_errors = vec![];
9713
9714 for path in paths {
9715 let result = cx
9716 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9717 .await;
9718 match result {
9719 Ok((_, project_path)) => {
9720 project_paths_to_open.push((path.clone(), Some(project_path)));
9721 }
9722 Err(error) => {
9723 project_path_errors.push(error);
9724 }
9725 };
9726 }
9727
9728 if project_paths_to_open.is_empty() {
9729 return Err(project_path_errors.pop().context("no paths given")?);
9730 }
9731
9732 let workspace = window.update(cx, |multi_workspace, window, cx| {
9733 telemetry::event!("SSH Project Opened");
9734
9735 let new_workspace = cx.new(|cx| {
9736 let mut workspace =
9737 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9738 workspace.update_history(cx);
9739
9740 if let Some(ref serialized) = serialized_workspace {
9741 workspace.centered_layout = serialized.centered_layout;
9742 }
9743
9744 workspace
9745 });
9746
9747 multi_workspace.activate(new_workspace.clone(), window, cx);
9748 new_workspace
9749 })?;
9750
9751 let items = window
9752 .update(cx, |_, window, cx| {
9753 window.activate_window();
9754 workspace.update(cx, |_workspace, cx| {
9755 open_items(serialized_workspace, project_paths_to_open, window, cx)
9756 })
9757 })?
9758 .await?;
9759
9760 workspace.update(cx, |workspace, cx| {
9761 for error in project_path_errors {
9762 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9763 if let Some(path) = error.error_tag("path") {
9764 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9765 }
9766 } else {
9767 workspace.show_error(&error, cx)
9768 }
9769 }
9770 });
9771
9772 Ok(items.into_iter().map(|item| item?.ok()).collect())
9773}
9774
9775fn deserialize_remote_project(
9776 connection_options: RemoteConnectionOptions,
9777 paths: Vec<PathBuf>,
9778 cx: &AsyncApp,
9779) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9780 let db = cx.update(|cx| WorkspaceDb::global(cx));
9781 cx.background_spawn(async move {
9782 let remote_connection_id = db
9783 .get_or_create_remote_connection(connection_options)
9784 .await?;
9785
9786 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9787
9788 let workspace_id = if let Some(workspace_id) =
9789 serialized_workspace.as_ref().map(|workspace| workspace.id)
9790 {
9791 workspace_id
9792 } else {
9793 db.next_id().await?
9794 };
9795
9796 Ok((workspace_id, serialized_workspace))
9797 })
9798}
9799
9800pub fn join_in_room_project(
9801 project_id: u64,
9802 follow_user_id: u64,
9803 app_state: Arc<AppState>,
9804 cx: &mut App,
9805) -> Task<Result<()>> {
9806 let windows = cx.windows();
9807 cx.spawn(async move |cx| {
9808 let existing_window_and_workspace: Option<(
9809 WindowHandle<MultiWorkspace>,
9810 Entity<Workspace>,
9811 )> = windows.into_iter().find_map(|window_handle| {
9812 window_handle
9813 .downcast::<MultiWorkspace>()
9814 .and_then(|window_handle| {
9815 window_handle
9816 .update(cx, |multi_workspace, _window, cx| {
9817 for workspace in multi_workspace.workspaces() {
9818 if workspace.read(cx).project().read(cx).remote_id()
9819 == Some(project_id)
9820 {
9821 return Some((window_handle, workspace.clone()));
9822 }
9823 }
9824 None
9825 })
9826 .unwrap_or(None)
9827 })
9828 });
9829
9830 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9831 existing_window_and_workspace
9832 {
9833 existing_window
9834 .update(cx, |multi_workspace, window, cx| {
9835 multi_workspace.activate(target_workspace, window, cx);
9836 })
9837 .ok();
9838 existing_window
9839 } else {
9840 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9841 let project = cx
9842 .update(|cx| {
9843 active_call.0.join_project(
9844 project_id,
9845 app_state.languages.clone(),
9846 app_state.fs.clone(),
9847 cx,
9848 )
9849 })
9850 .await?;
9851
9852 let window_bounds_override = window_bounds_env_override();
9853 cx.update(|cx| {
9854 let mut options = (app_state.build_window_options)(None, cx);
9855 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9856 cx.open_window(options, |window, cx| {
9857 let workspace = cx.new(|cx| {
9858 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9859 });
9860 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9861 })
9862 })?
9863 };
9864
9865 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9866 cx.activate(true);
9867 window.activate_window();
9868
9869 // We set the active workspace above, so this is the correct workspace.
9870 let workspace = multi_workspace.workspace().clone();
9871 workspace.update(cx, |workspace, cx| {
9872 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9873 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9874 .or_else(|| {
9875 // If we couldn't follow the given user, follow the host instead.
9876 let collaborator = workspace
9877 .project()
9878 .read(cx)
9879 .collaborators()
9880 .values()
9881 .find(|collaborator| collaborator.is_host)?;
9882 Some(collaborator.peer_id)
9883 });
9884
9885 if let Some(follow_peer_id) = follow_peer_id {
9886 workspace.follow(follow_peer_id, window, cx);
9887 }
9888 });
9889 })?;
9890
9891 anyhow::Ok(())
9892 })
9893}
9894
9895pub fn reload(cx: &mut App) {
9896 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9897 let mut workspace_windows = cx
9898 .windows()
9899 .into_iter()
9900 .filter_map(|window| window.downcast::<MultiWorkspace>())
9901 .collect::<Vec<_>>();
9902
9903 // If multiple windows have unsaved changes, and need a save prompt,
9904 // prompt in the active window before switching to a different window.
9905 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9906
9907 let mut prompt = None;
9908 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9909 prompt = window
9910 .update(cx, |_, window, cx| {
9911 window.prompt(
9912 PromptLevel::Info,
9913 "Are you sure you want to restart?",
9914 None,
9915 &["Restart", "Cancel"],
9916 cx,
9917 )
9918 })
9919 .ok();
9920 }
9921
9922 cx.spawn(async move |cx| {
9923 if let Some(prompt) = prompt {
9924 let answer = prompt.await?;
9925 if answer != 0 {
9926 return anyhow::Ok(());
9927 }
9928 }
9929
9930 // If the user cancels any save prompt, then keep the app open.
9931 for window in workspace_windows {
9932 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9933 let workspace = multi_workspace.workspace().clone();
9934 workspace.update(cx, |workspace, cx| {
9935 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9936 })
9937 }) && !should_close.await?
9938 {
9939 return anyhow::Ok(());
9940 }
9941 }
9942 cx.update(|cx| cx.restart());
9943 anyhow::Ok(())
9944 })
9945 .detach_and_log_err(cx);
9946}
9947
9948fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9949 let mut parts = value.split(',');
9950 let x: usize = parts.next()?.parse().ok()?;
9951 let y: usize = parts.next()?.parse().ok()?;
9952 Some(point(px(x as f32), px(y as f32)))
9953}
9954
9955fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9956 let mut parts = value.split(',');
9957 let width: usize = parts.next()?.parse().ok()?;
9958 let height: usize = parts.next()?.parse().ok()?;
9959 Some(size(px(width as f32), px(height as f32)))
9960}
9961
9962/// Add client-side decorations (rounded corners, shadows, resize handling) when
9963/// appropriate.
9964///
9965/// The `border_radius_tiling` parameter allows overriding which corners get
9966/// rounded, independently of the actual window tiling state. This is used
9967/// specifically for the workspace switcher sidebar: when the sidebar is open,
9968/// we want square corners on the left (so the sidebar appears flush with the
9969/// window edge) but we still need the shadow padding for proper visual
9970/// appearance. Unlike actual window tiling, this only affects border radius -
9971/// not padding or shadows.
9972pub fn client_side_decorations(
9973 element: impl IntoElement,
9974 window: &mut Window,
9975 cx: &mut App,
9976 border_radius_tiling: Tiling,
9977) -> Stateful<Div> {
9978 const BORDER_SIZE: Pixels = px(1.0);
9979 let decorations = window.window_decorations();
9980 let tiling = match decorations {
9981 Decorations::Server => Tiling::default(),
9982 Decorations::Client { tiling } => tiling,
9983 };
9984
9985 match decorations {
9986 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9987 Decorations::Server => window.set_client_inset(px(0.0)),
9988 }
9989
9990 struct GlobalResizeEdge(ResizeEdge);
9991 impl Global for GlobalResizeEdge {}
9992
9993 div()
9994 .id("window-backdrop")
9995 .bg(transparent_black())
9996 .map(|div| match decorations {
9997 Decorations::Server => div,
9998 Decorations::Client { .. } => div
9999 .when(
10000 !(tiling.top
10001 || tiling.right
10002 || border_radius_tiling.top
10003 || border_radius_tiling.right),
10004 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10005 )
10006 .when(
10007 !(tiling.top
10008 || tiling.left
10009 || border_radius_tiling.top
10010 || border_radius_tiling.left),
10011 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10012 )
10013 .when(
10014 !(tiling.bottom
10015 || tiling.right
10016 || border_radius_tiling.bottom
10017 || border_radius_tiling.right),
10018 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10019 )
10020 .when(
10021 !(tiling.bottom
10022 || tiling.left
10023 || border_radius_tiling.bottom
10024 || border_radius_tiling.left),
10025 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10026 )
10027 .when(!tiling.top, |div| {
10028 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10029 })
10030 .when(!tiling.bottom, |div| {
10031 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10032 })
10033 .when(!tiling.left, |div| {
10034 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10035 })
10036 .when(!tiling.right, |div| {
10037 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10038 })
10039 .on_mouse_move(move |e, window, cx| {
10040 let size = window.window_bounds().get_bounds().size;
10041 let pos = e.position;
10042
10043 let new_edge =
10044 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10045
10046 let edge = cx.try_global::<GlobalResizeEdge>();
10047 if new_edge != edge.map(|edge| edge.0) {
10048 window
10049 .window_handle()
10050 .update(cx, |workspace, _, cx| {
10051 cx.notify(workspace.entity_id());
10052 })
10053 .ok();
10054 }
10055 })
10056 .on_mouse_down(MouseButton::Left, move |e, window, _| {
10057 let size = window.window_bounds().get_bounds().size;
10058 let pos = e.position;
10059
10060 let edge = match resize_edge(
10061 pos,
10062 theme::CLIENT_SIDE_DECORATION_SHADOW,
10063 size,
10064 tiling,
10065 ) {
10066 Some(value) => value,
10067 None => return,
10068 };
10069
10070 window.start_window_resize(edge);
10071 }),
10072 })
10073 .size_full()
10074 .child(
10075 div()
10076 .cursor(CursorStyle::Arrow)
10077 .map(|div| match decorations {
10078 Decorations::Server => div,
10079 Decorations::Client { .. } => div
10080 .border_color(cx.theme().colors().border)
10081 .when(
10082 !(tiling.top
10083 || tiling.right
10084 || border_radius_tiling.top
10085 || border_radius_tiling.right),
10086 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10087 )
10088 .when(
10089 !(tiling.top
10090 || tiling.left
10091 || border_radius_tiling.top
10092 || border_radius_tiling.left),
10093 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10094 )
10095 .when(
10096 !(tiling.bottom
10097 || tiling.right
10098 || border_radius_tiling.bottom
10099 || border_radius_tiling.right),
10100 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10101 )
10102 .when(
10103 !(tiling.bottom
10104 || tiling.left
10105 || border_radius_tiling.bottom
10106 || border_radius_tiling.left),
10107 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10108 )
10109 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10110 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10111 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10112 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10113 .when(!tiling.is_tiled(), |div| {
10114 div.shadow(vec![gpui::BoxShadow {
10115 color: Hsla {
10116 h: 0.,
10117 s: 0.,
10118 l: 0.,
10119 a: 0.4,
10120 },
10121 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10122 spread_radius: px(0.),
10123 offset: point(px(0.0), px(0.0)),
10124 }])
10125 }),
10126 })
10127 .on_mouse_move(|_e, _, cx| {
10128 cx.stop_propagation();
10129 })
10130 .size_full()
10131 .child(element),
10132 )
10133 .map(|div| match decorations {
10134 Decorations::Server => div,
10135 Decorations::Client { tiling, .. } => div.child(
10136 canvas(
10137 |_bounds, window, _| {
10138 window.insert_hitbox(
10139 Bounds::new(
10140 point(px(0.0), px(0.0)),
10141 window.window_bounds().get_bounds().size,
10142 ),
10143 HitboxBehavior::Normal,
10144 )
10145 },
10146 move |_bounds, hitbox, window, cx| {
10147 let mouse = window.mouse_position();
10148 let size = window.window_bounds().get_bounds().size;
10149 let Some(edge) =
10150 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10151 else {
10152 return;
10153 };
10154 cx.set_global(GlobalResizeEdge(edge));
10155 window.set_cursor_style(
10156 match edge {
10157 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10158 ResizeEdge::Left | ResizeEdge::Right => {
10159 CursorStyle::ResizeLeftRight
10160 }
10161 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10162 CursorStyle::ResizeUpLeftDownRight
10163 }
10164 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10165 CursorStyle::ResizeUpRightDownLeft
10166 }
10167 },
10168 &hitbox,
10169 );
10170 },
10171 )
10172 .size_full()
10173 .absolute(),
10174 ),
10175 })
10176}
10177
10178fn resize_edge(
10179 pos: Point<Pixels>,
10180 shadow_size: Pixels,
10181 window_size: Size<Pixels>,
10182 tiling: Tiling,
10183) -> Option<ResizeEdge> {
10184 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10185 if bounds.contains(&pos) {
10186 return None;
10187 }
10188
10189 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10190 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10191 if !tiling.top && top_left_bounds.contains(&pos) {
10192 return Some(ResizeEdge::TopLeft);
10193 }
10194
10195 let top_right_bounds = Bounds::new(
10196 Point::new(window_size.width - corner_size.width, px(0.)),
10197 corner_size,
10198 );
10199 if !tiling.top && top_right_bounds.contains(&pos) {
10200 return Some(ResizeEdge::TopRight);
10201 }
10202
10203 let bottom_left_bounds = Bounds::new(
10204 Point::new(px(0.), window_size.height - corner_size.height),
10205 corner_size,
10206 );
10207 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10208 return Some(ResizeEdge::BottomLeft);
10209 }
10210
10211 let bottom_right_bounds = Bounds::new(
10212 Point::new(
10213 window_size.width - corner_size.width,
10214 window_size.height - corner_size.height,
10215 ),
10216 corner_size,
10217 );
10218 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10219 return Some(ResizeEdge::BottomRight);
10220 }
10221
10222 if !tiling.top && pos.y < shadow_size {
10223 Some(ResizeEdge::Top)
10224 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10225 Some(ResizeEdge::Bottom)
10226 } else if !tiling.left && pos.x < shadow_size {
10227 Some(ResizeEdge::Left)
10228 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10229 Some(ResizeEdge::Right)
10230 } else {
10231 None
10232 }
10233}
10234
10235fn join_pane_into_active(
10236 active_pane: &Entity<Pane>,
10237 pane: &Entity<Pane>,
10238 window: &mut Window,
10239 cx: &mut App,
10240) {
10241 if pane == active_pane {
10242 } else if pane.read(cx).items_len() == 0 {
10243 pane.update(cx, |_, cx| {
10244 cx.emit(pane::Event::Remove {
10245 focus_on_pane: None,
10246 });
10247 })
10248 } else {
10249 move_all_items(pane, active_pane, window, cx);
10250 }
10251}
10252
10253fn move_all_items(
10254 from_pane: &Entity<Pane>,
10255 to_pane: &Entity<Pane>,
10256 window: &mut Window,
10257 cx: &mut App,
10258) {
10259 let destination_is_different = from_pane != to_pane;
10260 let mut moved_items = 0;
10261 for (item_ix, item_handle) in from_pane
10262 .read(cx)
10263 .items()
10264 .enumerate()
10265 .map(|(ix, item)| (ix, item.clone()))
10266 .collect::<Vec<_>>()
10267 {
10268 let ix = item_ix - moved_items;
10269 if destination_is_different {
10270 // Close item from previous pane
10271 from_pane.update(cx, |source, cx| {
10272 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10273 });
10274 moved_items += 1;
10275 }
10276
10277 // This automatically removes duplicate items in the pane
10278 to_pane.update(cx, |destination, cx| {
10279 destination.add_item(item_handle, true, true, None, window, cx);
10280 window.focus(&destination.focus_handle(cx), cx)
10281 });
10282 }
10283}
10284
10285pub fn move_item(
10286 source: &Entity<Pane>,
10287 destination: &Entity<Pane>,
10288 item_id_to_move: EntityId,
10289 destination_index: usize,
10290 activate: bool,
10291 window: &mut Window,
10292 cx: &mut App,
10293) {
10294 let Some((item_ix, item_handle)) = source
10295 .read(cx)
10296 .items()
10297 .enumerate()
10298 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10299 .map(|(ix, item)| (ix, item.clone()))
10300 else {
10301 // Tab was closed during drag
10302 return;
10303 };
10304
10305 if source != destination {
10306 // Close item from previous pane
10307 source.update(cx, |source, cx| {
10308 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10309 });
10310 }
10311
10312 // This automatically removes duplicate items in the pane
10313 destination.update(cx, |destination, cx| {
10314 destination.add_item_inner(
10315 item_handle,
10316 activate,
10317 activate,
10318 activate,
10319 Some(destination_index),
10320 window,
10321 cx,
10322 );
10323 if activate {
10324 window.focus(&destination.focus_handle(cx), cx)
10325 }
10326 });
10327}
10328
10329pub fn move_active_item(
10330 source: &Entity<Pane>,
10331 destination: &Entity<Pane>,
10332 focus_destination: bool,
10333 close_if_empty: bool,
10334 window: &mut Window,
10335 cx: &mut App,
10336) {
10337 if source == destination {
10338 return;
10339 }
10340 let Some(active_item) = source.read(cx).active_item() else {
10341 return;
10342 };
10343 source.update(cx, |source_pane, cx| {
10344 let item_id = active_item.item_id();
10345 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10346 destination.update(cx, |target_pane, cx| {
10347 target_pane.add_item(
10348 active_item,
10349 focus_destination,
10350 focus_destination,
10351 Some(target_pane.items_len()),
10352 window,
10353 cx,
10354 );
10355 });
10356 });
10357}
10358
10359pub fn clone_active_item(
10360 workspace_id: Option<WorkspaceId>,
10361 source: &Entity<Pane>,
10362 destination: &Entity<Pane>,
10363 focus_destination: bool,
10364 window: &mut Window,
10365 cx: &mut App,
10366) {
10367 if source == destination {
10368 return;
10369 }
10370 let Some(active_item) = source.read(cx).active_item() else {
10371 return;
10372 };
10373 if !active_item.can_split(cx) {
10374 return;
10375 }
10376 let destination = destination.downgrade();
10377 let task = active_item.clone_on_split(workspace_id, window, cx);
10378 window
10379 .spawn(cx, async move |cx| {
10380 let Some(clone) = task.await else {
10381 return;
10382 };
10383 destination
10384 .update_in(cx, |target_pane, window, cx| {
10385 target_pane.add_item(
10386 clone,
10387 focus_destination,
10388 focus_destination,
10389 Some(target_pane.items_len()),
10390 window,
10391 cx,
10392 );
10393 })
10394 .log_err();
10395 })
10396 .detach();
10397}
10398
10399#[derive(Debug)]
10400pub struct WorkspacePosition {
10401 pub window_bounds: Option<WindowBounds>,
10402 pub display: Option<Uuid>,
10403 pub centered_layout: bool,
10404}
10405
10406pub fn remote_workspace_position_from_db(
10407 connection_options: RemoteConnectionOptions,
10408 paths_to_open: &[PathBuf],
10409 cx: &App,
10410) -> Task<Result<WorkspacePosition>> {
10411 let paths = paths_to_open.to_vec();
10412 let db = WorkspaceDb::global(cx);
10413 let kvp = db::kvp::KeyValueStore::global(cx);
10414
10415 cx.background_spawn(async move {
10416 let remote_connection_id = db
10417 .get_or_create_remote_connection(connection_options)
10418 .await
10419 .context("fetching serialized ssh project")?;
10420 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10421
10422 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10423 (Some(WindowBounds::Windowed(bounds)), None)
10424 } else {
10425 let restorable_bounds = serialized_workspace
10426 .as_ref()
10427 .and_then(|workspace| {
10428 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10429 })
10430 .or_else(|| persistence::read_default_window_bounds(&kvp));
10431
10432 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10433 (Some(serialized_bounds), Some(serialized_display))
10434 } else {
10435 (None, None)
10436 }
10437 };
10438
10439 let centered_layout = serialized_workspace
10440 .as_ref()
10441 .map(|w| w.centered_layout)
10442 .unwrap_or(false);
10443
10444 Ok(WorkspacePosition {
10445 window_bounds,
10446 display,
10447 centered_layout,
10448 })
10449 })
10450}
10451
10452pub fn with_active_or_new_workspace(
10453 cx: &mut App,
10454 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10455) {
10456 match cx
10457 .active_window()
10458 .and_then(|w| w.downcast::<MultiWorkspace>())
10459 {
10460 Some(multi_workspace) => {
10461 cx.defer(move |cx| {
10462 multi_workspace
10463 .update(cx, |multi_workspace, window, cx| {
10464 let workspace = multi_workspace.workspace().clone();
10465 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10466 })
10467 .log_err();
10468 });
10469 }
10470 None => {
10471 let app_state = AppState::global(cx);
10472 open_new(
10473 OpenOptions::default(),
10474 app_state,
10475 cx,
10476 move |workspace, window, cx| f(workspace, window, cx),
10477 )
10478 .detach_and_log_err(cx);
10479 }
10480 }
10481}
10482
10483/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10484/// key. This migration path only runs once per panel per workspace.
10485fn load_legacy_panel_size(
10486 panel_key: &str,
10487 dock_position: DockPosition,
10488 workspace: &Workspace,
10489 cx: &mut App,
10490) -> Option<Pixels> {
10491 #[derive(Deserialize)]
10492 struct LegacyPanelState {
10493 #[serde(default)]
10494 width: Option<Pixels>,
10495 #[serde(default)]
10496 height: Option<Pixels>,
10497 }
10498
10499 let workspace_id = workspace
10500 .database_id()
10501 .map(|id| i64::from(id).to_string())
10502 .or_else(|| workspace.session_id())?;
10503
10504 let legacy_key = match panel_key {
10505 "ProjectPanel" => {
10506 format!("{}-{:?}", "ProjectPanel", workspace_id)
10507 }
10508 "OutlinePanel" => {
10509 format!("{}-{:?}", "OutlinePanel", workspace_id)
10510 }
10511 "GitPanel" => {
10512 format!("{}-{:?}", "GitPanel", workspace_id)
10513 }
10514 "TerminalPanel" => {
10515 format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10516 }
10517 _ => return None,
10518 };
10519
10520 let kvp = db::kvp::KeyValueStore::global(cx);
10521 let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10522 let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10523 let size = match dock_position {
10524 DockPosition::Bottom => state.height,
10525 DockPosition::Left | DockPosition::Right => state.width,
10526 }?;
10527
10528 cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10529 .detach_and_log_err(cx);
10530
10531 Some(size)
10532}
10533
10534#[cfg(test)]
10535mod tests {
10536 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10537
10538 use super::*;
10539 use crate::{
10540 dock::{PanelEvent, test::TestPanel},
10541 item::{
10542 ItemBufferKind, ItemEvent,
10543 test::{TestItem, TestProjectItem},
10544 },
10545 };
10546 use fs::FakeFs;
10547 use gpui::{
10548 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10549 UpdateGlobal, VisualTestContext, px,
10550 };
10551 use project::{Project, ProjectEntryId};
10552 use serde_json::json;
10553 use settings::SettingsStore;
10554 use util::path;
10555 use util::rel_path::rel_path;
10556
10557 #[gpui::test]
10558 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10559 init_test(cx);
10560
10561 let fs = FakeFs::new(cx.executor());
10562 let project = Project::test(fs, [], cx).await;
10563 let (workspace, cx) =
10564 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10565
10566 // Adding an item with no ambiguity renders the tab without detail.
10567 let item1 = cx.new(|cx| {
10568 let mut item = TestItem::new(cx);
10569 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10570 item
10571 });
10572 workspace.update_in(cx, |workspace, window, cx| {
10573 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10574 });
10575 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10576
10577 // Adding an item that creates ambiguity increases the level of detail on
10578 // both tabs.
10579 let item2 = cx.new_window_entity(|_window, cx| {
10580 let mut item = TestItem::new(cx);
10581 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10582 item
10583 });
10584 workspace.update_in(cx, |workspace, window, cx| {
10585 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10586 });
10587 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10588 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10589
10590 // Adding an item that creates ambiguity increases the level of detail only
10591 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10592 // we stop at the highest detail available.
10593 let item3 = cx.new(|cx| {
10594 let mut item = TestItem::new(cx);
10595 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10596 item
10597 });
10598 workspace.update_in(cx, |workspace, window, cx| {
10599 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10600 });
10601 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10602 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10603 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10604 }
10605
10606 #[gpui::test]
10607 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10608 init_test(cx);
10609
10610 let fs = FakeFs::new(cx.executor());
10611 fs.insert_tree(
10612 "/root1",
10613 json!({
10614 "one.txt": "",
10615 "two.txt": "",
10616 }),
10617 )
10618 .await;
10619 fs.insert_tree(
10620 "/root2",
10621 json!({
10622 "three.txt": "",
10623 }),
10624 )
10625 .await;
10626
10627 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10628 let (workspace, cx) =
10629 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10630 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10631 let worktree_id = project.update(cx, |project, cx| {
10632 project.worktrees(cx).next().unwrap().read(cx).id()
10633 });
10634
10635 let item1 = cx.new(|cx| {
10636 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10637 });
10638 let item2 = cx.new(|cx| {
10639 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10640 });
10641
10642 // Add an item to an empty pane
10643 workspace.update_in(cx, |workspace, window, cx| {
10644 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10645 });
10646 project.update(cx, |project, cx| {
10647 assert_eq!(
10648 project.active_entry(),
10649 project
10650 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10651 .map(|e| e.id)
10652 );
10653 });
10654 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10655
10656 // Add a second item to a non-empty pane
10657 workspace.update_in(cx, |workspace, window, cx| {
10658 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10659 });
10660 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10661 project.update(cx, |project, cx| {
10662 assert_eq!(
10663 project.active_entry(),
10664 project
10665 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10666 .map(|e| e.id)
10667 );
10668 });
10669
10670 // Close the active item
10671 pane.update_in(cx, |pane, window, cx| {
10672 pane.close_active_item(&Default::default(), window, cx)
10673 })
10674 .await
10675 .unwrap();
10676 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10677 project.update(cx, |project, cx| {
10678 assert_eq!(
10679 project.active_entry(),
10680 project
10681 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10682 .map(|e| e.id)
10683 );
10684 });
10685
10686 // Add a project folder
10687 project
10688 .update(cx, |project, cx| {
10689 project.find_or_create_worktree("root2", true, cx)
10690 })
10691 .await
10692 .unwrap();
10693 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10694
10695 // Remove a project folder
10696 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10697 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10698 }
10699
10700 #[gpui::test]
10701 async fn test_close_window(cx: &mut TestAppContext) {
10702 init_test(cx);
10703
10704 let fs = FakeFs::new(cx.executor());
10705 fs.insert_tree("/root", json!({ "one": "" })).await;
10706
10707 let project = Project::test(fs, ["root".as_ref()], cx).await;
10708 let (workspace, cx) =
10709 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10710
10711 // When there are no dirty items, there's nothing to do.
10712 let item1 = cx.new(TestItem::new);
10713 workspace.update_in(cx, |w, window, cx| {
10714 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10715 });
10716 let task = workspace.update_in(cx, |w, window, cx| {
10717 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10718 });
10719 assert!(task.await.unwrap());
10720
10721 // When there are dirty untitled items, prompt to save each one. If the user
10722 // cancels any prompt, then abort.
10723 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10724 let item3 = cx.new(|cx| {
10725 TestItem::new(cx)
10726 .with_dirty(true)
10727 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10728 });
10729 workspace.update_in(cx, |w, window, cx| {
10730 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10731 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10732 });
10733 let task = workspace.update_in(cx, |w, window, cx| {
10734 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10735 });
10736 cx.executor().run_until_parked();
10737 cx.simulate_prompt_answer("Cancel"); // cancel save all
10738 cx.executor().run_until_parked();
10739 assert!(!cx.has_pending_prompt());
10740 assert!(!task.await.unwrap());
10741 }
10742
10743 #[gpui::test]
10744 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10745 init_test(cx);
10746
10747 let fs = FakeFs::new(cx.executor());
10748 fs.insert_tree("/root", json!({ "one": "" })).await;
10749
10750 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10751 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10752 let multi_workspace_handle =
10753 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10754 cx.run_until_parked();
10755
10756 let workspace_a = multi_workspace_handle
10757 .read_with(cx, |mw, _| mw.workspace().clone())
10758 .unwrap();
10759
10760 let workspace_b = multi_workspace_handle
10761 .update(cx, |mw, window, cx| {
10762 mw.test_add_workspace(project_b, window, cx)
10763 })
10764 .unwrap();
10765
10766 // Activate workspace A
10767 multi_workspace_handle
10768 .update(cx, |mw, window, cx| {
10769 let workspace = mw.workspaces()[0].clone();
10770 mw.activate(workspace, window, cx);
10771 })
10772 .unwrap();
10773
10774 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10775
10776 // Workspace A has a clean item
10777 let item_a = cx.new(TestItem::new);
10778 workspace_a.update_in(cx, |w, window, cx| {
10779 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10780 });
10781
10782 // Workspace B has a dirty item
10783 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10784 workspace_b.update_in(cx, |w, window, cx| {
10785 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10786 });
10787
10788 // Verify workspace A is active
10789 multi_workspace_handle
10790 .read_with(cx, |mw, _| {
10791 assert_eq!(mw.active_workspace_index(), 0);
10792 })
10793 .unwrap();
10794
10795 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10796 multi_workspace_handle
10797 .update(cx, |mw, window, cx| {
10798 mw.close_window(&CloseWindow, window, cx);
10799 })
10800 .unwrap();
10801 cx.run_until_parked();
10802
10803 // Workspace B should now be active since it has dirty items that need attention
10804 multi_workspace_handle
10805 .read_with(cx, |mw, _| {
10806 assert_eq!(
10807 mw.active_workspace_index(),
10808 1,
10809 "workspace B should be activated when it prompts"
10810 );
10811 })
10812 .unwrap();
10813
10814 // User cancels the save prompt from workspace B
10815 cx.simulate_prompt_answer("Cancel");
10816 cx.run_until_parked();
10817
10818 // Window should still exist because workspace B's close was cancelled
10819 assert!(
10820 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10821 "window should still exist after cancelling one workspace's close"
10822 );
10823 }
10824
10825 #[gpui::test]
10826 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10827 init_test(cx);
10828
10829 // Register TestItem as a serializable item
10830 cx.update(|cx| {
10831 register_serializable_item::<TestItem>(cx);
10832 });
10833
10834 let fs = FakeFs::new(cx.executor());
10835 fs.insert_tree("/root", json!({ "one": "" })).await;
10836
10837 let project = Project::test(fs, ["root".as_ref()], cx).await;
10838 let (workspace, cx) =
10839 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10840
10841 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10842 let item1 = cx.new(|cx| {
10843 TestItem::new(cx)
10844 .with_dirty(true)
10845 .with_serialize(|| Some(Task::ready(Ok(()))))
10846 });
10847 let item2 = cx.new(|cx| {
10848 TestItem::new(cx)
10849 .with_dirty(true)
10850 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10851 .with_serialize(|| Some(Task::ready(Ok(()))))
10852 });
10853 workspace.update_in(cx, |w, window, cx| {
10854 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10855 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10856 });
10857 let task = workspace.update_in(cx, |w, window, cx| {
10858 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10859 });
10860 assert!(task.await.unwrap());
10861 }
10862
10863 #[gpui::test]
10864 async fn test_close_pane_items(cx: &mut TestAppContext) {
10865 init_test(cx);
10866
10867 let fs = FakeFs::new(cx.executor());
10868
10869 let project = Project::test(fs, None, cx).await;
10870 let (workspace, cx) =
10871 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10872
10873 let item1 = cx.new(|cx| {
10874 TestItem::new(cx)
10875 .with_dirty(true)
10876 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10877 });
10878 let item2 = cx.new(|cx| {
10879 TestItem::new(cx)
10880 .with_dirty(true)
10881 .with_conflict(true)
10882 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10883 });
10884 let item3 = cx.new(|cx| {
10885 TestItem::new(cx)
10886 .with_dirty(true)
10887 .with_conflict(true)
10888 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10889 });
10890 let item4 = cx.new(|cx| {
10891 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10892 let project_item = TestProjectItem::new_untitled(cx);
10893 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10894 project_item
10895 }])
10896 });
10897 let pane = workspace.update_in(cx, |workspace, window, cx| {
10898 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10899 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10900 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10901 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10902 workspace.active_pane().clone()
10903 });
10904
10905 let close_items = pane.update_in(cx, |pane, window, cx| {
10906 pane.activate_item(1, true, true, window, cx);
10907 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10908 let item1_id = item1.item_id();
10909 let item3_id = item3.item_id();
10910 let item4_id = item4.item_id();
10911 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10912 [item1_id, item3_id, item4_id].contains(&id)
10913 })
10914 });
10915 cx.executor().run_until_parked();
10916
10917 assert!(cx.has_pending_prompt());
10918 cx.simulate_prompt_answer("Save all");
10919
10920 cx.executor().run_until_parked();
10921
10922 // Item 1 is saved. There's a prompt to save item 3.
10923 pane.update(cx, |pane, cx| {
10924 assert_eq!(item1.read(cx).save_count, 1);
10925 assert_eq!(item1.read(cx).save_as_count, 0);
10926 assert_eq!(item1.read(cx).reload_count, 0);
10927 assert_eq!(pane.items_len(), 3);
10928 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10929 });
10930 assert!(cx.has_pending_prompt());
10931
10932 // Cancel saving item 3.
10933 cx.simulate_prompt_answer("Discard");
10934 cx.executor().run_until_parked();
10935
10936 // Item 3 is reloaded. There's a prompt to save item 4.
10937 pane.update(cx, |pane, cx| {
10938 assert_eq!(item3.read(cx).save_count, 0);
10939 assert_eq!(item3.read(cx).save_as_count, 0);
10940 assert_eq!(item3.read(cx).reload_count, 1);
10941 assert_eq!(pane.items_len(), 2);
10942 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10943 });
10944
10945 // There's a prompt for a path for item 4.
10946 cx.simulate_new_path_selection(|_| Some(Default::default()));
10947 close_items.await.unwrap();
10948
10949 // The requested items are closed.
10950 pane.update(cx, |pane, cx| {
10951 assert_eq!(item4.read(cx).save_count, 0);
10952 assert_eq!(item4.read(cx).save_as_count, 1);
10953 assert_eq!(item4.read(cx).reload_count, 0);
10954 assert_eq!(pane.items_len(), 1);
10955 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10956 });
10957 }
10958
10959 #[gpui::test]
10960 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10961 init_test(cx);
10962
10963 let fs = FakeFs::new(cx.executor());
10964 let project = Project::test(fs, [], cx).await;
10965 let (workspace, cx) =
10966 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10967
10968 // Create several workspace items with single project entries, and two
10969 // workspace items with multiple project entries.
10970 let single_entry_items = (0..=4)
10971 .map(|project_entry_id| {
10972 cx.new(|cx| {
10973 TestItem::new(cx)
10974 .with_dirty(true)
10975 .with_project_items(&[dirty_project_item(
10976 project_entry_id,
10977 &format!("{project_entry_id}.txt"),
10978 cx,
10979 )])
10980 })
10981 })
10982 .collect::<Vec<_>>();
10983 let item_2_3 = cx.new(|cx| {
10984 TestItem::new(cx)
10985 .with_dirty(true)
10986 .with_buffer_kind(ItemBufferKind::Multibuffer)
10987 .with_project_items(&[
10988 single_entry_items[2].read(cx).project_items[0].clone(),
10989 single_entry_items[3].read(cx).project_items[0].clone(),
10990 ])
10991 });
10992 let item_3_4 = cx.new(|cx| {
10993 TestItem::new(cx)
10994 .with_dirty(true)
10995 .with_buffer_kind(ItemBufferKind::Multibuffer)
10996 .with_project_items(&[
10997 single_entry_items[3].read(cx).project_items[0].clone(),
10998 single_entry_items[4].read(cx).project_items[0].clone(),
10999 ])
11000 });
11001
11002 // Create two panes that contain the following project entries:
11003 // left pane:
11004 // multi-entry items: (2, 3)
11005 // single-entry items: 0, 2, 3, 4
11006 // right pane:
11007 // single-entry items: 4, 1
11008 // multi-entry items: (3, 4)
11009 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11010 let left_pane = workspace.active_pane().clone();
11011 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11012 workspace.add_item_to_active_pane(
11013 single_entry_items[0].boxed_clone(),
11014 None,
11015 true,
11016 window,
11017 cx,
11018 );
11019 workspace.add_item_to_active_pane(
11020 single_entry_items[2].boxed_clone(),
11021 None,
11022 true,
11023 window,
11024 cx,
11025 );
11026 workspace.add_item_to_active_pane(
11027 single_entry_items[3].boxed_clone(),
11028 None,
11029 true,
11030 window,
11031 cx,
11032 );
11033 workspace.add_item_to_active_pane(
11034 single_entry_items[4].boxed_clone(),
11035 None,
11036 true,
11037 window,
11038 cx,
11039 );
11040
11041 let right_pane =
11042 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11043
11044 let boxed_clone = single_entry_items[1].boxed_clone();
11045 let right_pane = window.spawn(cx, async move |cx| {
11046 right_pane.await.inspect(|right_pane| {
11047 right_pane
11048 .update_in(cx, |pane, window, cx| {
11049 pane.add_item(boxed_clone, true, true, None, window, cx);
11050 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11051 })
11052 .unwrap();
11053 })
11054 });
11055
11056 (left_pane, right_pane)
11057 });
11058 let right_pane = right_pane.await.unwrap();
11059 cx.focus(&right_pane);
11060
11061 let close = right_pane.update_in(cx, |pane, window, cx| {
11062 pane.close_all_items(&CloseAllItems::default(), window, cx)
11063 .unwrap()
11064 });
11065 cx.executor().run_until_parked();
11066
11067 let msg = cx.pending_prompt().unwrap().0;
11068 assert!(msg.contains("1.txt"));
11069 assert!(!msg.contains("2.txt"));
11070 assert!(!msg.contains("3.txt"));
11071 assert!(!msg.contains("4.txt"));
11072
11073 // With best-effort close, cancelling item 1 keeps it open but items 4
11074 // and (3,4) still close since their entries exist in left pane.
11075 cx.simulate_prompt_answer("Cancel");
11076 close.await;
11077
11078 right_pane.read_with(cx, |pane, _| {
11079 assert_eq!(pane.items_len(), 1);
11080 });
11081
11082 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11083 left_pane
11084 .update_in(cx, |left_pane, window, cx| {
11085 left_pane.close_item_by_id(
11086 single_entry_items[3].entity_id(),
11087 SaveIntent::Skip,
11088 window,
11089 cx,
11090 )
11091 })
11092 .await
11093 .unwrap();
11094
11095 let close = left_pane.update_in(cx, |pane, window, cx| {
11096 pane.close_all_items(&CloseAllItems::default(), window, cx)
11097 .unwrap()
11098 });
11099 cx.executor().run_until_parked();
11100
11101 let details = cx.pending_prompt().unwrap().1;
11102 assert!(details.contains("0.txt"));
11103 assert!(details.contains("3.txt"));
11104 assert!(details.contains("4.txt"));
11105 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11106 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11107 // assert!(!details.contains("2.txt"));
11108
11109 cx.simulate_prompt_answer("Save all");
11110 cx.executor().run_until_parked();
11111 close.await;
11112
11113 left_pane.read_with(cx, |pane, _| {
11114 assert_eq!(pane.items_len(), 0);
11115 });
11116 }
11117
11118 #[gpui::test]
11119 async fn test_autosave(cx: &mut gpui::TestAppContext) {
11120 init_test(cx);
11121
11122 let fs = FakeFs::new(cx.executor());
11123 let project = Project::test(fs, [], cx).await;
11124 let (workspace, cx) =
11125 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11126 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11127
11128 let item = cx.new(|cx| {
11129 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11130 });
11131 let item_id = item.entity_id();
11132 workspace.update_in(cx, |workspace, window, cx| {
11133 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11134 });
11135
11136 // Autosave on window change.
11137 item.update(cx, |item, cx| {
11138 SettingsStore::update_global(cx, |settings, cx| {
11139 settings.update_user_settings(cx, |settings| {
11140 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11141 })
11142 });
11143 item.is_dirty = true;
11144 });
11145
11146 // Deactivating the window saves the file.
11147 cx.deactivate_window();
11148 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11149
11150 // Re-activating the window doesn't save the file.
11151 cx.update(|window, _| window.activate_window());
11152 cx.executor().run_until_parked();
11153 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11154
11155 // Autosave on focus change.
11156 item.update_in(cx, |item, window, cx| {
11157 cx.focus_self(window);
11158 SettingsStore::update_global(cx, |settings, cx| {
11159 settings.update_user_settings(cx, |settings| {
11160 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11161 })
11162 });
11163 item.is_dirty = true;
11164 });
11165 // Blurring the item saves the file.
11166 item.update_in(cx, |_, window, _| window.blur());
11167 cx.executor().run_until_parked();
11168 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11169
11170 // Deactivating the window still saves the file.
11171 item.update_in(cx, |item, window, cx| {
11172 cx.focus_self(window);
11173 item.is_dirty = true;
11174 });
11175 cx.deactivate_window();
11176 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11177
11178 // Autosave after delay.
11179 item.update(cx, |item, cx| {
11180 SettingsStore::update_global(cx, |settings, cx| {
11181 settings.update_user_settings(cx, |settings| {
11182 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11183 milliseconds: 500.into(),
11184 });
11185 })
11186 });
11187 item.is_dirty = true;
11188 cx.emit(ItemEvent::Edit);
11189 });
11190
11191 // Delay hasn't fully expired, so the file is still dirty and unsaved.
11192 cx.executor().advance_clock(Duration::from_millis(250));
11193 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11194
11195 // After delay expires, the file is saved.
11196 cx.executor().advance_clock(Duration::from_millis(250));
11197 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11198
11199 // Autosave after delay, should save earlier than delay if tab is closed
11200 item.update(cx, |item, cx| {
11201 item.is_dirty = true;
11202 cx.emit(ItemEvent::Edit);
11203 });
11204 cx.executor().advance_clock(Duration::from_millis(250));
11205 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11206
11207 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11208 pane.update_in(cx, |pane, window, cx| {
11209 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11210 })
11211 .await
11212 .unwrap();
11213 assert!(!cx.has_pending_prompt());
11214 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11215
11216 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11217 workspace.update_in(cx, |workspace, window, cx| {
11218 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11219 });
11220 item.update_in(cx, |item, _window, cx| {
11221 item.is_dirty = true;
11222 for project_item in &mut item.project_items {
11223 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11224 }
11225 });
11226 cx.run_until_parked();
11227 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11228
11229 // Autosave on focus change, ensuring closing the tab counts as such.
11230 item.update(cx, |item, cx| {
11231 SettingsStore::update_global(cx, |settings, cx| {
11232 settings.update_user_settings(cx, |settings| {
11233 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11234 })
11235 });
11236 item.is_dirty = true;
11237 for project_item in &mut item.project_items {
11238 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11239 }
11240 });
11241
11242 pane.update_in(cx, |pane, window, cx| {
11243 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11244 })
11245 .await
11246 .unwrap();
11247 assert!(!cx.has_pending_prompt());
11248 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11249
11250 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11251 workspace.update_in(cx, |workspace, window, cx| {
11252 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11253 });
11254 item.update_in(cx, |item, window, cx| {
11255 item.project_items[0].update(cx, |item, _| {
11256 item.entry_id = None;
11257 });
11258 item.is_dirty = true;
11259 window.blur();
11260 });
11261 cx.run_until_parked();
11262 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11263
11264 // Ensure autosave is prevented for deleted files also when closing the buffer.
11265 let _close_items = pane.update_in(cx, |pane, window, cx| {
11266 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11267 });
11268 cx.run_until_parked();
11269 assert!(cx.has_pending_prompt());
11270 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11271 }
11272
11273 #[gpui::test]
11274 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11275 init_test(cx);
11276
11277 let fs = FakeFs::new(cx.executor());
11278 let project = Project::test(fs, [], cx).await;
11279 let (workspace, cx) =
11280 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11281
11282 // Create a multibuffer-like item with two child focus handles,
11283 // simulating individual buffer editors within a multibuffer.
11284 let item = cx.new(|cx| {
11285 TestItem::new(cx)
11286 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11287 .with_child_focus_handles(2, cx)
11288 });
11289 workspace.update_in(cx, |workspace, window, cx| {
11290 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11291 });
11292
11293 // Set autosave to OnFocusChange and focus the first child handle,
11294 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11295 item.update_in(cx, |item, window, cx| {
11296 SettingsStore::update_global(cx, |settings, cx| {
11297 settings.update_user_settings(cx, |settings| {
11298 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11299 })
11300 });
11301 item.is_dirty = true;
11302 window.focus(&item.child_focus_handles[0], cx);
11303 });
11304 cx.executor().run_until_parked();
11305 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11306
11307 // Moving focus from one child to another within the same item should
11308 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11309 item.update_in(cx, |item, window, cx| {
11310 window.focus(&item.child_focus_handles[1], cx);
11311 });
11312 cx.executor().run_until_parked();
11313 item.read_with(cx, |item, _| {
11314 assert_eq!(
11315 item.save_count, 0,
11316 "Switching focus between children within the same item should not autosave"
11317 );
11318 });
11319
11320 // Blurring the item saves the file. This is the core regression scenario:
11321 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11322 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11323 // the leaf is always a child focus handle, so `on_blur` never detected
11324 // focus leaving the item.
11325 item.update_in(cx, |_, window, _| window.blur());
11326 cx.executor().run_until_parked();
11327 item.read_with(cx, |item, _| {
11328 assert_eq!(
11329 item.save_count, 1,
11330 "Blurring should trigger autosave when focus was on a child of the item"
11331 );
11332 });
11333
11334 // Deactivating the window should also trigger autosave when a child of
11335 // the multibuffer item currently owns focus.
11336 item.update_in(cx, |item, window, cx| {
11337 item.is_dirty = true;
11338 window.focus(&item.child_focus_handles[0], cx);
11339 });
11340 cx.executor().run_until_parked();
11341 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11342
11343 cx.deactivate_window();
11344 item.read_with(cx, |item, _| {
11345 assert_eq!(
11346 item.save_count, 2,
11347 "Deactivating window should trigger autosave when focus was on a child"
11348 );
11349 });
11350 }
11351
11352 #[gpui::test]
11353 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11354 init_test(cx);
11355
11356 let fs = FakeFs::new(cx.executor());
11357
11358 let project = Project::test(fs, [], cx).await;
11359 let (workspace, cx) =
11360 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11361
11362 let item = cx.new(|cx| {
11363 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11364 });
11365 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11366 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11367 let toolbar_notify_count = Rc::new(RefCell::new(0));
11368
11369 workspace.update_in(cx, |workspace, window, cx| {
11370 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11371 let toolbar_notification_count = toolbar_notify_count.clone();
11372 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11373 *toolbar_notification_count.borrow_mut() += 1
11374 })
11375 .detach();
11376 });
11377
11378 pane.read_with(cx, |pane, _| {
11379 assert!(!pane.can_navigate_backward());
11380 assert!(!pane.can_navigate_forward());
11381 });
11382
11383 item.update_in(cx, |item, _, cx| {
11384 item.set_state("one".to_string(), cx);
11385 });
11386
11387 // Toolbar must be notified to re-render the navigation buttons
11388 assert_eq!(*toolbar_notify_count.borrow(), 1);
11389
11390 pane.read_with(cx, |pane, _| {
11391 assert!(pane.can_navigate_backward());
11392 assert!(!pane.can_navigate_forward());
11393 });
11394
11395 workspace
11396 .update_in(cx, |workspace, window, cx| {
11397 workspace.go_back(pane.downgrade(), window, cx)
11398 })
11399 .await
11400 .unwrap();
11401
11402 assert_eq!(*toolbar_notify_count.borrow(), 2);
11403 pane.read_with(cx, |pane, _| {
11404 assert!(!pane.can_navigate_backward());
11405 assert!(pane.can_navigate_forward());
11406 });
11407 }
11408
11409 /// Tests that the navigation history deduplicates entries for the same item.
11410 ///
11411 /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11412 /// the navigation history deduplicates by keeping only the most recent visit to each item,
11413 /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11414 /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11415 /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11416 ///
11417 /// This behavior prevents the navigation history from growing unnecessarily large and provides
11418 /// a better user experience by eliminating redundant navigation steps when jumping between files.
11419 #[gpui::test]
11420 async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11421 init_test(cx);
11422
11423 let fs = FakeFs::new(cx.executor());
11424 let project = Project::test(fs, [], cx).await;
11425 let (workspace, cx) =
11426 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11427
11428 let item_a = cx.new(|cx| {
11429 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11430 });
11431 let item_b = cx.new(|cx| {
11432 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11433 });
11434 let item_c = cx.new(|cx| {
11435 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11436 });
11437
11438 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11439
11440 workspace.update_in(cx, |workspace, window, cx| {
11441 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11442 workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11443 workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11444 });
11445
11446 workspace.update_in(cx, |workspace, window, cx| {
11447 workspace.activate_item(&item_a, false, false, window, cx);
11448 });
11449 cx.run_until_parked();
11450
11451 workspace.update_in(cx, |workspace, window, cx| {
11452 workspace.activate_item(&item_b, false, false, window, cx);
11453 });
11454 cx.run_until_parked();
11455
11456 workspace.update_in(cx, |workspace, window, cx| {
11457 workspace.activate_item(&item_a, false, false, window, cx);
11458 });
11459 cx.run_until_parked();
11460
11461 workspace.update_in(cx, |workspace, window, cx| {
11462 workspace.activate_item(&item_b, false, false, window, cx);
11463 });
11464 cx.run_until_parked();
11465
11466 workspace.update_in(cx, |workspace, window, cx| {
11467 workspace.activate_item(&item_a, false, false, window, cx);
11468 });
11469 cx.run_until_parked();
11470
11471 workspace.update_in(cx, |workspace, window, cx| {
11472 workspace.activate_item(&item_b, false, false, window, cx);
11473 });
11474 cx.run_until_parked();
11475
11476 workspace.update_in(cx, |workspace, window, cx| {
11477 workspace.activate_item(&item_c, false, false, window, cx);
11478 });
11479 cx.run_until_parked();
11480
11481 let backward_count = pane.read_with(cx, |pane, cx| {
11482 let mut count = 0;
11483 pane.nav_history().for_each_entry(cx, &mut |_, _| {
11484 count += 1;
11485 });
11486 count
11487 });
11488 assert!(
11489 backward_count <= 4,
11490 "Should have at most 4 entries, got {}",
11491 backward_count
11492 );
11493
11494 workspace
11495 .update_in(cx, |workspace, window, cx| {
11496 workspace.go_back(pane.downgrade(), window, cx)
11497 })
11498 .await
11499 .unwrap();
11500
11501 let active_item = workspace.read_with(cx, |workspace, cx| {
11502 workspace.active_item(cx).unwrap().item_id()
11503 });
11504 assert_eq!(
11505 active_item,
11506 item_b.entity_id(),
11507 "After first go_back, should be at item B"
11508 );
11509
11510 workspace
11511 .update_in(cx, |workspace, window, cx| {
11512 workspace.go_back(pane.downgrade(), window, cx)
11513 })
11514 .await
11515 .unwrap();
11516
11517 let active_item = workspace.read_with(cx, |workspace, cx| {
11518 workspace.active_item(cx).unwrap().item_id()
11519 });
11520 assert_eq!(
11521 active_item,
11522 item_a.entity_id(),
11523 "After second go_back, should be at item A"
11524 );
11525
11526 pane.read_with(cx, |pane, _| {
11527 assert!(pane.can_navigate_forward(), "Should be able to go forward");
11528 });
11529 }
11530
11531 #[gpui::test]
11532 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11533 init_test(cx);
11534 let fs = FakeFs::new(cx.executor());
11535 let project = Project::test(fs, [], cx).await;
11536 let (multi_workspace, cx) =
11537 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11538 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11539
11540 workspace.update_in(cx, |workspace, window, cx| {
11541 let first_item = cx.new(|cx| {
11542 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11543 });
11544 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11545 workspace.split_pane(
11546 workspace.active_pane().clone(),
11547 SplitDirection::Right,
11548 window,
11549 cx,
11550 );
11551 workspace.split_pane(
11552 workspace.active_pane().clone(),
11553 SplitDirection::Right,
11554 window,
11555 cx,
11556 );
11557 });
11558
11559 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11560 let panes = workspace.center.panes();
11561 assert!(panes.len() >= 2);
11562 (
11563 panes.first().expect("at least one pane").entity_id(),
11564 panes.last().expect("at least one pane").entity_id(),
11565 )
11566 });
11567
11568 workspace.update_in(cx, |workspace, window, cx| {
11569 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11570 });
11571 workspace.update(cx, |workspace, _| {
11572 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11573 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11574 });
11575
11576 cx.dispatch_action(ActivateLastPane);
11577
11578 workspace.update(cx, |workspace, _| {
11579 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11580 });
11581 }
11582
11583 #[gpui::test]
11584 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11585 init_test(cx);
11586 let fs = FakeFs::new(cx.executor());
11587
11588 let project = Project::test(fs, [], cx).await;
11589 let (workspace, cx) =
11590 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11591
11592 let panel = workspace.update_in(cx, |workspace, window, cx| {
11593 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11594 workspace.add_panel(panel.clone(), window, cx);
11595
11596 workspace
11597 .right_dock()
11598 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11599
11600 panel
11601 });
11602
11603 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11604 pane.update_in(cx, |pane, window, cx| {
11605 let item = cx.new(TestItem::new);
11606 pane.add_item(Box::new(item), true, true, None, window, cx);
11607 });
11608
11609 // Transfer focus from center to panel
11610 workspace.update_in(cx, |workspace, window, cx| {
11611 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11612 });
11613
11614 workspace.update_in(cx, |workspace, window, cx| {
11615 assert!(workspace.right_dock().read(cx).is_open());
11616 assert!(!panel.is_zoomed(window, cx));
11617 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11618 });
11619
11620 // Transfer focus from panel to center
11621 workspace.update_in(cx, |workspace, window, cx| {
11622 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11623 });
11624
11625 workspace.update_in(cx, |workspace, window, cx| {
11626 assert!(workspace.right_dock().read(cx).is_open());
11627 assert!(!panel.is_zoomed(window, cx));
11628 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11629 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11630 });
11631
11632 // Close the dock
11633 workspace.update_in(cx, |workspace, window, cx| {
11634 workspace.toggle_dock(DockPosition::Right, window, cx);
11635 });
11636
11637 workspace.update_in(cx, |workspace, window, cx| {
11638 assert!(!workspace.right_dock().read(cx).is_open());
11639 assert!(!panel.is_zoomed(window, cx));
11640 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11641 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11642 });
11643
11644 // Open the dock
11645 workspace.update_in(cx, |workspace, window, cx| {
11646 workspace.toggle_dock(DockPosition::Right, window, cx);
11647 });
11648
11649 workspace.update_in(cx, |workspace, window, cx| {
11650 assert!(workspace.right_dock().read(cx).is_open());
11651 assert!(!panel.is_zoomed(window, cx));
11652 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11653 });
11654
11655 // Focus and zoom panel
11656 panel.update_in(cx, |panel, window, cx| {
11657 cx.focus_self(window);
11658 panel.set_zoomed(true, window, cx)
11659 });
11660
11661 workspace.update_in(cx, |workspace, window, cx| {
11662 assert!(workspace.right_dock().read(cx).is_open());
11663 assert!(panel.is_zoomed(window, cx));
11664 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11665 });
11666
11667 // Transfer focus to the center closes the dock
11668 workspace.update_in(cx, |workspace, window, cx| {
11669 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11670 });
11671
11672 workspace.update_in(cx, |workspace, window, cx| {
11673 assert!(!workspace.right_dock().read(cx).is_open());
11674 assert!(panel.is_zoomed(window, cx));
11675 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11676 });
11677
11678 // Transferring focus back to the panel keeps it zoomed
11679 workspace.update_in(cx, |workspace, window, cx| {
11680 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11681 });
11682
11683 workspace.update_in(cx, |workspace, window, cx| {
11684 assert!(workspace.right_dock().read(cx).is_open());
11685 assert!(panel.is_zoomed(window, cx));
11686 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11687 });
11688
11689 // Close the dock while it is zoomed
11690 workspace.update_in(cx, |workspace, window, cx| {
11691 workspace.toggle_dock(DockPosition::Right, window, cx)
11692 });
11693
11694 workspace.update_in(cx, |workspace, window, cx| {
11695 assert!(!workspace.right_dock().read(cx).is_open());
11696 assert!(panel.is_zoomed(window, cx));
11697 assert!(workspace.zoomed.is_none());
11698 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11699 });
11700
11701 // Opening the dock, when it's zoomed, retains focus
11702 workspace.update_in(cx, |workspace, window, cx| {
11703 workspace.toggle_dock(DockPosition::Right, window, cx)
11704 });
11705
11706 workspace.update_in(cx, |workspace, window, cx| {
11707 assert!(workspace.right_dock().read(cx).is_open());
11708 assert!(panel.is_zoomed(window, cx));
11709 assert!(workspace.zoomed.is_some());
11710 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11711 });
11712
11713 // Unzoom and close the panel, zoom the active pane.
11714 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11715 workspace.update_in(cx, |workspace, window, cx| {
11716 workspace.toggle_dock(DockPosition::Right, window, cx)
11717 });
11718 pane.update_in(cx, |pane, window, cx| {
11719 pane.toggle_zoom(&Default::default(), window, cx)
11720 });
11721
11722 // Opening a dock unzooms the pane.
11723 workspace.update_in(cx, |workspace, window, cx| {
11724 workspace.toggle_dock(DockPosition::Right, window, cx)
11725 });
11726 workspace.update_in(cx, |workspace, window, cx| {
11727 let pane = pane.read(cx);
11728 assert!(!pane.is_zoomed());
11729 assert!(!pane.focus_handle(cx).is_focused(window));
11730 assert!(workspace.right_dock().read(cx).is_open());
11731 assert!(workspace.zoomed.is_none());
11732 });
11733 }
11734
11735 #[gpui::test]
11736 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11737 init_test(cx);
11738 let fs = FakeFs::new(cx.executor());
11739
11740 let project = Project::test(fs, [], cx).await;
11741 let (workspace, cx) =
11742 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11743
11744 let panel = workspace.update_in(cx, |workspace, window, cx| {
11745 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11746 workspace.add_panel(panel.clone(), window, cx);
11747 panel
11748 });
11749
11750 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11751 pane.update_in(cx, |pane, window, cx| {
11752 let item = cx.new(TestItem::new);
11753 pane.add_item(Box::new(item), true, true, None, window, cx);
11754 });
11755
11756 // Enable close_panel_on_toggle
11757 cx.update_global(|store: &mut SettingsStore, cx| {
11758 store.update_user_settings(cx, |settings| {
11759 settings.workspace.close_panel_on_toggle = Some(true);
11760 });
11761 });
11762
11763 // Panel starts closed. Toggling should open and focus it.
11764 workspace.update_in(cx, |workspace, window, cx| {
11765 assert!(!workspace.right_dock().read(cx).is_open());
11766 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11767 });
11768
11769 workspace.update_in(cx, |workspace, window, cx| {
11770 assert!(
11771 workspace.right_dock().read(cx).is_open(),
11772 "Dock should be open after toggling from center"
11773 );
11774 assert!(
11775 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11776 "Panel should be focused after toggling from center"
11777 );
11778 });
11779
11780 // Panel is open and focused. Toggling should close the panel and
11781 // return focus to the center.
11782 workspace.update_in(cx, |workspace, window, cx| {
11783 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11784 });
11785
11786 workspace.update_in(cx, |workspace, window, cx| {
11787 assert!(
11788 !workspace.right_dock().read(cx).is_open(),
11789 "Dock should be closed after toggling from focused panel"
11790 );
11791 assert!(
11792 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11793 "Panel should not be focused after toggling from focused panel"
11794 );
11795 });
11796
11797 // Open the dock and focus something else so the panel is open but not
11798 // focused. Toggling should focus the panel (not close it).
11799 workspace.update_in(cx, |workspace, window, cx| {
11800 workspace
11801 .right_dock()
11802 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11803 window.focus(&pane.read(cx).focus_handle(cx), cx);
11804 });
11805
11806 workspace.update_in(cx, |workspace, window, cx| {
11807 assert!(workspace.right_dock().read(cx).is_open());
11808 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11809 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11810 });
11811
11812 workspace.update_in(cx, |workspace, window, cx| {
11813 assert!(
11814 workspace.right_dock().read(cx).is_open(),
11815 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11816 );
11817 assert!(
11818 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11819 "Panel should be focused after toggling an open-but-unfocused panel"
11820 );
11821 });
11822
11823 // Now disable the setting and verify the original behavior: toggling
11824 // from a focused panel moves focus to center but leaves the dock open.
11825 cx.update_global(|store: &mut SettingsStore, cx| {
11826 store.update_user_settings(cx, |settings| {
11827 settings.workspace.close_panel_on_toggle = Some(false);
11828 });
11829 });
11830
11831 workspace.update_in(cx, |workspace, window, cx| {
11832 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11833 });
11834
11835 workspace.update_in(cx, |workspace, window, cx| {
11836 assert!(
11837 workspace.right_dock().read(cx).is_open(),
11838 "Dock should remain open when setting is disabled"
11839 );
11840 assert!(
11841 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11842 "Panel should not be focused after toggling with setting disabled"
11843 );
11844 });
11845 }
11846
11847 #[gpui::test]
11848 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11849 init_test(cx);
11850 let fs = FakeFs::new(cx.executor());
11851
11852 let project = Project::test(fs, [], cx).await;
11853 let (workspace, cx) =
11854 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11855
11856 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11857 workspace.active_pane().clone()
11858 });
11859
11860 // Add an item to the pane so it can be zoomed
11861 workspace.update_in(cx, |workspace, window, cx| {
11862 let item = cx.new(TestItem::new);
11863 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11864 });
11865
11866 // Initially not zoomed
11867 workspace.update_in(cx, |workspace, _window, cx| {
11868 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11869 assert!(
11870 workspace.zoomed.is_none(),
11871 "Workspace should track no zoomed pane"
11872 );
11873 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11874 });
11875
11876 // Zoom In
11877 pane.update_in(cx, |pane, window, cx| {
11878 pane.zoom_in(&crate::ZoomIn, window, cx);
11879 });
11880
11881 workspace.update_in(cx, |workspace, window, cx| {
11882 assert!(
11883 pane.read(cx).is_zoomed(),
11884 "Pane should be zoomed after ZoomIn"
11885 );
11886 assert!(
11887 workspace.zoomed.is_some(),
11888 "Workspace should track the zoomed pane"
11889 );
11890 assert!(
11891 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11892 "ZoomIn should focus the pane"
11893 );
11894 });
11895
11896 // Zoom In again is a no-op
11897 pane.update_in(cx, |pane, window, cx| {
11898 pane.zoom_in(&crate::ZoomIn, window, cx);
11899 });
11900
11901 workspace.update_in(cx, |workspace, window, cx| {
11902 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11903 assert!(
11904 workspace.zoomed.is_some(),
11905 "Workspace still tracks zoomed pane"
11906 );
11907 assert!(
11908 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11909 "Pane remains focused after repeated ZoomIn"
11910 );
11911 });
11912
11913 // Zoom Out
11914 pane.update_in(cx, |pane, window, cx| {
11915 pane.zoom_out(&crate::ZoomOut, window, cx);
11916 });
11917
11918 workspace.update_in(cx, |workspace, _window, cx| {
11919 assert!(
11920 !pane.read(cx).is_zoomed(),
11921 "Pane should unzoom after ZoomOut"
11922 );
11923 assert!(
11924 workspace.zoomed.is_none(),
11925 "Workspace clears zoom tracking after ZoomOut"
11926 );
11927 });
11928
11929 // Zoom Out again is a no-op
11930 pane.update_in(cx, |pane, window, cx| {
11931 pane.zoom_out(&crate::ZoomOut, window, cx);
11932 });
11933
11934 workspace.update_in(cx, |workspace, _window, cx| {
11935 assert!(
11936 !pane.read(cx).is_zoomed(),
11937 "Second ZoomOut keeps pane unzoomed"
11938 );
11939 assert!(
11940 workspace.zoomed.is_none(),
11941 "Workspace remains without zoomed pane"
11942 );
11943 });
11944 }
11945
11946 #[gpui::test]
11947 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11948 init_test(cx);
11949 let fs = FakeFs::new(cx.executor());
11950
11951 let project = Project::test(fs, [], cx).await;
11952 let (workspace, cx) =
11953 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11954 workspace.update_in(cx, |workspace, window, cx| {
11955 // Open two docks
11956 let left_dock = workspace.dock_at_position(DockPosition::Left);
11957 let right_dock = workspace.dock_at_position(DockPosition::Right);
11958
11959 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11960 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11961
11962 assert!(left_dock.read(cx).is_open());
11963 assert!(right_dock.read(cx).is_open());
11964 });
11965
11966 workspace.update_in(cx, |workspace, window, cx| {
11967 // Toggle all docks - should close both
11968 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11969
11970 let left_dock = workspace.dock_at_position(DockPosition::Left);
11971 let right_dock = workspace.dock_at_position(DockPosition::Right);
11972 assert!(!left_dock.read(cx).is_open());
11973 assert!(!right_dock.read(cx).is_open());
11974 });
11975
11976 workspace.update_in(cx, |workspace, window, cx| {
11977 // Toggle again - should reopen both
11978 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11979
11980 let left_dock = workspace.dock_at_position(DockPosition::Left);
11981 let right_dock = workspace.dock_at_position(DockPosition::Right);
11982 assert!(left_dock.read(cx).is_open());
11983 assert!(right_dock.read(cx).is_open());
11984 });
11985 }
11986
11987 #[gpui::test]
11988 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11989 init_test(cx);
11990 let fs = FakeFs::new(cx.executor());
11991
11992 let project = Project::test(fs, [], cx).await;
11993 let (workspace, cx) =
11994 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11995 workspace.update_in(cx, |workspace, window, cx| {
11996 // Open two docks
11997 let left_dock = workspace.dock_at_position(DockPosition::Left);
11998 let right_dock = workspace.dock_at_position(DockPosition::Right);
11999
12000 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12001 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12002
12003 assert!(left_dock.read(cx).is_open());
12004 assert!(right_dock.read(cx).is_open());
12005 });
12006
12007 workspace.update_in(cx, |workspace, window, cx| {
12008 // Close them manually
12009 workspace.toggle_dock(DockPosition::Left, window, cx);
12010 workspace.toggle_dock(DockPosition::Right, window, cx);
12011
12012 let left_dock = workspace.dock_at_position(DockPosition::Left);
12013 let right_dock = workspace.dock_at_position(DockPosition::Right);
12014 assert!(!left_dock.read(cx).is_open());
12015 assert!(!right_dock.read(cx).is_open());
12016 });
12017
12018 workspace.update_in(cx, |workspace, window, cx| {
12019 // Toggle all docks - only last closed (right dock) should reopen
12020 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12021
12022 let left_dock = workspace.dock_at_position(DockPosition::Left);
12023 let right_dock = workspace.dock_at_position(DockPosition::Right);
12024 assert!(!left_dock.read(cx).is_open());
12025 assert!(right_dock.read(cx).is_open());
12026 });
12027 }
12028
12029 #[gpui::test]
12030 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12031 init_test(cx);
12032 let fs = FakeFs::new(cx.executor());
12033 let project = Project::test(fs, [], cx).await;
12034 let (multi_workspace, cx) =
12035 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12036 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12037
12038 // Open two docks (left and right) with one panel each
12039 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12040 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12041 workspace.add_panel(left_panel.clone(), window, cx);
12042
12043 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12044 workspace.add_panel(right_panel.clone(), window, cx);
12045
12046 workspace.toggle_dock(DockPosition::Left, window, cx);
12047 workspace.toggle_dock(DockPosition::Right, window, cx);
12048
12049 // Verify initial state
12050 assert!(
12051 workspace.left_dock().read(cx).is_open(),
12052 "Left dock should be open"
12053 );
12054 assert_eq!(
12055 workspace
12056 .left_dock()
12057 .read(cx)
12058 .visible_panel()
12059 .unwrap()
12060 .panel_id(),
12061 left_panel.panel_id(),
12062 "Left panel should be visible in left dock"
12063 );
12064 assert!(
12065 workspace.right_dock().read(cx).is_open(),
12066 "Right dock should be open"
12067 );
12068 assert_eq!(
12069 workspace
12070 .right_dock()
12071 .read(cx)
12072 .visible_panel()
12073 .unwrap()
12074 .panel_id(),
12075 right_panel.panel_id(),
12076 "Right panel should be visible in right dock"
12077 );
12078 assert!(
12079 !workspace.bottom_dock().read(cx).is_open(),
12080 "Bottom dock should be closed"
12081 );
12082
12083 (left_panel, right_panel)
12084 });
12085
12086 // Focus the left panel and move it to the next position (bottom dock)
12087 workspace.update_in(cx, |workspace, window, cx| {
12088 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12089 assert!(
12090 left_panel.read(cx).focus_handle(cx).is_focused(window),
12091 "Left panel should be focused"
12092 );
12093 });
12094
12095 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12096
12097 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12098 workspace.update(cx, |workspace, cx| {
12099 assert!(
12100 !workspace.left_dock().read(cx).is_open(),
12101 "Left dock should be closed"
12102 );
12103 assert!(
12104 workspace.bottom_dock().read(cx).is_open(),
12105 "Bottom dock should now be open"
12106 );
12107 assert_eq!(
12108 left_panel.read(cx).position,
12109 DockPosition::Bottom,
12110 "Left panel should now be in the bottom dock"
12111 );
12112 assert_eq!(
12113 workspace
12114 .bottom_dock()
12115 .read(cx)
12116 .visible_panel()
12117 .unwrap()
12118 .panel_id(),
12119 left_panel.panel_id(),
12120 "Left panel should be the visible panel in the bottom dock"
12121 );
12122 });
12123
12124 // Toggle all docks off
12125 workspace.update_in(cx, |workspace, window, cx| {
12126 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12127 assert!(
12128 !workspace.left_dock().read(cx).is_open(),
12129 "Left dock should be closed"
12130 );
12131 assert!(
12132 !workspace.right_dock().read(cx).is_open(),
12133 "Right dock should be closed"
12134 );
12135 assert!(
12136 !workspace.bottom_dock().read(cx).is_open(),
12137 "Bottom dock should be closed"
12138 );
12139 });
12140
12141 // Toggle all docks back on and verify positions are restored
12142 workspace.update_in(cx, |workspace, window, cx| {
12143 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12144 assert!(
12145 !workspace.left_dock().read(cx).is_open(),
12146 "Left dock should remain closed"
12147 );
12148 assert!(
12149 workspace.right_dock().read(cx).is_open(),
12150 "Right dock should remain open"
12151 );
12152 assert!(
12153 workspace.bottom_dock().read(cx).is_open(),
12154 "Bottom dock should remain open"
12155 );
12156 assert_eq!(
12157 left_panel.read(cx).position,
12158 DockPosition::Bottom,
12159 "Left panel should remain in the bottom dock"
12160 );
12161 assert_eq!(
12162 right_panel.read(cx).position,
12163 DockPosition::Right,
12164 "Right panel should remain in the right dock"
12165 );
12166 assert_eq!(
12167 workspace
12168 .bottom_dock()
12169 .read(cx)
12170 .visible_panel()
12171 .unwrap()
12172 .panel_id(),
12173 left_panel.panel_id(),
12174 "Left panel should be the visible panel in the right dock"
12175 );
12176 });
12177 }
12178
12179 #[gpui::test]
12180 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12181 init_test(cx);
12182
12183 let fs = FakeFs::new(cx.executor());
12184
12185 let project = Project::test(fs, None, cx).await;
12186 let (workspace, cx) =
12187 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12188
12189 // Let's arrange the panes like this:
12190 //
12191 // +-----------------------+
12192 // | top |
12193 // +------+--------+-------+
12194 // | left | center | right |
12195 // +------+--------+-------+
12196 // | bottom |
12197 // +-----------------------+
12198
12199 let top_item = cx.new(|cx| {
12200 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12201 });
12202 let bottom_item = cx.new(|cx| {
12203 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12204 });
12205 let left_item = cx.new(|cx| {
12206 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12207 });
12208 let right_item = cx.new(|cx| {
12209 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12210 });
12211 let center_item = cx.new(|cx| {
12212 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12213 });
12214
12215 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12216 let top_pane_id = workspace.active_pane().entity_id();
12217 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12218 workspace.split_pane(
12219 workspace.active_pane().clone(),
12220 SplitDirection::Down,
12221 window,
12222 cx,
12223 );
12224 top_pane_id
12225 });
12226 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12227 let bottom_pane_id = workspace.active_pane().entity_id();
12228 workspace.add_item_to_active_pane(
12229 Box::new(bottom_item.clone()),
12230 None,
12231 false,
12232 window,
12233 cx,
12234 );
12235 workspace.split_pane(
12236 workspace.active_pane().clone(),
12237 SplitDirection::Up,
12238 window,
12239 cx,
12240 );
12241 bottom_pane_id
12242 });
12243 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12244 let left_pane_id = workspace.active_pane().entity_id();
12245 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12246 workspace.split_pane(
12247 workspace.active_pane().clone(),
12248 SplitDirection::Right,
12249 window,
12250 cx,
12251 );
12252 left_pane_id
12253 });
12254 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12255 let right_pane_id = workspace.active_pane().entity_id();
12256 workspace.add_item_to_active_pane(
12257 Box::new(right_item.clone()),
12258 None,
12259 false,
12260 window,
12261 cx,
12262 );
12263 workspace.split_pane(
12264 workspace.active_pane().clone(),
12265 SplitDirection::Left,
12266 window,
12267 cx,
12268 );
12269 right_pane_id
12270 });
12271 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12272 let center_pane_id = workspace.active_pane().entity_id();
12273 workspace.add_item_to_active_pane(
12274 Box::new(center_item.clone()),
12275 None,
12276 false,
12277 window,
12278 cx,
12279 );
12280 center_pane_id
12281 });
12282 cx.executor().run_until_parked();
12283
12284 workspace.update_in(cx, |workspace, window, cx| {
12285 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12286
12287 // Join into next from center pane into right
12288 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12289 });
12290
12291 workspace.update_in(cx, |workspace, window, cx| {
12292 let active_pane = workspace.active_pane();
12293 assert_eq!(right_pane_id, active_pane.entity_id());
12294 assert_eq!(2, active_pane.read(cx).items_len());
12295 let item_ids_in_pane =
12296 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12297 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12298 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12299
12300 // Join into next from right pane into bottom
12301 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12302 });
12303
12304 workspace.update_in(cx, |workspace, window, cx| {
12305 let active_pane = workspace.active_pane();
12306 assert_eq!(bottom_pane_id, active_pane.entity_id());
12307 assert_eq!(3, active_pane.read(cx).items_len());
12308 let item_ids_in_pane =
12309 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12310 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12311 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12312 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12313
12314 // Join into next from bottom pane into left
12315 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12316 });
12317
12318 workspace.update_in(cx, |workspace, window, cx| {
12319 let active_pane = workspace.active_pane();
12320 assert_eq!(left_pane_id, active_pane.entity_id());
12321 assert_eq!(4, active_pane.read(cx).items_len());
12322 let item_ids_in_pane =
12323 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12324 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12325 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12326 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12327 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12328
12329 // Join into next from left pane into top
12330 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12331 });
12332
12333 workspace.update_in(cx, |workspace, window, cx| {
12334 let active_pane = workspace.active_pane();
12335 assert_eq!(top_pane_id, active_pane.entity_id());
12336 assert_eq!(5, active_pane.read(cx).items_len());
12337 let item_ids_in_pane =
12338 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12339 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12340 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12341 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12342 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12343 assert!(item_ids_in_pane.contains(&top_item.item_id()));
12344
12345 // Single pane left: no-op
12346 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12347 });
12348
12349 workspace.update(cx, |workspace, _cx| {
12350 let active_pane = workspace.active_pane();
12351 assert_eq!(top_pane_id, active_pane.entity_id());
12352 });
12353 }
12354
12355 fn add_an_item_to_active_pane(
12356 cx: &mut VisualTestContext,
12357 workspace: &Entity<Workspace>,
12358 item_id: u64,
12359 ) -> Entity<TestItem> {
12360 let item = cx.new(|cx| {
12361 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12362 item_id,
12363 "item{item_id}.txt",
12364 cx,
12365 )])
12366 });
12367 workspace.update_in(cx, |workspace, window, cx| {
12368 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12369 });
12370 item
12371 }
12372
12373 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12374 workspace.update_in(cx, |workspace, window, cx| {
12375 workspace.split_pane(
12376 workspace.active_pane().clone(),
12377 SplitDirection::Right,
12378 window,
12379 cx,
12380 )
12381 })
12382 }
12383
12384 #[gpui::test]
12385 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12386 init_test(cx);
12387 let fs = FakeFs::new(cx.executor());
12388 let project = Project::test(fs, None, cx).await;
12389 let (workspace, cx) =
12390 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12391
12392 add_an_item_to_active_pane(cx, &workspace, 1);
12393 split_pane(cx, &workspace);
12394 add_an_item_to_active_pane(cx, &workspace, 2);
12395 split_pane(cx, &workspace); // empty pane
12396 split_pane(cx, &workspace);
12397 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12398
12399 cx.executor().run_until_parked();
12400
12401 workspace.update(cx, |workspace, cx| {
12402 let num_panes = workspace.panes().len();
12403 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12404 let active_item = workspace
12405 .active_pane()
12406 .read(cx)
12407 .active_item()
12408 .expect("item is in focus");
12409
12410 assert_eq!(num_panes, 4);
12411 assert_eq!(num_items_in_current_pane, 1);
12412 assert_eq!(active_item.item_id(), last_item.item_id());
12413 });
12414
12415 workspace.update_in(cx, |workspace, window, cx| {
12416 workspace.join_all_panes(window, cx);
12417 });
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, 1);
12429 assert_eq!(num_items_in_current_pane, 3);
12430 assert_eq!(active_item.item_id(), last_item.item_id());
12431 });
12432 }
12433
12434 #[gpui::test]
12435 async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12436 init_test(cx);
12437 let fs = FakeFs::new(cx.executor());
12438
12439 let project = Project::test(fs, [], cx).await;
12440 let (multi_workspace, cx) =
12441 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12442 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12443
12444 workspace.update(cx, |workspace, _cx| {
12445 workspace.bounds.size.width = px(800.);
12446 });
12447
12448 workspace.update_in(cx, |workspace, window, cx| {
12449 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12450 workspace.add_panel(panel, window, cx);
12451 workspace.toggle_dock(DockPosition::Right, window, cx);
12452 });
12453
12454 let (panel, resized_width, ratio_basis_width) =
12455 workspace.update_in(cx, |workspace, window, cx| {
12456 let item = cx.new(|cx| {
12457 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12458 });
12459 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12460
12461 let dock = workspace.right_dock().read(cx);
12462 let workspace_width = workspace.bounds.size.width;
12463 let initial_width = workspace
12464 .dock_size(&dock, window, cx)
12465 .expect("flexible dock should have an initial width");
12466
12467 assert_eq!(initial_width, workspace_width / 2.);
12468
12469 workspace.resize_right_dock(px(300.), window, cx);
12470
12471 let dock = workspace.right_dock().read(cx);
12472 let resized_width = workspace
12473 .dock_size(&dock, window, cx)
12474 .expect("flexible dock should keep its resized width");
12475
12476 assert_eq!(resized_width, px(300.));
12477
12478 let panel = workspace
12479 .right_dock()
12480 .read(cx)
12481 .visible_panel()
12482 .expect("flexible dock should have a visible panel")
12483 .panel_id();
12484
12485 (panel, resized_width, workspace_width)
12486 });
12487
12488 workspace.update_in(cx, |workspace, window, cx| {
12489 workspace.toggle_dock(DockPosition::Right, window, cx);
12490 workspace.toggle_dock(DockPosition::Right, window, cx);
12491
12492 let dock = workspace.right_dock().read(cx);
12493 let reopened_width = workspace
12494 .dock_size(&dock, window, cx)
12495 .expect("flexible dock should restore when reopened");
12496
12497 assert_eq!(reopened_width, resized_width);
12498
12499 let right_dock = workspace.right_dock().read(cx);
12500 let flexible_panel = right_dock
12501 .visible_panel()
12502 .expect("flexible dock should still have a visible panel");
12503 assert_eq!(flexible_panel.panel_id(), panel);
12504 assert_eq!(
12505 right_dock
12506 .stored_panel_size_state(flexible_panel.as_ref())
12507 .and_then(|size_state| size_state.flex),
12508 Some(
12509 resized_width.to_f64() as f32
12510 / (workspace.bounds.size.width - resized_width).to_f64() as f32
12511 )
12512 );
12513 });
12514
12515 workspace.update_in(cx, |workspace, window, cx| {
12516 workspace.split_pane(
12517 workspace.active_pane().clone(),
12518 SplitDirection::Right,
12519 window,
12520 cx,
12521 );
12522
12523 let dock = workspace.right_dock().read(cx);
12524 let split_width = workspace
12525 .dock_size(&dock, window, cx)
12526 .expect("flexible dock should keep its user-resized proportion");
12527
12528 assert_eq!(split_width, px(300.));
12529
12530 workspace.bounds.size.width = px(1600.);
12531
12532 let dock = workspace.right_dock().read(cx);
12533 let resized_window_width = workspace
12534 .dock_size(&dock, window, cx)
12535 .expect("flexible dock should preserve proportional size on window resize");
12536
12537 assert_eq!(
12538 resized_window_width,
12539 workspace.bounds.size.width
12540 * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12541 );
12542 });
12543 }
12544
12545 #[gpui::test]
12546 async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12547 init_test(cx);
12548 let fs = FakeFs::new(cx.executor());
12549
12550 // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12551 {
12552 let project = Project::test(fs.clone(), [], cx).await;
12553 let (multi_workspace, cx) =
12554 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12555 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12556
12557 workspace.update(cx, |workspace, _cx| {
12558 workspace.set_random_database_id();
12559 workspace.bounds.size.width = px(800.);
12560 });
12561
12562 let panel = workspace.update_in(cx, |workspace, window, cx| {
12563 let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12564 workspace.add_panel(panel.clone(), window, cx);
12565 workspace.toggle_dock(DockPosition::Left, window, cx);
12566 panel
12567 });
12568
12569 workspace.update_in(cx, |workspace, window, cx| {
12570 workspace.resize_left_dock(px(350.), window, cx);
12571 });
12572
12573 cx.run_until_parked();
12574
12575 let persisted = workspace.read_with(cx, |workspace, cx| {
12576 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12577 });
12578 assert_eq!(
12579 persisted.and_then(|s| s.size),
12580 Some(px(350.)),
12581 "fixed-width panel size should be persisted to KVP"
12582 );
12583
12584 // Remove the panel and re-add a fresh instance with the same key.
12585 // The new instance should have its size state restored from KVP.
12586 workspace.update_in(cx, |workspace, window, cx| {
12587 workspace.remove_panel(&panel, window, cx);
12588 });
12589
12590 workspace.update_in(cx, |workspace, window, cx| {
12591 let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12592 workspace.add_panel(new_panel, window, cx);
12593
12594 let left_dock = workspace.left_dock().read(cx);
12595 let size_state = left_dock
12596 .panel::<TestPanel>()
12597 .and_then(|p| left_dock.stored_panel_size_state(&p));
12598 assert_eq!(
12599 size_state.and_then(|s| s.size),
12600 Some(px(350.)),
12601 "re-added fixed-width panel should restore persisted size from KVP"
12602 );
12603 });
12604 }
12605
12606 // Flexible panel: both pixel size and ratio are persisted and restored.
12607 {
12608 let project = Project::test(fs.clone(), [], cx).await;
12609 let (multi_workspace, cx) =
12610 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12611 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12612
12613 workspace.update(cx, |workspace, _cx| {
12614 workspace.set_random_database_id();
12615 workspace.bounds.size.width = px(800.);
12616 });
12617
12618 let panel = workspace.update_in(cx, |workspace, window, cx| {
12619 let item = cx.new(|cx| {
12620 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12621 });
12622 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12623
12624 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12625 workspace.add_panel(panel.clone(), window, cx);
12626 workspace.toggle_dock(DockPosition::Right, window, cx);
12627 panel
12628 });
12629
12630 workspace.update_in(cx, |workspace, window, cx| {
12631 workspace.resize_right_dock(px(300.), window, cx);
12632 });
12633
12634 cx.run_until_parked();
12635
12636 let persisted = workspace
12637 .read_with(cx, |workspace, cx| {
12638 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12639 })
12640 .expect("flexible panel state should be persisted to KVP");
12641 assert_eq!(
12642 persisted.size, None,
12643 "flexible panel should not persist a redundant pixel size"
12644 );
12645 let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12646
12647 // Remove the panel and re-add: both size and ratio should be restored.
12648 workspace.update_in(cx, |workspace, window, cx| {
12649 workspace.remove_panel(&panel, window, cx);
12650 });
12651
12652 workspace.update_in(cx, |workspace, window, cx| {
12653 let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12654 workspace.add_panel(new_panel, window, cx);
12655
12656 let right_dock = workspace.right_dock().read(cx);
12657 let size_state = right_dock
12658 .panel::<TestPanel>()
12659 .and_then(|p| right_dock.stored_panel_size_state(&p))
12660 .expect("re-added flexible panel should have restored size state from KVP");
12661 assert_eq!(
12662 size_state.size, None,
12663 "re-added flexible panel should not have a persisted pixel size"
12664 );
12665 assert_eq!(
12666 size_state.flex,
12667 Some(original_ratio),
12668 "re-added flexible panel should restore persisted flex"
12669 );
12670 });
12671 }
12672 }
12673
12674 #[gpui::test]
12675 async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12676 init_test(cx);
12677 let fs = FakeFs::new(cx.executor());
12678
12679 let project = Project::test(fs, [], cx).await;
12680 let (multi_workspace, cx) =
12681 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12682 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12683
12684 workspace.update(cx, |workspace, _cx| {
12685 workspace.bounds.size.width = px(900.);
12686 });
12687
12688 // Step 1: Add a tab to the center pane then open a flexible panel in the left
12689 // dock. With one full-width center pane the default ratio is 0.5, so the panel
12690 // and the center pane each take half the workspace width.
12691 workspace.update_in(cx, |workspace, window, cx| {
12692 let item = cx.new(|cx| {
12693 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12694 });
12695 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12696
12697 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12698 workspace.add_panel(panel, window, cx);
12699 workspace.toggle_dock(DockPosition::Left, window, cx);
12700
12701 let left_dock = workspace.left_dock().read(cx);
12702 let left_width = workspace
12703 .dock_size(&left_dock, window, cx)
12704 .expect("left dock should have an active panel");
12705
12706 assert_eq!(
12707 left_width,
12708 workspace.bounds.size.width / 2.,
12709 "flexible left panel should split evenly with the center pane"
12710 );
12711 });
12712
12713 // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12714 // change horizontal width fractions, so the flexible panel stays at the same
12715 // width as each half of the split.
12716 workspace.update_in(cx, |workspace, window, cx| {
12717 workspace.split_pane(
12718 workspace.active_pane().clone(),
12719 SplitDirection::Down,
12720 window,
12721 cx,
12722 );
12723
12724 let left_dock = workspace.left_dock().read(cx);
12725 let left_width = workspace
12726 .dock_size(&left_dock, window, cx)
12727 .expect("left dock should still have an active panel after vertical split");
12728
12729 assert_eq!(
12730 left_width,
12731 workspace.bounds.size.width / 2.,
12732 "flexible left panel width should match each vertically-split pane"
12733 );
12734 });
12735
12736 // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12737 // size reduces the available width, so the flexible left panel and the center
12738 // panes all shrink proportionally to accommodate it.
12739 workspace.update_in(cx, |workspace, window, cx| {
12740 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12741 workspace.add_panel(panel, window, cx);
12742 workspace.toggle_dock(DockPosition::Right, window, cx);
12743
12744 let right_dock = workspace.right_dock().read(cx);
12745 let right_width = workspace
12746 .dock_size(&right_dock, window, cx)
12747 .expect("right dock should have an active panel");
12748
12749 let left_dock = workspace.left_dock().read(cx);
12750 let left_width = workspace
12751 .dock_size(&left_dock, window, cx)
12752 .expect("left dock should still have an active panel");
12753
12754 let available_width = workspace.bounds.size.width - right_width;
12755 assert_eq!(
12756 left_width,
12757 available_width / 2.,
12758 "flexible left panel should shrink proportionally as the right dock takes space"
12759 );
12760 });
12761
12762 // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12763 // flex sizing and the workspace width is divided among left-flex, center
12764 // (implicit flex 1.0), and right-flex.
12765 workspace.update_in(cx, |workspace, window, cx| {
12766 let right_dock = workspace.right_dock().clone();
12767 let right_panel = right_dock
12768 .read(cx)
12769 .visible_panel()
12770 .expect("right dock should have a visible panel")
12771 .clone();
12772 workspace.toggle_dock_panel_flexible_size(
12773 &right_dock,
12774 right_panel.as_ref(),
12775 window,
12776 cx,
12777 );
12778
12779 let right_dock = right_dock.read(cx);
12780 let right_panel = right_dock
12781 .visible_panel()
12782 .expect("right dock should still have a visible panel");
12783 assert!(
12784 right_panel.has_flexible_size(window, cx),
12785 "right panel should now be flexible"
12786 );
12787
12788 let right_size_state = right_dock
12789 .stored_panel_size_state(right_panel.as_ref())
12790 .expect("right panel should have a stored size state after toggling");
12791 let right_flex = right_size_state
12792 .flex
12793 .expect("right panel should have a flex value after toggling");
12794
12795 let left_dock = workspace.left_dock().read(cx);
12796 let left_width = workspace
12797 .dock_size(&left_dock, window, cx)
12798 .expect("left dock should still have an active panel");
12799 let right_width = workspace
12800 .dock_size(&right_dock, window, cx)
12801 .expect("right dock should still have an active panel");
12802
12803 let left_flex = workspace
12804 .default_dock_flex(DockPosition::Left)
12805 .expect("left dock should have a default flex");
12806
12807 let total_flex = left_flex + 1.0 + right_flex;
12808 let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12809 let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12810 assert_eq!(
12811 left_width, expected_left,
12812 "flexible left panel should share workspace width via flex ratios"
12813 );
12814 assert_eq!(
12815 right_width, expected_right,
12816 "flexible right panel should share workspace width via flex ratios"
12817 );
12818 });
12819 }
12820
12821 struct TestModal(FocusHandle);
12822
12823 impl TestModal {
12824 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12825 Self(cx.focus_handle())
12826 }
12827 }
12828
12829 impl EventEmitter<DismissEvent> for TestModal {}
12830
12831 impl Focusable for TestModal {
12832 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12833 self.0.clone()
12834 }
12835 }
12836
12837 impl ModalView for TestModal {}
12838
12839 impl Render for TestModal {
12840 fn render(
12841 &mut self,
12842 _window: &mut Window,
12843 _cx: &mut Context<TestModal>,
12844 ) -> impl IntoElement {
12845 div().track_focus(&self.0)
12846 }
12847 }
12848
12849 #[gpui::test]
12850 async fn test_panels(cx: &mut gpui::TestAppContext) {
12851 init_test(cx);
12852 let fs = FakeFs::new(cx.executor());
12853
12854 let project = Project::test(fs, [], cx).await;
12855 let (multi_workspace, cx) =
12856 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12857 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12858
12859 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12860 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12861 workspace.add_panel(panel_1.clone(), window, cx);
12862 workspace.toggle_dock(DockPosition::Left, window, cx);
12863 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12864 workspace.add_panel(panel_2.clone(), window, cx);
12865 workspace.toggle_dock(DockPosition::Right, window, cx);
12866
12867 let left_dock = workspace.left_dock();
12868 assert_eq!(
12869 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12870 panel_1.panel_id()
12871 );
12872 assert_eq!(
12873 workspace.dock_size(&left_dock.read(cx), window, cx),
12874 Some(px(300.))
12875 );
12876
12877 workspace.resize_left_dock(px(1337.), window, cx);
12878 assert_eq!(
12879 workspace
12880 .right_dock()
12881 .read(cx)
12882 .visible_panel()
12883 .unwrap()
12884 .panel_id(),
12885 panel_2.panel_id(),
12886 );
12887
12888 (panel_1, panel_2)
12889 });
12890
12891 // Move panel_1 to the right
12892 panel_1.update_in(cx, |panel_1, window, cx| {
12893 panel_1.set_position(DockPosition::Right, window, cx)
12894 });
12895
12896 workspace.update_in(cx, |workspace, window, cx| {
12897 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12898 // Since it was the only panel on the left, the left dock should now be closed.
12899 assert!(!workspace.left_dock().read(cx).is_open());
12900 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12901 let right_dock = workspace.right_dock();
12902 assert_eq!(
12903 right_dock.read(cx).visible_panel().unwrap().panel_id(),
12904 panel_1.panel_id()
12905 );
12906 assert_eq!(
12907 right_dock
12908 .read(cx)
12909 .active_panel_size()
12910 .unwrap()
12911 .size
12912 .unwrap(),
12913 px(1337.)
12914 );
12915
12916 // Now we move panel_2 to the left
12917 panel_2.set_position(DockPosition::Left, window, cx);
12918 });
12919
12920 workspace.update(cx, |workspace, cx| {
12921 // Since panel_2 was not visible on the right, we don't open the left dock.
12922 assert!(!workspace.left_dock().read(cx).is_open());
12923 // And the right dock is unaffected in its displaying of panel_1
12924 assert!(workspace.right_dock().read(cx).is_open());
12925 assert_eq!(
12926 workspace
12927 .right_dock()
12928 .read(cx)
12929 .visible_panel()
12930 .unwrap()
12931 .panel_id(),
12932 panel_1.panel_id(),
12933 );
12934 });
12935
12936 // Move panel_1 back to the left
12937 panel_1.update_in(cx, |panel_1, window, cx| {
12938 panel_1.set_position(DockPosition::Left, window, cx)
12939 });
12940
12941 workspace.update_in(cx, |workspace, window, cx| {
12942 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12943 let left_dock = workspace.left_dock();
12944 assert!(left_dock.read(cx).is_open());
12945 assert_eq!(
12946 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12947 panel_1.panel_id()
12948 );
12949 assert_eq!(
12950 workspace.dock_size(&left_dock.read(cx), window, cx),
12951 Some(px(1337.))
12952 );
12953 // And the right dock should be closed as it no longer has any panels.
12954 assert!(!workspace.right_dock().read(cx).is_open());
12955
12956 // Now we move panel_1 to the bottom
12957 panel_1.set_position(DockPosition::Bottom, window, cx);
12958 });
12959
12960 workspace.update_in(cx, |workspace, window, cx| {
12961 // Since panel_1 was visible on the left, we close the left dock.
12962 assert!(!workspace.left_dock().read(cx).is_open());
12963 // The bottom dock is sized based on the panel's default size,
12964 // since the panel orientation changed from vertical to horizontal.
12965 let bottom_dock = workspace.bottom_dock();
12966 assert_eq!(
12967 workspace.dock_size(&bottom_dock.read(cx), window, cx),
12968 Some(px(300.))
12969 );
12970 // Close bottom dock and move panel_1 back to the left.
12971 bottom_dock.update(cx, |bottom_dock, cx| {
12972 bottom_dock.set_open(false, window, cx)
12973 });
12974 panel_1.set_position(DockPosition::Left, window, cx);
12975 });
12976
12977 // Emit activated event on panel 1
12978 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12979
12980 // Now the left dock is open and panel_1 is active and focused.
12981 workspace.update_in(cx, |workspace, window, cx| {
12982 let left_dock = workspace.left_dock();
12983 assert!(left_dock.read(cx).is_open());
12984 assert_eq!(
12985 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12986 panel_1.panel_id(),
12987 );
12988 assert!(panel_1.focus_handle(cx).is_focused(window));
12989 });
12990
12991 // Emit closed event on panel 2, which is not active
12992 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12993
12994 // Wo don't close the left dock, because panel_2 wasn't the active panel
12995 workspace.update(cx, |workspace, cx| {
12996 let left_dock = workspace.left_dock();
12997 assert!(left_dock.read(cx).is_open());
12998 assert_eq!(
12999 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13000 panel_1.panel_id(),
13001 );
13002 });
13003
13004 // Emitting a ZoomIn event shows the panel as zoomed.
13005 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
13006 workspace.read_with(cx, |workspace, _| {
13007 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13008 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13009 });
13010
13011 // Move panel to another dock while it is zoomed
13012 panel_1.update_in(cx, |panel, window, cx| {
13013 panel.set_position(DockPosition::Right, window, cx)
13014 });
13015 workspace.read_with(cx, |workspace, _| {
13016 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13017
13018 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13019 });
13020
13021 // This is a helper for getting a:
13022 // - valid focus on an element,
13023 // - that isn't a part of the panes and panels system of the Workspace,
13024 // - and doesn't trigger the 'on_focus_lost' API.
13025 let focus_other_view = {
13026 let workspace = workspace.clone();
13027 move |cx: &mut VisualTestContext| {
13028 workspace.update_in(cx, |workspace, window, cx| {
13029 if workspace.active_modal::<TestModal>(cx).is_some() {
13030 workspace.toggle_modal(window, cx, TestModal::new);
13031 workspace.toggle_modal(window, cx, TestModal::new);
13032 } else {
13033 workspace.toggle_modal(window, cx, TestModal::new);
13034 }
13035 })
13036 }
13037 };
13038
13039 // If focus is transferred to another view that's not a panel or another pane, we still show
13040 // the panel as zoomed.
13041 focus_other_view(cx);
13042 workspace.read_with(cx, |workspace, _| {
13043 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13044 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13045 });
13046
13047 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13048 workspace.update_in(cx, |_workspace, window, cx| {
13049 cx.focus_self(window);
13050 });
13051 workspace.read_with(cx, |workspace, _| {
13052 assert_eq!(workspace.zoomed, None);
13053 assert_eq!(workspace.zoomed_position, None);
13054 });
13055
13056 // If focus is transferred again to another view that's not a panel or a pane, we won't
13057 // show the panel as zoomed because it wasn't zoomed before.
13058 focus_other_view(cx);
13059 workspace.read_with(cx, |workspace, _| {
13060 assert_eq!(workspace.zoomed, None);
13061 assert_eq!(workspace.zoomed_position, None);
13062 });
13063
13064 // When the panel is activated, it is zoomed again.
13065 cx.dispatch_action(ToggleRightDock);
13066 workspace.read_with(cx, |workspace, _| {
13067 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13068 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13069 });
13070
13071 // Emitting a ZoomOut event unzooms the panel.
13072 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13073 workspace.read_with(cx, |workspace, _| {
13074 assert_eq!(workspace.zoomed, None);
13075 assert_eq!(workspace.zoomed_position, None);
13076 });
13077
13078 // Emit closed event on panel 1, which is active
13079 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13080
13081 // Now the left dock is closed, because panel_1 was the active panel
13082 workspace.update(cx, |workspace, cx| {
13083 let right_dock = workspace.right_dock();
13084 assert!(!right_dock.read(cx).is_open());
13085 });
13086 }
13087
13088 #[gpui::test]
13089 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13090 init_test(cx);
13091
13092 let fs = FakeFs::new(cx.background_executor.clone());
13093 let project = Project::test(fs, [], cx).await;
13094 let (workspace, cx) =
13095 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13096 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13097
13098 let dirty_regular_buffer = cx.new(|cx| {
13099 TestItem::new(cx)
13100 .with_dirty(true)
13101 .with_label("1.txt")
13102 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13103 });
13104 let dirty_regular_buffer_2 = cx.new(|cx| {
13105 TestItem::new(cx)
13106 .with_dirty(true)
13107 .with_label("2.txt")
13108 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13109 });
13110 let dirty_multi_buffer_with_both = cx.new(|cx| {
13111 TestItem::new(cx)
13112 .with_dirty(true)
13113 .with_buffer_kind(ItemBufferKind::Multibuffer)
13114 .with_label("Fake Project Search")
13115 .with_project_items(&[
13116 dirty_regular_buffer.read(cx).project_items[0].clone(),
13117 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13118 ])
13119 });
13120 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13121 workspace.update_in(cx, |workspace, window, cx| {
13122 workspace.add_item(
13123 pane.clone(),
13124 Box::new(dirty_regular_buffer.clone()),
13125 None,
13126 false,
13127 false,
13128 window,
13129 cx,
13130 );
13131 workspace.add_item(
13132 pane.clone(),
13133 Box::new(dirty_regular_buffer_2.clone()),
13134 None,
13135 false,
13136 false,
13137 window,
13138 cx,
13139 );
13140 workspace.add_item(
13141 pane.clone(),
13142 Box::new(dirty_multi_buffer_with_both.clone()),
13143 None,
13144 false,
13145 false,
13146 window,
13147 cx,
13148 );
13149 });
13150
13151 pane.update_in(cx, |pane, window, cx| {
13152 pane.activate_item(2, true, true, window, cx);
13153 assert_eq!(
13154 pane.active_item().unwrap().item_id(),
13155 multi_buffer_with_both_files_id,
13156 "Should select the multi buffer in the pane"
13157 );
13158 });
13159 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13160 pane.close_other_items(
13161 &CloseOtherItems {
13162 save_intent: Some(SaveIntent::Save),
13163 close_pinned: true,
13164 },
13165 None,
13166 window,
13167 cx,
13168 )
13169 });
13170 cx.background_executor.run_until_parked();
13171 assert!(!cx.has_pending_prompt());
13172 close_all_but_multi_buffer_task
13173 .await
13174 .expect("Closing all buffers but the multi buffer failed");
13175 pane.update(cx, |pane, cx| {
13176 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13177 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13178 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13179 assert_eq!(pane.items_len(), 1);
13180 assert_eq!(
13181 pane.active_item().unwrap().item_id(),
13182 multi_buffer_with_both_files_id,
13183 "Should have only the multi buffer left in the pane"
13184 );
13185 assert!(
13186 dirty_multi_buffer_with_both.read(cx).is_dirty,
13187 "The multi buffer containing the unsaved buffer should still be dirty"
13188 );
13189 });
13190
13191 dirty_regular_buffer.update(cx, |buffer, cx| {
13192 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13193 });
13194
13195 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13196 pane.close_active_item(
13197 &CloseActiveItem {
13198 save_intent: Some(SaveIntent::Close),
13199 close_pinned: false,
13200 },
13201 window,
13202 cx,
13203 )
13204 });
13205 cx.background_executor.run_until_parked();
13206 assert!(
13207 cx.has_pending_prompt(),
13208 "Dirty multi buffer should prompt a save dialog"
13209 );
13210 cx.simulate_prompt_answer("Save");
13211 cx.background_executor.run_until_parked();
13212 close_multi_buffer_task
13213 .await
13214 .expect("Closing the multi buffer failed");
13215 pane.update(cx, |pane, cx| {
13216 assert_eq!(
13217 dirty_multi_buffer_with_both.read(cx).save_count,
13218 1,
13219 "Multi buffer item should get be saved"
13220 );
13221 // Test impl does not save inner items, so we do not assert them
13222 assert_eq!(
13223 pane.items_len(),
13224 0,
13225 "No more items should be left in the pane"
13226 );
13227 assert!(pane.active_item().is_none());
13228 });
13229 }
13230
13231 #[gpui::test]
13232 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13233 cx: &mut TestAppContext,
13234 ) {
13235 init_test(cx);
13236
13237 let fs = FakeFs::new(cx.background_executor.clone());
13238 let project = Project::test(fs, [], cx).await;
13239 let (workspace, cx) =
13240 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13241 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13242
13243 let dirty_regular_buffer = cx.new(|cx| {
13244 TestItem::new(cx)
13245 .with_dirty(true)
13246 .with_label("1.txt")
13247 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13248 });
13249 let dirty_regular_buffer_2 = cx.new(|cx| {
13250 TestItem::new(cx)
13251 .with_dirty(true)
13252 .with_label("2.txt")
13253 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13254 });
13255 let clear_regular_buffer = cx.new(|cx| {
13256 TestItem::new(cx)
13257 .with_label("3.txt")
13258 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13259 });
13260
13261 let dirty_multi_buffer_with_both = cx.new(|cx| {
13262 TestItem::new(cx)
13263 .with_dirty(true)
13264 .with_buffer_kind(ItemBufferKind::Multibuffer)
13265 .with_label("Fake Project Search")
13266 .with_project_items(&[
13267 dirty_regular_buffer.read(cx).project_items[0].clone(),
13268 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13269 clear_regular_buffer.read(cx).project_items[0].clone(),
13270 ])
13271 });
13272 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13273 workspace.update_in(cx, |workspace, window, cx| {
13274 workspace.add_item(
13275 pane.clone(),
13276 Box::new(dirty_regular_buffer.clone()),
13277 None,
13278 false,
13279 false,
13280 window,
13281 cx,
13282 );
13283 workspace.add_item(
13284 pane.clone(),
13285 Box::new(dirty_multi_buffer_with_both.clone()),
13286 None,
13287 false,
13288 false,
13289 window,
13290 cx,
13291 );
13292 });
13293
13294 pane.update_in(cx, |pane, window, cx| {
13295 pane.activate_item(1, true, true, window, cx);
13296 assert_eq!(
13297 pane.active_item().unwrap().item_id(),
13298 multi_buffer_with_both_files_id,
13299 "Should select the multi buffer in the pane"
13300 );
13301 });
13302 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13303 pane.close_active_item(
13304 &CloseActiveItem {
13305 save_intent: None,
13306 close_pinned: false,
13307 },
13308 window,
13309 cx,
13310 )
13311 });
13312 cx.background_executor.run_until_parked();
13313 assert!(
13314 cx.has_pending_prompt(),
13315 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13316 );
13317 }
13318
13319 /// Tests that when `close_on_file_delete` is enabled, files are automatically
13320 /// closed when they are deleted from disk.
13321 #[gpui::test]
13322 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13323 init_test(cx);
13324
13325 // Enable the close_on_disk_deletion setting
13326 cx.update_global(|store: &mut SettingsStore, cx| {
13327 store.update_user_settings(cx, |settings| {
13328 settings.workspace.close_on_file_delete = Some(true);
13329 });
13330 });
13331
13332 let fs = FakeFs::new(cx.background_executor.clone());
13333 let project = Project::test(fs, [], cx).await;
13334 let (workspace, cx) =
13335 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13336 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13337
13338 // Create a test item that simulates a file
13339 let item = cx.new(|cx| {
13340 TestItem::new(cx)
13341 .with_label("test.txt")
13342 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13343 });
13344
13345 // Add item to workspace
13346 workspace.update_in(cx, |workspace, window, cx| {
13347 workspace.add_item(
13348 pane.clone(),
13349 Box::new(item.clone()),
13350 None,
13351 false,
13352 false,
13353 window,
13354 cx,
13355 );
13356 });
13357
13358 // Verify the item is in the pane
13359 pane.read_with(cx, |pane, _| {
13360 assert_eq!(pane.items().count(), 1);
13361 });
13362
13363 // Simulate file deletion by setting the item's deleted state
13364 item.update(cx, |item, _| {
13365 item.set_has_deleted_file(true);
13366 });
13367
13368 // Emit UpdateTab event to trigger the close behavior
13369 cx.run_until_parked();
13370 item.update(cx, |_, cx| {
13371 cx.emit(ItemEvent::UpdateTab);
13372 });
13373
13374 // Allow the close operation to complete
13375 cx.run_until_parked();
13376
13377 // Verify the item was automatically closed
13378 pane.read_with(cx, |pane, _| {
13379 assert_eq!(
13380 pane.items().count(),
13381 0,
13382 "Item should be automatically closed when file is deleted"
13383 );
13384 });
13385 }
13386
13387 /// Tests that when `close_on_file_delete` is disabled (default), files remain
13388 /// open with a strikethrough when they are deleted from disk.
13389 #[gpui::test]
13390 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13391 init_test(cx);
13392
13393 // Ensure close_on_disk_deletion is disabled (default)
13394 cx.update_global(|store: &mut SettingsStore, cx| {
13395 store.update_user_settings(cx, |settings| {
13396 settings.workspace.close_on_file_delete = Some(false);
13397 });
13398 });
13399
13400 let fs = FakeFs::new(cx.background_executor.clone());
13401 let project = Project::test(fs, [], cx).await;
13402 let (workspace, cx) =
13403 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13404 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13405
13406 // Create a test item that simulates a file
13407 let item = cx.new(|cx| {
13408 TestItem::new(cx)
13409 .with_label("test.txt")
13410 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13411 });
13412
13413 // Add item to workspace
13414 workspace.update_in(cx, |workspace, window, cx| {
13415 workspace.add_item(
13416 pane.clone(),
13417 Box::new(item.clone()),
13418 None,
13419 false,
13420 false,
13421 window,
13422 cx,
13423 );
13424 });
13425
13426 // Verify the item is in the pane
13427 pane.read_with(cx, |pane, _| {
13428 assert_eq!(pane.items().count(), 1);
13429 });
13430
13431 // Simulate file deletion
13432 item.update(cx, |item, _| {
13433 item.set_has_deleted_file(true);
13434 });
13435
13436 // Emit UpdateTab event
13437 cx.run_until_parked();
13438 item.update(cx, |_, cx| {
13439 cx.emit(ItemEvent::UpdateTab);
13440 });
13441
13442 // Allow any potential close operation to complete
13443 cx.run_until_parked();
13444
13445 // Verify the item remains open (with strikethrough)
13446 pane.read_with(cx, |pane, _| {
13447 assert_eq!(
13448 pane.items().count(),
13449 1,
13450 "Item should remain open when close_on_disk_deletion is disabled"
13451 );
13452 });
13453
13454 // Verify the item shows as deleted
13455 item.read_with(cx, |item, _| {
13456 assert!(
13457 item.has_deleted_file,
13458 "Item should be marked as having deleted file"
13459 );
13460 });
13461 }
13462
13463 /// Tests that dirty files are not automatically closed when deleted from disk,
13464 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13465 /// unsaved changes without being prompted.
13466 #[gpui::test]
13467 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13468 init_test(cx);
13469
13470 // Enable the close_on_file_delete setting
13471 cx.update_global(|store: &mut SettingsStore, cx| {
13472 store.update_user_settings(cx, |settings| {
13473 settings.workspace.close_on_file_delete = Some(true);
13474 });
13475 });
13476
13477 let fs = FakeFs::new(cx.background_executor.clone());
13478 let project = Project::test(fs, [], cx).await;
13479 let (workspace, cx) =
13480 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13481 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13482
13483 // Create a dirty test item
13484 let item = cx.new(|cx| {
13485 TestItem::new(cx)
13486 .with_dirty(true)
13487 .with_label("test.txt")
13488 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13489 });
13490
13491 // Add item to workspace
13492 workspace.update_in(cx, |workspace, window, cx| {
13493 workspace.add_item(
13494 pane.clone(),
13495 Box::new(item.clone()),
13496 None,
13497 false,
13498 false,
13499 window,
13500 cx,
13501 );
13502 });
13503
13504 // Simulate file deletion
13505 item.update(cx, |item, _| {
13506 item.set_has_deleted_file(true);
13507 });
13508
13509 // Emit UpdateTab event to trigger the close behavior
13510 cx.run_until_parked();
13511 item.update(cx, |_, cx| {
13512 cx.emit(ItemEvent::UpdateTab);
13513 });
13514
13515 // Allow any potential close operation to complete
13516 cx.run_until_parked();
13517
13518 // Verify the item remains open (dirty files are not auto-closed)
13519 pane.read_with(cx, |pane, _| {
13520 assert_eq!(
13521 pane.items().count(),
13522 1,
13523 "Dirty items should not be automatically closed even when file is deleted"
13524 );
13525 });
13526
13527 // Verify the item is marked as deleted and still dirty
13528 item.read_with(cx, |item, _| {
13529 assert!(
13530 item.has_deleted_file,
13531 "Item should be marked as having deleted file"
13532 );
13533 assert!(item.is_dirty, "Item should still be dirty");
13534 });
13535 }
13536
13537 /// Tests that navigation history is cleaned up when files are auto-closed
13538 /// due to deletion from disk.
13539 #[gpui::test]
13540 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13541 init_test(cx);
13542
13543 // Enable the close_on_file_delete setting
13544 cx.update_global(|store: &mut SettingsStore, cx| {
13545 store.update_user_settings(cx, |settings| {
13546 settings.workspace.close_on_file_delete = Some(true);
13547 });
13548 });
13549
13550 let fs = FakeFs::new(cx.background_executor.clone());
13551 let project = Project::test(fs, [], cx).await;
13552 let (workspace, cx) =
13553 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13554 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13555
13556 // Create test items
13557 let item1 = cx.new(|cx| {
13558 TestItem::new(cx)
13559 .with_label("test1.txt")
13560 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13561 });
13562 let item1_id = item1.item_id();
13563
13564 let item2 = cx.new(|cx| {
13565 TestItem::new(cx)
13566 .with_label("test2.txt")
13567 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13568 });
13569
13570 // Add items to workspace
13571 workspace.update_in(cx, |workspace, window, cx| {
13572 workspace.add_item(
13573 pane.clone(),
13574 Box::new(item1.clone()),
13575 None,
13576 false,
13577 false,
13578 window,
13579 cx,
13580 );
13581 workspace.add_item(
13582 pane.clone(),
13583 Box::new(item2.clone()),
13584 None,
13585 false,
13586 false,
13587 window,
13588 cx,
13589 );
13590 });
13591
13592 // Activate item1 to ensure it gets navigation entries
13593 pane.update_in(cx, |pane, window, cx| {
13594 pane.activate_item(0, true, true, window, cx);
13595 });
13596
13597 // Switch to item2 and back to create navigation history
13598 pane.update_in(cx, |pane, window, cx| {
13599 pane.activate_item(1, true, true, window, cx);
13600 });
13601 cx.run_until_parked();
13602
13603 pane.update_in(cx, |pane, window, cx| {
13604 pane.activate_item(0, true, true, window, cx);
13605 });
13606 cx.run_until_parked();
13607
13608 // Simulate file deletion for item1
13609 item1.update(cx, |item, _| {
13610 item.set_has_deleted_file(true);
13611 });
13612
13613 // Emit UpdateTab event to trigger the close behavior
13614 item1.update(cx, |_, cx| {
13615 cx.emit(ItemEvent::UpdateTab);
13616 });
13617 cx.run_until_parked();
13618
13619 // Verify item1 was closed
13620 pane.read_with(cx, |pane, _| {
13621 assert_eq!(
13622 pane.items().count(),
13623 1,
13624 "Should have 1 item remaining after auto-close"
13625 );
13626 });
13627
13628 // Check navigation history after close
13629 let has_item = pane.read_with(cx, |pane, cx| {
13630 let mut has_item = false;
13631 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13632 if entry.item.id() == item1_id {
13633 has_item = true;
13634 }
13635 });
13636 has_item
13637 });
13638
13639 assert!(
13640 !has_item,
13641 "Navigation history should not contain closed item entries"
13642 );
13643 }
13644
13645 #[gpui::test]
13646 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13647 cx: &mut TestAppContext,
13648 ) {
13649 init_test(cx);
13650
13651 let fs = FakeFs::new(cx.background_executor.clone());
13652 let project = Project::test(fs, [], cx).await;
13653 let (workspace, cx) =
13654 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13655 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13656
13657 let dirty_regular_buffer = cx.new(|cx| {
13658 TestItem::new(cx)
13659 .with_dirty(true)
13660 .with_label("1.txt")
13661 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13662 });
13663 let dirty_regular_buffer_2 = cx.new(|cx| {
13664 TestItem::new(cx)
13665 .with_dirty(true)
13666 .with_label("2.txt")
13667 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13668 });
13669 let clear_regular_buffer = cx.new(|cx| {
13670 TestItem::new(cx)
13671 .with_label("3.txt")
13672 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13673 });
13674
13675 let dirty_multi_buffer = cx.new(|cx| {
13676 TestItem::new(cx)
13677 .with_dirty(true)
13678 .with_buffer_kind(ItemBufferKind::Multibuffer)
13679 .with_label("Fake Project Search")
13680 .with_project_items(&[
13681 dirty_regular_buffer.read(cx).project_items[0].clone(),
13682 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13683 clear_regular_buffer.read(cx).project_items[0].clone(),
13684 ])
13685 });
13686 workspace.update_in(cx, |workspace, window, cx| {
13687 workspace.add_item(
13688 pane.clone(),
13689 Box::new(dirty_regular_buffer.clone()),
13690 None,
13691 false,
13692 false,
13693 window,
13694 cx,
13695 );
13696 workspace.add_item(
13697 pane.clone(),
13698 Box::new(dirty_regular_buffer_2.clone()),
13699 None,
13700 false,
13701 false,
13702 window,
13703 cx,
13704 );
13705 workspace.add_item(
13706 pane.clone(),
13707 Box::new(dirty_multi_buffer.clone()),
13708 None,
13709 false,
13710 false,
13711 window,
13712 cx,
13713 );
13714 });
13715
13716 pane.update_in(cx, |pane, window, cx| {
13717 pane.activate_item(2, true, true, window, cx);
13718 assert_eq!(
13719 pane.active_item().unwrap().item_id(),
13720 dirty_multi_buffer.item_id(),
13721 "Should select the multi buffer in the pane"
13722 );
13723 });
13724 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13725 pane.close_active_item(
13726 &CloseActiveItem {
13727 save_intent: None,
13728 close_pinned: false,
13729 },
13730 window,
13731 cx,
13732 )
13733 });
13734 cx.background_executor.run_until_parked();
13735 assert!(
13736 !cx.has_pending_prompt(),
13737 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13738 );
13739 close_multi_buffer_task
13740 .await
13741 .expect("Closing multi buffer failed");
13742 pane.update(cx, |pane, cx| {
13743 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13744 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13745 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13746 assert_eq!(
13747 pane.items()
13748 .map(|item| item.item_id())
13749 .sorted()
13750 .collect::<Vec<_>>(),
13751 vec![
13752 dirty_regular_buffer.item_id(),
13753 dirty_regular_buffer_2.item_id(),
13754 ],
13755 "Should have no multi buffer left in the pane"
13756 );
13757 assert!(dirty_regular_buffer.read(cx).is_dirty);
13758 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13759 });
13760 }
13761
13762 #[gpui::test]
13763 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13764 init_test(cx);
13765 let fs = FakeFs::new(cx.executor());
13766 let project = Project::test(fs, [], cx).await;
13767 let (multi_workspace, cx) =
13768 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13769 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13770
13771 // Add a new panel to the right dock, opening the dock and setting the
13772 // focus to the new panel.
13773 let panel = workspace.update_in(cx, |workspace, window, cx| {
13774 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13775 workspace.add_panel(panel.clone(), window, cx);
13776
13777 workspace
13778 .right_dock()
13779 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13780
13781 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13782
13783 panel
13784 });
13785
13786 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13787 // panel to the next valid position which, in this case, is the left
13788 // dock.
13789 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13790 workspace.update(cx, |workspace, cx| {
13791 assert!(workspace.left_dock().read(cx).is_open());
13792 assert_eq!(panel.read(cx).position, DockPosition::Left);
13793 });
13794
13795 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13796 // panel to the next valid position which, in this case, is the bottom
13797 // dock.
13798 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13799 workspace.update(cx, |workspace, cx| {
13800 assert!(workspace.bottom_dock().read(cx).is_open());
13801 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13802 });
13803
13804 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13805 // around moving the panel to its initial position, the right dock.
13806 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13807 workspace.update(cx, |workspace, cx| {
13808 assert!(workspace.right_dock().read(cx).is_open());
13809 assert_eq!(panel.read(cx).position, DockPosition::Right);
13810 });
13811
13812 // Remove focus from the panel, ensuring that, if the panel is not
13813 // focused, the `MoveFocusedPanelToNextPosition` action does not update
13814 // the panel's position, so the panel is still in the right dock.
13815 workspace.update_in(cx, |workspace, window, cx| {
13816 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13817 });
13818
13819 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13820 workspace.update(cx, |workspace, cx| {
13821 assert!(workspace.right_dock().read(cx).is_open());
13822 assert_eq!(panel.read(cx).position, DockPosition::Right);
13823 });
13824 }
13825
13826 #[gpui::test]
13827 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13828 init_test(cx);
13829
13830 let fs = FakeFs::new(cx.executor());
13831 let project = Project::test(fs, [], cx).await;
13832 let (workspace, cx) =
13833 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13834
13835 let item_1 = cx.new(|cx| {
13836 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13837 });
13838 workspace.update_in(cx, |workspace, window, cx| {
13839 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13840 workspace.move_item_to_pane_in_direction(
13841 &MoveItemToPaneInDirection {
13842 direction: SplitDirection::Right,
13843 focus: true,
13844 clone: false,
13845 },
13846 window,
13847 cx,
13848 );
13849 workspace.move_item_to_pane_at_index(
13850 &MoveItemToPane {
13851 destination: 3,
13852 focus: true,
13853 clone: false,
13854 },
13855 window,
13856 cx,
13857 );
13858
13859 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13860 assert_eq!(
13861 pane_items_paths(&workspace.active_pane, cx),
13862 vec!["first.txt".to_string()],
13863 "Single item was not moved anywhere"
13864 );
13865 });
13866
13867 let item_2 = cx.new(|cx| {
13868 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13869 });
13870 workspace.update_in(cx, |workspace, window, cx| {
13871 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13872 assert_eq!(
13873 pane_items_paths(&workspace.panes[0], cx),
13874 vec!["first.txt".to_string(), "second.txt".to_string()],
13875 );
13876 workspace.move_item_to_pane_in_direction(
13877 &MoveItemToPaneInDirection {
13878 direction: SplitDirection::Right,
13879 focus: true,
13880 clone: false,
13881 },
13882 window,
13883 cx,
13884 );
13885
13886 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13887 assert_eq!(
13888 pane_items_paths(&workspace.panes[0], cx),
13889 vec!["first.txt".to_string()],
13890 "After moving, one item should be left in the original pane"
13891 );
13892 assert_eq!(
13893 pane_items_paths(&workspace.panes[1], cx),
13894 vec!["second.txt".to_string()],
13895 "New item should have been moved to the new pane"
13896 );
13897 });
13898
13899 let item_3 = cx.new(|cx| {
13900 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13901 });
13902 workspace.update_in(cx, |workspace, window, cx| {
13903 let original_pane = workspace.panes[0].clone();
13904 workspace.set_active_pane(&original_pane, window, cx);
13905 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13906 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13907 assert_eq!(
13908 pane_items_paths(&workspace.active_pane, cx),
13909 vec!["first.txt".to_string(), "third.txt".to_string()],
13910 "New pane should be ready to move one item out"
13911 );
13912
13913 workspace.move_item_to_pane_at_index(
13914 &MoveItemToPane {
13915 destination: 3,
13916 focus: true,
13917 clone: false,
13918 },
13919 window,
13920 cx,
13921 );
13922 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13923 assert_eq!(
13924 pane_items_paths(&workspace.active_pane, cx),
13925 vec!["first.txt".to_string()],
13926 "After moving, one item should be left in the original pane"
13927 );
13928 assert_eq!(
13929 pane_items_paths(&workspace.panes[1], cx),
13930 vec!["second.txt".to_string()],
13931 "Previously created pane should be unchanged"
13932 );
13933 assert_eq!(
13934 pane_items_paths(&workspace.panes[2], cx),
13935 vec!["third.txt".to_string()],
13936 "New item should have been moved to the new pane"
13937 );
13938 });
13939 }
13940
13941 #[gpui::test]
13942 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13943 init_test(cx);
13944
13945 let fs = FakeFs::new(cx.executor());
13946 let project = Project::test(fs, [], cx).await;
13947 let (workspace, cx) =
13948 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13949
13950 let item_1 = cx.new(|cx| {
13951 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13952 });
13953 workspace.update_in(cx, |workspace, window, cx| {
13954 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13955 workspace.move_item_to_pane_in_direction(
13956 &MoveItemToPaneInDirection {
13957 direction: SplitDirection::Right,
13958 focus: true,
13959 clone: true,
13960 },
13961 window,
13962 cx,
13963 );
13964 });
13965 cx.run_until_parked();
13966 workspace.update_in(cx, |workspace, window, cx| {
13967 workspace.move_item_to_pane_at_index(
13968 &MoveItemToPane {
13969 destination: 3,
13970 focus: true,
13971 clone: true,
13972 },
13973 window,
13974 cx,
13975 );
13976 });
13977 cx.run_until_parked();
13978
13979 workspace.update(cx, |workspace, cx| {
13980 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13981 for pane in workspace.panes() {
13982 assert_eq!(
13983 pane_items_paths(pane, cx),
13984 vec!["first.txt".to_string()],
13985 "Single item exists in all panes"
13986 );
13987 }
13988 });
13989
13990 // verify that the active pane has been updated after waiting for the
13991 // pane focus event to fire and resolve
13992 workspace.read_with(cx, |workspace, _app| {
13993 assert_eq!(
13994 workspace.active_pane(),
13995 &workspace.panes[2],
13996 "The third pane should be the active one: {:?}",
13997 workspace.panes
13998 );
13999 })
14000 }
14001
14002 #[gpui::test]
14003 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
14004 init_test(cx);
14005
14006 let fs = FakeFs::new(cx.executor());
14007 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14008
14009 let project = Project::test(fs, ["root".as_ref()], cx).await;
14010 let (workspace, cx) =
14011 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14012
14013 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14014 // Add item to pane A with project path
14015 let item_a = cx.new(|cx| {
14016 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14017 });
14018 workspace.update_in(cx, |workspace, window, cx| {
14019 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14020 });
14021
14022 // Split to create pane B
14023 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14024 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14025 });
14026
14027 // Add item with SAME project path to pane B, and pin it
14028 let item_b = cx.new(|cx| {
14029 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14030 });
14031 pane_b.update_in(cx, |pane, window, cx| {
14032 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14033 pane.set_pinned_count(1);
14034 });
14035
14036 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14037 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14038
14039 // close_pinned: false should only close the unpinned copy
14040 workspace.update_in(cx, |workspace, window, cx| {
14041 workspace.close_item_in_all_panes(
14042 &CloseItemInAllPanes {
14043 save_intent: Some(SaveIntent::Close),
14044 close_pinned: false,
14045 },
14046 window,
14047 cx,
14048 )
14049 });
14050 cx.executor().run_until_parked();
14051
14052 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14053 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14054 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14055 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14056
14057 // Split again, seeing as closing the previous item also closed its
14058 // pane, so only pane remains, which does not allow us to properly test
14059 // that both items close when `close_pinned: true`.
14060 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14061 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14062 });
14063
14064 // Add an item with the same project path to pane C so that
14065 // close_item_in_all_panes can determine what to close across all panes
14066 // (it reads the active item from the active pane, and split_pane
14067 // creates an empty pane).
14068 let item_c = cx.new(|cx| {
14069 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14070 });
14071 pane_c.update_in(cx, |pane, window, cx| {
14072 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14073 });
14074
14075 // close_pinned: true should close the pinned copy too
14076 workspace.update_in(cx, |workspace, window, cx| {
14077 let panes_count = workspace.panes().len();
14078 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14079
14080 workspace.close_item_in_all_panes(
14081 &CloseItemInAllPanes {
14082 save_intent: Some(SaveIntent::Close),
14083 close_pinned: true,
14084 },
14085 window,
14086 cx,
14087 )
14088 });
14089 cx.executor().run_until_parked();
14090
14091 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14092 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14093 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14094 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14095 }
14096
14097 mod register_project_item_tests {
14098
14099 use super::*;
14100
14101 // View
14102 struct TestPngItemView {
14103 focus_handle: FocusHandle,
14104 }
14105 // Model
14106 struct TestPngItem {}
14107
14108 impl project::ProjectItem for TestPngItem {
14109 fn try_open(
14110 _project: &Entity<Project>,
14111 path: &ProjectPath,
14112 cx: &mut App,
14113 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14114 if path.path.extension().unwrap() == "png" {
14115 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14116 } else {
14117 None
14118 }
14119 }
14120
14121 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14122 None
14123 }
14124
14125 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14126 None
14127 }
14128
14129 fn is_dirty(&self) -> bool {
14130 false
14131 }
14132 }
14133
14134 impl Item for TestPngItemView {
14135 type Event = ();
14136 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14137 "".into()
14138 }
14139 }
14140 impl EventEmitter<()> for TestPngItemView {}
14141 impl Focusable for TestPngItemView {
14142 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14143 self.focus_handle.clone()
14144 }
14145 }
14146
14147 impl Render for TestPngItemView {
14148 fn render(
14149 &mut self,
14150 _window: &mut Window,
14151 _cx: &mut Context<Self>,
14152 ) -> impl IntoElement {
14153 Empty
14154 }
14155 }
14156
14157 impl ProjectItem for TestPngItemView {
14158 type Item = TestPngItem;
14159
14160 fn for_project_item(
14161 _project: Entity<Project>,
14162 _pane: Option<&Pane>,
14163 _item: Entity<Self::Item>,
14164 _: &mut Window,
14165 cx: &mut Context<Self>,
14166 ) -> Self
14167 where
14168 Self: Sized,
14169 {
14170 Self {
14171 focus_handle: cx.focus_handle(),
14172 }
14173 }
14174 }
14175
14176 // View
14177 struct TestIpynbItemView {
14178 focus_handle: FocusHandle,
14179 }
14180 // Model
14181 struct TestIpynbItem {}
14182
14183 impl project::ProjectItem for TestIpynbItem {
14184 fn try_open(
14185 _project: &Entity<Project>,
14186 path: &ProjectPath,
14187 cx: &mut App,
14188 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14189 if path.path.extension().unwrap() == "ipynb" {
14190 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14191 } else {
14192 None
14193 }
14194 }
14195
14196 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14197 None
14198 }
14199
14200 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14201 None
14202 }
14203
14204 fn is_dirty(&self) -> bool {
14205 false
14206 }
14207 }
14208
14209 impl Item for TestIpynbItemView {
14210 type Event = ();
14211 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14212 "".into()
14213 }
14214 }
14215 impl EventEmitter<()> for TestIpynbItemView {}
14216 impl Focusable for TestIpynbItemView {
14217 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14218 self.focus_handle.clone()
14219 }
14220 }
14221
14222 impl Render for TestIpynbItemView {
14223 fn render(
14224 &mut self,
14225 _window: &mut Window,
14226 _cx: &mut Context<Self>,
14227 ) -> impl IntoElement {
14228 Empty
14229 }
14230 }
14231
14232 impl ProjectItem for TestIpynbItemView {
14233 type Item = TestIpynbItem;
14234
14235 fn for_project_item(
14236 _project: Entity<Project>,
14237 _pane: Option<&Pane>,
14238 _item: Entity<Self::Item>,
14239 _: &mut Window,
14240 cx: &mut Context<Self>,
14241 ) -> Self
14242 where
14243 Self: Sized,
14244 {
14245 Self {
14246 focus_handle: cx.focus_handle(),
14247 }
14248 }
14249 }
14250
14251 struct TestAlternatePngItemView {
14252 focus_handle: FocusHandle,
14253 }
14254
14255 impl Item for TestAlternatePngItemView {
14256 type Event = ();
14257 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14258 "".into()
14259 }
14260 }
14261
14262 impl EventEmitter<()> for TestAlternatePngItemView {}
14263 impl Focusable for TestAlternatePngItemView {
14264 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14265 self.focus_handle.clone()
14266 }
14267 }
14268
14269 impl Render for TestAlternatePngItemView {
14270 fn render(
14271 &mut self,
14272 _window: &mut Window,
14273 _cx: &mut Context<Self>,
14274 ) -> impl IntoElement {
14275 Empty
14276 }
14277 }
14278
14279 impl ProjectItem for TestAlternatePngItemView {
14280 type Item = TestPngItem;
14281
14282 fn for_project_item(
14283 _project: Entity<Project>,
14284 _pane: Option<&Pane>,
14285 _item: Entity<Self::Item>,
14286 _: &mut Window,
14287 cx: &mut Context<Self>,
14288 ) -> Self
14289 where
14290 Self: Sized,
14291 {
14292 Self {
14293 focus_handle: cx.focus_handle(),
14294 }
14295 }
14296 }
14297
14298 #[gpui::test]
14299 async fn test_register_project_item(cx: &mut TestAppContext) {
14300 init_test(cx);
14301
14302 cx.update(|cx| {
14303 register_project_item::<TestPngItemView>(cx);
14304 register_project_item::<TestIpynbItemView>(cx);
14305 });
14306
14307 let fs = FakeFs::new(cx.executor());
14308 fs.insert_tree(
14309 "/root1",
14310 json!({
14311 "one.png": "BINARYDATAHERE",
14312 "two.ipynb": "{ totally a notebook }",
14313 "three.txt": "editing text, sure why not?"
14314 }),
14315 )
14316 .await;
14317
14318 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14319 let (workspace, cx) =
14320 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14321
14322 let worktree_id = project.update(cx, |project, cx| {
14323 project.worktrees(cx).next().unwrap().read(cx).id()
14324 });
14325
14326 let handle = workspace
14327 .update_in(cx, |workspace, window, cx| {
14328 let project_path = (worktree_id, rel_path("one.png"));
14329 workspace.open_path(project_path, None, true, window, cx)
14330 })
14331 .await
14332 .unwrap();
14333
14334 // Now we can check if the handle we got back errored or not
14335 assert_eq!(
14336 handle.to_any_view().entity_type(),
14337 TypeId::of::<TestPngItemView>()
14338 );
14339
14340 let handle = workspace
14341 .update_in(cx, |workspace, window, cx| {
14342 let project_path = (worktree_id, rel_path("two.ipynb"));
14343 workspace.open_path(project_path, None, true, window, cx)
14344 })
14345 .await
14346 .unwrap();
14347
14348 assert_eq!(
14349 handle.to_any_view().entity_type(),
14350 TypeId::of::<TestIpynbItemView>()
14351 );
14352
14353 let handle = workspace
14354 .update_in(cx, |workspace, window, cx| {
14355 let project_path = (worktree_id, rel_path("three.txt"));
14356 workspace.open_path(project_path, None, true, window, cx)
14357 })
14358 .await;
14359 assert!(handle.is_err());
14360 }
14361
14362 #[gpui::test]
14363 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14364 init_test(cx);
14365
14366 cx.update(|cx| {
14367 register_project_item::<TestPngItemView>(cx);
14368 register_project_item::<TestAlternatePngItemView>(cx);
14369 });
14370
14371 let fs = FakeFs::new(cx.executor());
14372 fs.insert_tree(
14373 "/root1",
14374 json!({
14375 "one.png": "BINARYDATAHERE",
14376 "two.ipynb": "{ totally a notebook }",
14377 "three.txt": "editing text, sure why not?"
14378 }),
14379 )
14380 .await;
14381 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14382 let (workspace, cx) =
14383 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14384 let worktree_id = project.update(cx, |project, cx| {
14385 project.worktrees(cx).next().unwrap().read(cx).id()
14386 });
14387
14388 let handle = workspace
14389 .update_in(cx, |workspace, window, cx| {
14390 let project_path = (worktree_id, rel_path("one.png"));
14391 workspace.open_path(project_path, None, true, window, cx)
14392 })
14393 .await
14394 .unwrap();
14395
14396 // This _must_ be the second item registered
14397 assert_eq!(
14398 handle.to_any_view().entity_type(),
14399 TypeId::of::<TestAlternatePngItemView>()
14400 );
14401
14402 let handle = workspace
14403 .update_in(cx, |workspace, window, cx| {
14404 let project_path = (worktree_id, rel_path("three.txt"));
14405 workspace.open_path(project_path, None, true, window, cx)
14406 })
14407 .await;
14408 assert!(handle.is_err());
14409 }
14410 }
14411
14412 #[gpui::test]
14413 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14414 init_test(cx);
14415
14416 let fs = FakeFs::new(cx.executor());
14417 let project = Project::test(fs, [], cx).await;
14418 let (workspace, _cx) =
14419 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14420
14421 // Test with status bar shown (default)
14422 workspace.read_with(cx, |workspace, cx| {
14423 let visible = workspace.status_bar_visible(cx);
14424 assert!(visible, "Status bar should be visible by default");
14425 });
14426
14427 // Test with status bar hidden
14428 cx.update_global(|store: &mut SettingsStore, cx| {
14429 store.update_user_settings(cx, |settings| {
14430 settings.status_bar.get_or_insert_default().show = Some(false);
14431 });
14432 });
14433
14434 workspace.read_with(cx, |workspace, cx| {
14435 let visible = workspace.status_bar_visible(cx);
14436 assert!(!visible, "Status bar should be hidden when show is false");
14437 });
14438
14439 // Test with status bar shown explicitly
14440 cx.update_global(|store: &mut SettingsStore, cx| {
14441 store.update_user_settings(cx, |settings| {
14442 settings.status_bar.get_or_insert_default().show = Some(true);
14443 });
14444 });
14445
14446 workspace.read_with(cx, |workspace, cx| {
14447 let visible = workspace.status_bar_visible(cx);
14448 assert!(visible, "Status bar should be visible when show is true");
14449 });
14450 }
14451
14452 #[gpui::test]
14453 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14454 init_test(cx);
14455
14456 let fs = FakeFs::new(cx.executor());
14457 let project = Project::test(fs, [], cx).await;
14458 let (multi_workspace, cx) =
14459 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14460 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14461 let panel = workspace.update_in(cx, |workspace, window, cx| {
14462 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14463 workspace.add_panel(panel.clone(), window, cx);
14464
14465 workspace
14466 .right_dock()
14467 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14468
14469 panel
14470 });
14471
14472 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14473 let item_a = cx.new(TestItem::new);
14474 let item_b = cx.new(TestItem::new);
14475 let item_a_id = item_a.entity_id();
14476 let item_b_id = item_b.entity_id();
14477
14478 pane.update_in(cx, |pane, window, cx| {
14479 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14480 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14481 });
14482
14483 pane.read_with(cx, |pane, _| {
14484 assert_eq!(pane.items_len(), 2);
14485 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14486 });
14487
14488 workspace.update_in(cx, |workspace, window, cx| {
14489 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14490 });
14491
14492 workspace.update_in(cx, |_, window, cx| {
14493 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14494 });
14495
14496 // Assert that the `pane::CloseActiveItem` action is handled at the
14497 // workspace level when one of the dock panels is focused and, in that
14498 // case, the center pane's active item is closed but the focus is not
14499 // moved.
14500 cx.dispatch_action(pane::CloseActiveItem::default());
14501 cx.run_until_parked();
14502
14503 pane.read_with(cx, |pane, _| {
14504 assert_eq!(pane.items_len(), 1);
14505 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14506 });
14507
14508 workspace.update_in(cx, |workspace, window, cx| {
14509 assert!(workspace.right_dock().read(cx).is_open());
14510 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14511 });
14512 }
14513
14514 #[gpui::test]
14515 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14516 init_test(cx);
14517 let fs = FakeFs::new(cx.executor());
14518
14519 let project_a = Project::test(fs.clone(), [], cx).await;
14520 let project_b = Project::test(fs, [], cx).await;
14521
14522 let multi_workspace_handle =
14523 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14524 cx.run_until_parked();
14525
14526 let workspace_a = multi_workspace_handle
14527 .read_with(cx, |mw, _| mw.workspace().clone())
14528 .unwrap();
14529
14530 let _workspace_b = multi_workspace_handle
14531 .update(cx, |mw, window, cx| {
14532 mw.test_add_workspace(project_b, window, cx)
14533 })
14534 .unwrap();
14535
14536 // Switch to workspace A
14537 multi_workspace_handle
14538 .update(cx, |mw, window, cx| {
14539 let workspace = mw.workspaces()[0].clone();
14540 mw.activate(workspace, window, cx);
14541 })
14542 .unwrap();
14543
14544 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14545
14546 // Add a panel to workspace A's right dock and open the dock
14547 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14548 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14549 workspace.add_panel(panel.clone(), window, cx);
14550 workspace
14551 .right_dock()
14552 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14553 panel
14554 });
14555
14556 // Focus the panel through the workspace (matching existing test pattern)
14557 workspace_a.update_in(cx, |workspace, window, cx| {
14558 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14559 });
14560
14561 // Zoom the panel
14562 panel.update_in(cx, |panel, window, cx| {
14563 panel.set_zoomed(true, window, cx);
14564 });
14565
14566 // Verify the panel is zoomed and the dock is open
14567 workspace_a.update_in(cx, |workspace, window, cx| {
14568 assert!(
14569 workspace.right_dock().read(cx).is_open(),
14570 "dock should be open before switch"
14571 );
14572 assert!(
14573 panel.is_zoomed(window, cx),
14574 "panel should be zoomed before switch"
14575 );
14576 assert!(
14577 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14578 "panel should be focused before switch"
14579 );
14580 });
14581
14582 // Switch to workspace B
14583 multi_workspace_handle
14584 .update(cx, |mw, window, cx| {
14585 let workspace = mw.workspaces()[1].clone();
14586 mw.activate(workspace, window, cx);
14587 })
14588 .unwrap();
14589 cx.run_until_parked();
14590
14591 // Switch back to workspace A
14592 multi_workspace_handle
14593 .update(cx, |mw, window, cx| {
14594 let workspace = mw.workspaces()[0].clone();
14595 mw.activate(workspace, window, cx);
14596 })
14597 .unwrap();
14598 cx.run_until_parked();
14599
14600 // Verify the panel is still zoomed and the dock is still open
14601 workspace_a.update_in(cx, |workspace, window, cx| {
14602 assert!(
14603 workspace.right_dock().read(cx).is_open(),
14604 "dock should still be open after switching back"
14605 );
14606 assert!(
14607 panel.is_zoomed(window, cx),
14608 "panel should still be zoomed after switching back"
14609 );
14610 });
14611 }
14612
14613 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14614 pane.read(cx)
14615 .items()
14616 .flat_map(|item| {
14617 item.project_paths(cx)
14618 .into_iter()
14619 .map(|path| path.path.display(PathStyle::local()).into_owned())
14620 })
14621 .collect()
14622 }
14623
14624 pub fn init_test(cx: &mut TestAppContext) {
14625 cx.update(|cx| {
14626 let settings_store = SettingsStore::test(cx);
14627 cx.set_global(settings_store);
14628 cx.set_global(db::AppDatabase::test_new());
14629 theme_settings::init(theme::LoadThemes::JustBase, cx);
14630 });
14631 }
14632
14633 #[gpui::test]
14634 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14635 use settings::{ThemeName, ThemeSelection};
14636 use theme::SystemAppearance;
14637 use zed_actions::theme::ToggleMode;
14638
14639 init_test(cx);
14640
14641 let fs = FakeFs::new(cx.executor());
14642 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14643
14644 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14645 .await;
14646
14647 // Build a test project and workspace view so the test can invoke
14648 // the workspace action handler the same way the UI would.
14649 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14650 let (workspace, cx) =
14651 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14652
14653 // Seed the settings file with a plain static light theme so the
14654 // first toggle always starts from a known persisted state.
14655 workspace.update_in(cx, |_workspace, _window, cx| {
14656 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14657 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14658 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14659 });
14660 });
14661 cx.executor().advance_clock(Duration::from_millis(200));
14662 cx.run_until_parked();
14663
14664 // Confirm the initial persisted settings contain the static theme
14665 // we just wrote before any toggling happens.
14666 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14667 assert!(settings_text.contains(r#""theme": "One Light""#));
14668
14669 // Toggle once. This should migrate the persisted theme settings
14670 // into light/dark slots and enable system mode.
14671 workspace.update_in(cx, |workspace, window, cx| {
14672 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14673 });
14674 cx.executor().advance_clock(Duration::from_millis(200));
14675 cx.run_until_parked();
14676
14677 // 1. Static -> Dynamic
14678 // this assertion checks theme changed from static to dynamic.
14679 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14680 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14681 assert_eq!(
14682 parsed["theme"],
14683 serde_json::json!({
14684 "mode": "system",
14685 "light": "One Light",
14686 "dark": "One Dark"
14687 })
14688 );
14689
14690 // 2. Toggle again, suppose it will change the mode to light
14691 workspace.update_in(cx, |workspace, window, cx| {
14692 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14693 });
14694 cx.executor().advance_clock(Duration::from_millis(200));
14695 cx.run_until_parked();
14696
14697 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14698 assert!(settings_text.contains(r#""mode": "light""#));
14699 }
14700
14701 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14702 let item = TestProjectItem::new(id, path, cx);
14703 item.update(cx, |item, _| {
14704 item.is_dirty = true;
14705 });
14706 item
14707 }
14708
14709 #[gpui::test]
14710 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14711 cx: &mut gpui::TestAppContext,
14712 ) {
14713 init_test(cx);
14714 let fs = FakeFs::new(cx.executor());
14715
14716 let project = Project::test(fs, [], cx).await;
14717 let (workspace, cx) =
14718 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14719
14720 let panel = workspace.update_in(cx, |workspace, window, cx| {
14721 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14722 workspace.add_panel(panel.clone(), window, cx);
14723 workspace
14724 .right_dock()
14725 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14726 panel
14727 });
14728
14729 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14730 pane.update_in(cx, |pane, window, cx| {
14731 let item = cx.new(TestItem::new);
14732 pane.add_item(Box::new(item), true, true, None, window, cx);
14733 });
14734
14735 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14736 // mirrors the real-world flow and avoids side effects from directly
14737 // focusing the panel while the center pane is active.
14738 workspace.update_in(cx, |workspace, window, cx| {
14739 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14740 });
14741
14742 panel.update_in(cx, |panel, window, cx| {
14743 panel.set_zoomed(true, window, cx);
14744 });
14745
14746 workspace.update_in(cx, |workspace, window, cx| {
14747 assert!(workspace.right_dock().read(cx).is_open());
14748 assert!(panel.is_zoomed(window, cx));
14749 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14750 });
14751
14752 // Simulate a spurious pane::Event::Focus on the center pane while the
14753 // panel still has focus. This mirrors what happens during macOS window
14754 // activation: the center pane fires a focus event even though actual
14755 // focus remains on the dock panel.
14756 pane.update_in(cx, |_, _, cx| {
14757 cx.emit(pane::Event::Focus);
14758 });
14759
14760 // The dock must remain open because the panel had focus at the time the
14761 // event was processed. Before the fix, dock_to_preserve was None for
14762 // panels that don't implement pane(), causing the dock to close.
14763 workspace.update_in(cx, |workspace, window, cx| {
14764 assert!(
14765 workspace.right_dock().read(cx).is_open(),
14766 "Dock should stay open when its zoomed panel (without pane()) still has focus"
14767 );
14768 assert!(panel.is_zoomed(window, cx));
14769 });
14770 }
14771
14772 #[gpui::test]
14773 async fn test_panels_stay_open_after_position_change_and_settings_update(
14774 cx: &mut gpui::TestAppContext,
14775 ) {
14776 init_test(cx);
14777 let fs = FakeFs::new(cx.executor());
14778 let project = Project::test(fs, [], cx).await;
14779 let (workspace, cx) =
14780 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14781
14782 // Add two panels to the left dock and open it.
14783 let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14784 let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14785 let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14786 workspace.add_panel(panel_a.clone(), window, cx);
14787 workspace.add_panel(panel_b.clone(), window, cx);
14788 workspace.left_dock().update(cx, |dock, cx| {
14789 dock.set_open(true, window, cx);
14790 dock.activate_panel(0, window, cx);
14791 });
14792 (panel_a, panel_b)
14793 });
14794
14795 workspace.update_in(cx, |workspace, _, cx| {
14796 assert!(workspace.left_dock().read(cx).is_open());
14797 });
14798
14799 // Simulate a feature flag changing default dock positions: both panels
14800 // move from Left to Right.
14801 workspace.update_in(cx, |_workspace, _window, cx| {
14802 panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14803 panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14804 cx.update_global::<SettingsStore, _>(|_, _| {});
14805 });
14806
14807 // Both panels should now be in the right dock.
14808 workspace.update_in(cx, |workspace, _, cx| {
14809 let right_dock = workspace.right_dock().read(cx);
14810 assert_eq!(right_dock.panels_len(), 2);
14811 });
14812
14813 // Open the right dock and activate panel_b (simulating the user
14814 // opening the panel after it moved).
14815 workspace.update_in(cx, |workspace, window, cx| {
14816 workspace.right_dock().update(cx, |dock, cx| {
14817 dock.set_open(true, window, cx);
14818 dock.activate_panel(1, window, cx);
14819 });
14820 });
14821
14822 // Now trigger another SettingsStore change
14823 workspace.update_in(cx, |_workspace, _window, cx| {
14824 cx.update_global::<SettingsStore, _>(|_, _| {});
14825 });
14826
14827 workspace.update_in(cx, |workspace, _, cx| {
14828 assert!(
14829 workspace.right_dock().read(cx).is_open(),
14830 "Right dock should still be open after a settings change"
14831 );
14832 assert_eq!(
14833 workspace.right_dock().read(cx).panels_len(),
14834 2,
14835 "Both panels should still be in the right dock"
14836 );
14837 });
14838 }
14839}