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;
8pub mod notifications;
9pub mod pane;
10pub mod pane_group;
11pub mod path_list {
12 pub use util::path_list::{PathList, SerializedPathList};
13}
14mod persistence;
15pub mod searchable;
16mod security_modal;
17pub mod shared_screen;
18use db::smol::future::yield_now;
19pub use shared_screen::SharedScreen;
20mod status_bar;
21pub mod tasks;
22mod theme_preview;
23mod toast_layer;
24mod toolbar;
25pub mod welcome;
26mod workspace_settings;
27
28pub use crate::notifications::NotificationFrame;
29pub use dock::Panel;
30pub use multi_workspace::{
31 CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
32 MultiWorkspaceEvent, NextWorkspace, PreviousWorkspace, Sidebar, SidebarHandle,
33 SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar, sidebar_side_context_menu,
34};
35pub use path_list::{PathList, SerializedPathList};
36pub use toast_layer::{ToastAction, ToastLayer, ToastView};
37
38use anyhow::{Context as _, Result, anyhow};
39use client::{
40 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
41 proto::{self, ErrorCode, PanelId, PeerId},
42};
43use collections::{HashMap, HashSet, hash_map};
44use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
45use fs::Fs;
46use futures::{
47 Future, FutureExt, StreamExt,
48 channel::{
49 mpsc::{self, UnboundedReceiver, UnboundedSender},
50 oneshot,
51 },
52 future::{Shared, try_join_all},
53};
54use gpui::{
55 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
56 Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
57 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
58 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
59 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
60 WindowOptions, actions, canvas, point, relative, size, transparent_black,
61};
62pub use history_manager::*;
63pub use item::{
64 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
65 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
66};
67use itertools::Itertools;
68use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
69pub use modal_layer::*;
70use node_runtime::NodeRuntime;
71use notifications::{
72 DetachAndPromptErr, Notifications, dismiss_app_notification,
73 simple_message_notification::MessageNotification,
74};
75pub use pane::*;
76pub use pane_group::{
77 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
78 SplitDirection,
79};
80use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
81pub use persistence::{
82 WorkspaceDb, delete_unloaded_items,
83 model::{
84 DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
85 SessionWorkspace,
86 },
87 read_serialized_multi_workspaces, resolve_worktree_workspaces,
88};
89use postage::stream::Stream;
90use project::{
91 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
92 WorktreeSettings,
93 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
94 project_settings::ProjectSettings,
95 toolchain_store::ToolchainStoreEvent,
96 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
97};
98use remote::{
99 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
100 remote_client::ConnectionIdentifier,
101};
102use schemars::JsonSchema;
103use serde::Deserialize;
104use session::AppSession;
105use settings::{
106 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
107};
108
109use sqlez::{
110 bindable::{Bind, Column, StaticColumnCount},
111 statement::Statement,
112};
113use status_bar::StatusBar;
114pub use status_bar::StatusItemView;
115use std::{
116 any::TypeId,
117 borrow::Cow,
118 cell::RefCell,
119 cmp,
120 collections::VecDeque,
121 env,
122 hash::Hash,
123 path::{Path, PathBuf},
124 process::ExitStatus,
125 rc::Rc,
126 sync::{
127 Arc, LazyLock,
128 atomic::{AtomicBool, AtomicUsize},
129 },
130 time::Duration,
131};
132use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
133use theme::{ActiveTheme, SystemAppearance};
134use theme_settings::ThemeSettings;
135pub use toolbar::{
136 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
137};
138pub use ui;
139use ui::{Window, prelude::*};
140use util::{
141 ResultExt, TryFutureExt,
142 paths::{PathStyle, SanitizedPath},
143 rel_path::RelPath,
144 serde::default_true,
145};
146use uuid::Uuid;
147pub use workspace_settings::{
148 AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
149 WorkspaceSettings,
150};
151use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
152
153use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::NotificationId};
154use crate::{
155 persistence::{
156 SerializedAxis,
157 model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
158 },
159 security_modal::SecurityModal,
160};
161
162pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
163
164static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
165 env::var("ZED_WINDOW_SIZE")
166 .ok()
167 .as_deref()
168 .and_then(parse_pixel_size_env_var)
169});
170
171static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
172 env::var("ZED_WINDOW_POSITION")
173 .ok()
174 .as_deref()
175 .and_then(parse_pixel_position_env_var)
176});
177
178pub trait TerminalProvider {
179 fn spawn(
180 &self,
181 task: SpawnInTerminal,
182 window: &mut Window,
183 cx: &mut App,
184 ) -> Task<Option<Result<ExitStatus>>>;
185}
186
187pub trait DebuggerProvider {
188 // `active_buffer` is used to resolve build task's name against language-specific tasks.
189 fn start_session(
190 &self,
191 definition: DebugScenario,
192 task_context: SharedTaskContext,
193 active_buffer: Option<Entity<Buffer>>,
194 worktree_id: Option<WorktreeId>,
195 window: &mut Window,
196 cx: &mut App,
197 );
198
199 fn spawn_task_or_modal(
200 &self,
201 workspace: &mut Workspace,
202 action: &Spawn,
203 window: &mut Window,
204 cx: &mut Context<Workspace>,
205 );
206
207 fn task_scheduled(&self, cx: &mut App);
208 fn debug_scenario_scheduled(&self, cx: &mut App);
209 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
210
211 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
212}
213
214/// Opens a file or directory.
215#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
216#[action(namespace = workspace)]
217pub struct Open {
218 /// When true, opens in a new window. When false, adds to the current
219 /// window as a new workspace (multi-workspace).
220 #[serde(default = "Open::default_create_new_window")]
221 pub create_new_window: bool,
222}
223
224impl Open {
225 pub const DEFAULT: Self = Self {
226 create_new_window: true,
227 };
228
229 /// Used by `#[serde(default)]` on the `create_new_window` field so that
230 /// the serde default and `Open::DEFAULT` stay in sync.
231 fn default_create_new_window() -> bool {
232 Self::DEFAULT.create_new_window
233 }
234}
235
236impl Default for Open {
237 fn default() -> Self {
238 Self::DEFAULT
239 }
240}
241
242actions!(
243 workspace,
244 [
245 /// Activates the next pane in the workspace.
246 ActivateNextPane,
247 /// Activates the previous pane in the workspace.
248 ActivatePreviousPane,
249 /// Activates the last pane in the workspace.
250 ActivateLastPane,
251 /// Switches to the next window.
252 ActivateNextWindow,
253 /// Switches to the previous window.
254 ActivatePreviousWindow,
255 /// Adds a folder to the current project.
256 AddFolderToProject,
257 /// Clears all notifications.
258 ClearAllNotifications,
259 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
260 ClearNavigationHistory,
261 /// Closes the active dock.
262 CloseActiveDock,
263 /// Closes all docks.
264 CloseAllDocks,
265 /// Toggles all docks.
266 ToggleAllDocks,
267 /// Closes the current window.
268 CloseWindow,
269 /// Closes the current project.
270 CloseProject,
271 /// Opens the feedback dialog.
272 Feedback,
273 /// Follows the next collaborator in the session.
274 FollowNextCollaborator,
275 /// Moves the focused panel to the next position.
276 MoveFocusedPanelToNextPosition,
277 /// Creates a new file.
278 NewFile,
279 /// Creates a new file in a vertical split.
280 NewFileSplitVertical,
281 /// Creates a new file in a horizontal split.
282 NewFileSplitHorizontal,
283 /// Opens a new search.
284 NewSearch,
285 /// Opens a new window.
286 NewWindow,
287 /// Opens multiple files.
288 OpenFiles,
289 /// Opens the current location in terminal.
290 OpenInTerminal,
291 /// Opens the component preview.
292 OpenComponentPreview,
293 /// Reloads the active item.
294 ReloadActiveItem,
295 /// Resets the active dock to its default size.
296 ResetActiveDockSize,
297 /// Resets all open docks to their default sizes.
298 ResetOpenDocksSize,
299 /// Reloads the application
300 Reload,
301 /// Saves the current file with a new name.
302 SaveAs,
303 /// Saves without formatting.
304 SaveWithoutFormat,
305 /// Shuts down all debug adapters.
306 ShutdownDebugAdapters,
307 /// Suppresses the current notification.
308 SuppressNotification,
309 /// Toggles the bottom dock.
310 ToggleBottomDock,
311 /// Toggles centered layout mode.
312 ToggleCenteredLayout,
313 /// Toggles edit prediction feature globally for all files.
314 ToggleEditPrediction,
315 /// Toggles the left dock.
316 ToggleLeftDock,
317 /// Toggles the right dock.
318 ToggleRightDock,
319 /// Toggles zoom on the active pane.
320 ToggleZoom,
321 /// Toggles read-only mode for the active item (if supported by that item).
322 ToggleReadOnlyFile,
323 /// Zooms in on the active pane.
324 ZoomIn,
325 /// Zooms out of the active pane.
326 ZoomOut,
327 /// If any worktrees are in restricted mode, shows a modal with possible actions.
328 /// If the modal is shown already, closes it without trusting any worktree.
329 ToggleWorktreeSecurity,
330 /// Clears all trusted worktrees, placing them in restricted mode on next open.
331 /// Requires restart to take effect on already opened projects.
332 ClearTrustedWorktrees,
333 /// Stops following a collaborator.
334 Unfollow,
335 /// Restores the banner.
336 RestoreBanner,
337 /// Toggles expansion of the selected item.
338 ToggleExpandItem,
339 ]
340);
341
342/// Activates a specific pane by its index.
343#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
344#[action(namespace = workspace)]
345pub struct ActivatePane(pub usize);
346
347/// Moves an item to a specific pane by index.
348#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
349#[action(namespace = workspace)]
350#[serde(deny_unknown_fields)]
351pub struct MoveItemToPane {
352 #[serde(default = "default_1")]
353 pub destination: usize,
354 #[serde(default = "default_true")]
355 pub focus: bool,
356 #[serde(default)]
357 pub clone: bool,
358}
359
360fn default_1() -> usize {
361 1
362}
363
364/// Moves an item to a pane in the specified direction.
365#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
366#[action(namespace = workspace)]
367#[serde(deny_unknown_fields)]
368pub struct MoveItemToPaneInDirection {
369 #[serde(default = "default_right")]
370 pub direction: SplitDirection,
371 #[serde(default = "default_true")]
372 pub focus: bool,
373 #[serde(default)]
374 pub clone: bool,
375}
376
377/// Creates a new file in a split of the desired direction.
378#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
379#[action(namespace = workspace)]
380#[serde(deny_unknown_fields)]
381pub struct NewFileSplit(pub SplitDirection);
382
383fn default_right() -> SplitDirection {
384 SplitDirection::Right
385}
386
387/// Saves all open files in the workspace.
388#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
389#[action(namespace = workspace)]
390#[serde(deny_unknown_fields)]
391pub struct SaveAll {
392 #[serde(default)]
393 pub save_intent: Option<SaveIntent>,
394}
395
396/// Saves the current file with the specified options.
397#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
398#[action(namespace = workspace)]
399#[serde(deny_unknown_fields)]
400pub struct Save {
401 #[serde(default)]
402 pub save_intent: Option<SaveIntent>,
403}
404
405/// Moves Focus to the central panes in the workspace.
406#[derive(Clone, Debug, PartialEq, Eq, Action)]
407#[action(namespace = workspace)]
408pub struct FocusCenterPane;
409
410/// Closes all items and panes in the workspace.
411#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
412#[action(namespace = workspace)]
413#[serde(deny_unknown_fields)]
414pub struct CloseAllItemsAndPanes {
415 #[serde(default)]
416 pub save_intent: Option<SaveIntent>,
417}
418
419/// Closes all inactive tabs and panes in the workspace.
420#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
421#[action(namespace = workspace)]
422#[serde(deny_unknown_fields)]
423pub struct CloseInactiveTabsAndPanes {
424 #[serde(default)]
425 pub save_intent: Option<SaveIntent>,
426}
427
428/// Closes the active item across all panes.
429#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
430#[action(namespace = workspace)]
431#[serde(deny_unknown_fields)]
432pub struct CloseItemInAllPanes {
433 #[serde(default)]
434 pub save_intent: Option<SaveIntent>,
435 #[serde(default)]
436 pub close_pinned: bool,
437}
438
439/// Sends a sequence of keystrokes to the active element.
440#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
441#[action(namespace = workspace)]
442pub struct SendKeystrokes(pub String);
443
444actions!(
445 project_symbols,
446 [
447 /// Toggles the project symbols search.
448 #[action(name = "Toggle")]
449 ToggleProjectSymbols
450 ]
451);
452
453/// Toggles the file finder interface.
454#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
455#[action(namespace = file_finder, name = "Toggle")]
456#[serde(deny_unknown_fields)]
457pub struct ToggleFileFinder {
458 #[serde(default)]
459 pub separate_history: bool,
460}
461
462/// Opens a new terminal in the center.
463#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
464#[action(namespace = workspace)]
465#[serde(deny_unknown_fields)]
466pub struct NewCenterTerminal {
467 /// If true, creates a local terminal even in remote projects.
468 #[serde(default)]
469 pub local: bool,
470}
471
472/// Opens a new terminal.
473#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
474#[action(namespace = workspace)]
475#[serde(deny_unknown_fields)]
476pub struct NewTerminal {
477 /// If true, creates a local terminal even in remote projects.
478 #[serde(default)]
479 pub local: bool,
480}
481
482/// Increases size of a currently focused dock by a given amount of pixels.
483#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
484#[action(namespace = workspace)]
485#[serde(deny_unknown_fields)]
486pub struct IncreaseActiveDockSize {
487 /// For 0px parameter, uses UI font size value.
488 #[serde(default)]
489 pub px: u32,
490}
491
492/// Decreases size of a currently focused dock by a given amount of pixels.
493#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
494#[action(namespace = workspace)]
495#[serde(deny_unknown_fields)]
496pub struct DecreaseActiveDockSize {
497 /// For 0px parameter, uses UI font size value.
498 #[serde(default)]
499 pub px: u32,
500}
501
502/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
503#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
504#[action(namespace = workspace)]
505#[serde(deny_unknown_fields)]
506pub struct IncreaseOpenDocksSize {
507 /// For 0px parameter, uses UI font size value.
508 #[serde(default)]
509 pub px: u32,
510}
511
512/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
513#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
514#[action(namespace = workspace)]
515#[serde(deny_unknown_fields)]
516pub struct DecreaseOpenDocksSize {
517 /// For 0px parameter, uses UI font size value.
518 #[serde(default)]
519 pub px: u32,
520}
521
522actions!(
523 workspace,
524 [
525 /// Activates the pane to the left.
526 ActivatePaneLeft,
527 /// Activates the pane to the right.
528 ActivatePaneRight,
529 /// Activates the pane above.
530 ActivatePaneUp,
531 /// Activates the pane below.
532 ActivatePaneDown,
533 /// Swaps the current pane with the one to the left.
534 SwapPaneLeft,
535 /// Swaps the current pane with the one to the right.
536 SwapPaneRight,
537 /// Swaps the current pane with the one above.
538 SwapPaneUp,
539 /// Swaps the current pane with the one below.
540 SwapPaneDown,
541 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
542 SwapPaneAdjacent,
543 /// Move the current pane to be at the far left.
544 MovePaneLeft,
545 /// Move the current pane to be at the far right.
546 MovePaneRight,
547 /// Move the current pane to be at the very top.
548 MovePaneUp,
549 /// Move the current pane to be at the very bottom.
550 MovePaneDown,
551 ]
552);
553
554#[derive(PartialEq, Eq, Debug)]
555pub enum CloseIntent {
556 /// Quit the program entirely.
557 Quit,
558 /// Close a window.
559 CloseWindow,
560 /// Replace the workspace in an existing window.
561 ReplaceWindow,
562}
563
564#[derive(Clone)]
565pub struct Toast {
566 id: NotificationId,
567 msg: Cow<'static, str>,
568 autohide: bool,
569 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
570}
571
572impl Toast {
573 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
574 Toast {
575 id,
576 msg: msg.into(),
577 on_click: None,
578 autohide: false,
579 }
580 }
581
582 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
583 where
584 M: Into<Cow<'static, str>>,
585 F: Fn(&mut Window, &mut App) + 'static,
586 {
587 self.on_click = Some((message.into(), Arc::new(on_click)));
588 self
589 }
590
591 pub fn autohide(mut self) -> Self {
592 self.autohide = true;
593 self
594 }
595}
596
597impl PartialEq for Toast {
598 fn eq(&self, other: &Self) -> bool {
599 self.id == other.id
600 && self.msg == other.msg
601 && self.on_click.is_some() == other.on_click.is_some()
602 }
603}
604
605/// Opens a new terminal with the specified working directory.
606#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
607#[action(namespace = workspace)]
608#[serde(deny_unknown_fields)]
609pub struct OpenTerminal {
610 pub working_directory: PathBuf,
611 /// If true, creates a local terminal even in remote projects.
612 #[serde(default)]
613 pub local: bool,
614}
615
616#[derive(
617 Clone,
618 Copy,
619 Debug,
620 Default,
621 Hash,
622 PartialEq,
623 Eq,
624 PartialOrd,
625 Ord,
626 serde::Serialize,
627 serde::Deserialize,
628)]
629pub struct WorkspaceId(i64);
630
631impl WorkspaceId {
632 pub fn from_i64(value: i64) -> Self {
633 Self(value)
634 }
635}
636
637impl StaticColumnCount for WorkspaceId {}
638impl Bind for WorkspaceId {
639 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
640 self.0.bind(statement, start_index)
641 }
642}
643impl Column for WorkspaceId {
644 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
645 i64::column(statement, start_index)
646 .map(|(i, next_index)| (Self(i), next_index))
647 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
648 }
649}
650impl From<WorkspaceId> for i64 {
651 fn from(val: WorkspaceId) -> Self {
652 val.0
653 }
654}
655
656fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
657 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
658 workspace_window
659 .update(cx, |multi_workspace, window, cx| {
660 let workspace = multi_workspace.workspace().clone();
661 workspace.update(cx, |workspace, cx| {
662 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
663 });
664 })
665 .ok();
666 } else {
667 let task = Workspace::new_local(
668 Vec::new(),
669 app_state.clone(),
670 None,
671 None,
672 None,
673 OpenMode::Replace,
674 cx,
675 );
676 cx.spawn(async move |cx| {
677 let OpenResult { window, .. } = task.await?;
678 window.update(cx, |multi_workspace, window, cx| {
679 window.activate_window();
680 let workspace = multi_workspace.workspace().clone();
681 workspace.update(cx, |workspace, cx| {
682 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
683 });
684 })?;
685 anyhow::Ok(())
686 })
687 .detach_and_log_err(cx);
688 }
689}
690
691pub fn prompt_for_open_path_and_open(
692 workspace: &mut Workspace,
693 app_state: Arc<AppState>,
694 options: PathPromptOptions,
695 create_new_window: bool,
696 window: &mut Window,
697 cx: &mut Context<Workspace>,
698) {
699 let paths = workspace.prompt_for_open_path(
700 options,
701 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
702 window,
703 cx,
704 );
705 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
706 cx.spawn_in(window, async move |this, cx| {
707 let Some(paths) = paths.await.log_err().flatten() else {
708 return;
709 };
710 if !create_new_window {
711 if let Some(handle) = multi_workspace_handle {
712 if let Some(task) = handle
713 .update(cx, |multi_workspace, window, cx| {
714 multi_workspace.open_project(paths, OpenMode::Replace, window, cx)
715 })
716 .log_err()
717 {
718 task.await.log_err();
719 }
720 return;
721 }
722 }
723 if let Some(task) = this
724 .update_in(cx, |this, window, cx| {
725 this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
726 })
727 .log_err()
728 {
729 task.await.log_err();
730 }
731 })
732 .detach();
733}
734
735pub fn init(app_state: Arc<AppState>, cx: &mut App) {
736 component::init();
737 theme_preview::init(cx);
738 toast_layer::init(cx);
739 history_manager::init(app_state.fs.clone(), cx);
740
741 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
742 .on_action(|_: &Reload, cx| reload(cx))
743 .on_action(|_: &Open, cx: &mut App| {
744 let app_state = AppState::global(cx);
745 prompt_and_open_paths(
746 app_state,
747 PathPromptOptions {
748 files: true,
749 directories: true,
750 multiple: true,
751 prompt: None,
752 },
753 cx,
754 );
755 })
756 .on_action(|_: &OpenFiles, cx: &mut App| {
757 let directories = cx.can_select_mixed_files_and_dirs();
758 let app_state = AppState::global(cx);
759 prompt_and_open_paths(
760 app_state,
761 PathPromptOptions {
762 files: true,
763 directories,
764 multiple: true,
765 prompt: None,
766 },
767 cx,
768 );
769 });
770}
771
772type BuildProjectItemFn =
773 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
774
775type BuildProjectItemForPathFn =
776 fn(
777 &Entity<Project>,
778 &ProjectPath,
779 &mut Window,
780 &mut App,
781 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
782
783#[derive(Clone, Default)]
784struct ProjectItemRegistry {
785 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
786 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
787}
788
789impl ProjectItemRegistry {
790 fn register<T: ProjectItem>(&mut self) {
791 self.build_project_item_fns_by_type.insert(
792 TypeId::of::<T::Item>(),
793 |item, project, pane, window, cx| {
794 let item = item.downcast().unwrap();
795 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
796 as Box<dyn ItemHandle>
797 },
798 );
799 self.build_project_item_for_path_fns
800 .push(|project, project_path, window, cx| {
801 let project_path = project_path.clone();
802 let is_file = project
803 .read(cx)
804 .entry_for_path(&project_path, cx)
805 .is_some_and(|entry| entry.is_file());
806 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
807 let is_local = project.read(cx).is_local();
808 let project_item =
809 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
810 let project = project.clone();
811 Some(window.spawn(cx, async move |cx| {
812 match project_item.await.with_context(|| {
813 format!(
814 "opening project path {:?}",
815 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
816 )
817 }) {
818 Ok(project_item) => {
819 let project_item = project_item;
820 let project_entry_id: Option<ProjectEntryId> =
821 project_item.read_with(cx, project::ProjectItem::entry_id);
822 let build_workspace_item = Box::new(
823 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
824 Box::new(cx.new(|cx| {
825 T::for_project_item(
826 project,
827 Some(pane),
828 project_item,
829 window,
830 cx,
831 )
832 })) as Box<dyn ItemHandle>
833 },
834 ) as Box<_>;
835 Ok((project_entry_id, build_workspace_item))
836 }
837 Err(e) => {
838 log::warn!("Failed to open a project item: {e:#}");
839 if e.error_code() == ErrorCode::Internal {
840 if let Some(abs_path) =
841 entry_abs_path.as_deref().filter(|_| is_file)
842 {
843 if let Some(broken_project_item_view) =
844 cx.update(|window, cx| {
845 T::for_broken_project_item(
846 abs_path, is_local, &e, window, cx,
847 )
848 })?
849 {
850 let build_workspace_item = Box::new(
851 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
852 cx.new(|_| broken_project_item_view).boxed_clone()
853 },
854 )
855 as Box<_>;
856 return Ok((None, build_workspace_item));
857 }
858 }
859 }
860 Err(e)
861 }
862 }
863 }))
864 });
865 }
866
867 fn open_path(
868 &self,
869 project: &Entity<Project>,
870 path: &ProjectPath,
871 window: &mut Window,
872 cx: &mut App,
873 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
874 let Some(open_project_item) = self
875 .build_project_item_for_path_fns
876 .iter()
877 .rev()
878 .find_map(|open_project_item| open_project_item(project, path, window, cx))
879 else {
880 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
881 };
882 open_project_item
883 }
884
885 fn build_item<T: project::ProjectItem>(
886 &self,
887 item: Entity<T>,
888 project: Entity<Project>,
889 pane: Option<&Pane>,
890 window: &mut Window,
891 cx: &mut App,
892 ) -> Option<Box<dyn ItemHandle>> {
893 let build = self
894 .build_project_item_fns_by_type
895 .get(&TypeId::of::<T>())?;
896 Some(build(item.into_any(), project, pane, window, cx))
897 }
898}
899
900type WorkspaceItemBuilder =
901 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
902
903impl Global for ProjectItemRegistry {}
904
905/// Registers a [ProjectItem] for the app. When opening a file, all the registered
906/// items will get a chance to open the file, starting from the project item that
907/// was added last.
908pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
909 cx.default_global::<ProjectItemRegistry>().register::<I>();
910}
911
912#[derive(Default)]
913pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
914
915struct FollowableViewDescriptor {
916 from_state_proto: fn(
917 Entity<Workspace>,
918 ViewId,
919 &mut Option<proto::view::Variant>,
920 &mut Window,
921 &mut App,
922 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
923 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
924}
925
926impl Global for FollowableViewRegistry {}
927
928impl FollowableViewRegistry {
929 pub fn register<I: FollowableItem>(cx: &mut App) {
930 cx.default_global::<Self>().0.insert(
931 TypeId::of::<I>(),
932 FollowableViewDescriptor {
933 from_state_proto: |workspace, id, state, window, cx| {
934 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
935 cx.foreground_executor()
936 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
937 })
938 },
939 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
940 },
941 );
942 }
943
944 pub fn from_state_proto(
945 workspace: Entity<Workspace>,
946 view_id: ViewId,
947 mut state: Option<proto::view::Variant>,
948 window: &mut Window,
949 cx: &mut App,
950 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
951 cx.update_default_global(|this: &mut Self, cx| {
952 this.0.values().find_map(|descriptor| {
953 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
954 })
955 })
956 }
957
958 pub fn to_followable_view(
959 view: impl Into<AnyView>,
960 cx: &App,
961 ) -> Option<Box<dyn FollowableItemHandle>> {
962 let this = cx.try_global::<Self>()?;
963 let view = view.into();
964 let descriptor = this.0.get(&view.entity_type())?;
965 Some((descriptor.to_followable_view)(&view))
966 }
967}
968
969#[derive(Copy, Clone)]
970struct SerializableItemDescriptor {
971 deserialize: fn(
972 Entity<Project>,
973 WeakEntity<Workspace>,
974 WorkspaceId,
975 ItemId,
976 &mut Window,
977 &mut Context<Pane>,
978 ) -> Task<Result<Box<dyn ItemHandle>>>,
979 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
980 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
981}
982
983#[derive(Default)]
984struct SerializableItemRegistry {
985 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
986 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
987}
988
989impl Global for SerializableItemRegistry {}
990
991impl SerializableItemRegistry {
992 fn deserialize(
993 item_kind: &str,
994 project: Entity<Project>,
995 workspace: WeakEntity<Workspace>,
996 workspace_id: WorkspaceId,
997 item_item: ItemId,
998 window: &mut Window,
999 cx: &mut Context<Pane>,
1000 ) -> Task<Result<Box<dyn ItemHandle>>> {
1001 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1002 return Task::ready(Err(anyhow!(
1003 "cannot deserialize {}, descriptor not found",
1004 item_kind
1005 )));
1006 };
1007
1008 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1009 }
1010
1011 fn cleanup(
1012 item_kind: &str,
1013 workspace_id: WorkspaceId,
1014 loaded_items: Vec<ItemId>,
1015 window: &mut Window,
1016 cx: &mut App,
1017 ) -> Task<Result<()>> {
1018 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1019 return Task::ready(Err(anyhow!(
1020 "cannot cleanup {}, descriptor not found",
1021 item_kind
1022 )));
1023 };
1024
1025 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1026 }
1027
1028 fn view_to_serializable_item_handle(
1029 view: AnyView,
1030 cx: &App,
1031 ) -> Option<Box<dyn SerializableItemHandle>> {
1032 let this = cx.try_global::<Self>()?;
1033 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1034 Some((descriptor.view_to_serializable_item)(view))
1035 }
1036
1037 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1038 let this = cx.try_global::<Self>()?;
1039 this.descriptors_by_kind.get(item_kind).copied()
1040 }
1041}
1042
1043pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1044 let serialized_item_kind = I::serialized_item_kind();
1045
1046 let registry = cx.default_global::<SerializableItemRegistry>();
1047 let descriptor = SerializableItemDescriptor {
1048 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1049 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1050 cx.foreground_executor()
1051 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1052 },
1053 cleanup: |workspace_id, loaded_items, window, cx| {
1054 I::cleanup(workspace_id, loaded_items, window, cx)
1055 },
1056 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1057 };
1058 registry
1059 .descriptors_by_kind
1060 .insert(Arc::from(serialized_item_kind), descriptor);
1061 registry
1062 .descriptors_by_type
1063 .insert(TypeId::of::<I>(), descriptor);
1064}
1065
1066pub struct AppState {
1067 pub languages: Arc<LanguageRegistry>,
1068 pub client: Arc<Client>,
1069 pub user_store: Entity<UserStore>,
1070 pub workspace_store: Entity<WorkspaceStore>,
1071 pub fs: Arc<dyn fs::Fs>,
1072 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1073 pub node_runtime: NodeRuntime,
1074 pub session: Entity<AppSession>,
1075}
1076
1077struct GlobalAppState(Arc<AppState>);
1078
1079impl Global for GlobalAppState {}
1080
1081pub struct WorkspaceStore {
1082 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1083 client: Arc<Client>,
1084 _subscriptions: Vec<client::Subscription>,
1085}
1086
1087#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1088pub enum CollaboratorId {
1089 PeerId(PeerId),
1090 Agent,
1091}
1092
1093impl From<PeerId> for CollaboratorId {
1094 fn from(peer_id: PeerId) -> Self {
1095 CollaboratorId::PeerId(peer_id)
1096 }
1097}
1098
1099impl From<&PeerId> for CollaboratorId {
1100 fn from(peer_id: &PeerId) -> Self {
1101 CollaboratorId::PeerId(*peer_id)
1102 }
1103}
1104
1105#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1106struct Follower {
1107 project_id: Option<u64>,
1108 peer_id: PeerId,
1109}
1110
1111impl AppState {
1112 #[track_caller]
1113 pub fn global(cx: &App) -> Arc<Self> {
1114 cx.global::<GlobalAppState>().0.clone()
1115 }
1116 pub fn try_global(cx: &App) -> Option<Arc<Self>> {
1117 cx.try_global::<GlobalAppState>()
1118 .map(|state| state.0.clone())
1119 }
1120 pub fn set_global(state: Arc<AppState>, cx: &mut App) {
1121 cx.set_global(GlobalAppState(state));
1122 }
1123
1124 #[cfg(any(test, feature = "test-support"))]
1125 pub fn test(cx: &mut App) -> Arc<Self> {
1126 use fs::Fs;
1127 use node_runtime::NodeRuntime;
1128 use session::Session;
1129 use settings::SettingsStore;
1130
1131 if !cx.has_global::<SettingsStore>() {
1132 let settings_store = SettingsStore::test(cx);
1133 cx.set_global(settings_store);
1134 }
1135
1136 let fs = fs::FakeFs::new(cx.background_executor().clone());
1137 <dyn Fs>::set_global(fs.clone(), cx);
1138 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1139 let clock = Arc::new(clock::FakeSystemClock::new());
1140 let http_client = http_client::FakeHttpClient::with_404_response();
1141 let client = Client::new(clock, http_client, cx);
1142 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1143 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1144 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1145
1146 theme_settings::init(theme::LoadThemes::JustBase, cx);
1147 client::init(&client, cx);
1148
1149 Arc::new(Self {
1150 client,
1151 fs,
1152 languages,
1153 user_store,
1154 workspace_store,
1155 node_runtime: NodeRuntime::unavailable(),
1156 build_window_options: |_, _| Default::default(),
1157 session,
1158 })
1159 }
1160}
1161
1162struct DelayedDebouncedEditAction {
1163 task: Option<Task<()>>,
1164 cancel_channel: Option<oneshot::Sender<()>>,
1165}
1166
1167impl DelayedDebouncedEditAction {
1168 fn new() -> DelayedDebouncedEditAction {
1169 DelayedDebouncedEditAction {
1170 task: None,
1171 cancel_channel: None,
1172 }
1173 }
1174
1175 fn fire_new<F>(
1176 &mut self,
1177 delay: Duration,
1178 window: &mut Window,
1179 cx: &mut Context<Workspace>,
1180 func: F,
1181 ) where
1182 F: 'static
1183 + Send
1184 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1185 {
1186 if let Some(channel) = self.cancel_channel.take() {
1187 _ = channel.send(());
1188 }
1189
1190 let (sender, mut receiver) = oneshot::channel::<()>();
1191 self.cancel_channel = Some(sender);
1192
1193 let previous_task = self.task.take();
1194 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1195 let mut timer = cx.background_executor().timer(delay).fuse();
1196 if let Some(previous_task) = previous_task {
1197 previous_task.await;
1198 }
1199
1200 futures::select_biased! {
1201 _ = receiver => return,
1202 _ = timer => {}
1203 }
1204
1205 if let Some(result) = workspace
1206 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1207 .log_err()
1208 {
1209 result.await.log_err();
1210 }
1211 }));
1212 }
1213}
1214
1215pub enum Event {
1216 PaneAdded(Entity<Pane>),
1217 PaneRemoved,
1218 ItemAdded {
1219 item: Box<dyn ItemHandle>,
1220 },
1221 ActiveItemChanged,
1222 ItemRemoved {
1223 item_id: EntityId,
1224 },
1225 UserSavedItem {
1226 pane: WeakEntity<Pane>,
1227 item: Box<dyn WeakItemHandle>,
1228 save_intent: SaveIntent,
1229 },
1230 ContactRequestedJoin(u64),
1231 WorkspaceCreated(WeakEntity<Workspace>),
1232 OpenBundledFile {
1233 text: Cow<'static, str>,
1234 title: &'static str,
1235 language: &'static str,
1236 },
1237 ZoomChanged,
1238 ModalOpened,
1239 Activate,
1240 PanelAdded(AnyView),
1241}
1242
1243#[derive(Debug, Clone)]
1244pub enum OpenVisible {
1245 All,
1246 None,
1247 OnlyFiles,
1248 OnlyDirectories,
1249}
1250
1251enum WorkspaceLocation {
1252 // Valid local paths or SSH project to serialize
1253 Location(SerializedWorkspaceLocation, PathList),
1254 // No valid location found hence clear session id
1255 DetachFromSession,
1256 // No valid location found to serialize
1257 None,
1258}
1259
1260type PromptForNewPath = Box<
1261 dyn Fn(
1262 &mut Workspace,
1263 DirectoryLister,
1264 Option<String>,
1265 &mut Window,
1266 &mut Context<Workspace>,
1267 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1268>;
1269
1270type PromptForOpenPath = Box<
1271 dyn Fn(
1272 &mut Workspace,
1273 DirectoryLister,
1274 &mut Window,
1275 &mut Context<Workspace>,
1276 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1277>;
1278
1279#[derive(Default)]
1280struct DispatchingKeystrokes {
1281 dispatched: HashSet<Vec<Keystroke>>,
1282 queue: VecDeque<Keystroke>,
1283 task: Option<Shared<Task<()>>>,
1284}
1285
1286/// Collects everything project-related for a certain window opened.
1287/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1288///
1289/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1290/// The `Workspace` owns everybody's state and serves as a default, "global context",
1291/// that can be used to register a global action to be triggered from any place in the window.
1292pub struct Workspace {
1293 weak_self: WeakEntity<Self>,
1294 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1295 zoomed: Option<AnyWeakView>,
1296 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1297 zoomed_position: Option<DockPosition>,
1298 center: PaneGroup,
1299 left_dock: Entity<Dock>,
1300 bottom_dock: Entity<Dock>,
1301 right_dock: Entity<Dock>,
1302 panes: Vec<Entity<Pane>>,
1303 active_worktree_override: Option<WorktreeId>,
1304 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1305 active_pane: Entity<Pane>,
1306 last_active_center_pane: Option<WeakEntity<Pane>>,
1307 last_active_view_id: Option<proto::ViewId>,
1308 status_bar: Entity<StatusBar>,
1309 pub(crate) modal_layer: Entity<ModalLayer>,
1310 toast_layer: Entity<ToastLayer>,
1311 titlebar_item: Option<AnyView>,
1312 notifications: Notifications,
1313 suppressed_notifications: HashSet<NotificationId>,
1314 project: Entity<Project>,
1315 follower_states: HashMap<CollaboratorId, FollowerState>,
1316 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1317 window_edited: bool,
1318 last_window_title: Option<String>,
1319 dirty_items: HashMap<EntityId, Subscription>,
1320 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1321 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1322 database_id: Option<WorkspaceId>,
1323 app_state: Arc<AppState>,
1324 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1325 _subscriptions: Vec<Subscription>,
1326 _apply_leader_updates: Task<Result<()>>,
1327 _observe_current_user: Task<Result<()>>,
1328 _schedule_serialize_workspace: Option<Task<()>>,
1329 _serialize_workspace_task: Option<Task<()>>,
1330 _schedule_serialize_ssh_paths: Option<Task<()>>,
1331 pane_history_timestamp: Arc<AtomicUsize>,
1332 bounds: Bounds<Pixels>,
1333 pub centered_layout: bool,
1334 bounds_save_task_queued: Option<Task<()>>,
1335 on_prompt_for_new_path: Option<PromptForNewPath>,
1336 on_prompt_for_open_path: Option<PromptForOpenPath>,
1337 terminal_provider: Option<Box<dyn TerminalProvider>>,
1338 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1339 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1340 _items_serializer: Task<Result<()>>,
1341 session_id: Option<String>,
1342 scheduled_tasks: Vec<Task<()>>,
1343 last_open_dock_positions: Vec<DockPosition>,
1344 removing: bool,
1345 _panels_task: Option<Task<Result<()>>>,
1346 sidebar_focus_handle: Option<FocusHandle>,
1347 multi_workspace: Option<WeakEntity<MultiWorkspace>>,
1348}
1349
1350impl EventEmitter<Event> for Workspace {}
1351
1352#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1353pub struct ViewId {
1354 pub creator: CollaboratorId,
1355 pub id: u64,
1356}
1357
1358pub struct FollowerState {
1359 center_pane: Entity<Pane>,
1360 dock_pane: Option<Entity<Pane>>,
1361 active_view_id: Option<ViewId>,
1362 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1363}
1364
1365struct FollowerView {
1366 view: Box<dyn FollowableItemHandle>,
1367 location: Option<proto::PanelId>,
1368}
1369
1370#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1371pub enum OpenMode {
1372 /// Open the workspace in a new window.
1373 NewWindow,
1374 /// Add to the window's multi workspace without activating it (used during deserialization).
1375 Add,
1376 /// Add to the window's multi workspace and activate it.
1377 #[default]
1378 Activate,
1379 /// Replace the currently active workspace, and any of it's linked workspaces
1380 Replace,
1381}
1382
1383impl Workspace {
1384 pub fn new(
1385 workspace_id: Option<WorkspaceId>,
1386 project: Entity<Project>,
1387 app_state: Arc<AppState>,
1388 window: &mut Window,
1389 cx: &mut Context<Self>,
1390 ) -> Self {
1391 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1392 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1393 if let TrustedWorktreesEvent::Trusted(..) = e {
1394 // Do not persist auto trusted worktrees
1395 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1396 worktrees_store.update(cx, |worktrees_store, cx| {
1397 worktrees_store.schedule_serialization(
1398 cx,
1399 |new_trusted_worktrees, cx| {
1400 let timeout =
1401 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1402 let db = WorkspaceDb::global(cx);
1403 cx.background_spawn(async move {
1404 timeout.await;
1405 db.save_trusted_worktrees(new_trusted_worktrees)
1406 .await
1407 .log_err();
1408 })
1409 },
1410 )
1411 });
1412 }
1413 }
1414 })
1415 .detach();
1416
1417 cx.observe_global::<SettingsStore>(|_, cx| {
1418 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1419 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1420 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1421 trusted_worktrees.auto_trust_all(cx);
1422 })
1423 }
1424 }
1425 })
1426 .detach();
1427 }
1428
1429 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1430 match event {
1431 project::Event::RemoteIdChanged(_) => {
1432 this.update_window_title(window, cx);
1433 }
1434
1435 project::Event::CollaboratorLeft(peer_id) => {
1436 this.collaborator_left(*peer_id, window, cx);
1437 }
1438
1439 &project::Event::WorktreeRemoved(_) => {
1440 this.update_window_title(window, cx);
1441 this.serialize_workspace(window, cx);
1442 this.update_history(cx);
1443 }
1444
1445 &project::Event::WorktreeAdded(id) => {
1446 this.update_window_title(window, cx);
1447 if this
1448 .project()
1449 .read(cx)
1450 .worktree_for_id(id, cx)
1451 .is_some_and(|wt| wt.read(cx).is_visible())
1452 {
1453 this.serialize_workspace(window, cx);
1454 this.update_history(cx);
1455 }
1456 }
1457 project::Event::WorktreeUpdatedEntries(..) => {
1458 this.update_window_title(window, cx);
1459 this.serialize_workspace(window, cx);
1460 }
1461
1462 project::Event::DisconnectedFromHost => {
1463 this.update_window_edited(window, cx);
1464 let leaders_to_unfollow =
1465 this.follower_states.keys().copied().collect::<Vec<_>>();
1466 for leader_id in leaders_to_unfollow {
1467 this.unfollow(leader_id, window, cx);
1468 }
1469 }
1470
1471 project::Event::DisconnectedFromRemote {
1472 server_not_running: _,
1473 } => {
1474 this.update_window_edited(window, cx);
1475 }
1476
1477 project::Event::Closed => {
1478 window.remove_window();
1479 }
1480
1481 project::Event::DeletedEntry(_, entry_id) => {
1482 for pane in this.panes.iter() {
1483 pane.update(cx, |pane, cx| {
1484 pane.handle_deleted_project_item(*entry_id, window, cx)
1485 });
1486 }
1487 }
1488
1489 project::Event::Toast {
1490 notification_id,
1491 message,
1492 link,
1493 } => this.show_notification(
1494 NotificationId::named(notification_id.clone()),
1495 cx,
1496 |cx| {
1497 let mut notification = MessageNotification::new(message.clone(), cx);
1498 if let Some(link) = link {
1499 notification = notification
1500 .more_info_message(link.label)
1501 .more_info_url(link.url);
1502 }
1503
1504 cx.new(|_| notification)
1505 },
1506 ),
1507
1508 project::Event::HideToast { notification_id } => {
1509 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1510 }
1511
1512 project::Event::LanguageServerPrompt(request) => {
1513 struct LanguageServerPrompt;
1514
1515 this.show_notification(
1516 NotificationId::composite::<LanguageServerPrompt>(request.id),
1517 cx,
1518 |cx| {
1519 cx.new(|cx| {
1520 notifications::LanguageServerPrompt::new(request.clone(), cx)
1521 })
1522 },
1523 );
1524 }
1525
1526 project::Event::AgentLocationChanged => {
1527 this.handle_agent_location_changed(window, cx)
1528 }
1529
1530 _ => {}
1531 }
1532 cx.notify()
1533 })
1534 .detach();
1535
1536 cx.subscribe_in(
1537 &project.read(cx).breakpoint_store(),
1538 window,
1539 |workspace, _, event, window, cx| match event {
1540 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1541 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1542 workspace.serialize_workspace(window, cx);
1543 }
1544 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1545 },
1546 )
1547 .detach();
1548 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1549 cx.subscribe_in(
1550 &toolchain_store,
1551 window,
1552 |workspace, _, event, window, cx| match event {
1553 ToolchainStoreEvent::CustomToolchainsModified => {
1554 workspace.serialize_workspace(window, cx);
1555 }
1556 _ => {}
1557 },
1558 )
1559 .detach();
1560 }
1561
1562 cx.on_focus_lost(window, |this, window, cx| {
1563 let focus_handle = this.focus_handle(cx);
1564 window.focus(&focus_handle, cx);
1565 })
1566 .detach();
1567
1568 let weak_handle = cx.entity().downgrade();
1569 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1570
1571 let center_pane = cx.new(|cx| {
1572 let mut center_pane = Pane::new(
1573 weak_handle.clone(),
1574 project.clone(),
1575 pane_history_timestamp.clone(),
1576 None,
1577 NewFile.boxed_clone(),
1578 true,
1579 window,
1580 cx,
1581 );
1582 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1583 center_pane.set_should_display_welcome_page(true);
1584 center_pane
1585 });
1586 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1587 .detach();
1588
1589 window.focus(¢er_pane.focus_handle(cx), cx);
1590
1591 cx.emit(Event::PaneAdded(center_pane.clone()));
1592
1593 let any_window_handle = window.window_handle();
1594 app_state.workspace_store.update(cx, |store, _| {
1595 store
1596 .workspaces
1597 .insert((any_window_handle, weak_handle.clone()));
1598 });
1599
1600 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1601 let mut connection_status = app_state.client.status();
1602 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1603 current_user.next().await;
1604 connection_status.next().await;
1605 let mut stream =
1606 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1607
1608 while stream.recv().await.is_some() {
1609 this.update(cx, |_, cx| cx.notify())?;
1610 }
1611 anyhow::Ok(())
1612 });
1613
1614 // All leader updates are enqueued and then processed in a single task, so
1615 // that each asynchronous operation can be run in order.
1616 let (leader_updates_tx, mut leader_updates_rx) =
1617 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1618 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1619 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1620 Self::process_leader_update(&this, leader_id, update, cx)
1621 .await
1622 .log_err();
1623 }
1624
1625 Ok(())
1626 });
1627
1628 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1629 let modal_layer = cx.new(|_| ModalLayer::new());
1630 let toast_layer = cx.new(|_| ToastLayer::new());
1631 cx.subscribe(
1632 &modal_layer,
1633 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1634 cx.emit(Event::ModalOpened);
1635 },
1636 )
1637 .detach();
1638
1639 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1640 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1641 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1642 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1643 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1644 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1645 let multi_workspace = window
1646 .root::<MultiWorkspace>()
1647 .flatten()
1648 .map(|mw| mw.downgrade());
1649 let status_bar = cx.new(|cx| {
1650 let mut status_bar =
1651 StatusBar::new(¢er_pane.clone(), multi_workspace.clone(), window, cx);
1652 status_bar.add_left_item(left_dock_buttons, window, cx);
1653 status_bar.add_right_item(right_dock_buttons, window, cx);
1654 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1655 status_bar
1656 });
1657
1658 let session_id = app_state.session.read(cx).id().to_owned();
1659
1660 let mut active_call = None;
1661 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1662 let subscriptions =
1663 vec![
1664 call.0
1665 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1666 ];
1667 active_call = Some((call, subscriptions));
1668 }
1669
1670 let (serializable_items_tx, serializable_items_rx) =
1671 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1672 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1673 Self::serialize_items(&this, serializable_items_rx, cx).await
1674 });
1675
1676 let subscriptions = vec![
1677 cx.observe_window_activation(window, Self::on_window_activation_changed),
1678 cx.observe_window_bounds(window, move |this, window, cx| {
1679 if this.bounds_save_task_queued.is_some() {
1680 return;
1681 }
1682 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1683 cx.background_executor()
1684 .timer(Duration::from_millis(100))
1685 .await;
1686 this.update_in(cx, |this, window, cx| {
1687 this.save_window_bounds(window, cx).detach();
1688 this.bounds_save_task_queued.take();
1689 })
1690 .ok();
1691 }));
1692 cx.notify();
1693 }),
1694 cx.observe_window_appearance(window, |_, window, cx| {
1695 let window_appearance = window.appearance();
1696
1697 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1698
1699 theme_settings::reload_theme(cx);
1700 theme_settings::reload_icon_theme(cx);
1701 }),
1702 cx.on_release({
1703 let weak_handle = weak_handle.clone();
1704 move |this, cx| {
1705 this.app_state.workspace_store.update(cx, move |store, _| {
1706 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1707 })
1708 }
1709 }),
1710 ];
1711
1712 cx.defer_in(window, move |this, window, cx| {
1713 this.update_window_title(window, cx);
1714 this.show_initial_notifications(cx);
1715 });
1716
1717 let mut center = PaneGroup::new(center_pane.clone());
1718 center.set_is_center(true);
1719 center.mark_positions(cx);
1720
1721 Workspace {
1722 weak_self: weak_handle.clone(),
1723 zoomed: None,
1724 zoomed_position: None,
1725 previous_dock_drag_coordinates: None,
1726 center,
1727 panes: vec![center_pane.clone()],
1728 panes_by_item: Default::default(),
1729 active_pane: center_pane.clone(),
1730 last_active_center_pane: Some(center_pane.downgrade()),
1731 last_active_view_id: None,
1732 status_bar,
1733 modal_layer,
1734 toast_layer,
1735 titlebar_item: None,
1736 active_worktree_override: None,
1737 notifications: Notifications::default(),
1738 suppressed_notifications: HashSet::default(),
1739 left_dock,
1740 bottom_dock,
1741 right_dock,
1742 _panels_task: None,
1743 project: project.clone(),
1744 follower_states: Default::default(),
1745 last_leaders_by_pane: Default::default(),
1746 dispatching_keystrokes: Default::default(),
1747 window_edited: false,
1748 last_window_title: None,
1749 dirty_items: Default::default(),
1750 active_call,
1751 database_id: workspace_id,
1752 app_state,
1753 _observe_current_user,
1754 _apply_leader_updates,
1755 _schedule_serialize_workspace: None,
1756 _serialize_workspace_task: None,
1757 _schedule_serialize_ssh_paths: None,
1758 leader_updates_tx,
1759 _subscriptions: subscriptions,
1760 pane_history_timestamp,
1761 workspace_actions: Default::default(),
1762 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1763 bounds: Default::default(),
1764 centered_layout: false,
1765 bounds_save_task_queued: None,
1766 on_prompt_for_new_path: None,
1767 on_prompt_for_open_path: None,
1768 terminal_provider: None,
1769 debugger_provider: None,
1770 serializable_items_tx,
1771 _items_serializer,
1772 session_id: Some(session_id),
1773
1774 scheduled_tasks: Vec::new(),
1775 last_open_dock_positions: Vec::new(),
1776 removing: false,
1777 sidebar_focus_handle: None,
1778 multi_workspace,
1779 }
1780 }
1781
1782 pub fn new_local(
1783 abs_paths: Vec<PathBuf>,
1784 app_state: Arc<AppState>,
1785 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1786 env: Option<HashMap<String, String>>,
1787 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1788 open_mode: OpenMode,
1789 cx: &mut App,
1790 ) -> Task<anyhow::Result<OpenResult>> {
1791 let project_handle = Project::local(
1792 app_state.client.clone(),
1793 app_state.node_runtime.clone(),
1794 app_state.user_store.clone(),
1795 app_state.languages.clone(),
1796 app_state.fs.clone(),
1797 env,
1798 Default::default(),
1799 cx,
1800 );
1801
1802 let db = WorkspaceDb::global(cx);
1803 let kvp = db::kvp::KeyValueStore::global(cx);
1804 cx.spawn(async move |cx| {
1805 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1806 for path in abs_paths.into_iter() {
1807 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1808 paths_to_open.push(canonical)
1809 } else {
1810 paths_to_open.push(path)
1811 }
1812 }
1813
1814 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1815
1816 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1817 paths_to_open = paths.ordered_paths().cloned().collect();
1818 if !paths.is_lexicographically_ordered() {
1819 project_handle.update(cx, |project, cx| {
1820 project.set_worktrees_reordered(true, cx);
1821 });
1822 }
1823 }
1824
1825 // Get project paths for all of the abs_paths
1826 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1827 Vec::with_capacity(paths_to_open.len());
1828
1829 for path in paths_to_open.into_iter() {
1830 if let Some((_, project_entry)) = cx
1831 .update(|cx| {
1832 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1833 })
1834 .await
1835 .log_err()
1836 {
1837 project_paths.push((path, Some(project_entry)));
1838 } else {
1839 project_paths.push((path, None));
1840 }
1841 }
1842
1843 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1844 serialized_workspace.id
1845 } else {
1846 db.next_id().await.unwrap_or_else(|_| Default::default())
1847 };
1848
1849 let toolchains = db.toolchains(workspace_id).await?;
1850
1851 for (toolchain, worktree_path, path) in toolchains {
1852 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1853 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1854 this.find_worktree(&worktree_path, cx)
1855 .and_then(|(worktree, rel_path)| {
1856 if rel_path.is_empty() {
1857 Some(worktree.read(cx).id())
1858 } else {
1859 None
1860 }
1861 })
1862 }) else {
1863 // We did not find a worktree with a given path, but that's whatever.
1864 continue;
1865 };
1866 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1867 continue;
1868 }
1869
1870 project_handle
1871 .update(cx, |this, cx| {
1872 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1873 })
1874 .await;
1875 }
1876 if let Some(workspace) = serialized_workspace.as_ref() {
1877 project_handle.update(cx, |this, cx| {
1878 for (scope, toolchains) in &workspace.user_toolchains {
1879 for toolchain in toolchains {
1880 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1881 }
1882 }
1883 });
1884 }
1885
1886 let window_to_replace = match open_mode {
1887 OpenMode::NewWindow => None,
1888 _ => requesting_window,
1889 };
1890
1891 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1892 if let Some(window) = window_to_replace {
1893 let centered_layout = serialized_workspace
1894 .as_ref()
1895 .map(|w| w.centered_layout)
1896 .unwrap_or(false);
1897
1898 let workspace = window.update(cx, |multi_workspace, window, cx| {
1899 let workspace = cx.new(|cx| {
1900 let mut workspace = Workspace::new(
1901 Some(workspace_id),
1902 project_handle.clone(),
1903 app_state.clone(),
1904 window,
1905 cx,
1906 );
1907
1908 workspace.centered_layout = centered_layout;
1909
1910 // Call init callback to add items before window renders
1911 if let Some(init) = init {
1912 init(&mut workspace, window, cx);
1913 }
1914
1915 workspace
1916 });
1917 match open_mode {
1918 OpenMode::Replace => {
1919 multi_workspace.replace(workspace.clone(), &*window, cx);
1920 }
1921 OpenMode::Activate => {
1922 multi_workspace.activate(workspace.clone(), window, cx);
1923 }
1924 OpenMode::Add => {
1925 multi_workspace.add(workspace.clone(), &*window, cx);
1926 }
1927 OpenMode::NewWindow => {
1928 unreachable!()
1929 }
1930 }
1931 workspace
1932 })?;
1933 (window, workspace)
1934 } else {
1935 let window_bounds_override = window_bounds_env_override();
1936
1937 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1938 (Some(WindowBounds::Windowed(bounds)), None)
1939 } else if let Some(workspace) = serialized_workspace.as_ref()
1940 && let Some(display) = workspace.display
1941 && let Some(bounds) = workspace.window_bounds.as_ref()
1942 {
1943 // Reopening an existing workspace - restore its saved bounds
1944 (Some(bounds.0), Some(display))
1945 } else if let Some((display, bounds)) =
1946 persistence::read_default_window_bounds(&kvp)
1947 {
1948 // New or empty workspace - use the last known window bounds
1949 (Some(bounds), Some(display))
1950 } else {
1951 // New window - let GPUI's default_bounds() handle cascading
1952 (None, None)
1953 };
1954
1955 // Use the serialized workspace to construct the new window
1956 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1957 options.window_bounds = window_bounds;
1958 let centered_layout = serialized_workspace
1959 .as_ref()
1960 .map(|w| w.centered_layout)
1961 .unwrap_or(false);
1962 let window = cx.open_window(options, {
1963 let app_state = app_state.clone();
1964 let project_handle = project_handle.clone();
1965 move |window, cx| {
1966 let workspace = cx.new(|cx| {
1967 let mut workspace = Workspace::new(
1968 Some(workspace_id),
1969 project_handle,
1970 app_state,
1971 window,
1972 cx,
1973 );
1974 workspace.centered_layout = centered_layout;
1975
1976 // Call init callback to add items before window renders
1977 if let Some(init) = init {
1978 init(&mut workspace, window, cx);
1979 }
1980
1981 workspace
1982 });
1983 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1984 }
1985 })?;
1986 let workspace =
1987 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1988 multi_workspace.workspace().clone()
1989 })?;
1990 (window, workspace)
1991 };
1992
1993 notify_if_database_failed(window, cx);
1994 // Check if this is an empty workspace (no paths to open)
1995 // An empty workspace is one where project_paths is empty
1996 let is_empty_workspace = project_paths.is_empty();
1997 // Check if serialized workspace has paths before it's moved
1998 let serialized_workspace_has_paths = serialized_workspace
1999 .as_ref()
2000 .map(|ws| !ws.paths.is_empty())
2001 .unwrap_or(false);
2002
2003 let opened_items = window
2004 .update(cx, |_, window, cx| {
2005 workspace.update(cx, |_workspace: &mut Workspace, cx| {
2006 open_items(serialized_workspace, project_paths, window, cx)
2007 })
2008 })?
2009 .await
2010 .unwrap_or_default();
2011
2012 // Restore default dock state for empty workspaces
2013 // Only restore if:
2014 // 1. This is an empty workspace (no paths), AND
2015 // 2. The serialized workspace either doesn't exist or has no paths
2016 if is_empty_workspace && !serialized_workspace_has_paths {
2017 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
2018 window
2019 .update(cx, |_, window, cx| {
2020 workspace.update(cx, |workspace, cx| {
2021 for (dock, serialized_dock) in [
2022 (&workspace.right_dock, &default_docks.right),
2023 (&workspace.left_dock, &default_docks.left),
2024 (&workspace.bottom_dock, &default_docks.bottom),
2025 ] {
2026 dock.update(cx, |dock, cx| {
2027 dock.serialized_dock = Some(serialized_dock.clone());
2028 dock.restore_state(window, cx);
2029 });
2030 }
2031 cx.notify();
2032 });
2033 })
2034 .log_err();
2035 }
2036 }
2037
2038 window
2039 .update(cx, |_, _window, cx| {
2040 workspace.update(cx, |this: &mut Workspace, cx| {
2041 this.update_history(cx);
2042 });
2043 })
2044 .log_err();
2045 Ok(OpenResult {
2046 window,
2047 workspace,
2048 opened_items,
2049 })
2050 })
2051 }
2052
2053 pub fn weak_handle(&self) -> WeakEntity<Self> {
2054 self.weak_self.clone()
2055 }
2056
2057 pub fn left_dock(&self) -> &Entity<Dock> {
2058 &self.left_dock
2059 }
2060
2061 pub fn bottom_dock(&self) -> &Entity<Dock> {
2062 &self.bottom_dock
2063 }
2064
2065 pub fn set_bottom_dock_layout(
2066 &mut self,
2067 layout: BottomDockLayout,
2068 window: &mut Window,
2069 cx: &mut Context<Self>,
2070 ) {
2071 let fs = self.project().read(cx).fs();
2072 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2073 content.workspace.bottom_dock_layout = Some(layout);
2074 });
2075
2076 cx.notify();
2077 self.serialize_workspace(window, cx);
2078 }
2079
2080 pub fn right_dock(&self) -> &Entity<Dock> {
2081 &self.right_dock
2082 }
2083
2084 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2085 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2086 }
2087
2088 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2089 let left_dock = self.left_dock.read(cx);
2090 let left_visible = left_dock.is_open();
2091 let left_active_panel = left_dock
2092 .active_panel()
2093 .map(|panel| panel.persistent_name().to_string());
2094 // `zoomed_position` is kept in sync with individual panel zoom state
2095 // by the dock code in `Dock::new` and `Dock::add_panel`.
2096 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2097
2098 let right_dock = self.right_dock.read(cx);
2099 let right_visible = right_dock.is_open();
2100 let right_active_panel = right_dock
2101 .active_panel()
2102 .map(|panel| panel.persistent_name().to_string());
2103 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2104
2105 let bottom_dock = self.bottom_dock.read(cx);
2106 let bottom_visible = bottom_dock.is_open();
2107 let bottom_active_panel = bottom_dock
2108 .active_panel()
2109 .map(|panel| panel.persistent_name().to_string());
2110 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2111
2112 DockStructure {
2113 left: DockData {
2114 visible: left_visible,
2115 active_panel: left_active_panel,
2116 zoom: left_dock_zoom,
2117 },
2118 right: DockData {
2119 visible: right_visible,
2120 active_panel: right_active_panel,
2121 zoom: right_dock_zoom,
2122 },
2123 bottom: DockData {
2124 visible: bottom_visible,
2125 active_panel: bottom_active_panel,
2126 zoom: bottom_dock_zoom,
2127 },
2128 }
2129 }
2130
2131 pub fn set_dock_structure(
2132 &self,
2133 docks: DockStructure,
2134 window: &mut Window,
2135 cx: &mut Context<Self>,
2136 ) {
2137 for (dock, data) in [
2138 (&self.left_dock, docks.left),
2139 (&self.bottom_dock, docks.bottom),
2140 (&self.right_dock, docks.right),
2141 ] {
2142 dock.update(cx, |dock, cx| {
2143 dock.serialized_dock = Some(data);
2144 dock.restore_state(window, cx);
2145 });
2146 }
2147 }
2148
2149 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2150 self.items(cx)
2151 .filter_map(|item| {
2152 let project_path = item.project_path(cx)?;
2153 self.project.read(cx).absolute_path(&project_path, cx)
2154 })
2155 .collect()
2156 }
2157
2158 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2159 match position {
2160 DockPosition::Left => &self.left_dock,
2161 DockPosition::Bottom => &self.bottom_dock,
2162 DockPosition::Right => &self.right_dock,
2163 }
2164 }
2165
2166 pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
2167 self.all_docks().into_iter().find_map(|dock| {
2168 let dock = dock.read(cx);
2169 dock.has_agent_panel(cx).then_some(dock.position())
2170 })
2171 }
2172
2173 pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
2174 self.all_docks().into_iter().find_map(|dock| {
2175 let dock = dock.read(cx);
2176 let panel = dock.panel::<T>()?;
2177 dock.stored_panel_size_state(&panel)
2178 })
2179 }
2180
2181 pub fn persisted_panel_size_state(
2182 &self,
2183 panel_key: &'static str,
2184 cx: &App,
2185 ) -> Option<dock::PanelSizeState> {
2186 dock::Dock::load_persisted_size_state(self, panel_key, cx)
2187 }
2188
2189 pub fn persist_panel_size_state(
2190 &self,
2191 panel_key: &str,
2192 size_state: dock::PanelSizeState,
2193 cx: &mut App,
2194 ) {
2195 let Some(workspace_id) = self
2196 .database_id()
2197 .map(|id| i64::from(id).to_string())
2198 .or(self.session_id())
2199 else {
2200 return;
2201 };
2202
2203 let kvp = db::kvp::KeyValueStore::global(cx);
2204 let panel_key = panel_key.to_string();
2205 cx.background_spawn(async move {
2206 let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
2207 scope
2208 .write(
2209 format!("{workspace_id}:{panel_key}"),
2210 serde_json::to_string(&size_state)?,
2211 )
2212 .await
2213 })
2214 .detach_and_log_err(cx);
2215 }
2216
2217 pub fn set_panel_size_state<T: Panel>(
2218 &mut self,
2219 size_state: dock::PanelSizeState,
2220 window: &mut Window,
2221 cx: &mut Context<Self>,
2222 ) -> bool {
2223 let Some(panel) = self.panel::<T>(cx) else {
2224 return false;
2225 };
2226
2227 let dock = self.dock_at_position(panel.position(window, cx));
2228 let did_set = dock.update(cx, |dock, cx| {
2229 dock.set_panel_size_state(&panel, size_state, cx)
2230 });
2231
2232 if did_set {
2233 self.persist_panel_size_state(T::panel_key(), size_state, cx);
2234 }
2235
2236 did_set
2237 }
2238
2239 pub fn toggle_dock_panel_flexible_size(
2240 &self,
2241 dock: &Entity<Dock>,
2242 panel: &dyn PanelHandle,
2243 window: &mut Window,
2244 cx: &mut App,
2245 ) {
2246 let position = dock.read(cx).position();
2247 let current_size = self.dock_size(&dock.read(cx), window, cx);
2248 let current_flex =
2249 current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
2250 dock.update(cx, |dock, cx| {
2251 dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
2252 });
2253 }
2254
2255 fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
2256 let panel = dock.active_panel()?;
2257 let size_state = dock
2258 .stored_panel_size_state(panel.as_ref())
2259 .unwrap_or_default();
2260 let position = dock.position();
2261
2262 let use_flex = panel.has_flexible_size(window, cx);
2263
2264 if position.axis() == Axis::Horizontal
2265 && use_flex
2266 && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
2267 {
2268 let workspace_width = self.bounds.size.width;
2269 if workspace_width <= Pixels::ZERO {
2270 return None;
2271 }
2272 let flex = flex.max(0.001);
2273 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2274 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2275 // Both docks are flex items sharing the full workspace width.
2276 let total_flex = flex + 1.0 + opposite_flex;
2277 return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
2278 } else {
2279 // Opposite dock is fixed-width; flex items share (W - fixed).
2280 let opposite_fixed = opposite
2281 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2282 .unwrap_or_default();
2283 let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
2284 return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
2285 }
2286 }
2287
2288 Some(
2289 size_state
2290 .size
2291 .unwrap_or_else(|| panel.default_size(window, cx)),
2292 )
2293 }
2294
2295 pub fn dock_flex_for_size(
2296 &self,
2297 position: DockPosition,
2298 size: Pixels,
2299 window: &Window,
2300 cx: &App,
2301 ) -> Option<f32> {
2302 if position.axis() != Axis::Horizontal {
2303 return None;
2304 }
2305
2306 let workspace_width = self.bounds.size.width;
2307 if workspace_width <= Pixels::ZERO {
2308 return None;
2309 }
2310
2311 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2312 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2313 let size = size.clamp(px(0.), workspace_width - px(1.));
2314 Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
2315 } else {
2316 let opposite_width = opposite
2317 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2318 .unwrap_or_default();
2319 let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
2320 let remaining = (available - size).max(px(1.));
2321 Some((size / remaining).max(0.0))
2322 }
2323 }
2324
2325 fn opposite_dock_panel_and_size_state(
2326 &self,
2327 position: DockPosition,
2328 window: &Window,
2329 cx: &App,
2330 ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
2331 let opposite_position = match position {
2332 DockPosition::Left => DockPosition::Right,
2333 DockPosition::Right => DockPosition::Left,
2334 DockPosition::Bottom => return None,
2335 };
2336
2337 let opposite_dock = self.dock_at_position(opposite_position).read(cx);
2338 let panel = opposite_dock.visible_panel()?;
2339 let mut size_state = opposite_dock
2340 .stored_panel_size_state(panel.as_ref())
2341 .unwrap_or_default();
2342 if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
2343 size_state.flex = self.default_dock_flex(opposite_position);
2344 }
2345 Some((panel.clone(), size_state))
2346 }
2347
2348 pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
2349 if position.axis() != Axis::Horizontal {
2350 return None;
2351 }
2352
2353 let pane = self.last_active_center_pane.clone()?.upgrade()?;
2354 Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
2355 }
2356
2357 pub fn is_edited(&self) -> bool {
2358 self.window_edited
2359 }
2360
2361 pub fn add_panel<T: Panel>(
2362 &mut self,
2363 panel: Entity<T>,
2364 window: &mut Window,
2365 cx: &mut Context<Self>,
2366 ) {
2367 let focus_handle = panel.panel_focus_handle(cx);
2368 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2369 .detach();
2370
2371 let dock_position = panel.position(window, cx);
2372 let dock = self.dock_at_position(dock_position);
2373 let any_panel = panel.to_any();
2374 let persisted_size_state =
2375 self.persisted_panel_size_state(T::panel_key(), cx)
2376 .or_else(|| {
2377 load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
2378 let state = dock::PanelSizeState {
2379 size: Some(size),
2380 flex: None,
2381 };
2382 self.persist_panel_size_state(T::panel_key(), state, cx);
2383 state
2384 })
2385 });
2386
2387 dock.update(cx, |dock, cx| {
2388 let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
2389 if let Some(size_state) = persisted_size_state {
2390 dock.set_panel_size_state(&panel, size_state, cx);
2391 }
2392 index
2393 });
2394
2395 cx.emit(Event::PanelAdded(any_panel));
2396 }
2397
2398 pub fn remove_panel<T: Panel>(
2399 &mut self,
2400 panel: &Entity<T>,
2401 window: &mut Window,
2402 cx: &mut Context<Self>,
2403 ) {
2404 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2405 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2406 }
2407 }
2408
2409 pub fn status_bar(&self) -> &Entity<StatusBar> {
2410 &self.status_bar
2411 }
2412
2413 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2414 self.sidebar_focus_handle = handle;
2415 }
2416
2417 pub fn status_bar_visible(&self, cx: &App) -> bool {
2418 StatusBarSettings::get_global(cx).show
2419 }
2420
2421 pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
2422 self.multi_workspace.as_ref()
2423 }
2424
2425 pub fn set_multi_workspace(
2426 &mut self,
2427 multi_workspace: WeakEntity<MultiWorkspace>,
2428 cx: &mut App,
2429 ) {
2430 self.status_bar.update(cx, |status_bar, cx| {
2431 status_bar.set_multi_workspace(multi_workspace.clone(), cx);
2432 });
2433 self.multi_workspace = Some(multi_workspace);
2434 }
2435
2436 pub fn app_state(&self) -> &Arc<AppState> {
2437 &self.app_state
2438 }
2439
2440 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2441 self._panels_task = Some(task);
2442 }
2443
2444 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2445 self._panels_task.take()
2446 }
2447
2448 pub fn user_store(&self) -> &Entity<UserStore> {
2449 &self.app_state.user_store
2450 }
2451
2452 pub fn project(&self) -> &Entity<Project> {
2453 &self.project
2454 }
2455
2456 pub fn path_style(&self, cx: &App) -> PathStyle {
2457 self.project.read(cx).path_style(cx)
2458 }
2459
2460 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2461 let mut history: HashMap<EntityId, usize> = HashMap::default();
2462
2463 for pane_handle in &self.panes {
2464 let pane = pane_handle.read(cx);
2465
2466 for entry in pane.activation_history() {
2467 history.insert(
2468 entry.entity_id,
2469 history
2470 .get(&entry.entity_id)
2471 .cloned()
2472 .unwrap_or(0)
2473 .max(entry.timestamp),
2474 );
2475 }
2476 }
2477
2478 history
2479 }
2480
2481 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2482 let mut recent_item: Option<Entity<T>> = None;
2483 let mut recent_timestamp = 0;
2484 for pane_handle in &self.panes {
2485 let pane = pane_handle.read(cx);
2486 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2487 pane.items().map(|item| (item.item_id(), item)).collect();
2488 for entry in pane.activation_history() {
2489 if entry.timestamp > recent_timestamp
2490 && let Some(&item) = item_map.get(&entry.entity_id)
2491 && let Some(typed_item) = item.act_as::<T>(cx)
2492 {
2493 recent_timestamp = entry.timestamp;
2494 recent_item = Some(typed_item);
2495 }
2496 }
2497 }
2498 recent_item
2499 }
2500
2501 pub fn recent_navigation_history_iter(
2502 &self,
2503 cx: &App,
2504 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2505 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2506 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2507
2508 for pane in &self.panes {
2509 let pane = pane.read(cx);
2510
2511 pane.nav_history()
2512 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2513 if let Some(fs_path) = &fs_path {
2514 abs_paths_opened
2515 .entry(fs_path.clone())
2516 .or_default()
2517 .insert(project_path.clone());
2518 }
2519 let timestamp = entry.timestamp;
2520 match history.entry(project_path) {
2521 hash_map::Entry::Occupied(mut entry) => {
2522 let (_, old_timestamp) = entry.get();
2523 if ×tamp > old_timestamp {
2524 entry.insert((fs_path, timestamp));
2525 }
2526 }
2527 hash_map::Entry::Vacant(entry) => {
2528 entry.insert((fs_path, timestamp));
2529 }
2530 }
2531 });
2532
2533 if let Some(item) = pane.active_item()
2534 && let Some(project_path) = item.project_path(cx)
2535 {
2536 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2537
2538 if let Some(fs_path) = &fs_path {
2539 abs_paths_opened
2540 .entry(fs_path.clone())
2541 .or_default()
2542 .insert(project_path.clone());
2543 }
2544
2545 history.insert(project_path, (fs_path, std::usize::MAX));
2546 }
2547 }
2548
2549 history
2550 .into_iter()
2551 .sorted_by_key(|(_, (_, order))| *order)
2552 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2553 .rev()
2554 .filter(move |(history_path, abs_path)| {
2555 let latest_project_path_opened = abs_path
2556 .as_ref()
2557 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2558 .and_then(|project_paths| {
2559 project_paths
2560 .iter()
2561 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2562 });
2563
2564 latest_project_path_opened.is_none_or(|path| path == history_path)
2565 })
2566 }
2567
2568 pub fn recent_navigation_history(
2569 &self,
2570 limit: Option<usize>,
2571 cx: &App,
2572 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2573 self.recent_navigation_history_iter(cx)
2574 .take(limit.unwrap_or(usize::MAX))
2575 .collect()
2576 }
2577
2578 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2579 for pane in &self.panes {
2580 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2581 }
2582 }
2583
2584 fn navigate_history(
2585 &mut self,
2586 pane: WeakEntity<Pane>,
2587 mode: NavigationMode,
2588 window: &mut Window,
2589 cx: &mut Context<Workspace>,
2590 ) -> Task<Result<()>> {
2591 self.navigate_history_impl(
2592 pane,
2593 mode,
2594 window,
2595 &mut |history, cx| history.pop(mode, cx),
2596 cx,
2597 )
2598 }
2599
2600 fn navigate_tag_history(
2601 &mut self,
2602 pane: WeakEntity<Pane>,
2603 mode: TagNavigationMode,
2604 window: &mut Window,
2605 cx: &mut Context<Workspace>,
2606 ) -> Task<Result<()>> {
2607 self.navigate_history_impl(
2608 pane,
2609 NavigationMode::Normal,
2610 window,
2611 &mut |history, _cx| history.pop_tag(mode),
2612 cx,
2613 )
2614 }
2615
2616 fn navigate_history_impl(
2617 &mut self,
2618 pane: WeakEntity<Pane>,
2619 mode: NavigationMode,
2620 window: &mut Window,
2621 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2622 cx: &mut Context<Workspace>,
2623 ) -> Task<Result<()>> {
2624 let to_load = if let Some(pane) = pane.upgrade() {
2625 pane.update(cx, |pane, cx| {
2626 window.focus(&pane.focus_handle(cx), cx);
2627 loop {
2628 // Retrieve the weak item handle from the history.
2629 let entry = cb(pane.nav_history_mut(), cx)?;
2630
2631 // If the item is still present in this pane, then activate it.
2632 if let Some(index) = entry
2633 .item
2634 .upgrade()
2635 .and_then(|v| pane.index_for_item(v.as_ref()))
2636 {
2637 let prev_active_item_index = pane.active_item_index();
2638 pane.nav_history_mut().set_mode(mode);
2639 pane.activate_item(index, true, true, window, cx);
2640 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2641
2642 let mut navigated = prev_active_item_index != pane.active_item_index();
2643 if let Some(data) = entry.data {
2644 navigated |= pane.active_item()?.navigate(data, window, cx);
2645 }
2646
2647 if navigated {
2648 break None;
2649 }
2650 } else {
2651 // If the item is no longer present in this pane, then retrieve its
2652 // path info in order to reopen it.
2653 break pane
2654 .nav_history()
2655 .path_for_item(entry.item.id())
2656 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2657 }
2658 }
2659 })
2660 } else {
2661 None
2662 };
2663
2664 if let Some((project_path, abs_path, entry)) = to_load {
2665 // If the item was no longer present, then load it again from its previous path, first try the local path
2666 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2667
2668 cx.spawn_in(window, async move |workspace, cx| {
2669 let open_by_project_path = open_by_project_path.await;
2670 let mut navigated = false;
2671 match open_by_project_path
2672 .with_context(|| format!("Navigating to {project_path:?}"))
2673 {
2674 Ok((project_entry_id, build_item)) => {
2675 let prev_active_item_id = pane.update(cx, |pane, _| {
2676 pane.nav_history_mut().set_mode(mode);
2677 pane.active_item().map(|p| p.item_id())
2678 })?;
2679
2680 pane.update_in(cx, |pane, window, cx| {
2681 let item = pane.open_item(
2682 project_entry_id,
2683 project_path,
2684 true,
2685 entry.is_preview,
2686 true,
2687 None,
2688 window, cx,
2689 build_item,
2690 );
2691 navigated |= Some(item.item_id()) != prev_active_item_id;
2692 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2693 if let Some(data) = entry.data {
2694 navigated |= item.navigate(data, window, cx);
2695 }
2696 })?;
2697 }
2698 Err(open_by_project_path_e) => {
2699 // Fall back to opening by abs path, in case an external file was opened and closed,
2700 // and its worktree is now dropped
2701 if let Some(abs_path) = abs_path {
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 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2707 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2708 })?;
2709 match open_by_abs_path
2710 .await
2711 .with_context(|| format!("Navigating to {abs_path:?}"))
2712 {
2713 Ok(item) => {
2714 pane.update_in(cx, |pane, window, cx| {
2715 navigated |= Some(item.item_id()) != prev_active_item_id;
2716 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2717 if let Some(data) = entry.data {
2718 navigated |= item.navigate(data, window, cx);
2719 }
2720 })?;
2721 }
2722 Err(open_by_abs_path_e) => {
2723 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2724 }
2725 }
2726 }
2727 }
2728 }
2729
2730 if !navigated {
2731 workspace
2732 .update_in(cx, |workspace, window, cx| {
2733 Self::navigate_history(workspace, pane, mode, window, cx)
2734 })?
2735 .await?;
2736 }
2737
2738 Ok(())
2739 })
2740 } else {
2741 Task::ready(Ok(()))
2742 }
2743 }
2744
2745 pub fn go_back(
2746 &mut self,
2747 pane: WeakEntity<Pane>,
2748 window: &mut Window,
2749 cx: &mut Context<Workspace>,
2750 ) -> Task<Result<()>> {
2751 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2752 }
2753
2754 pub fn go_forward(
2755 &mut self,
2756 pane: WeakEntity<Pane>,
2757 window: &mut Window,
2758 cx: &mut Context<Workspace>,
2759 ) -> Task<Result<()>> {
2760 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2761 }
2762
2763 pub fn reopen_closed_item(
2764 &mut self,
2765 window: &mut Window,
2766 cx: &mut Context<Workspace>,
2767 ) -> Task<Result<()>> {
2768 self.navigate_history(
2769 self.active_pane().downgrade(),
2770 NavigationMode::ReopeningClosedItem,
2771 window,
2772 cx,
2773 )
2774 }
2775
2776 pub fn client(&self) -> &Arc<Client> {
2777 &self.app_state.client
2778 }
2779
2780 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2781 self.titlebar_item = Some(item);
2782 cx.notify();
2783 }
2784
2785 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2786 self.on_prompt_for_new_path = Some(prompt)
2787 }
2788
2789 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2790 self.on_prompt_for_open_path = Some(prompt)
2791 }
2792
2793 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2794 self.terminal_provider = Some(Box::new(provider));
2795 }
2796
2797 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2798 self.debugger_provider = Some(Arc::new(provider));
2799 }
2800
2801 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2802 self.debugger_provider.clone()
2803 }
2804
2805 pub fn prompt_for_open_path(
2806 &mut self,
2807 path_prompt_options: PathPromptOptions,
2808 lister: DirectoryLister,
2809 window: &mut Window,
2810 cx: &mut Context<Self>,
2811 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2812 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2813 let prompt = self.on_prompt_for_open_path.take().unwrap();
2814 let rx = prompt(self, lister, window, cx);
2815 self.on_prompt_for_open_path = Some(prompt);
2816 rx
2817 } else {
2818 let (tx, rx) = oneshot::channel();
2819 let abs_path = cx.prompt_for_paths(path_prompt_options);
2820
2821 cx.spawn_in(window, async move |workspace, cx| {
2822 let Ok(result) = abs_path.await else {
2823 return Ok(());
2824 };
2825
2826 match result {
2827 Ok(result) => {
2828 tx.send(result).ok();
2829 }
2830 Err(err) => {
2831 let rx = workspace.update_in(cx, |workspace, window, cx| {
2832 workspace.show_portal_error(err.to_string(), cx);
2833 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2834 let rx = prompt(workspace, lister, window, cx);
2835 workspace.on_prompt_for_open_path = Some(prompt);
2836 rx
2837 })?;
2838 if let Ok(path) = rx.await {
2839 tx.send(path).ok();
2840 }
2841 }
2842 };
2843 anyhow::Ok(())
2844 })
2845 .detach();
2846
2847 rx
2848 }
2849 }
2850
2851 pub fn prompt_for_new_path(
2852 &mut self,
2853 lister: DirectoryLister,
2854 suggested_name: Option<String>,
2855 window: &mut Window,
2856 cx: &mut Context<Self>,
2857 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2858 if self.project.read(cx).is_via_collab()
2859 || self.project.read(cx).is_via_remote_server()
2860 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2861 {
2862 let prompt = self.on_prompt_for_new_path.take().unwrap();
2863 let rx = prompt(self, lister, suggested_name, window, cx);
2864 self.on_prompt_for_new_path = Some(prompt);
2865 return rx;
2866 }
2867
2868 let (tx, rx) = oneshot::channel();
2869 cx.spawn_in(window, async move |workspace, cx| {
2870 let abs_path = workspace.update(cx, |workspace, cx| {
2871 let relative_to = workspace
2872 .most_recent_active_path(cx)
2873 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2874 .or_else(|| {
2875 let project = workspace.project.read(cx);
2876 project.visible_worktrees(cx).find_map(|worktree| {
2877 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2878 })
2879 })
2880 .or_else(std::env::home_dir)
2881 .unwrap_or_else(|| PathBuf::from(""));
2882 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2883 })?;
2884 let abs_path = match abs_path.await? {
2885 Ok(path) => path,
2886 Err(err) => {
2887 let rx = workspace.update_in(cx, |workspace, window, cx| {
2888 workspace.show_portal_error(err.to_string(), cx);
2889
2890 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2891 let rx = prompt(workspace, lister, suggested_name, window, cx);
2892 workspace.on_prompt_for_new_path = Some(prompt);
2893 rx
2894 })?;
2895 if let Ok(path) = rx.await {
2896 tx.send(path).ok();
2897 }
2898 return anyhow::Ok(());
2899 }
2900 };
2901
2902 tx.send(abs_path.map(|path| vec![path])).ok();
2903 anyhow::Ok(())
2904 })
2905 .detach();
2906
2907 rx
2908 }
2909
2910 pub fn titlebar_item(&self) -> Option<AnyView> {
2911 self.titlebar_item.clone()
2912 }
2913
2914 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2915 /// When set, git-related operations should use this worktree instead of deriving
2916 /// the active worktree from the focused file.
2917 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2918 self.active_worktree_override
2919 }
2920
2921 pub fn set_active_worktree_override(
2922 &mut self,
2923 worktree_id: Option<WorktreeId>,
2924 cx: &mut Context<Self>,
2925 ) {
2926 self.active_worktree_override = worktree_id;
2927 cx.notify();
2928 }
2929
2930 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2931 self.active_worktree_override = None;
2932 cx.notify();
2933 }
2934
2935 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2936 ///
2937 /// If the given workspace has a local project, then it will be passed
2938 /// to the callback. Otherwise, a new empty window will be created.
2939 pub fn with_local_workspace<T, F>(
2940 &mut self,
2941 window: &mut Window,
2942 cx: &mut Context<Self>,
2943 callback: F,
2944 ) -> Task<Result<T>>
2945 where
2946 T: 'static,
2947 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2948 {
2949 if self.project.read(cx).is_local() {
2950 Task::ready(Ok(callback(self, window, cx)))
2951 } else {
2952 let env = self.project.read(cx).cli_environment(cx);
2953 let task = Self::new_local(
2954 Vec::new(),
2955 self.app_state.clone(),
2956 None,
2957 env,
2958 None,
2959 OpenMode::Activate,
2960 cx,
2961 );
2962 cx.spawn_in(window, async move |_vh, cx| {
2963 let OpenResult {
2964 window: multi_workspace_window,
2965 ..
2966 } = task.await?;
2967 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2968 let workspace = multi_workspace.workspace().clone();
2969 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2970 })
2971 })
2972 }
2973 }
2974
2975 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2976 ///
2977 /// If the given workspace has a local project, then it will be passed
2978 /// to the callback. Otherwise, a new empty window will be created.
2979 pub fn with_local_or_wsl_workspace<T, F>(
2980 &mut self,
2981 window: &mut Window,
2982 cx: &mut Context<Self>,
2983 callback: F,
2984 ) -> Task<Result<T>>
2985 where
2986 T: 'static,
2987 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2988 {
2989 let project = self.project.read(cx);
2990 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2991 Task::ready(Ok(callback(self, window, cx)))
2992 } else {
2993 let env = self.project.read(cx).cli_environment(cx);
2994 let task = Self::new_local(
2995 Vec::new(),
2996 self.app_state.clone(),
2997 None,
2998 env,
2999 None,
3000 OpenMode::Activate,
3001 cx,
3002 );
3003 cx.spawn_in(window, async move |_vh, cx| {
3004 let OpenResult {
3005 window: multi_workspace_window,
3006 ..
3007 } = task.await?;
3008 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
3009 let workspace = multi_workspace.workspace().clone();
3010 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3011 })
3012 })
3013 }
3014 }
3015
3016 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3017 self.project.read(cx).worktrees(cx)
3018 }
3019
3020 pub fn visible_worktrees<'a>(
3021 &self,
3022 cx: &'a App,
3023 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3024 self.project.read(cx).visible_worktrees(cx)
3025 }
3026
3027 #[cfg(any(test, feature = "test-support"))]
3028 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
3029 let futures = self
3030 .worktrees(cx)
3031 .filter_map(|worktree| worktree.read(cx).as_local())
3032 .map(|worktree| worktree.scan_complete())
3033 .collect::<Vec<_>>();
3034 async move {
3035 for future in futures {
3036 future.await;
3037 }
3038 }
3039 }
3040
3041 pub fn close_global(cx: &mut App) {
3042 cx.defer(|cx| {
3043 cx.windows().iter().find(|window| {
3044 window
3045 .update(cx, |_, window, _| {
3046 if window.is_window_active() {
3047 //This can only get called when the window's project connection has been lost
3048 //so we don't need to prompt the user for anything and instead just close the window
3049 window.remove_window();
3050 true
3051 } else {
3052 false
3053 }
3054 })
3055 .unwrap_or(false)
3056 });
3057 });
3058 }
3059
3060 pub fn move_focused_panel_to_next_position(
3061 &mut self,
3062 _: &MoveFocusedPanelToNextPosition,
3063 window: &mut Window,
3064 cx: &mut Context<Self>,
3065 ) {
3066 let docks = self.all_docks();
3067 let active_dock = docks
3068 .into_iter()
3069 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
3070
3071 if let Some(dock) = active_dock {
3072 dock.update(cx, |dock, cx| {
3073 let active_panel = dock
3074 .active_panel()
3075 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
3076
3077 if let Some(panel) = active_panel {
3078 panel.move_to_next_position(window, cx);
3079 }
3080 })
3081 }
3082 }
3083
3084 pub fn prepare_to_close(
3085 &mut self,
3086 close_intent: CloseIntent,
3087 window: &mut Window,
3088 cx: &mut Context<Self>,
3089 ) -> Task<Result<bool>> {
3090 let active_call = self.active_global_call();
3091
3092 cx.spawn_in(window, async move |this, cx| {
3093 this.update(cx, |this, _| {
3094 if close_intent == CloseIntent::CloseWindow {
3095 this.removing = true;
3096 }
3097 })?;
3098
3099 let workspace_count = cx.update(|_window, cx| {
3100 cx.windows()
3101 .iter()
3102 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
3103 .count()
3104 })?;
3105
3106 #[cfg(target_os = "macos")]
3107 let save_last_workspace = false;
3108
3109 // On Linux and Windows, closing the last window should restore the last workspace.
3110 #[cfg(not(target_os = "macos"))]
3111 let save_last_workspace = {
3112 let remaining_workspaces = cx.update(|_window, cx| {
3113 cx.windows()
3114 .iter()
3115 .filter_map(|window| window.downcast::<MultiWorkspace>())
3116 .filter_map(|multi_workspace| {
3117 multi_workspace
3118 .update(cx, |multi_workspace, _, cx| {
3119 multi_workspace.workspace().read(cx).removing
3120 })
3121 .ok()
3122 })
3123 .filter(|removing| !removing)
3124 .count()
3125 })?;
3126
3127 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
3128 };
3129
3130 if let Some(active_call) = active_call
3131 && workspace_count == 1
3132 && cx
3133 .update(|_window, cx| active_call.0.is_in_room(cx))
3134 .unwrap_or(false)
3135 {
3136 if close_intent == CloseIntent::CloseWindow {
3137 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
3138 let answer = cx.update(|window, cx| {
3139 window.prompt(
3140 PromptLevel::Warning,
3141 "Do you want to leave the current call?",
3142 None,
3143 &["Close window and hang up", "Cancel"],
3144 cx,
3145 )
3146 })?;
3147
3148 if answer.await.log_err() == Some(1) {
3149 return anyhow::Ok(false);
3150 } else {
3151 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
3152 task.await.log_err();
3153 }
3154 }
3155 }
3156 if close_intent == CloseIntent::ReplaceWindow {
3157 _ = cx.update(|_window, cx| {
3158 let multi_workspace = cx
3159 .windows()
3160 .iter()
3161 .filter_map(|window| window.downcast::<MultiWorkspace>())
3162 .next()
3163 .unwrap();
3164 let project = multi_workspace
3165 .read(cx)?
3166 .workspace()
3167 .read(cx)
3168 .project
3169 .clone();
3170 if project.read(cx).is_shared() {
3171 active_call.0.unshare_project(project, cx)?;
3172 }
3173 Ok::<_, anyhow::Error>(())
3174 });
3175 }
3176 }
3177
3178 let save_result = this
3179 .update_in(cx, |this, window, cx| {
3180 this.save_all_internal(SaveIntent::Close, window, cx)
3181 })?
3182 .await;
3183
3184 // If we're not quitting, but closing, we remove the workspace from
3185 // the current session.
3186 if close_intent != CloseIntent::Quit
3187 && !save_last_workspace
3188 && save_result.as_ref().is_ok_and(|&res| res)
3189 {
3190 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
3191 .await;
3192 }
3193
3194 save_result
3195 })
3196 }
3197
3198 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
3199 self.save_all_internal(
3200 action.save_intent.unwrap_or(SaveIntent::SaveAll),
3201 window,
3202 cx,
3203 )
3204 .detach_and_log_err(cx);
3205 }
3206
3207 fn send_keystrokes(
3208 &mut self,
3209 action: &SendKeystrokes,
3210 window: &mut Window,
3211 cx: &mut Context<Self>,
3212 ) {
3213 let keystrokes: Vec<Keystroke> = action
3214 .0
3215 .split(' ')
3216 .flat_map(|k| Keystroke::parse(k).log_err())
3217 .map(|k| {
3218 cx.keyboard_mapper()
3219 .map_key_equivalent(k, false)
3220 .inner()
3221 .clone()
3222 })
3223 .collect();
3224 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
3225 }
3226
3227 pub fn send_keystrokes_impl(
3228 &mut self,
3229 keystrokes: Vec<Keystroke>,
3230 window: &mut Window,
3231 cx: &mut Context<Self>,
3232 ) -> Shared<Task<()>> {
3233 let mut state = self.dispatching_keystrokes.borrow_mut();
3234 if !state.dispatched.insert(keystrokes.clone()) {
3235 cx.propagate();
3236 return state.task.clone().unwrap();
3237 }
3238
3239 state.queue.extend(keystrokes);
3240
3241 let keystrokes = self.dispatching_keystrokes.clone();
3242 if state.task.is_none() {
3243 state.task = Some(
3244 window
3245 .spawn(cx, async move |cx| {
3246 // limit to 100 keystrokes to avoid infinite recursion.
3247 for _ in 0..100 {
3248 let keystroke = {
3249 let mut state = keystrokes.borrow_mut();
3250 let Some(keystroke) = state.queue.pop_front() else {
3251 state.dispatched.clear();
3252 state.task.take();
3253 return;
3254 };
3255 keystroke
3256 };
3257 cx.update(|window, cx| {
3258 let focused = window.focused(cx);
3259 window.dispatch_keystroke(keystroke.clone(), cx);
3260 if window.focused(cx) != focused {
3261 // dispatch_keystroke may cause the focus to change.
3262 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3263 // And we need that to happen before the next keystroke to keep vim mode happy...
3264 // (Note that the tests always do this implicitly, so you must manually test with something like:
3265 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3266 // )
3267 window.draw(cx).clear();
3268 }
3269 })
3270 .ok();
3271
3272 // Yield between synthetic keystrokes so deferred focus and
3273 // other effects can settle before dispatching the next key.
3274 yield_now().await;
3275 }
3276
3277 *keystrokes.borrow_mut() = Default::default();
3278 log::error!("over 100 keystrokes passed to send_keystrokes");
3279 })
3280 .shared(),
3281 );
3282 }
3283 state.task.clone().unwrap()
3284 }
3285
3286 fn save_all_internal(
3287 &mut self,
3288 mut save_intent: SaveIntent,
3289 window: &mut Window,
3290 cx: &mut Context<Self>,
3291 ) -> Task<Result<bool>> {
3292 if self.project.read(cx).is_disconnected(cx) {
3293 return Task::ready(Ok(true));
3294 }
3295 let dirty_items = self
3296 .panes
3297 .iter()
3298 .flat_map(|pane| {
3299 pane.read(cx).items().filter_map(|item| {
3300 if item.is_dirty(cx) {
3301 item.tab_content_text(0, cx);
3302 Some((pane.downgrade(), item.boxed_clone()))
3303 } else {
3304 None
3305 }
3306 })
3307 })
3308 .collect::<Vec<_>>();
3309
3310 let project = self.project.clone();
3311 cx.spawn_in(window, async move |workspace, cx| {
3312 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3313 let (serialize_tasks, remaining_dirty_items) =
3314 workspace.update_in(cx, |workspace, window, cx| {
3315 let mut remaining_dirty_items = Vec::new();
3316 let mut serialize_tasks = Vec::new();
3317 for (pane, item) in dirty_items {
3318 if let Some(task) = item
3319 .to_serializable_item_handle(cx)
3320 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3321 {
3322 serialize_tasks.push(task);
3323 } else {
3324 remaining_dirty_items.push((pane, item));
3325 }
3326 }
3327 (serialize_tasks, remaining_dirty_items)
3328 })?;
3329
3330 futures::future::try_join_all(serialize_tasks).await?;
3331
3332 if !remaining_dirty_items.is_empty() {
3333 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3334 }
3335
3336 if remaining_dirty_items.len() > 1 {
3337 let answer = workspace.update_in(cx, |_, window, cx| {
3338 let detail = Pane::file_names_for_prompt(
3339 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3340 cx,
3341 );
3342 window.prompt(
3343 PromptLevel::Warning,
3344 "Do you want to save all changes in the following files?",
3345 Some(&detail),
3346 &["Save all", "Discard all", "Cancel"],
3347 cx,
3348 )
3349 })?;
3350 match answer.await.log_err() {
3351 Some(0) => save_intent = SaveIntent::SaveAll,
3352 Some(1) => save_intent = SaveIntent::Skip,
3353 Some(2) => return Ok(false),
3354 _ => {}
3355 }
3356 }
3357
3358 remaining_dirty_items
3359 } else {
3360 dirty_items
3361 };
3362
3363 for (pane, item) in dirty_items {
3364 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3365 (
3366 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3367 item.project_entry_ids(cx),
3368 )
3369 })?;
3370 if (singleton || !project_entry_ids.is_empty())
3371 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3372 {
3373 return Ok(false);
3374 }
3375 }
3376 Ok(true)
3377 })
3378 }
3379
3380 pub fn open_workspace_for_paths(
3381 &mut self,
3382 // replace_current_window: bool,
3383 mut open_mode: OpenMode,
3384 paths: Vec<PathBuf>,
3385 window: &mut Window,
3386 cx: &mut Context<Self>,
3387 ) -> Task<Result<Entity<Workspace>>> {
3388 let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
3389 let is_remote = self.project.read(cx).is_via_collab();
3390 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3391 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3392
3393 let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
3394 if workspace_is_empty {
3395 open_mode = OpenMode::Replace;
3396 }
3397
3398 let app_state = self.app_state.clone();
3399
3400 cx.spawn(async move |_, cx| {
3401 let OpenResult { workspace, .. } = cx
3402 .update(|cx| {
3403 open_paths(
3404 &paths,
3405 app_state,
3406 OpenOptions {
3407 requesting_window,
3408 open_mode,
3409 ..Default::default()
3410 },
3411 cx,
3412 )
3413 })
3414 .await?;
3415 Ok(workspace)
3416 })
3417 }
3418
3419 #[allow(clippy::type_complexity)]
3420 pub fn open_paths(
3421 &mut self,
3422 mut abs_paths: Vec<PathBuf>,
3423 options: OpenOptions,
3424 pane: Option<WeakEntity<Pane>>,
3425 window: &mut Window,
3426 cx: &mut Context<Self>,
3427 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3428 let fs = self.app_state.fs.clone();
3429
3430 let caller_ordered_abs_paths = abs_paths.clone();
3431
3432 // Sort the paths to ensure we add worktrees for parents before their children.
3433 abs_paths.sort_unstable();
3434 cx.spawn_in(window, async move |this, cx| {
3435 let mut tasks = Vec::with_capacity(abs_paths.len());
3436
3437 for abs_path in &abs_paths {
3438 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3439 OpenVisible::All => Some(true),
3440 OpenVisible::None => Some(false),
3441 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3442 Some(Some(metadata)) => Some(!metadata.is_dir),
3443 Some(None) => Some(true),
3444 None => None,
3445 },
3446 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3447 Some(Some(metadata)) => Some(metadata.is_dir),
3448 Some(None) => Some(false),
3449 None => None,
3450 },
3451 };
3452 let project_path = match visible {
3453 Some(visible) => match this
3454 .update(cx, |this, cx| {
3455 Workspace::project_path_for_path(
3456 this.project.clone(),
3457 abs_path,
3458 visible,
3459 cx,
3460 )
3461 })
3462 .log_err()
3463 {
3464 Some(project_path) => project_path.await.log_err(),
3465 None => None,
3466 },
3467 None => None,
3468 };
3469
3470 let this = this.clone();
3471 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3472 let fs = fs.clone();
3473 let pane = pane.clone();
3474 let task = cx.spawn(async move |cx| {
3475 let (_worktree, project_path) = project_path?;
3476 if fs.is_dir(&abs_path).await {
3477 // Opening a directory should not race to update the active entry.
3478 // We'll select/reveal a deterministic final entry after all paths finish opening.
3479 None
3480 } else {
3481 Some(
3482 this.update_in(cx, |this, window, cx| {
3483 this.open_path(
3484 project_path,
3485 pane,
3486 options.focus.unwrap_or(true),
3487 window,
3488 cx,
3489 )
3490 })
3491 .ok()?
3492 .await,
3493 )
3494 }
3495 });
3496 tasks.push(task);
3497 }
3498
3499 let results = futures::future::join_all(tasks).await;
3500
3501 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3502 let mut winner: Option<(PathBuf, bool)> = None;
3503 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3504 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3505 if !metadata.is_dir {
3506 winner = Some((abs_path, false));
3507 break;
3508 }
3509 if winner.is_none() {
3510 winner = Some((abs_path, true));
3511 }
3512 } else if winner.is_none() {
3513 winner = Some((abs_path, false));
3514 }
3515 }
3516
3517 // Compute the winner entry id on the foreground thread and emit once, after all
3518 // paths finish opening. This avoids races between concurrently-opening paths
3519 // (directories in particular) and makes the resulting project panel selection
3520 // deterministic.
3521 if let Some((winner_abs_path, winner_is_dir)) = winner {
3522 'emit_winner: {
3523 let winner_abs_path: Arc<Path> =
3524 SanitizedPath::new(&winner_abs_path).as_path().into();
3525
3526 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3527 OpenVisible::All => true,
3528 OpenVisible::None => false,
3529 OpenVisible::OnlyFiles => !winner_is_dir,
3530 OpenVisible::OnlyDirectories => winner_is_dir,
3531 };
3532
3533 let Some(worktree_task) = this
3534 .update(cx, |workspace, cx| {
3535 workspace.project.update(cx, |project, cx| {
3536 project.find_or_create_worktree(
3537 winner_abs_path.as_ref(),
3538 visible,
3539 cx,
3540 )
3541 })
3542 })
3543 .ok()
3544 else {
3545 break 'emit_winner;
3546 };
3547
3548 let Ok((worktree, _)) = worktree_task.await else {
3549 break 'emit_winner;
3550 };
3551
3552 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3553 let worktree = worktree.read(cx);
3554 let worktree_abs_path = worktree.abs_path();
3555 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3556 worktree.root_entry()
3557 } else {
3558 winner_abs_path
3559 .strip_prefix(worktree_abs_path.as_ref())
3560 .ok()
3561 .and_then(|relative_path| {
3562 let relative_path =
3563 RelPath::new(relative_path, PathStyle::local())
3564 .log_err()?;
3565 worktree.entry_for_path(&relative_path)
3566 })
3567 }?;
3568 Some(entry.id)
3569 }) else {
3570 break 'emit_winner;
3571 };
3572
3573 this.update(cx, |workspace, cx| {
3574 workspace.project.update(cx, |_, cx| {
3575 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3576 });
3577 })
3578 .ok();
3579 }
3580 }
3581
3582 results
3583 })
3584 }
3585
3586 pub fn open_resolved_path(
3587 &mut self,
3588 path: ResolvedPath,
3589 window: &mut Window,
3590 cx: &mut Context<Self>,
3591 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3592 match path {
3593 ResolvedPath::ProjectPath { project_path, .. } => {
3594 self.open_path(project_path, None, true, window, cx)
3595 }
3596 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3597 PathBuf::from(path),
3598 OpenOptions {
3599 visible: Some(OpenVisible::None),
3600 ..Default::default()
3601 },
3602 window,
3603 cx,
3604 ),
3605 }
3606 }
3607
3608 pub fn absolute_path_of_worktree(
3609 &self,
3610 worktree_id: WorktreeId,
3611 cx: &mut Context<Self>,
3612 ) -> Option<PathBuf> {
3613 self.project
3614 .read(cx)
3615 .worktree_for_id(worktree_id, cx)
3616 // TODO: use `abs_path` or `root_dir`
3617 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3618 }
3619
3620 pub fn add_folder_to_project(
3621 &mut self,
3622 _: &AddFolderToProject,
3623 window: &mut Window,
3624 cx: &mut Context<Self>,
3625 ) {
3626 let project = self.project.read(cx);
3627 if project.is_via_collab() {
3628 self.show_error(
3629 &anyhow!("You cannot add folders to someone else's project"),
3630 cx,
3631 );
3632 return;
3633 }
3634 let paths = self.prompt_for_open_path(
3635 PathPromptOptions {
3636 files: false,
3637 directories: true,
3638 multiple: true,
3639 prompt: None,
3640 },
3641 DirectoryLister::Project(self.project.clone()),
3642 window,
3643 cx,
3644 );
3645 cx.spawn_in(window, async move |this, cx| {
3646 if let Some(paths) = paths.await.log_err().flatten() {
3647 let results = this
3648 .update_in(cx, |this, window, cx| {
3649 this.open_paths(
3650 paths,
3651 OpenOptions {
3652 visible: Some(OpenVisible::All),
3653 ..Default::default()
3654 },
3655 None,
3656 window,
3657 cx,
3658 )
3659 })?
3660 .await;
3661 for result in results.into_iter().flatten() {
3662 result.log_err();
3663 }
3664 }
3665 anyhow::Ok(())
3666 })
3667 .detach_and_log_err(cx);
3668 }
3669
3670 pub fn project_path_for_path(
3671 project: Entity<Project>,
3672 abs_path: &Path,
3673 visible: bool,
3674 cx: &mut App,
3675 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3676 let entry = project.update(cx, |project, cx| {
3677 project.find_or_create_worktree(abs_path, visible, cx)
3678 });
3679 cx.spawn(async move |cx| {
3680 let (worktree, path) = entry.await?;
3681 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3682 Ok((worktree, ProjectPath { worktree_id, path }))
3683 })
3684 }
3685
3686 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3687 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3688 }
3689
3690 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3691 self.items_of_type(cx).max_by_key(|item| item.item_id())
3692 }
3693
3694 pub fn items_of_type<'a, T: Item>(
3695 &'a self,
3696 cx: &'a App,
3697 ) -> impl 'a + Iterator<Item = Entity<T>> {
3698 self.panes
3699 .iter()
3700 .flat_map(|pane| pane.read(cx).items_of_type())
3701 }
3702
3703 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3704 self.active_pane().read(cx).active_item()
3705 }
3706
3707 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3708 let item = self.active_item(cx)?;
3709 item.to_any_view().downcast::<I>().ok()
3710 }
3711
3712 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3713 self.active_item(cx).and_then(|item| item.project_path(cx))
3714 }
3715
3716 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3717 self.recent_navigation_history_iter(cx)
3718 .filter_map(|(path, abs_path)| {
3719 let worktree = self
3720 .project
3721 .read(cx)
3722 .worktree_for_id(path.worktree_id, cx)?;
3723 if worktree.read(cx).is_visible() {
3724 abs_path
3725 } else {
3726 None
3727 }
3728 })
3729 .next()
3730 }
3731
3732 pub fn save_active_item(
3733 &mut self,
3734 save_intent: SaveIntent,
3735 window: &mut Window,
3736 cx: &mut App,
3737 ) -> Task<Result<()>> {
3738 let project = self.project.clone();
3739 let pane = self.active_pane();
3740 let item = pane.read(cx).active_item();
3741 let pane = pane.downgrade();
3742
3743 window.spawn(cx, async move |cx| {
3744 if let Some(item) = item {
3745 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3746 .await
3747 .map(|_| ())
3748 } else {
3749 Ok(())
3750 }
3751 })
3752 }
3753
3754 pub fn close_inactive_items_and_panes(
3755 &mut self,
3756 action: &CloseInactiveTabsAndPanes,
3757 window: &mut Window,
3758 cx: &mut Context<Self>,
3759 ) {
3760 if let Some(task) = self.close_all_internal(
3761 true,
3762 action.save_intent.unwrap_or(SaveIntent::Close),
3763 window,
3764 cx,
3765 ) {
3766 task.detach_and_log_err(cx)
3767 }
3768 }
3769
3770 pub fn close_all_items_and_panes(
3771 &mut self,
3772 action: &CloseAllItemsAndPanes,
3773 window: &mut Window,
3774 cx: &mut Context<Self>,
3775 ) {
3776 if let Some(task) = self.close_all_internal(
3777 false,
3778 action.save_intent.unwrap_or(SaveIntent::Close),
3779 window,
3780 cx,
3781 ) {
3782 task.detach_and_log_err(cx)
3783 }
3784 }
3785
3786 /// Closes the active item across all panes.
3787 pub fn close_item_in_all_panes(
3788 &mut self,
3789 action: &CloseItemInAllPanes,
3790 window: &mut Window,
3791 cx: &mut Context<Self>,
3792 ) {
3793 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3794 return;
3795 };
3796
3797 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3798 let close_pinned = action.close_pinned;
3799
3800 if let Some(project_path) = active_item.project_path(cx) {
3801 self.close_items_with_project_path(
3802 &project_path,
3803 save_intent,
3804 close_pinned,
3805 window,
3806 cx,
3807 );
3808 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3809 let item_id = active_item.item_id();
3810 self.active_pane().update(cx, |pane, cx| {
3811 pane.close_item_by_id(item_id, save_intent, window, cx)
3812 .detach_and_log_err(cx);
3813 });
3814 }
3815 }
3816
3817 /// Closes all items with the given project path across all panes.
3818 pub fn close_items_with_project_path(
3819 &mut self,
3820 project_path: &ProjectPath,
3821 save_intent: SaveIntent,
3822 close_pinned: bool,
3823 window: &mut Window,
3824 cx: &mut Context<Self>,
3825 ) {
3826 let panes = self.panes().to_vec();
3827 for pane in panes {
3828 pane.update(cx, |pane, cx| {
3829 pane.close_items_for_project_path(
3830 project_path,
3831 save_intent,
3832 close_pinned,
3833 window,
3834 cx,
3835 )
3836 .detach_and_log_err(cx);
3837 });
3838 }
3839 }
3840
3841 fn close_all_internal(
3842 &mut self,
3843 retain_active_pane: bool,
3844 save_intent: SaveIntent,
3845 window: &mut Window,
3846 cx: &mut Context<Self>,
3847 ) -> Option<Task<Result<()>>> {
3848 let current_pane = self.active_pane();
3849
3850 let mut tasks = Vec::new();
3851
3852 if retain_active_pane {
3853 let current_pane_close = current_pane.update(cx, |pane, cx| {
3854 pane.close_other_items(
3855 &CloseOtherItems {
3856 save_intent: None,
3857 close_pinned: false,
3858 },
3859 None,
3860 window,
3861 cx,
3862 )
3863 });
3864
3865 tasks.push(current_pane_close);
3866 }
3867
3868 for pane in self.panes() {
3869 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3870 continue;
3871 }
3872
3873 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3874 pane.close_all_items(
3875 &CloseAllItems {
3876 save_intent: Some(save_intent),
3877 close_pinned: false,
3878 },
3879 window,
3880 cx,
3881 )
3882 });
3883
3884 tasks.push(close_pane_items)
3885 }
3886
3887 if tasks.is_empty() {
3888 None
3889 } else {
3890 Some(cx.spawn_in(window, async move |_, _| {
3891 for task in tasks {
3892 task.await?
3893 }
3894 Ok(())
3895 }))
3896 }
3897 }
3898
3899 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3900 self.dock_at_position(position).read(cx).is_open()
3901 }
3902
3903 pub fn toggle_dock(
3904 &mut self,
3905 dock_side: DockPosition,
3906 window: &mut Window,
3907 cx: &mut Context<Self>,
3908 ) {
3909 let mut focus_center = false;
3910 let mut reveal_dock = false;
3911
3912 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3913 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3914
3915 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3916 telemetry::event!(
3917 "Panel Button Clicked",
3918 name = panel.persistent_name(),
3919 toggle_state = !was_visible
3920 );
3921 }
3922 if was_visible {
3923 self.save_open_dock_positions(cx);
3924 }
3925
3926 let dock = self.dock_at_position(dock_side);
3927 dock.update(cx, |dock, cx| {
3928 dock.set_open(!was_visible, window, cx);
3929
3930 if dock.active_panel().is_none() {
3931 let Some(panel_ix) = dock
3932 .first_enabled_panel_idx(cx)
3933 .log_with_level(log::Level::Info)
3934 else {
3935 return;
3936 };
3937 dock.activate_panel(panel_ix, window, cx);
3938 }
3939
3940 if let Some(active_panel) = dock.active_panel() {
3941 if was_visible {
3942 if active_panel
3943 .panel_focus_handle(cx)
3944 .contains_focused(window, cx)
3945 {
3946 focus_center = true;
3947 }
3948 } else {
3949 let focus_handle = &active_panel.panel_focus_handle(cx);
3950 window.focus(focus_handle, cx);
3951 reveal_dock = true;
3952 }
3953 }
3954 });
3955
3956 if reveal_dock {
3957 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3958 }
3959
3960 if focus_center {
3961 self.active_pane
3962 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3963 }
3964
3965 cx.notify();
3966 self.serialize_workspace(window, cx);
3967 }
3968
3969 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3970 self.all_docks().into_iter().find(|&dock| {
3971 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3972 })
3973 }
3974
3975 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3976 if let Some(dock) = self.active_dock(window, cx).cloned() {
3977 self.save_open_dock_positions(cx);
3978 dock.update(cx, |dock, cx| {
3979 dock.set_open(false, window, cx);
3980 });
3981 return true;
3982 }
3983 false
3984 }
3985
3986 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3987 self.save_open_dock_positions(cx);
3988 for dock in self.all_docks() {
3989 dock.update(cx, |dock, cx| {
3990 dock.set_open(false, window, cx);
3991 });
3992 }
3993
3994 cx.focus_self(window);
3995 cx.notify();
3996 self.serialize_workspace(window, cx);
3997 }
3998
3999 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
4000 self.all_docks()
4001 .into_iter()
4002 .filter_map(|dock| {
4003 let dock_ref = dock.read(cx);
4004 if dock_ref.is_open() {
4005 Some(dock_ref.position())
4006 } else {
4007 None
4008 }
4009 })
4010 .collect()
4011 }
4012
4013 /// Saves the positions of currently open docks.
4014 ///
4015 /// Updates `last_open_dock_positions` with positions of all currently open
4016 /// docks, to later be restored by the 'Toggle All Docks' action.
4017 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
4018 let open_dock_positions = self.get_open_dock_positions(cx);
4019 if !open_dock_positions.is_empty() {
4020 self.last_open_dock_positions = open_dock_positions;
4021 }
4022 }
4023
4024 /// Toggles all docks between open and closed states.
4025 ///
4026 /// If any docks are open, closes all and remembers their positions. If all
4027 /// docks are closed, restores the last remembered dock configuration.
4028 fn toggle_all_docks(
4029 &mut self,
4030 _: &ToggleAllDocks,
4031 window: &mut Window,
4032 cx: &mut Context<Self>,
4033 ) {
4034 let open_dock_positions = self.get_open_dock_positions(cx);
4035
4036 if !open_dock_positions.is_empty() {
4037 self.close_all_docks(window, cx);
4038 } else if !self.last_open_dock_positions.is_empty() {
4039 self.restore_last_open_docks(window, cx);
4040 }
4041 }
4042
4043 /// Reopens docks from the most recently remembered configuration.
4044 ///
4045 /// Opens all docks whose positions are stored in `last_open_dock_positions`
4046 /// and clears the stored positions.
4047 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4048 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
4049
4050 for position in positions_to_open {
4051 let dock = self.dock_at_position(position);
4052 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
4053 }
4054
4055 cx.focus_self(window);
4056 cx.notify();
4057 self.serialize_workspace(window, cx);
4058 }
4059
4060 /// Transfer focus to the panel of the given type.
4061 pub fn focus_panel<T: Panel>(
4062 &mut self,
4063 window: &mut Window,
4064 cx: &mut Context<Self>,
4065 ) -> Option<Entity<T>> {
4066 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
4067 panel.to_any().downcast().ok()
4068 }
4069
4070 /// Focus the panel of the given type if it isn't already focused. If it is
4071 /// already focused, then transfer focus back to the workspace center.
4072 /// When the `close_panel_on_toggle` setting is enabled, also closes the
4073 /// panel when transferring focus back to the center.
4074 pub fn toggle_panel_focus<T: Panel>(
4075 &mut self,
4076 window: &mut Window,
4077 cx: &mut Context<Self>,
4078 ) -> bool {
4079 let mut did_focus_panel = false;
4080 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
4081 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
4082 did_focus_panel
4083 });
4084
4085 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
4086 self.close_panel::<T>(window, cx);
4087 }
4088
4089 telemetry::event!(
4090 "Panel Button Clicked",
4091 name = T::persistent_name(),
4092 toggle_state = did_focus_panel
4093 );
4094
4095 did_focus_panel
4096 }
4097
4098 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4099 if let Some(item) = self.active_item(cx) {
4100 item.item_focus_handle(cx).focus(window, cx);
4101 } else {
4102 log::error!("Could not find a focus target when switching focus to the center panes",);
4103 }
4104 }
4105
4106 pub fn activate_panel_for_proto_id(
4107 &mut self,
4108 panel_id: PanelId,
4109 window: &mut Window,
4110 cx: &mut Context<Self>,
4111 ) -> Option<Arc<dyn PanelHandle>> {
4112 let mut panel = None;
4113 for dock in self.all_docks() {
4114 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
4115 panel = dock.update(cx, |dock, cx| {
4116 dock.activate_panel(panel_index, window, cx);
4117 dock.set_open(true, window, cx);
4118 dock.active_panel().cloned()
4119 });
4120 break;
4121 }
4122 }
4123
4124 if panel.is_some() {
4125 cx.notify();
4126 self.serialize_workspace(window, cx);
4127 }
4128
4129 panel
4130 }
4131
4132 /// Focus or unfocus the given panel type, depending on the given callback.
4133 fn focus_or_unfocus_panel<T: Panel>(
4134 &mut self,
4135 window: &mut Window,
4136 cx: &mut Context<Self>,
4137 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
4138 ) -> Option<Arc<dyn PanelHandle>> {
4139 let mut result_panel = None;
4140 let mut serialize = false;
4141 for dock in self.all_docks() {
4142 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4143 let mut focus_center = false;
4144 let panel = dock.update(cx, |dock, cx| {
4145 dock.activate_panel(panel_index, window, cx);
4146
4147 let panel = dock.active_panel().cloned();
4148 if let Some(panel) = panel.as_ref() {
4149 if should_focus(&**panel, window, cx) {
4150 dock.set_open(true, window, cx);
4151 panel.panel_focus_handle(cx).focus(window, cx);
4152 } else {
4153 focus_center = true;
4154 }
4155 }
4156 panel
4157 });
4158
4159 if focus_center {
4160 self.active_pane
4161 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4162 }
4163
4164 result_panel = panel;
4165 serialize = true;
4166 break;
4167 }
4168 }
4169
4170 if serialize {
4171 self.serialize_workspace(window, cx);
4172 }
4173
4174 cx.notify();
4175 result_panel
4176 }
4177
4178 /// Open the panel of the given type
4179 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4180 for dock in self.all_docks() {
4181 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4182 dock.update(cx, |dock, cx| {
4183 dock.activate_panel(panel_index, window, cx);
4184 dock.set_open(true, window, cx);
4185 });
4186 }
4187 }
4188 }
4189
4190 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
4191 for dock in self.all_docks().iter() {
4192 dock.update(cx, |dock, cx| {
4193 if dock.panel::<T>().is_some() {
4194 dock.set_open(false, window, cx)
4195 }
4196 })
4197 }
4198 }
4199
4200 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
4201 self.all_docks()
4202 .iter()
4203 .find_map(|dock| dock.read(cx).panel::<T>())
4204 }
4205
4206 fn dismiss_zoomed_items_to_reveal(
4207 &mut self,
4208 dock_to_reveal: Option<DockPosition>,
4209 window: &mut Window,
4210 cx: &mut Context<Self>,
4211 ) {
4212 // If a center pane is zoomed, unzoom it.
4213 for pane in &self.panes {
4214 if pane != &self.active_pane || dock_to_reveal.is_some() {
4215 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4216 }
4217 }
4218
4219 // If another dock is zoomed, hide it.
4220 let mut focus_center = false;
4221 for dock in self.all_docks() {
4222 dock.update(cx, |dock, cx| {
4223 if Some(dock.position()) != dock_to_reveal
4224 && let Some(panel) = dock.active_panel()
4225 && panel.is_zoomed(window, cx)
4226 {
4227 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
4228 dock.set_open(false, window, cx);
4229 }
4230 });
4231 }
4232
4233 if focus_center {
4234 self.active_pane
4235 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4236 }
4237
4238 if self.zoomed_position != dock_to_reveal {
4239 self.zoomed = None;
4240 self.zoomed_position = None;
4241 cx.emit(Event::ZoomChanged);
4242 }
4243
4244 cx.notify();
4245 }
4246
4247 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4248 let pane = cx.new(|cx| {
4249 let mut pane = Pane::new(
4250 self.weak_handle(),
4251 self.project.clone(),
4252 self.pane_history_timestamp.clone(),
4253 None,
4254 NewFile.boxed_clone(),
4255 true,
4256 window,
4257 cx,
4258 );
4259 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4260 pane
4261 });
4262 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4263 .detach();
4264 self.panes.push(pane.clone());
4265
4266 window.focus(&pane.focus_handle(cx), cx);
4267
4268 cx.emit(Event::PaneAdded(pane.clone()));
4269 pane
4270 }
4271
4272 pub fn add_item_to_center(
4273 &mut self,
4274 item: Box<dyn ItemHandle>,
4275 window: &mut Window,
4276 cx: &mut Context<Self>,
4277 ) -> bool {
4278 if let Some(center_pane) = self.last_active_center_pane.clone() {
4279 if let Some(center_pane) = center_pane.upgrade() {
4280 center_pane.update(cx, |pane, cx| {
4281 pane.add_item(item, true, true, None, window, cx)
4282 });
4283 true
4284 } else {
4285 false
4286 }
4287 } else {
4288 false
4289 }
4290 }
4291
4292 pub fn add_item_to_active_pane(
4293 &mut self,
4294 item: Box<dyn ItemHandle>,
4295 destination_index: Option<usize>,
4296 focus_item: bool,
4297 window: &mut Window,
4298 cx: &mut App,
4299 ) {
4300 self.add_item(
4301 self.active_pane.clone(),
4302 item,
4303 destination_index,
4304 false,
4305 focus_item,
4306 window,
4307 cx,
4308 )
4309 }
4310
4311 pub fn add_item(
4312 &mut self,
4313 pane: Entity<Pane>,
4314 item: Box<dyn ItemHandle>,
4315 destination_index: Option<usize>,
4316 activate_pane: bool,
4317 focus_item: bool,
4318 window: &mut Window,
4319 cx: &mut App,
4320 ) {
4321 pane.update(cx, |pane, cx| {
4322 pane.add_item(
4323 item,
4324 activate_pane,
4325 focus_item,
4326 destination_index,
4327 window,
4328 cx,
4329 )
4330 });
4331 }
4332
4333 pub fn split_item(
4334 &mut self,
4335 split_direction: SplitDirection,
4336 item: Box<dyn ItemHandle>,
4337 window: &mut Window,
4338 cx: &mut Context<Self>,
4339 ) {
4340 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4341 self.add_item(new_pane, item, None, true, true, window, cx);
4342 }
4343
4344 pub fn open_abs_path(
4345 &mut self,
4346 abs_path: PathBuf,
4347 options: OpenOptions,
4348 window: &mut Window,
4349 cx: &mut Context<Self>,
4350 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4351 cx.spawn_in(window, async move |workspace, cx| {
4352 let open_paths_task_result = workspace
4353 .update_in(cx, |workspace, window, cx| {
4354 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4355 })
4356 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4357 .await;
4358 anyhow::ensure!(
4359 open_paths_task_result.len() == 1,
4360 "open abs path {abs_path:?} task returned incorrect number of results"
4361 );
4362 match open_paths_task_result
4363 .into_iter()
4364 .next()
4365 .expect("ensured single task result")
4366 {
4367 Some(open_result) => {
4368 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4369 }
4370 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4371 }
4372 })
4373 }
4374
4375 pub fn split_abs_path(
4376 &mut self,
4377 abs_path: PathBuf,
4378 visible: bool,
4379 window: &mut Window,
4380 cx: &mut Context<Self>,
4381 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4382 let project_path_task =
4383 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4384 cx.spawn_in(window, async move |this, cx| {
4385 let (_, path) = project_path_task.await?;
4386 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4387 .await
4388 })
4389 }
4390
4391 pub fn open_path(
4392 &mut self,
4393 path: impl Into<ProjectPath>,
4394 pane: Option<WeakEntity<Pane>>,
4395 focus_item: bool,
4396 window: &mut Window,
4397 cx: &mut App,
4398 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4399 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4400 }
4401
4402 pub fn open_path_preview(
4403 &mut self,
4404 path: impl Into<ProjectPath>,
4405 pane: Option<WeakEntity<Pane>>,
4406 focus_item: bool,
4407 allow_preview: bool,
4408 activate: bool,
4409 window: &mut Window,
4410 cx: &mut App,
4411 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4412 let pane = pane.unwrap_or_else(|| {
4413 self.last_active_center_pane.clone().unwrap_or_else(|| {
4414 self.panes
4415 .first()
4416 .expect("There must be an active pane")
4417 .downgrade()
4418 })
4419 });
4420
4421 let project_path = path.into();
4422 let task = self.load_path(project_path.clone(), window, cx);
4423 window.spawn(cx, async move |cx| {
4424 let (project_entry_id, build_item) = task.await?;
4425
4426 pane.update_in(cx, |pane, window, cx| {
4427 pane.open_item(
4428 project_entry_id,
4429 project_path,
4430 focus_item,
4431 allow_preview,
4432 activate,
4433 None,
4434 window,
4435 cx,
4436 build_item,
4437 )
4438 })
4439 })
4440 }
4441
4442 pub fn split_path(
4443 &mut self,
4444 path: impl Into<ProjectPath>,
4445 window: &mut Window,
4446 cx: &mut Context<Self>,
4447 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4448 self.split_path_preview(path, false, None, window, cx)
4449 }
4450
4451 pub fn split_path_preview(
4452 &mut self,
4453 path: impl Into<ProjectPath>,
4454 allow_preview: bool,
4455 split_direction: Option<SplitDirection>,
4456 window: &mut Window,
4457 cx: &mut Context<Self>,
4458 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4459 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4460 self.panes
4461 .first()
4462 .expect("There must be an active pane")
4463 .downgrade()
4464 });
4465
4466 if let Member::Pane(center_pane) = &self.center.root
4467 && center_pane.read(cx).items_len() == 0
4468 {
4469 return self.open_path(path, Some(pane), true, window, cx);
4470 }
4471
4472 let project_path = path.into();
4473 let task = self.load_path(project_path.clone(), window, cx);
4474 cx.spawn_in(window, async move |this, cx| {
4475 let (project_entry_id, build_item) = task.await?;
4476 this.update_in(cx, move |this, window, cx| -> Option<_> {
4477 let pane = pane.upgrade()?;
4478 let new_pane = this.split_pane(
4479 pane,
4480 split_direction.unwrap_or(SplitDirection::Right),
4481 window,
4482 cx,
4483 );
4484 new_pane.update(cx, |new_pane, cx| {
4485 Some(new_pane.open_item(
4486 project_entry_id,
4487 project_path,
4488 true,
4489 allow_preview,
4490 true,
4491 None,
4492 window,
4493 cx,
4494 build_item,
4495 ))
4496 })
4497 })
4498 .map(|option| option.context("pane was dropped"))?
4499 })
4500 }
4501
4502 fn load_path(
4503 &mut self,
4504 path: ProjectPath,
4505 window: &mut Window,
4506 cx: &mut App,
4507 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4508 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4509 registry.open_path(self.project(), &path, window, cx)
4510 }
4511
4512 pub fn find_project_item<T>(
4513 &self,
4514 pane: &Entity<Pane>,
4515 project_item: &Entity<T::Item>,
4516 cx: &App,
4517 ) -> Option<Entity<T>>
4518 where
4519 T: ProjectItem,
4520 {
4521 use project::ProjectItem as _;
4522 let project_item = project_item.read(cx);
4523 let entry_id = project_item.entry_id(cx);
4524 let project_path = project_item.project_path(cx);
4525
4526 let mut item = None;
4527 if let Some(entry_id) = entry_id {
4528 item = pane.read(cx).item_for_entry(entry_id, cx);
4529 }
4530 if item.is_none()
4531 && let Some(project_path) = project_path
4532 {
4533 item = pane.read(cx).item_for_path(project_path, cx);
4534 }
4535
4536 item.and_then(|item| item.downcast::<T>())
4537 }
4538
4539 pub fn is_project_item_open<T>(
4540 &self,
4541 pane: &Entity<Pane>,
4542 project_item: &Entity<T::Item>,
4543 cx: &App,
4544 ) -> bool
4545 where
4546 T: ProjectItem,
4547 {
4548 self.find_project_item::<T>(pane, project_item, cx)
4549 .is_some()
4550 }
4551
4552 pub fn open_project_item<T>(
4553 &mut self,
4554 pane: Entity<Pane>,
4555 project_item: Entity<T::Item>,
4556 activate_pane: bool,
4557 focus_item: bool,
4558 keep_old_preview: bool,
4559 allow_new_preview: bool,
4560 window: &mut Window,
4561 cx: &mut Context<Self>,
4562 ) -> Entity<T>
4563 where
4564 T: ProjectItem,
4565 {
4566 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4567
4568 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4569 if !keep_old_preview
4570 && let Some(old_id) = old_item_id
4571 && old_id != item.item_id()
4572 {
4573 // switching to a different item, so unpreview old active item
4574 pane.update(cx, |pane, _| {
4575 pane.unpreview_item_if_preview(old_id);
4576 });
4577 }
4578
4579 self.activate_item(&item, activate_pane, focus_item, window, cx);
4580 if !allow_new_preview {
4581 pane.update(cx, |pane, _| {
4582 pane.unpreview_item_if_preview(item.item_id());
4583 });
4584 }
4585 return item;
4586 }
4587
4588 let item = pane.update(cx, |pane, cx| {
4589 cx.new(|cx| {
4590 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4591 })
4592 });
4593 let mut destination_index = None;
4594 pane.update(cx, |pane, cx| {
4595 if !keep_old_preview && let Some(old_id) = old_item_id {
4596 pane.unpreview_item_if_preview(old_id);
4597 }
4598 if allow_new_preview {
4599 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4600 }
4601 });
4602
4603 self.add_item(
4604 pane,
4605 Box::new(item.clone()),
4606 destination_index,
4607 activate_pane,
4608 focus_item,
4609 window,
4610 cx,
4611 );
4612 item
4613 }
4614
4615 pub fn open_shared_screen(
4616 &mut self,
4617 peer_id: PeerId,
4618 window: &mut Window,
4619 cx: &mut Context<Self>,
4620 ) {
4621 if let Some(shared_screen) =
4622 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4623 {
4624 self.active_pane.update(cx, |pane, cx| {
4625 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4626 });
4627 }
4628 }
4629
4630 pub fn activate_item(
4631 &mut self,
4632 item: &dyn ItemHandle,
4633 activate_pane: bool,
4634 focus_item: bool,
4635 window: &mut Window,
4636 cx: &mut App,
4637 ) -> bool {
4638 let result = self.panes.iter().find_map(|pane| {
4639 pane.read(cx)
4640 .index_for_item(item)
4641 .map(|ix| (pane.clone(), ix))
4642 });
4643 if let Some((pane, ix)) = result {
4644 pane.update(cx, |pane, cx| {
4645 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4646 });
4647 true
4648 } else {
4649 false
4650 }
4651 }
4652
4653 fn activate_pane_at_index(
4654 &mut self,
4655 action: &ActivatePane,
4656 window: &mut Window,
4657 cx: &mut Context<Self>,
4658 ) {
4659 let panes = self.center.panes();
4660 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4661 window.focus(&pane.focus_handle(cx), cx);
4662 } else {
4663 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4664 .detach();
4665 }
4666 }
4667
4668 fn move_item_to_pane_at_index(
4669 &mut self,
4670 action: &MoveItemToPane,
4671 window: &mut Window,
4672 cx: &mut Context<Self>,
4673 ) {
4674 let panes = self.center.panes();
4675 let destination = match panes.get(action.destination) {
4676 Some(&destination) => destination.clone(),
4677 None => {
4678 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4679 return;
4680 }
4681 let direction = SplitDirection::Right;
4682 let split_off_pane = self
4683 .find_pane_in_direction(direction, cx)
4684 .unwrap_or_else(|| self.active_pane.clone());
4685 let new_pane = self.add_pane(window, cx);
4686 self.center.split(&split_off_pane, &new_pane, direction, cx);
4687 new_pane
4688 }
4689 };
4690
4691 if action.clone {
4692 if self
4693 .active_pane
4694 .read(cx)
4695 .active_item()
4696 .is_some_and(|item| item.can_split(cx))
4697 {
4698 clone_active_item(
4699 self.database_id(),
4700 &self.active_pane,
4701 &destination,
4702 action.focus,
4703 window,
4704 cx,
4705 );
4706 return;
4707 }
4708 }
4709 move_active_item(
4710 &self.active_pane,
4711 &destination,
4712 action.focus,
4713 true,
4714 window,
4715 cx,
4716 )
4717 }
4718
4719 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4720 let panes = self.center.panes();
4721 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4722 let next_ix = (ix + 1) % panes.len();
4723 let next_pane = panes[next_ix].clone();
4724 window.focus(&next_pane.focus_handle(cx), cx);
4725 }
4726 }
4727
4728 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4729 let panes = self.center.panes();
4730 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4731 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4732 let prev_pane = panes[prev_ix].clone();
4733 window.focus(&prev_pane.focus_handle(cx), cx);
4734 }
4735 }
4736
4737 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4738 let last_pane = self.center.last_pane();
4739 window.focus(&last_pane.focus_handle(cx), cx);
4740 }
4741
4742 pub fn activate_pane_in_direction(
4743 &mut self,
4744 direction: SplitDirection,
4745 window: &mut Window,
4746 cx: &mut App,
4747 ) {
4748 use ActivateInDirectionTarget as Target;
4749 enum Origin {
4750 Sidebar,
4751 LeftDock,
4752 RightDock,
4753 BottomDock,
4754 Center,
4755 }
4756
4757 let origin: Origin = if self
4758 .sidebar_focus_handle
4759 .as_ref()
4760 .is_some_and(|h| h.contains_focused(window, cx))
4761 {
4762 Origin::Sidebar
4763 } else {
4764 [
4765 (&self.left_dock, Origin::LeftDock),
4766 (&self.right_dock, Origin::RightDock),
4767 (&self.bottom_dock, Origin::BottomDock),
4768 ]
4769 .into_iter()
4770 .find_map(|(dock, origin)| {
4771 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4772 Some(origin)
4773 } else {
4774 None
4775 }
4776 })
4777 .unwrap_or(Origin::Center)
4778 };
4779
4780 let get_last_active_pane = || {
4781 let pane = self
4782 .last_active_center_pane
4783 .clone()
4784 .unwrap_or_else(|| {
4785 self.panes
4786 .first()
4787 .expect("There must be an active pane")
4788 .downgrade()
4789 })
4790 .upgrade()?;
4791 (pane.read(cx).items_len() != 0).then_some(pane)
4792 };
4793
4794 let try_dock =
4795 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4796
4797 let sidebar_target = self
4798 .sidebar_focus_handle
4799 .as_ref()
4800 .map(|h| Target::Sidebar(h.clone()));
4801
4802 let target = match (origin, direction) {
4803 // From the sidebar, only Right navigates into the workspace.
4804 (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
4805 .or_else(|| get_last_active_pane().map(Target::Pane))
4806 .or_else(|| try_dock(&self.bottom_dock))
4807 .or_else(|| try_dock(&self.right_dock)),
4808
4809 (Origin::Sidebar, _) => None,
4810
4811 // We're in the center, so we first try to go to a different pane,
4812 // otherwise try to go to a dock.
4813 (Origin::Center, direction) => {
4814 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4815 Some(Target::Pane(pane))
4816 } else {
4817 match direction {
4818 SplitDirection::Up => None,
4819 SplitDirection::Down => try_dock(&self.bottom_dock),
4820 SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
4821 SplitDirection::Right => try_dock(&self.right_dock),
4822 }
4823 }
4824 }
4825
4826 (Origin::LeftDock, SplitDirection::Right) => {
4827 if let Some(last_active_pane) = get_last_active_pane() {
4828 Some(Target::Pane(last_active_pane))
4829 } else {
4830 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4831 }
4832 }
4833
4834 (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
4835
4836 (Origin::LeftDock, SplitDirection::Down)
4837 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4838
4839 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4840 (Origin::BottomDock, SplitDirection::Left) => {
4841 try_dock(&self.left_dock).or(sidebar_target)
4842 }
4843 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4844
4845 (Origin::RightDock, SplitDirection::Left) => {
4846 if let Some(last_active_pane) = get_last_active_pane() {
4847 Some(Target::Pane(last_active_pane))
4848 } else {
4849 try_dock(&self.bottom_dock)
4850 .or_else(|| try_dock(&self.left_dock))
4851 .or(sidebar_target)
4852 }
4853 }
4854
4855 _ => None,
4856 };
4857
4858 match target {
4859 Some(ActivateInDirectionTarget::Pane(pane)) => {
4860 let pane = pane.read(cx);
4861 if let Some(item) = pane.active_item() {
4862 item.item_focus_handle(cx).focus(window, cx);
4863 } else {
4864 log::error!(
4865 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4866 );
4867 }
4868 }
4869 Some(ActivateInDirectionTarget::Dock(dock)) => {
4870 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4871 window.defer(cx, move |window, cx| {
4872 let dock = dock.read(cx);
4873 if let Some(panel) = dock.active_panel() {
4874 panel.panel_focus_handle(cx).focus(window, cx);
4875 } else {
4876 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4877 }
4878 })
4879 }
4880 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4881 focus_handle.focus(window, cx);
4882 }
4883 None => {}
4884 }
4885 }
4886
4887 pub fn move_item_to_pane_in_direction(
4888 &mut self,
4889 action: &MoveItemToPaneInDirection,
4890 window: &mut Window,
4891 cx: &mut Context<Self>,
4892 ) {
4893 let destination = match self.find_pane_in_direction(action.direction, cx) {
4894 Some(destination) => destination,
4895 None => {
4896 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4897 return;
4898 }
4899 let new_pane = self.add_pane(window, cx);
4900 self.center
4901 .split(&self.active_pane, &new_pane, action.direction, cx);
4902 new_pane
4903 }
4904 };
4905
4906 if action.clone {
4907 if self
4908 .active_pane
4909 .read(cx)
4910 .active_item()
4911 .is_some_and(|item| item.can_split(cx))
4912 {
4913 clone_active_item(
4914 self.database_id(),
4915 &self.active_pane,
4916 &destination,
4917 action.focus,
4918 window,
4919 cx,
4920 );
4921 return;
4922 }
4923 }
4924 move_active_item(
4925 &self.active_pane,
4926 &destination,
4927 action.focus,
4928 true,
4929 window,
4930 cx,
4931 );
4932 }
4933
4934 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4935 self.center.bounding_box_for_pane(pane)
4936 }
4937
4938 pub fn find_pane_in_direction(
4939 &mut self,
4940 direction: SplitDirection,
4941 cx: &App,
4942 ) -> Option<Entity<Pane>> {
4943 self.center
4944 .find_pane_in_direction(&self.active_pane, direction, cx)
4945 .cloned()
4946 }
4947
4948 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4949 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4950 self.center.swap(&self.active_pane, &to, cx);
4951 cx.notify();
4952 }
4953 }
4954
4955 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4956 if self
4957 .center
4958 .move_to_border(&self.active_pane, direction, cx)
4959 .unwrap()
4960 {
4961 cx.notify();
4962 }
4963 }
4964
4965 pub fn resize_pane(
4966 &mut self,
4967 axis: gpui::Axis,
4968 amount: Pixels,
4969 window: &mut Window,
4970 cx: &mut Context<Self>,
4971 ) {
4972 let docks = self.all_docks();
4973 let active_dock = docks
4974 .into_iter()
4975 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4976
4977 if let Some(dock_entity) = active_dock {
4978 let dock = dock_entity.read(cx);
4979 let Some(panel_size) = self.dock_size(&dock, window, cx) else {
4980 return;
4981 };
4982 match dock.position() {
4983 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4984 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4985 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4986 }
4987 } else {
4988 self.center
4989 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4990 }
4991 cx.notify();
4992 }
4993
4994 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4995 self.center.reset_pane_sizes(cx);
4996 cx.notify();
4997 }
4998
4999 fn handle_pane_focused(
5000 &mut self,
5001 pane: Entity<Pane>,
5002 window: &mut Window,
5003 cx: &mut Context<Self>,
5004 ) {
5005 // This is explicitly hoisted out of the following check for pane identity as
5006 // terminal panel panes are not registered as a center panes.
5007 self.status_bar.update(cx, |status_bar, cx| {
5008 status_bar.set_active_pane(&pane, window, cx);
5009 });
5010 if self.active_pane != pane {
5011 self.set_active_pane(&pane, window, cx);
5012 }
5013
5014 if self.last_active_center_pane.is_none() {
5015 self.last_active_center_pane = Some(pane.downgrade());
5016 }
5017
5018 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
5019 // This prevents the dock from closing when focus events fire during window activation.
5020 // We also preserve any dock whose active panel itself has focus — this covers
5021 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
5022 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
5023 let dock_read = dock.read(cx);
5024 if let Some(panel) = dock_read.active_panel() {
5025 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
5026 || panel.panel_focus_handle(cx).contains_focused(window, cx)
5027 {
5028 return Some(dock_read.position());
5029 }
5030 }
5031 None
5032 });
5033
5034 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
5035 if pane.read(cx).is_zoomed() {
5036 self.zoomed = Some(pane.downgrade().into());
5037 } else {
5038 self.zoomed = None;
5039 }
5040 self.zoomed_position = None;
5041 cx.emit(Event::ZoomChanged);
5042 self.update_active_view_for_followers(window, cx);
5043 pane.update(cx, |pane, _| {
5044 pane.track_alternate_file_items();
5045 });
5046
5047 cx.notify();
5048 }
5049
5050 fn set_active_pane(
5051 &mut self,
5052 pane: &Entity<Pane>,
5053 window: &mut Window,
5054 cx: &mut Context<Self>,
5055 ) {
5056 self.active_pane = pane.clone();
5057 self.active_item_path_changed(true, window, cx);
5058 self.last_active_center_pane = Some(pane.downgrade());
5059 }
5060
5061 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5062 self.update_active_view_for_followers(window, cx);
5063 }
5064
5065 fn handle_pane_event(
5066 &mut self,
5067 pane: &Entity<Pane>,
5068 event: &pane::Event,
5069 window: &mut Window,
5070 cx: &mut Context<Self>,
5071 ) {
5072 let mut serialize_workspace = true;
5073 match event {
5074 pane::Event::AddItem { item } => {
5075 item.added_to_pane(self, pane.clone(), window, cx);
5076 cx.emit(Event::ItemAdded {
5077 item: item.boxed_clone(),
5078 });
5079 }
5080 pane::Event::Split { direction, mode } => {
5081 match mode {
5082 SplitMode::ClonePane => {
5083 self.split_and_clone(pane.clone(), *direction, window, cx)
5084 .detach();
5085 }
5086 SplitMode::EmptyPane => {
5087 self.split_pane(pane.clone(), *direction, window, cx);
5088 }
5089 SplitMode::MovePane => {
5090 self.split_and_move(pane.clone(), *direction, window, cx);
5091 }
5092 };
5093 }
5094 pane::Event::JoinIntoNext => {
5095 self.join_pane_into_next(pane.clone(), window, cx);
5096 }
5097 pane::Event::JoinAll => {
5098 self.join_all_panes(window, cx);
5099 }
5100 pane::Event::Remove { focus_on_pane } => {
5101 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
5102 }
5103 pane::Event::ActivateItem {
5104 local,
5105 focus_changed,
5106 } => {
5107 window.invalidate_character_coordinates();
5108
5109 pane.update(cx, |pane, _| {
5110 pane.track_alternate_file_items();
5111 });
5112 if *local {
5113 self.unfollow_in_pane(pane, window, cx);
5114 }
5115 serialize_workspace = *focus_changed || pane != self.active_pane();
5116 if pane == self.active_pane() {
5117 self.active_item_path_changed(*focus_changed, window, cx);
5118 self.update_active_view_for_followers(window, cx);
5119 } else if *local {
5120 self.set_active_pane(pane, window, cx);
5121 }
5122 }
5123 pane::Event::UserSavedItem { item, save_intent } => {
5124 cx.emit(Event::UserSavedItem {
5125 pane: pane.downgrade(),
5126 item: item.boxed_clone(),
5127 save_intent: *save_intent,
5128 });
5129 serialize_workspace = false;
5130 }
5131 pane::Event::ChangeItemTitle => {
5132 if *pane == self.active_pane {
5133 self.active_item_path_changed(false, window, cx);
5134 }
5135 serialize_workspace = false;
5136 }
5137 pane::Event::RemovedItem { item } => {
5138 cx.emit(Event::ActiveItemChanged);
5139 self.update_window_edited(window, cx);
5140 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
5141 && entry.get().entity_id() == pane.entity_id()
5142 {
5143 entry.remove();
5144 }
5145 cx.emit(Event::ItemRemoved {
5146 item_id: item.item_id(),
5147 });
5148 }
5149 pane::Event::Focus => {
5150 window.invalidate_character_coordinates();
5151 self.handle_pane_focused(pane.clone(), window, cx);
5152 }
5153 pane::Event::ZoomIn => {
5154 if *pane == self.active_pane {
5155 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
5156 if pane.read(cx).has_focus(window, cx) {
5157 self.zoomed = Some(pane.downgrade().into());
5158 self.zoomed_position = None;
5159 cx.emit(Event::ZoomChanged);
5160 }
5161 cx.notify();
5162 }
5163 }
5164 pane::Event::ZoomOut => {
5165 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
5166 if self.zoomed_position.is_none() {
5167 self.zoomed = None;
5168 cx.emit(Event::ZoomChanged);
5169 }
5170 cx.notify();
5171 }
5172 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
5173 }
5174
5175 if serialize_workspace {
5176 self.serialize_workspace(window, cx);
5177 }
5178 }
5179
5180 pub fn unfollow_in_pane(
5181 &mut self,
5182 pane: &Entity<Pane>,
5183 window: &mut Window,
5184 cx: &mut Context<Workspace>,
5185 ) -> Option<CollaboratorId> {
5186 let leader_id = self.leader_for_pane(pane)?;
5187 self.unfollow(leader_id, window, cx);
5188 Some(leader_id)
5189 }
5190
5191 pub fn split_pane(
5192 &mut self,
5193 pane_to_split: Entity<Pane>,
5194 split_direction: SplitDirection,
5195 window: &mut Window,
5196 cx: &mut Context<Self>,
5197 ) -> Entity<Pane> {
5198 let new_pane = self.add_pane(window, cx);
5199 self.center
5200 .split(&pane_to_split, &new_pane, split_direction, cx);
5201 cx.notify();
5202 new_pane
5203 }
5204
5205 pub fn split_and_move(
5206 &mut self,
5207 pane: Entity<Pane>,
5208 direction: SplitDirection,
5209 window: &mut Window,
5210 cx: &mut Context<Self>,
5211 ) {
5212 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
5213 return;
5214 };
5215 let new_pane = self.add_pane(window, cx);
5216 new_pane.update(cx, |pane, cx| {
5217 pane.add_item(item, true, true, None, window, cx)
5218 });
5219 self.center.split(&pane, &new_pane, direction, cx);
5220 cx.notify();
5221 }
5222
5223 pub fn split_and_clone(
5224 &mut self,
5225 pane: Entity<Pane>,
5226 direction: SplitDirection,
5227 window: &mut Window,
5228 cx: &mut Context<Self>,
5229 ) -> Task<Option<Entity<Pane>>> {
5230 let Some(item) = pane.read(cx).active_item() else {
5231 return Task::ready(None);
5232 };
5233 if !item.can_split(cx) {
5234 return Task::ready(None);
5235 }
5236 let task = item.clone_on_split(self.database_id(), window, cx);
5237 cx.spawn_in(window, async move |this, cx| {
5238 if let Some(clone) = task.await {
5239 this.update_in(cx, |this, window, cx| {
5240 let new_pane = this.add_pane(window, cx);
5241 let nav_history = pane.read(cx).fork_nav_history();
5242 new_pane.update(cx, |pane, cx| {
5243 pane.set_nav_history(nav_history, cx);
5244 pane.add_item(clone, true, true, None, window, cx)
5245 });
5246 this.center.split(&pane, &new_pane, direction, cx);
5247 cx.notify();
5248 new_pane
5249 })
5250 .ok()
5251 } else {
5252 None
5253 }
5254 })
5255 }
5256
5257 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5258 let active_item = self.active_pane.read(cx).active_item();
5259 for pane in &self.panes {
5260 join_pane_into_active(&self.active_pane, pane, window, cx);
5261 }
5262 if let Some(active_item) = active_item {
5263 self.activate_item(active_item.as_ref(), true, true, window, cx);
5264 }
5265 cx.notify();
5266 }
5267
5268 pub fn join_pane_into_next(
5269 &mut self,
5270 pane: Entity<Pane>,
5271 window: &mut Window,
5272 cx: &mut Context<Self>,
5273 ) {
5274 let next_pane = self
5275 .find_pane_in_direction(SplitDirection::Right, cx)
5276 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5277 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5278 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5279 let Some(next_pane) = next_pane else {
5280 return;
5281 };
5282 move_all_items(&pane, &next_pane, window, cx);
5283 cx.notify();
5284 }
5285
5286 fn remove_pane(
5287 &mut self,
5288 pane: Entity<Pane>,
5289 focus_on: Option<Entity<Pane>>,
5290 window: &mut Window,
5291 cx: &mut Context<Self>,
5292 ) {
5293 if self.center.remove(&pane, cx).unwrap() {
5294 self.force_remove_pane(&pane, &focus_on, window, cx);
5295 self.unfollow_in_pane(&pane, window, cx);
5296 self.last_leaders_by_pane.remove(&pane.downgrade());
5297 for removed_item in pane.read(cx).items() {
5298 self.panes_by_item.remove(&removed_item.item_id());
5299 }
5300
5301 cx.notify();
5302 } else {
5303 self.active_item_path_changed(true, window, cx);
5304 }
5305 cx.emit(Event::PaneRemoved);
5306 }
5307
5308 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5309 &mut self.panes
5310 }
5311
5312 pub fn panes(&self) -> &[Entity<Pane>] {
5313 &self.panes
5314 }
5315
5316 pub fn active_pane(&self) -> &Entity<Pane> {
5317 &self.active_pane
5318 }
5319
5320 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5321 for dock in self.all_docks() {
5322 if dock.focus_handle(cx).contains_focused(window, cx)
5323 && let Some(pane) = dock
5324 .read(cx)
5325 .active_panel()
5326 .and_then(|panel| panel.pane(cx))
5327 {
5328 return pane;
5329 }
5330 }
5331 self.active_pane().clone()
5332 }
5333
5334 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5335 self.find_pane_in_direction(SplitDirection::Right, cx)
5336 .unwrap_or_else(|| {
5337 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5338 })
5339 }
5340
5341 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5342 self.pane_for_item_id(handle.item_id())
5343 }
5344
5345 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5346 let weak_pane = self.panes_by_item.get(&item_id)?;
5347 weak_pane.upgrade()
5348 }
5349
5350 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5351 self.panes
5352 .iter()
5353 .find(|pane| pane.entity_id() == entity_id)
5354 .cloned()
5355 }
5356
5357 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5358 self.follower_states.retain(|leader_id, state| {
5359 if *leader_id == CollaboratorId::PeerId(peer_id) {
5360 for item in state.items_by_leader_view_id.values() {
5361 item.view.set_leader_id(None, window, cx);
5362 }
5363 false
5364 } else {
5365 true
5366 }
5367 });
5368 cx.notify();
5369 }
5370
5371 pub fn start_following(
5372 &mut self,
5373 leader_id: impl Into<CollaboratorId>,
5374 window: &mut Window,
5375 cx: &mut Context<Self>,
5376 ) -> Option<Task<Result<()>>> {
5377 let leader_id = leader_id.into();
5378 let pane = self.active_pane().clone();
5379
5380 self.last_leaders_by_pane
5381 .insert(pane.downgrade(), leader_id);
5382 self.unfollow(leader_id, window, cx);
5383 self.unfollow_in_pane(&pane, window, cx);
5384 self.follower_states.insert(
5385 leader_id,
5386 FollowerState {
5387 center_pane: pane.clone(),
5388 dock_pane: None,
5389 active_view_id: None,
5390 items_by_leader_view_id: Default::default(),
5391 },
5392 );
5393 cx.notify();
5394
5395 match leader_id {
5396 CollaboratorId::PeerId(leader_peer_id) => {
5397 let room_id = self.active_call()?.room_id(cx)?;
5398 let project_id = self.project.read(cx).remote_id();
5399 let request = self.app_state.client.request(proto::Follow {
5400 room_id,
5401 project_id,
5402 leader_id: Some(leader_peer_id),
5403 });
5404
5405 Some(cx.spawn_in(window, async move |this, cx| {
5406 let response = request.await?;
5407 this.update(cx, |this, _| {
5408 let state = this
5409 .follower_states
5410 .get_mut(&leader_id)
5411 .context("following interrupted")?;
5412 state.active_view_id = response
5413 .active_view
5414 .as_ref()
5415 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5416 anyhow::Ok(())
5417 })??;
5418 if let Some(view) = response.active_view {
5419 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5420 }
5421 this.update_in(cx, |this, window, cx| {
5422 this.leader_updated(leader_id, window, cx)
5423 })?;
5424 Ok(())
5425 }))
5426 }
5427 CollaboratorId::Agent => {
5428 self.leader_updated(leader_id, window, cx)?;
5429 Some(Task::ready(Ok(())))
5430 }
5431 }
5432 }
5433
5434 pub fn follow_next_collaborator(
5435 &mut self,
5436 _: &FollowNextCollaborator,
5437 window: &mut Window,
5438 cx: &mut Context<Self>,
5439 ) {
5440 let collaborators = self.project.read(cx).collaborators();
5441 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5442 let mut collaborators = collaborators.keys().copied();
5443 for peer_id in collaborators.by_ref() {
5444 if CollaboratorId::PeerId(peer_id) == leader_id {
5445 break;
5446 }
5447 }
5448 collaborators.next().map(CollaboratorId::PeerId)
5449 } else if let Some(last_leader_id) =
5450 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5451 {
5452 match last_leader_id {
5453 CollaboratorId::PeerId(peer_id) => {
5454 if collaborators.contains_key(peer_id) {
5455 Some(*last_leader_id)
5456 } else {
5457 None
5458 }
5459 }
5460 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5461 }
5462 } else {
5463 None
5464 };
5465
5466 let pane = self.active_pane.clone();
5467 let Some(leader_id) = next_leader_id.or_else(|| {
5468 Some(CollaboratorId::PeerId(
5469 collaborators.keys().copied().next()?,
5470 ))
5471 }) else {
5472 return;
5473 };
5474 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5475 return;
5476 }
5477 if let Some(task) = self.start_following(leader_id, window, cx) {
5478 task.detach_and_log_err(cx)
5479 }
5480 }
5481
5482 pub fn follow(
5483 &mut self,
5484 leader_id: impl Into<CollaboratorId>,
5485 window: &mut Window,
5486 cx: &mut Context<Self>,
5487 ) {
5488 let leader_id = leader_id.into();
5489
5490 if let CollaboratorId::PeerId(peer_id) = leader_id {
5491 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5492 return;
5493 };
5494 let Some(remote_participant) =
5495 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5496 else {
5497 return;
5498 };
5499
5500 let project = self.project.read(cx);
5501
5502 let other_project_id = match remote_participant.location {
5503 ParticipantLocation::External => None,
5504 ParticipantLocation::UnsharedProject => None,
5505 ParticipantLocation::SharedProject { project_id } => {
5506 if Some(project_id) == project.remote_id() {
5507 None
5508 } else {
5509 Some(project_id)
5510 }
5511 }
5512 };
5513
5514 // if they are active in another project, follow there.
5515 if let Some(project_id) = other_project_id {
5516 let app_state = self.app_state.clone();
5517 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5518 .detach_and_log_err(cx);
5519 }
5520 }
5521
5522 // if you're already following, find the right pane and focus it.
5523 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5524 window.focus(&follower_state.pane().focus_handle(cx), cx);
5525
5526 return;
5527 }
5528
5529 // Otherwise, follow.
5530 if let Some(task) = self.start_following(leader_id, window, cx) {
5531 task.detach_and_log_err(cx)
5532 }
5533 }
5534
5535 pub fn unfollow(
5536 &mut self,
5537 leader_id: impl Into<CollaboratorId>,
5538 window: &mut Window,
5539 cx: &mut Context<Self>,
5540 ) -> Option<()> {
5541 cx.notify();
5542
5543 let leader_id = leader_id.into();
5544 let state = self.follower_states.remove(&leader_id)?;
5545 for (_, item) in state.items_by_leader_view_id {
5546 item.view.set_leader_id(None, window, cx);
5547 }
5548
5549 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5550 let project_id = self.project.read(cx).remote_id();
5551 let room_id = self.active_call()?.room_id(cx)?;
5552 self.app_state
5553 .client
5554 .send(proto::Unfollow {
5555 room_id,
5556 project_id,
5557 leader_id: Some(leader_peer_id),
5558 })
5559 .log_err();
5560 }
5561
5562 Some(())
5563 }
5564
5565 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5566 self.follower_states.contains_key(&id.into())
5567 }
5568
5569 fn active_item_path_changed(
5570 &mut self,
5571 focus_changed: bool,
5572 window: &mut Window,
5573 cx: &mut Context<Self>,
5574 ) {
5575 cx.emit(Event::ActiveItemChanged);
5576 let active_entry = self.active_project_path(cx);
5577 self.project.update(cx, |project, cx| {
5578 project.set_active_path(active_entry.clone(), cx)
5579 });
5580
5581 if focus_changed && let Some(project_path) = &active_entry {
5582 let git_store_entity = self.project.read(cx).git_store().clone();
5583 git_store_entity.update(cx, |git_store, cx| {
5584 git_store.set_active_repo_for_path(project_path, cx);
5585 });
5586 }
5587
5588 self.update_window_title(window, cx);
5589 }
5590
5591 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5592 let project = self.project().read(cx);
5593 let mut title = String::new();
5594
5595 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5596 let name = {
5597 let settings_location = SettingsLocation {
5598 worktree_id: worktree.read(cx).id(),
5599 path: RelPath::empty(),
5600 };
5601
5602 let settings = WorktreeSettings::get(Some(settings_location), cx);
5603 match &settings.project_name {
5604 Some(name) => name.as_str(),
5605 None => worktree.read(cx).root_name_str(),
5606 }
5607 };
5608 if i > 0 {
5609 title.push_str(", ");
5610 }
5611 title.push_str(name);
5612 }
5613
5614 if title.is_empty() {
5615 title = "empty project".to_string();
5616 }
5617
5618 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5619 let filename = path.path.file_name().or_else(|| {
5620 Some(
5621 project
5622 .worktree_for_id(path.worktree_id, cx)?
5623 .read(cx)
5624 .root_name_str(),
5625 )
5626 });
5627
5628 if let Some(filename) = filename {
5629 title.push_str(" — ");
5630 title.push_str(filename.as_ref());
5631 }
5632 }
5633
5634 if project.is_via_collab() {
5635 title.push_str(" ↙");
5636 } else if project.is_shared() {
5637 title.push_str(" ↗");
5638 }
5639
5640 if let Some(last_title) = self.last_window_title.as_ref()
5641 && &title == last_title
5642 {
5643 return;
5644 }
5645 window.set_window_title(&title);
5646 SystemWindowTabController::update_tab_title(
5647 cx,
5648 window.window_handle().window_id(),
5649 SharedString::from(&title),
5650 );
5651 self.last_window_title = Some(title);
5652 }
5653
5654 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5655 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5656 if is_edited != self.window_edited {
5657 self.window_edited = is_edited;
5658 window.set_window_edited(self.window_edited)
5659 }
5660 }
5661
5662 fn update_item_dirty_state(
5663 &mut self,
5664 item: &dyn ItemHandle,
5665 window: &mut Window,
5666 cx: &mut App,
5667 ) {
5668 let is_dirty = item.is_dirty(cx);
5669 let item_id = item.item_id();
5670 let was_dirty = self.dirty_items.contains_key(&item_id);
5671 if is_dirty == was_dirty {
5672 return;
5673 }
5674 if was_dirty {
5675 self.dirty_items.remove(&item_id);
5676 self.update_window_edited(window, cx);
5677 return;
5678 }
5679
5680 let workspace = self.weak_handle();
5681 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5682 return;
5683 };
5684 let on_release_callback = Box::new(move |cx: &mut App| {
5685 window_handle
5686 .update(cx, |_, window, cx| {
5687 workspace
5688 .update(cx, |workspace, cx| {
5689 workspace.dirty_items.remove(&item_id);
5690 workspace.update_window_edited(window, cx)
5691 })
5692 .ok();
5693 })
5694 .ok();
5695 });
5696
5697 let s = item.on_release(cx, on_release_callback);
5698 self.dirty_items.insert(item_id, s);
5699 self.update_window_edited(window, cx);
5700 }
5701
5702 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5703 if self.notifications.is_empty() {
5704 None
5705 } else {
5706 Some(
5707 div()
5708 .absolute()
5709 .right_3()
5710 .bottom_3()
5711 .w_112()
5712 .h_full()
5713 .flex()
5714 .flex_col()
5715 .justify_end()
5716 .gap_2()
5717 .children(
5718 self.notifications
5719 .iter()
5720 .map(|(_, notification)| notification.clone().into_any()),
5721 ),
5722 )
5723 }
5724 }
5725
5726 // RPC handlers
5727
5728 fn active_view_for_follower(
5729 &self,
5730 follower_project_id: Option<u64>,
5731 window: &mut Window,
5732 cx: &mut Context<Self>,
5733 ) -> Option<proto::View> {
5734 let (item, panel_id) = self.active_item_for_followers(window, cx);
5735 let item = item?;
5736 let leader_id = self
5737 .pane_for(&*item)
5738 .and_then(|pane| self.leader_for_pane(&pane));
5739 let leader_peer_id = match leader_id {
5740 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5741 Some(CollaboratorId::Agent) | None => None,
5742 };
5743
5744 let item_handle = item.to_followable_item_handle(cx)?;
5745 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5746 let variant = item_handle.to_state_proto(window, cx)?;
5747
5748 if item_handle.is_project_item(window, cx)
5749 && (follower_project_id.is_none()
5750 || follower_project_id != self.project.read(cx).remote_id())
5751 {
5752 return None;
5753 }
5754
5755 Some(proto::View {
5756 id: id.to_proto(),
5757 leader_id: leader_peer_id,
5758 variant: Some(variant),
5759 panel_id: panel_id.map(|id| id as i32),
5760 })
5761 }
5762
5763 fn handle_follow(
5764 &mut self,
5765 follower_project_id: Option<u64>,
5766 window: &mut Window,
5767 cx: &mut Context<Self>,
5768 ) -> proto::FollowResponse {
5769 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5770
5771 cx.notify();
5772 proto::FollowResponse {
5773 views: active_view.iter().cloned().collect(),
5774 active_view,
5775 }
5776 }
5777
5778 fn handle_update_followers(
5779 &mut self,
5780 leader_id: PeerId,
5781 message: proto::UpdateFollowers,
5782 _window: &mut Window,
5783 _cx: &mut Context<Self>,
5784 ) {
5785 self.leader_updates_tx
5786 .unbounded_send((leader_id, message))
5787 .ok();
5788 }
5789
5790 async fn process_leader_update(
5791 this: &WeakEntity<Self>,
5792 leader_id: PeerId,
5793 update: proto::UpdateFollowers,
5794 cx: &mut AsyncWindowContext,
5795 ) -> Result<()> {
5796 match update.variant.context("invalid update")? {
5797 proto::update_followers::Variant::CreateView(view) => {
5798 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5799 let should_add_view = this.update(cx, |this, _| {
5800 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5801 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5802 } else {
5803 anyhow::Ok(false)
5804 }
5805 })??;
5806
5807 if should_add_view {
5808 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5809 }
5810 }
5811 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5812 let should_add_view = this.update(cx, |this, _| {
5813 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5814 state.active_view_id = update_active_view
5815 .view
5816 .as_ref()
5817 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5818
5819 if state.active_view_id.is_some_and(|view_id| {
5820 !state.items_by_leader_view_id.contains_key(&view_id)
5821 }) {
5822 anyhow::Ok(true)
5823 } else {
5824 anyhow::Ok(false)
5825 }
5826 } else {
5827 anyhow::Ok(false)
5828 }
5829 })??;
5830
5831 if should_add_view && let Some(view) = update_active_view.view {
5832 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5833 }
5834 }
5835 proto::update_followers::Variant::UpdateView(update_view) => {
5836 let variant = update_view.variant.context("missing update view variant")?;
5837 let id = update_view.id.context("missing update view id")?;
5838 let mut tasks = Vec::new();
5839 this.update_in(cx, |this, window, cx| {
5840 let project = this.project.clone();
5841 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5842 let view_id = ViewId::from_proto(id.clone())?;
5843 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5844 tasks.push(item.view.apply_update_proto(
5845 &project,
5846 variant.clone(),
5847 window,
5848 cx,
5849 ));
5850 }
5851 }
5852 anyhow::Ok(())
5853 })??;
5854 try_join_all(tasks).await.log_err();
5855 }
5856 }
5857 this.update_in(cx, |this, window, cx| {
5858 this.leader_updated(leader_id, window, cx)
5859 })?;
5860 Ok(())
5861 }
5862
5863 async fn add_view_from_leader(
5864 this: WeakEntity<Self>,
5865 leader_id: PeerId,
5866 view: &proto::View,
5867 cx: &mut AsyncWindowContext,
5868 ) -> Result<()> {
5869 let this = this.upgrade().context("workspace dropped")?;
5870
5871 let Some(id) = view.id.clone() else {
5872 anyhow::bail!("no id for view");
5873 };
5874 let id = ViewId::from_proto(id)?;
5875 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5876
5877 let pane = this.update(cx, |this, _cx| {
5878 let state = this
5879 .follower_states
5880 .get(&leader_id.into())
5881 .context("stopped following")?;
5882 anyhow::Ok(state.pane().clone())
5883 })?;
5884 let existing_item = pane.update_in(cx, |pane, window, cx| {
5885 let client = this.read(cx).client().clone();
5886 pane.items().find_map(|item| {
5887 let item = item.to_followable_item_handle(cx)?;
5888 if item.remote_id(&client, window, cx) == Some(id) {
5889 Some(item)
5890 } else {
5891 None
5892 }
5893 })
5894 })?;
5895 let item = if let Some(existing_item) = existing_item {
5896 existing_item
5897 } else {
5898 let variant = view.variant.clone();
5899 anyhow::ensure!(variant.is_some(), "missing view variant");
5900
5901 let task = cx.update(|window, cx| {
5902 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5903 })?;
5904
5905 let Some(task) = task else {
5906 anyhow::bail!(
5907 "failed to construct view from leader (maybe from a different version of zed?)"
5908 );
5909 };
5910
5911 let mut new_item = task.await?;
5912 pane.update_in(cx, |pane, window, cx| {
5913 let mut item_to_remove = None;
5914 for (ix, item) in pane.items().enumerate() {
5915 if let Some(item) = item.to_followable_item_handle(cx) {
5916 match new_item.dedup(item.as_ref(), window, cx) {
5917 Some(item::Dedup::KeepExisting) => {
5918 new_item =
5919 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5920 break;
5921 }
5922 Some(item::Dedup::ReplaceExisting) => {
5923 item_to_remove = Some((ix, item.item_id()));
5924 break;
5925 }
5926 None => {}
5927 }
5928 }
5929 }
5930
5931 if let Some((ix, id)) = item_to_remove {
5932 pane.remove_item(id, false, false, window, cx);
5933 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5934 }
5935 })?;
5936
5937 new_item
5938 };
5939
5940 this.update_in(cx, |this, window, cx| {
5941 let state = this.follower_states.get_mut(&leader_id.into())?;
5942 item.set_leader_id(Some(leader_id.into()), window, cx);
5943 state.items_by_leader_view_id.insert(
5944 id,
5945 FollowerView {
5946 view: item,
5947 location: panel_id,
5948 },
5949 );
5950
5951 Some(())
5952 })
5953 .context("no follower state")?;
5954
5955 Ok(())
5956 }
5957
5958 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5959 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5960 return;
5961 };
5962
5963 if let Some(agent_location) = self.project.read(cx).agent_location() {
5964 let buffer_entity_id = agent_location.buffer.entity_id();
5965 let view_id = ViewId {
5966 creator: CollaboratorId::Agent,
5967 id: buffer_entity_id.as_u64(),
5968 };
5969 follower_state.active_view_id = Some(view_id);
5970
5971 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5972 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5973 hash_map::Entry::Vacant(entry) => {
5974 let existing_view =
5975 follower_state
5976 .center_pane
5977 .read(cx)
5978 .items()
5979 .find_map(|item| {
5980 let item = item.to_followable_item_handle(cx)?;
5981 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5982 && item.project_item_model_ids(cx).as_slice()
5983 == [buffer_entity_id]
5984 {
5985 Some(item)
5986 } else {
5987 None
5988 }
5989 });
5990 let view = existing_view.or_else(|| {
5991 agent_location.buffer.upgrade().and_then(|buffer| {
5992 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5993 registry.build_item(buffer, self.project.clone(), None, window, cx)
5994 })?
5995 .to_followable_item_handle(cx)
5996 })
5997 });
5998
5999 view.map(|view| {
6000 entry.insert(FollowerView {
6001 view,
6002 location: None,
6003 })
6004 })
6005 }
6006 };
6007
6008 if let Some(item) = item {
6009 item.view
6010 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
6011 item.view
6012 .update_agent_location(agent_location.position, window, cx);
6013 }
6014 } else {
6015 follower_state.active_view_id = None;
6016 }
6017
6018 self.leader_updated(CollaboratorId::Agent, window, cx);
6019 }
6020
6021 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
6022 let mut is_project_item = true;
6023 let mut update = proto::UpdateActiveView::default();
6024 if window.is_window_active() {
6025 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
6026
6027 if let Some(item) = active_item
6028 && item.item_focus_handle(cx).contains_focused(window, cx)
6029 {
6030 let leader_id = self
6031 .pane_for(&*item)
6032 .and_then(|pane| self.leader_for_pane(&pane));
6033 let leader_peer_id = match leader_id {
6034 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
6035 Some(CollaboratorId::Agent) | None => None,
6036 };
6037
6038 if let Some(item) = item.to_followable_item_handle(cx) {
6039 let id = item
6040 .remote_id(&self.app_state.client, window, cx)
6041 .map(|id| id.to_proto());
6042
6043 if let Some(id) = id
6044 && let Some(variant) = item.to_state_proto(window, cx)
6045 {
6046 let view = Some(proto::View {
6047 id,
6048 leader_id: leader_peer_id,
6049 variant: Some(variant),
6050 panel_id: panel_id.map(|id| id as i32),
6051 });
6052
6053 is_project_item = item.is_project_item(window, cx);
6054 update = proto::UpdateActiveView { view };
6055 };
6056 }
6057 }
6058 }
6059
6060 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
6061 if active_view_id != self.last_active_view_id.as_ref() {
6062 self.last_active_view_id = active_view_id.cloned();
6063 self.update_followers(
6064 is_project_item,
6065 proto::update_followers::Variant::UpdateActiveView(update),
6066 window,
6067 cx,
6068 );
6069 }
6070 }
6071
6072 fn active_item_for_followers(
6073 &self,
6074 window: &mut Window,
6075 cx: &mut App,
6076 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
6077 let mut active_item = None;
6078 let mut panel_id = None;
6079 for dock in self.all_docks() {
6080 if dock.focus_handle(cx).contains_focused(window, cx)
6081 && let Some(panel) = dock.read(cx).active_panel()
6082 && let Some(pane) = panel.pane(cx)
6083 && let Some(item) = pane.read(cx).active_item()
6084 {
6085 active_item = Some(item);
6086 panel_id = panel.remote_id();
6087 break;
6088 }
6089 }
6090
6091 if active_item.is_none() {
6092 active_item = self.active_pane().read(cx).active_item();
6093 }
6094 (active_item, panel_id)
6095 }
6096
6097 fn update_followers(
6098 &self,
6099 project_only: bool,
6100 update: proto::update_followers::Variant,
6101 _: &mut Window,
6102 cx: &mut App,
6103 ) -> Option<()> {
6104 // If this update only applies to for followers in the current project,
6105 // then skip it unless this project is shared. If it applies to all
6106 // followers, regardless of project, then set `project_id` to none,
6107 // indicating that it goes to all followers.
6108 let project_id = if project_only {
6109 Some(self.project.read(cx).remote_id()?)
6110 } else {
6111 None
6112 };
6113 self.app_state().workspace_store.update(cx, |store, cx| {
6114 store.update_followers(project_id, update, cx)
6115 })
6116 }
6117
6118 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
6119 self.follower_states.iter().find_map(|(leader_id, state)| {
6120 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
6121 Some(*leader_id)
6122 } else {
6123 None
6124 }
6125 })
6126 }
6127
6128 fn leader_updated(
6129 &mut self,
6130 leader_id: impl Into<CollaboratorId>,
6131 window: &mut Window,
6132 cx: &mut Context<Self>,
6133 ) -> Option<Box<dyn ItemHandle>> {
6134 cx.notify();
6135
6136 let leader_id = leader_id.into();
6137 let (panel_id, item) = match leader_id {
6138 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
6139 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
6140 };
6141
6142 let state = self.follower_states.get(&leader_id)?;
6143 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
6144 let pane;
6145 if let Some(panel_id) = panel_id {
6146 pane = self
6147 .activate_panel_for_proto_id(panel_id, window, cx)?
6148 .pane(cx)?;
6149 let state = self.follower_states.get_mut(&leader_id)?;
6150 state.dock_pane = Some(pane.clone());
6151 } else {
6152 pane = state.center_pane.clone();
6153 let state = self.follower_states.get_mut(&leader_id)?;
6154 if let Some(dock_pane) = state.dock_pane.take() {
6155 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
6156 }
6157 }
6158
6159 pane.update(cx, |pane, cx| {
6160 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
6161 if let Some(index) = pane.index_for_item(item.as_ref()) {
6162 pane.activate_item(index, false, false, window, cx);
6163 } else {
6164 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
6165 }
6166
6167 if focus_active_item {
6168 pane.focus_active_item(window, cx)
6169 }
6170 });
6171
6172 Some(item)
6173 }
6174
6175 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
6176 let state = self.follower_states.get(&CollaboratorId::Agent)?;
6177 let active_view_id = state.active_view_id?;
6178 Some(
6179 state
6180 .items_by_leader_view_id
6181 .get(&active_view_id)?
6182 .view
6183 .boxed_clone(),
6184 )
6185 }
6186
6187 fn active_item_for_peer(
6188 &self,
6189 peer_id: PeerId,
6190 window: &mut Window,
6191 cx: &mut Context<Self>,
6192 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
6193 let call = self.active_call()?;
6194 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
6195 let leader_in_this_app;
6196 let leader_in_this_project;
6197 match participant.location {
6198 ParticipantLocation::SharedProject { project_id } => {
6199 leader_in_this_app = true;
6200 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
6201 }
6202 ParticipantLocation::UnsharedProject => {
6203 leader_in_this_app = true;
6204 leader_in_this_project = false;
6205 }
6206 ParticipantLocation::External => {
6207 leader_in_this_app = false;
6208 leader_in_this_project = false;
6209 }
6210 };
6211 let state = self.follower_states.get(&peer_id.into())?;
6212 let mut item_to_activate = None;
6213 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
6214 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
6215 && (leader_in_this_project || !item.view.is_project_item(window, cx))
6216 {
6217 item_to_activate = Some((item.location, item.view.boxed_clone()));
6218 }
6219 } else if let Some(shared_screen) =
6220 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
6221 {
6222 item_to_activate = Some((None, Box::new(shared_screen)));
6223 }
6224 item_to_activate
6225 }
6226
6227 fn shared_screen_for_peer(
6228 &self,
6229 peer_id: PeerId,
6230 pane: &Entity<Pane>,
6231 window: &mut Window,
6232 cx: &mut App,
6233 ) -> Option<Entity<SharedScreen>> {
6234 self.active_call()?
6235 .create_shared_screen(peer_id, pane, window, cx)
6236 }
6237
6238 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6239 if window.is_window_active() {
6240 self.update_active_view_for_followers(window, cx);
6241
6242 if let Some(database_id) = self.database_id {
6243 let db = WorkspaceDb::global(cx);
6244 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6245 .detach();
6246 }
6247 } else {
6248 for pane in &self.panes {
6249 pane.update(cx, |pane, cx| {
6250 if let Some(item) = pane.active_item() {
6251 item.workspace_deactivated(window, cx);
6252 }
6253 for item in pane.items() {
6254 if matches!(
6255 item.workspace_settings(cx).autosave,
6256 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6257 ) {
6258 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6259 .detach_and_log_err(cx);
6260 }
6261 }
6262 });
6263 }
6264 }
6265 }
6266
6267 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6268 self.active_call.as_ref().map(|(call, _)| &*call.0)
6269 }
6270
6271 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6272 self.active_call.as_ref().map(|(call, _)| call.clone())
6273 }
6274
6275 fn on_active_call_event(
6276 &mut self,
6277 event: &ActiveCallEvent,
6278 window: &mut Window,
6279 cx: &mut Context<Self>,
6280 ) {
6281 match event {
6282 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6283 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6284 self.leader_updated(participant_id, window, cx);
6285 }
6286 }
6287 }
6288
6289 pub fn database_id(&self) -> Option<WorkspaceId> {
6290 self.database_id
6291 }
6292
6293 #[cfg(any(test, feature = "test-support"))]
6294 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6295 self.database_id = Some(id);
6296 }
6297
6298 pub fn session_id(&self) -> Option<String> {
6299 self.session_id.clone()
6300 }
6301
6302 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6303 let Some(display) = window.display(cx) else {
6304 return Task::ready(());
6305 };
6306 let Ok(display_uuid) = display.uuid() else {
6307 return Task::ready(());
6308 };
6309
6310 let window_bounds = window.inner_window_bounds();
6311 let database_id = self.database_id;
6312 let has_paths = !self.root_paths(cx).is_empty();
6313 let db = WorkspaceDb::global(cx);
6314 let kvp = db::kvp::KeyValueStore::global(cx);
6315
6316 cx.background_executor().spawn(async move {
6317 if !has_paths {
6318 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6319 .await
6320 .log_err();
6321 }
6322 if let Some(database_id) = database_id {
6323 db.set_window_open_status(
6324 database_id,
6325 SerializedWindowBounds(window_bounds),
6326 display_uuid,
6327 )
6328 .await
6329 .log_err();
6330 } else {
6331 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6332 .await
6333 .log_err();
6334 }
6335 })
6336 }
6337
6338 /// Bypass the 200ms serialization throttle and write workspace state to
6339 /// the DB immediately. Returns a task the caller can await to ensure the
6340 /// write completes. Used by the quit handler so the most recent state
6341 /// isn't lost to a pending throttle timer when the process exits.
6342 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6343 self._schedule_serialize_workspace.take();
6344 self._serialize_workspace_task.take();
6345 self.bounds_save_task_queued.take();
6346
6347 let bounds_task = self.save_window_bounds(window, cx);
6348 let serialize_task = self.serialize_workspace_internal(window, cx);
6349 cx.spawn(async move |_| {
6350 bounds_task.await;
6351 serialize_task.await;
6352 })
6353 }
6354
6355 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6356 let project = self.project().read(cx);
6357 project
6358 .visible_worktrees(cx)
6359 .map(|worktree| worktree.read(cx).abs_path())
6360 .collect::<Vec<_>>()
6361 }
6362
6363 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6364 match member {
6365 Member::Axis(PaneAxis { members, .. }) => {
6366 for child in members.iter() {
6367 self.remove_panes(child.clone(), window, cx)
6368 }
6369 }
6370 Member::Pane(pane) => {
6371 self.force_remove_pane(&pane, &None, window, cx);
6372 }
6373 }
6374 }
6375
6376 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6377 self.session_id.take();
6378 self.serialize_workspace_internal(window, cx)
6379 }
6380
6381 fn force_remove_pane(
6382 &mut self,
6383 pane: &Entity<Pane>,
6384 focus_on: &Option<Entity<Pane>>,
6385 window: &mut Window,
6386 cx: &mut Context<Workspace>,
6387 ) {
6388 self.panes.retain(|p| p != pane);
6389 if let Some(focus_on) = focus_on {
6390 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6391 } else if self.active_pane() == pane {
6392 self.panes
6393 .last()
6394 .unwrap()
6395 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6396 }
6397 if self.last_active_center_pane == Some(pane.downgrade()) {
6398 self.last_active_center_pane = None;
6399 }
6400 cx.notify();
6401 }
6402
6403 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6404 if self._schedule_serialize_workspace.is_none() {
6405 self._schedule_serialize_workspace =
6406 Some(cx.spawn_in(window, async move |this, cx| {
6407 cx.background_executor()
6408 .timer(SERIALIZATION_THROTTLE_TIME)
6409 .await;
6410 this.update_in(cx, |this, window, cx| {
6411 this._serialize_workspace_task =
6412 Some(this.serialize_workspace_internal(window, cx));
6413 this._schedule_serialize_workspace.take();
6414 })
6415 .log_err();
6416 }));
6417 }
6418 }
6419
6420 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6421 let Some(database_id) = self.database_id() else {
6422 return Task::ready(());
6423 };
6424
6425 fn serialize_pane_handle(
6426 pane_handle: &Entity<Pane>,
6427 window: &mut Window,
6428 cx: &mut App,
6429 ) -> SerializedPane {
6430 let (items, active, pinned_count) = {
6431 let pane = pane_handle.read(cx);
6432 let active_item_id = pane.active_item().map(|item| item.item_id());
6433 (
6434 pane.items()
6435 .filter_map(|handle| {
6436 let handle = handle.to_serializable_item_handle(cx)?;
6437
6438 Some(SerializedItem {
6439 kind: Arc::from(handle.serialized_item_kind()),
6440 item_id: handle.item_id().as_u64(),
6441 active: Some(handle.item_id()) == active_item_id,
6442 preview: pane.is_active_preview_item(handle.item_id()),
6443 })
6444 })
6445 .collect::<Vec<_>>(),
6446 pane.has_focus(window, cx),
6447 pane.pinned_count(),
6448 )
6449 };
6450
6451 SerializedPane::new(items, active, pinned_count)
6452 }
6453
6454 fn build_serialized_pane_group(
6455 pane_group: &Member,
6456 window: &mut Window,
6457 cx: &mut App,
6458 ) -> SerializedPaneGroup {
6459 match pane_group {
6460 Member::Axis(PaneAxis {
6461 axis,
6462 members,
6463 flexes,
6464 bounding_boxes: _,
6465 }) => SerializedPaneGroup::Group {
6466 axis: SerializedAxis(*axis),
6467 children: members
6468 .iter()
6469 .map(|member| build_serialized_pane_group(member, window, cx))
6470 .collect::<Vec<_>>(),
6471 flexes: Some(flexes.lock().clone()),
6472 },
6473 Member::Pane(pane_handle) => {
6474 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6475 }
6476 }
6477 }
6478
6479 fn build_serialized_docks(
6480 this: &Workspace,
6481 window: &mut Window,
6482 cx: &mut App,
6483 ) -> DockStructure {
6484 this.capture_dock_state(window, cx)
6485 }
6486
6487 match self.workspace_location(cx) {
6488 WorkspaceLocation::Location(location, paths) => {
6489 let breakpoints = self.project.update(cx, |project, cx| {
6490 project
6491 .breakpoint_store()
6492 .read(cx)
6493 .all_source_breakpoints(cx)
6494 });
6495 let user_toolchains = self
6496 .project
6497 .read(cx)
6498 .user_toolchains(cx)
6499 .unwrap_or_default();
6500
6501 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6502 let docks = build_serialized_docks(self, window, cx);
6503 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6504
6505 let serialized_workspace = SerializedWorkspace {
6506 id: database_id,
6507 location,
6508 paths,
6509 center_group,
6510 window_bounds,
6511 display: Default::default(),
6512 docks,
6513 centered_layout: self.centered_layout,
6514 session_id: self.session_id.clone(),
6515 breakpoints,
6516 window_id: Some(window.window_handle().window_id().as_u64()),
6517 user_toolchains,
6518 };
6519
6520 let db = WorkspaceDb::global(cx);
6521 window.spawn(cx, async move |_| {
6522 db.save_workspace(serialized_workspace).await;
6523 })
6524 }
6525 WorkspaceLocation::DetachFromSession => {
6526 let window_bounds = SerializedWindowBounds(window.window_bounds());
6527 let display = window.display(cx).and_then(|d| d.uuid().ok());
6528 // Save dock state for empty local workspaces
6529 let docks = build_serialized_docks(self, window, cx);
6530 let db = WorkspaceDb::global(cx);
6531 let kvp = db::kvp::KeyValueStore::global(cx);
6532 window.spawn(cx, async move |_| {
6533 db.set_window_open_status(
6534 database_id,
6535 window_bounds,
6536 display.unwrap_or_default(),
6537 )
6538 .await
6539 .log_err();
6540 db.set_session_id(database_id, None).await.log_err();
6541 persistence::write_default_dock_state(&kvp, docks)
6542 .await
6543 .log_err();
6544 })
6545 }
6546 WorkspaceLocation::None => {
6547 // Save dock state for empty non-local workspaces
6548 let docks = build_serialized_docks(self, window, cx);
6549 let kvp = db::kvp::KeyValueStore::global(cx);
6550 window.spawn(cx, async move |_| {
6551 persistence::write_default_dock_state(&kvp, docks)
6552 .await
6553 .log_err();
6554 })
6555 }
6556 }
6557 }
6558
6559 fn has_any_items_open(&self, cx: &App) -> bool {
6560 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6561 }
6562
6563 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6564 let paths = PathList::new(&self.root_paths(cx));
6565 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6566 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6567 } else if self.project.read(cx).is_local() {
6568 if !paths.is_empty() || self.has_any_items_open(cx) {
6569 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6570 } else {
6571 WorkspaceLocation::DetachFromSession
6572 }
6573 } else {
6574 WorkspaceLocation::None
6575 }
6576 }
6577
6578 fn update_history(&self, cx: &mut App) {
6579 let Some(id) = self.database_id() else {
6580 return;
6581 };
6582 if !self.project.read(cx).is_local() {
6583 return;
6584 }
6585 if let Some(manager) = HistoryManager::global(cx) {
6586 let paths = PathList::new(&self.root_paths(cx));
6587 manager.update(cx, |this, cx| {
6588 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6589 });
6590 }
6591 }
6592
6593 async fn serialize_items(
6594 this: &WeakEntity<Self>,
6595 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6596 cx: &mut AsyncWindowContext,
6597 ) -> Result<()> {
6598 const CHUNK_SIZE: usize = 200;
6599
6600 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6601
6602 while let Some(items_received) = serializable_items.next().await {
6603 let unique_items =
6604 items_received
6605 .into_iter()
6606 .fold(HashMap::default(), |mut acc, item| {
6607 acc.entry(item.item_id()).or_insert(item);
6608 acc
6609 });
6610
6611 // We use into_iter() here so that the references to the items are moved into
6612 // the tasks and not kept alive while we're sleeping.
6613 for (_, item) in unique_items.into_iter() {
6614 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6615 item.serialize(workspace, false, window, cx)
6616 }) {
6617 cx.background_spawn(async move { task.await.log_err() })
6618 .detach();
6619 }
6620 }
6621
6622 cx.background_executor()
6623 .timer(SERIALIZATION_THROTTLE_TIME)
6624 .await;
6625 }
6626
6627 Ok(())
6628 }
6629
6630 pub(crate) fn enqueue_item_serialization(
6631 &mut self,
6632 item: Box<dyn SerializableItemHandle>,
6633 ) -> Result<()> {
6634 self.serializable_items_tx
6635 .unbounded_send(item)
6636 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6637 }
6638
6639 pub(crate) fn load_workspace(
6640 serialized_workspace: SerializedWorkspace,
6641 paths_to_open: Vec<Option<ProjectPath>>,
6642 window: &mut Window,
6643 cx: &mut Context<Workspace>,
6644 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6645 cx.spawn_in(window, async move |workspace, cx| {
6646 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6647
6648 let mut center_group = None;
6649 let mut center_items = None;
6650
6651 // Traverse the splits tree and add to things
6652 if let Some((group, active_pane, items)) = serialized_workspace
6653 .center_group
6654 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6655 .await
6656 {
6657 center_items = Some(items);
6658 center_group = Some((group, active_pane))
6659 }
6660
6661 let mut items_by_project_path = HashMap::default();
6662 let mut item_ids_by_kind = HashMap::default();
6663 let mut all_deserialized_items = Vec::default();
6664 cx.update(|_, cx| {
6665 for item in center_items.unwrap_or_default().into_iter().flatten() {
6666 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6667 item_ids_by_kind
6668 .entry(serializable_item_handle.serialized_item_kind())
6669 .or_insert(Vec::new())
6670 .push(item.item_id().as_u64() as ItemId);
6671 }
6672
6673 if let Some(project_path) = item.project_path(cx) {
6674 items_by_project_path.insert(project_path, item.clone());
6675 }
6676 all_deserialized_items.push(item);
6677 }
6678 })?;
6679
6680 let opened_items = paths_to_open
6681 .into_iter()
6682 .map(|path_to_open| {
6683 path_to_open
6684 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6685 })
6686 .collect::<Vec<_>>();
6687
6688 // Remove old panes from workspace panes list
6689 workspace.update_in(cx, |workspace, window, cx| {
6690 if let Some((center_group, active_pane)) = center_group {
6691 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6692
6693 // Swap workspace center group
6694 workspace.center = PaneGroup::with_root(center_group);
6695 workspace.center.set_is_center(true);
6696 workspace.center.mark_positions(cx);
6697
6698 if let Some(active_pane) = active_pane {
6699 workspace.set_active_pane(&active_pane, window, cx);
6700 cx.focus_self(window);
6701 } else {
6702 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6703 }
6704 }
6705
6706 let docks = serialized_workspace.docks;
6707
6708 for (dock, serialized_dock) in [
6709 (&mut workspace.right_dock, docks.right),
6710 (&mut workspace.left_dock, docks.left),
6711 (&mut workspace.bottom_dock, docks.bottom),
6712 ]
6713 .iter_mut()
6714 {
6715 dock.update(cx, |dock, cx| {
6716 dock.serialized_dock = Some(serialized_dock.clone());
6717 dock.restore_state(window, cx);
6718 });
6719 }
6720
6721 cx.notify();
6722 })?;
6723
6724 let _ = project
6725 .update(cx, |project, cx| {
6726 project
6727 .breakpoint_store()
6728 .update(cx, |breakpoint_store, cx| {
6729 breakpoint_store
6730 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6731 })
6732 })
6733 .await;
6734
6735 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6736 // after loading the items, we might have different items and in order to avoid
6737 // the database filling up, we delete items that haven't been loaded now.
6738 //
6739 // The items that have been loaded, have been saved after they've been added to the workspace.
6740 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6741 item_ids_by_kind
6742 .into_iter()
6743 .map(|(item_kind, loaded_items)| {
6744 SerializableItemRegistry::cleanup(
6745 item_kind,
6746 serialized_workspace.id,
6747 loaded_items,
6748 window,
6749 cx,
6750 )
6751 .log_err()
6752 })
6753 .collect::<Vec<_>>()
6754 })?;
6755
6756 futures::future::join_all(clean_up_tasks).await;
6757
6758 workspace
6759 .update_in(cx, |workspace, window, cx| {
6760 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6761 workspace.serialize_workspace_internal(window, cx).detach();
6762
6763 // Ensure that we mark the window as edited if we did load dirty items
6764 workspace.update_window_edited(window, cx);
6765 })
6766 .ok();
6767
6768 Ok(opened_items)
6769 })
6770 }
6771
6772 pub fn key_context(&self, cx: &App) -> KeyContext {
6773 let mut context = KeyContext::new_with_defaults();
6774 context.add("Workspace");
6775 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6776 if let Some(status) = self
6777 .debugger_provider
6778 .as_ref()
6779 .and_then(|provider| provider.active_thread_state(cx))
6780 {
6781 match status {
6782 ThreadStatus::Running | ThreadStatus::Stepping => {
6783 context.add("debugger_running");
6784 }
6785 ThreadStatus::Stopped => context.add("debugger_stopped"),
6786 ThreadStatus::Exited | ThreadStatus::Ended => {}
6787 }
6788 }
6789
6790 if self.left_dock.read(cx).is_open() {
6791 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6792 context.set("left_dock", active_panel.panel_key());
6793 }
6794 }
6795
6796 if self.right_dock.read(cx).is_open() {
6797 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6798 context.set("right_dock", active_panel.panel_key());
6799 }
6800 }
6801
6802 if self.bottom_dock.read(cx).is_open() {
6803 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6804 context.set("bottom_dock", active_panel.panel_key());
6805 }
6806 }
6807
6808 context
6809 }
6810
6811 /// Multiworkspace uses this to add workspace action handling to itself
6812 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6813 self.add_workspace_actions_listeners(div, window, cx)
6814 .on_action(cx.listener(
6815 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6816 for action in &action_sequence.0 {
6817 window.dispatch_action(action.boxed_clone(), cx);
6818 }
6819 },
6820 ))
6821 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6822 .on_action(cx.listener(Self::close_all_items_and_panes))
6823 .on_action(cx.listener(Self::close_item_in_all_panes))
6824 .on_action(cx.listener(Self::save_all))
6825 .on_action(cx.listener(Self::send_keystrokes))
6826 .on_action(cx.listener(Self::add_folder_to_project))
6827 .on_action(cx.listener(Self::follow_next_collaborator))
6828 .on_action(cx.listener(Self::activate_pane_at_index))
6829 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6830 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6831 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6832 .on_action(cx.listener(Self::toggle_theme_mode))
6833 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6834 let pane = workspace.active_pane().clone();
6835 workspace.unfollow_in_pane(&pane, window, cx);
6836 }))
6837 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6838 workspace
6839 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6840 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6841 }))
6842 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6843 workspace
6844 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6845 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6846 }))
6847 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6848 workspace
6849 .save_active_item(SaveIntent::SaveAs, window, cx)
6850 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6851 }))
6852 .on_action(
6853 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6854 workspace.activate_previous_pane(window, cx)
6855 }),
6856 )
6857 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6858 workspace.activate_next_pane(window, cx)
6859 }))
6860 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6861 workspace.activate_last_pane(window, cx)
6862 }))
6863 .on_action(
6864 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6865 workspace.activate_next_window(cx)
6866 }),
6867 )
6868 .on_action(
6869 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6870 workspace.activate_previous_window(cx)
6871 }),
6872 )
6873 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6874 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6875 }))
6876 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6877 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6878 }))
6879 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6880 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6881 }))
6882 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6883 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6884 }))
6885 .on_action(cx.listener(
6886 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6887 workspace.move_item_to_pane_in_direction(action, window, cx)
6888 },
6889 ))
6890 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6891 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6892 }))
6893 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6894 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6895 }))
6896 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6897 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6898 }))
6899 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6900 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6901 }))
6902 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6903 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6904 SplitDirection::Down,
6905 SplitDirection::Up,
6906 SplitDirection::Right,
6907 SplitDirection::Left,
6908 ];
6909 for dir in DIRECTION_PRIORITY {
6910 if workspace.find_pane_in_direction(dir, cx).is_some() {
6911 workspace.swap_pane_in_direction(dir, cx);
6912 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6913 break;
6914 }
6915 }
6916 }))
6917 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6918 workspace.move_pane_to_border(SplitDirection::Left, cx)
6919 }))
6920 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6921 workspace.move_pane_to_border(SplitDirection::Right, cx)
6922 }))
6923 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6924 workspace.move_pane_to_border(SplitDirection::Up, cx)
6925 }))
6926 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6927 workspace.move_pane_to_border(SplitDirection::Down, cx)
6928 }))
6929 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6930 this.toggle_dock(DockPosition::Left, window, cx);
6931 }))
6932 .on_action(cx.listener(
6933 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6934 workspace.toggle_dock(DockPosition::Right, window, cx);
6935 },
6936 ))
6937 .on_action(cx.listener(
6938 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6939 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6940 },
6941 ))
6942 .on_action(cx.listener(
6943 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6944 if !workspace.close_active_dock(window, cx) {
6945 cx.propagate();
6946 }
6947 },
6948 ))
6949 .on_action(
6950 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6951 workspace.close_all_docks(window, cx);
6952 }),
6953 )
6954 .on_action(cx.listener(Self::toggle_all_docks))
6955 .on_action(cx.listener(
6956 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6957 workspace.clear_all_notifications(cx);
6958 },
6959 ))
6960 .on_action(cx.listener(
6961 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6962 workspace.clear_navigation_history(window, cx);
6963 },
6964 ))
6965 .on_action(cx.listener(
6966 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6967 if let Some((notification_id, _)) = workspace.notifications.pop() {
6968 workspace.suppress_notification(¬ification_id, cx);
6969 }
6970 },
6971 ))
6972 .on_action(cx.listener(
6973 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6974 workspace.show_worktree_trust_security_modal(true, window, cx);
6975 },
6976 ))
6977 .on_action(
6978 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6979 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6980 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6981 trusted_worktrees.clear_trusted_paths()
6982 });
6983 let db = WorkspaceDb::global(cx);
6984 cx.spawn(async move |_, cx| {
6985 if db.clear_trusted_worktrees().await.log_err().is_some() {
6986 cx.update(|cx| reload(cx));
6987 }
6988 })
6989 .detach();
6990 }
6991 }),
6992 )
6993 .on_action(cx.listener(
6994 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6995 workspace.reopen_closed_item(window, cx).detach();
6996 },
6997 ))
6998 .on_action(cx.listener(
6999 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
7000 for dock in workspace.all_docks() {
7001 if dock.focus_handle(cx).contains_focused(window, cx) {
7002 let panel = dock.read(cx).active_panel().cloned();
7003 if let Some(panel) = panel {
7004 dock.update(cx, |dock, cx| {
7005 dock.set_panel_size_state(
7006 panel.as_ref(),
7007 dock::PanelSizeState::default(),
7008 cx,
7009 );
7010 });
7011 }
7012 return;
7013 }
7014 }
7015 },
7016 ))
7017 .on_action(cx.listener(
7018 |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
7019 for dock in workspace.all_docks() {
7020 let panel = dock.read(cx).visible_panel().cloned();
7021 if let Some(panel) = panel {
7022 dock.update(cx, |dock, cx| {
7023 dock.set_panel_size_state(
7024 panel.as_ref(),
7025 dock::PanelSizeState::default(),
7026 cx,
7027 );
7028 });
7029 }
7030 }
7031 },
7032 ))
7033 .on_action(cx.listener(
7034 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
7035 adjust_active_dock_size_by_px(
7036 px_with_ui_font_fallback(act.px, cx),
7037 workspace,
7038 window,
7039 cx,
7040 );
7041 },
7042 ))
7043 .on_action(cx.listener(
7044 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
7045 adjust_active_dock_size_by_px(
7046 px_with_ui_font_fallback(act.px, cx) * -1.,
7047 workspace,
7048 window,
7049 cx,
7050 );
7051 },
7052 ))
7053 .on_action(cx.listener(
7054 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
7055 adjust_open_docks_size_by_px(
7056 px_with_ui_font_fallback(act.px, cx),
7057 workspace,
7058 window,
7059 cx,
7060 );
7061 },
7062 ))
7063 .on_action(cx.listener(
7064 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
7065 adjust_open_docks_size_by_px(
7066 px_with_ui_font_fallback(act.px, cx) * -1.,
7067 workspace,
7068 window,
7069 cx,
7070 );
7071 },
7072 ))
7073 .on_action(cx.listener(Workspace::toggle_centered_layout))
7074 .on_action(cx.listener(
7075 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
7076 if let Some(active_dock) = workspace.active_dock(window, cx) {
7077 let dock = active_dock.read(cx);
7078 if let Some(active_panel) = dock.active_panel() {
7079 if active_panel.pane(cx).is_none() {
7080 let mut recent_pane: Option<Entity<Pane>> = None;
7081 let mut recent_timestamp = 0;
7082 for pane_handle in workspace.panes() {
7083 let pane = pane_handle.read(cx);
7084 for entry in pane.activation_history() {
7085 if entry.timestamp > recent_timestamp {
7086 recent_timestamp = entry.timestamp;
7087 recent_pane = Some(pane_handle.clone());
7088 }
7089 }
7090 }
7091
7092 if let Some(pane) = recent_pane {
7093 pane.update(cx, |pane, cx| {
7094 let current_index = pane.active_item_index();
7095 let items_len = pane.items_len();
7096 if items_len > 0 {
7097 let next_index = if current_index + 1 < items_len {
7098 current_index + 1
7099 } else {
7100 0
7101 };
7102 pane.activate_item(
7103 next_index, false, false, window, cx,
7104 );
7105 }
7106 });
7107 return;
7108 }
7109 }
7110 }
7111 }
7112 cx.propagate();
7113 },
7114 ))
7115 .on_action(cx.listener(
7116 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
7117 if let Some(active_dock) = workspace.active_dock(window, cx) {
7118 let dock = active_dock.read(cx);
7119 if let Some(active_panel) = dock.active_panel() {
7120 if active_panel.pane(cx).is_none() {
7121 let mut recent_pane: Option<Entity<Pane>> = None;
7122 let mut recent_timestamp = 0;
7123 for pane_handle in workspace.panes() {
7124 let pane = pane_handle.read(cx);
7125 for entry in pane.activation_history() {
7126 if entry.timestamp > recent_timestamp {
7127 recent_timestamp = entry.timestamp;
7128 recent_pane = Some(pane_handle.clone());
7129 }
7130 }
7131 }
7132
7133 if let Some(pane) = recent_pane {
7134 pane.update(cx, |pane, cx| {
7135 let current_index = pane.active_item_index();
7136 let items_len = pane.items_len();
7137 if items_len > 0 {
7138 let prev_index = if current_index > 0 {
7139 current_index - 1
7140 } else {
7141 items_len.saturating_sub(1)
7142 };
7143 pane.activate_item(
7144 prev_index, false, false, window, cx,
7145 );
7146 }
7147 });
7148 return;
7149 }
7150 }
7151 }
7152 }
7153 cx.propagate();
7154 },
7155 ))
7156 .on_action(cx.listener(
7157 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
7158 if let Some(active_dock) = workspace.active_dock(window, cx) {
7159 let dock = active_dock.read(cx);
7160 if let Some(active_panel) = dock.active_panel() {
7161 if active_panel.pane(cx).is_none() {
7162 let active_pane = workspace.active_pane().clone();
7163 active_pane.update(cx, |pane, cx| {
7164 pane.close_active_item(action, window, cx)
7165 .detach_and_log_err(cx);
7166 });
7167 return;
7168 }
7169 }
7170 }
7171 cx.propagate();
7172 },
7173 ))
7174 .on_action(
7175 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
7176 let pane = workspace.active_pane().clone();
7177 if let Some(item) = pane.read(cx).active_item() {
7178 item.toggle_read_only(window, cx);
7179 }
7180 }),
7181 )
7182 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
7183 workspace.focus_center_pane(window, cx);
7184 }))
7185 .on_action(cx.listener(Workspace::cancel))
7186 }
7187
7188 #[cfg(any(test, feature = "test-support"))]
7189 pub fn set_random_database_id(&mut self) {
7190 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
7191 }
7192
7193 #[cfg(any(test, feature = "test-support"))]
7194 pub(crate) fn test_new(
7195 project: Entity<Project>,
7196 window: &mut Window,
7197 cx: &mut Context<Self>,
7198 ) -> Self {
7199 use node_runtime::NodeRuntime;
7200 use session::Session;
7201
7202 let client = project.read(cx).client();
7203 let user_store = project.read(cx).user_store();
7204 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
7205 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
7206 window.activate_window();
7207 let app_state = Arc::new(AppState {
7208 languages: project.read(cx).languages().clone(),
7209 workspace_store,
7210 client,
7211 user_store,
7212 fs: project.read(cx).fs().clone(),
7213 build_window_options: |_, _| Default::default(),
7214 node_runtime: NodeRuntime::unavailable(),
7215 session,
7216 });
7217 let workspace = Self::new(Default::default(), project, app_state, window, cx);
7218 workspace
7219 .active_pane
7220 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
7221 workspace
7222 }
7223
7224 pub fn register_action<A: Action>(
7225 &mut self,
7226 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
7227 ) -> &mut Self {
7228 let callback = Arc::new(callback);
7229
7230 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
7231 let callback = callback.clone();
7232 div.on_action(cx.listener(move |workspace, event, window, cx| {
7233 (callback)(workspace, event, window, cx)
7234 }))
7235 }));
7236 self
7237 }
7238 pub fn register_action_renderer(
7239 &mut self,
7240 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
7241 ) -> &mut Self {
7242 self.workspace_actions.push(Box::new(callback));
7243 self
7244 }
7245
7246 fn add_workspace_actions_listeners(
7247 &self,
7248 mut div: Div,
7249 window: &mut Window,
7250 cx: &mut Context<Self>,
7251 ) -> Div {
7252 for action in self.workspace_actions.iter() {
7253 div = (action)(div, self, window, cx)
7254 }
7255 div
7256 }
7257
7258 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7259 self.modal_layer.read(cx).has_active_modal()
7260 }
7261
7262 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7263 self.modal_layer
7264 .read(cx)
7265 .is_active_modal_command_palette(cx)
7266 }
7267
7268 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7269 self.modal_layer.read(cx).active_modal()
7270 }
7271
7272 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7273 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7274 /// If no modal is active, the new modal will be shown.
7275 ///
7276 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7277 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7278 /// will not be shown.
7279 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7280 where
7281 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7282 {
7283 self.modal_layer.update(cx, |modal_layer, cx| {
7284 modal_layer.toggle_modal(window, cx, build)
7285 })
7286 }
7287
7288 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7289 self.modal_layer
7290 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7291 }
7292
7293 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7294 self.toast_layer
7295 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7296 }
7297
7298 pub fn toggle_centered_layout(
7299 &mut self,
7300 _: &ToggleCenteredLayout,
7301 _: &mut Window,
7302 cx: &mut Context<Self>,
7303 ) {
7304 self.centered_layout = !self.centered_layout;
7305 if let Some(database_id) = self.database_id() {
7306 let db = WorkspaceDb::global(cx);
7307 let centered_layout = self.centered_layout;
7308 cx.background_spawn(async move {
7309 db.set_centered_layout(database_id, centered_layout).await
7310 })
7311 .detach_and_log_err(cx);
7312 }
7313 cx.notify();
7314 }
7315
7316 fn adjust_padding(padding: Option<f32>) -> f32 {
7317 padding
7318 .unwrap_or(CenteredPaddingSettings::default().0)
7319 .clamp(
7320 CenteredPaddingSettings::MIN_PADDING,
7321 CenteredPaddingSettings::MAX_PADDING,
7322 )
7323 }
7324
7325 fn render_dock(
7326 &self,
7327 position: DockPosition,
7328 dock: &Entity<Dock>,
7329 window: &mut Window,
7330 cx: &mut App,
7331 ) -> Option<Div> {
7332 if self.zoomed_position == Some(position) {
7333 return None;
7334 }
7335
7336 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7337 let pane = panel.pane(cx)?;
7338 let follower_states = &self.follower_states;
7339 leader_border_for_pane(follower_states, &pane, window, cx)
7340 });
7341
7342 let mut container = div()
7343 .flex()
7344 .overflow_hidden()
7345 .flex_none()
7346 .child(dock.clone())
7347 .children(leader_border);
7348
7349 // Apply sizing only when the dock is open. When closed the dock is still
7350 // included in the element tree so its focus handle remains mounted — without
7351 // this, toggle_panel_focus cannot focus the panel when the dock is closed.
7352 let dock = dock.read(cx);
7353 if let Some(panel) = dock.visible_panel() {
7354 let size_state = dock.stored_panel_size_state(panel.as_ref());
7355 if position.axis() == Axis::Horizontal {
7356 let use_flexible = panel.has_flexible_size(window, cx);
7357 let flex_grow = if use_flexible {
7358 size_state
7359 .and_then(|state| state.flex)
7360 .or_else(|| self.default_dock_flex(position))
7361 } else {
7362 None
7363 };
7364 if let Some(grow) = flex_grow {
7365 let grow = grow.max(0.001);
7366 let style = container.style();
7367 style.flex_grow = Some(grow);
7368 style.flex_shrink = Some(1.0);
7369 style.flex_basis = Some(relative(0.).into());
7370 } else {
7371 let size = size_state
7372 .and_then(|state| state.size)
7373 .unwrap_or_else(|| panel.default_size(window, cx));
7374 container = container.w(size);
7375 }
7376 } else {
7377 let size = size_state
7378 .and_then(|state| state.size)
7379 .unwrap_or_else(|| panel.default_size(window, cx));
7380 container = container.h(size);
7381 }
7382 }
7383
7384 Some(container)
7385 }
7386
7387 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7388 window
7389 .root::<MultiWorkspace>()
7390 .flatten()
7391 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7392 }
7393
7394 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7395 self.zoomed.as_ref()
7396 }
7397
7398 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7399 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7400 return;
7401 };
7402 let windows = cx.windows();
7403 let next_window =
7404 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7405 || {
7406 windows
7407 .iter()
7408 .cycle()
7409 .skip_while(|window| window.window_id() != current_window_id)
7410 .nth(1)
7411 },
7412 );
7413
7414 if let Some(window) = next_window {
7415 window
7416 .update(cx, |_, window, _| window.activate_window())
7417 .ok();
7418 }
7419 }
7420
7421 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7422 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7423 return;
7424 };
7425 let windows = cx.windows();
7426 let prev_window =
7427 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7428 || {
7429 windows
7430 .iter()
7431 .rev()
7432 .cycle()
7433 .skip_while(|window| window.window_id() != current_window_id)
7434 .nth(1)
7435 },
7436 );
7437
7438 if let Some(window) = prev_window {
7439 window
7440 .update(cx, |_, window, _| window.activate_window())
7441 .ok();
7442 }
7443 }
7444
7445 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7446 if cx.stop_active_drag(window) {
7447 } else if let Some((notification_id, _)) = self.notifications.pop() {
7448 dismiss_app_notification(¬ification_id, cx);
7449 } else {
7450 cx.propagate();
7451 }
7452 }
7453
7454 fn resize_dock(
7455 &mut self,
7456 dock_pos: DockPosition,
7457 new_size: Pixels,
7458 window: &mut Window,
7459 cx: &mut Context<Self>,
7460 ) {
7461 match dock_pos {
7462 DockPosition::Left => self.resize_left_dock(new_size, window, cx),
7463 DockPosition::Right => self.resize_right_dock(new_size, window, cx),
7464 DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
7465 }
7466 }
7467
7468 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7469 let workspace_width = self.bounds.size.width;
7470 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7471
7472 self.right_dock.read_with(cx, |right_dock, cx| {
7473 let right_dock_size = right_dock
7474 .stored_active_panel_size(window, cx)
7475 .unwrap_or(Pixels::ZERO);
7476 if right_dock_size + size > workspace_width {
7477 size = workspace_width - right_dock_size
7478 }
7479 });
7480
7481 let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
7482 self.left_dock.update(cx, |left_dock, cx| {
7483 if WorkspaceSettings::get_global(cx)
7484 .resize_all_panels_in_dock
7485 .contains(&DockPosition::Left)
7486 {
7487 left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7488 } else {
7489 left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7490 }
7491 });
7492 }
7493
7494 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7495 let workspace_width = self.bounds.size.width;
7496 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7497 self.left_dock.read_with(cx, |left_dock, cx| {
7498 let left_dock_size = left_dock
7499 .stored_active_panel_size(window, cx)
7500 .unwrap_or(Pixels::ZERO);
7501 if left_dock_size + size > workspace_width {
7502 size = workspace_width - left_dock_size
7503 }
7504 });
7505 let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
7506 self.right_dock.update(cx, |right_dock, cx| {
7507 if WorkspaceSettings::get_global(cx)
7508 .resize_all_panels_in_dock
7509 .contains(&DockPosition::Right)
7510 {
7511 right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7512 } else {
7513 right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7514 }
7515 });
7516 }
7517
7518 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7519 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7520 self.bottom_dock.update(cx, |bottom_dock, cx| {
7521 if WorkspaceSettings::get_global(cx)
7522 .resize_all_panels_in_dock
7523 .contains(&DockPosition::Bottom)
7524 {
7525 bottom_dock.resize_all_panels(Some(size), None, window, cx);
7526 } else {
7527 bottom_dock.resize_active_panel(Some(size), None, window, cx);
7528 }
7529 });
7530 }
7531
7532 fn toggle_edit_predictions_all_files(
7533 &mut self,
7534 _: &ToggleEditPrediction,
7535 _window: &mut Window,
7536 cx: &mut Context<Self>,
7537 ) {
7538 let fs = self.project().read(cx).fs().clone();
7539 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7540 update_settings_file(fs, cx, move |file, _| {
7541 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7542 });
7543 }
7544
7545 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7546 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7547 let next_mode = match current_mode {
7548 Some(theme_settings::ThemeAppearanceMode::Light) => {
7549 theme_settings::ThemeAppearanceMode::Dark
7550 }
7551 Some(theme_settings::ThemeAppearanceMode::Dark) => {
7552 theme_settings::ThemeAppearanceMode::Light
7553 }
7554 Some(theme_settings::ThemeAppearanceMode::System) | None => {
7555 match cx.theme().appearance() {
7556 theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
7557 theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
7558 }
7559 }
7560 };
7561
7562 let fs = self.project().read(cx).fs().clone();
7563 settings::update_settings_file(fs, cx, move |settings, _cx| {
7564 theme_settings::set_mode(settings, next_mode);
7565 });
7566 }
7567
7568 pub fn show_worktree_trust_security_modal(
7569 &mut self,
7570 toggle: bool,
7571 window: &mut Window,
7572 cx: &mut Context<Self>,
7573 ) {
7574 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7575 if toggle {
7576 security_modal.update(cx, |security_modal, cx| {
7577 security_modal.dismiss(cx);
7578 })
7579 } else {
7580 security_modal.update(cx, |security_modal, cx| {
7581 security_modal.refresh_restricted_paths(cx);
7582 });
7583 }
7584 } else {
7585 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7586 .map(|trusted_worktrees| {
7587 trusted_worktrees
7588 .read(cx)
7589 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7590 })
7591 .unwrap_or(false);
7592 if has_restricted_worktrees {
7593 let project = self.project().read(cx);
7594 let remote_host = project
7595 .remote_connection_options(cx)
7596 .map(RemoteHostLocation::from);
7597 let worktree_store = project.worktree_store().downgrade();
7598 self.toggle_modal(window, cx, |_, cx| {
7599 SecurityModal::new(worktree_store, remote_host, cx)
7600 });
7601 }
7602 }
7603 }
7604}
7605
7606pub trait AnyActiveCall {
7607 fn entity(&self) -> AnyEntity;
7608 fn is_in_room(&self, _: &App) -> bool;
7609 fn room_id(&self, _: &App) -> Option<u64>;
7610 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7611 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7612 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7613 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7614 fn is_sharing_project(&self, _: &App) -> bool;
7615 fn has_remote_participants(&self, _: &App) -> bool;
7616 fn local_participant_is_guest(&self, _: &App) -> bool;
7617 fn client(&self, _: &App) -> Arc<Client>;
7618 fn share_on_join(&self, _: &App) -> bool;
7619 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7620 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7621 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7622 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7623 fn join_project(
7624 &self,
7625 _: u64,
7626 _: Arc<LanguageRegistry>,
7627 _: Arc<dyn Fs>,
7628 _: &mut App,
7629 ) -> Task<Result<Entity<Project>>>;
7630 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7631 fn subscribe(
7632 &self,
7633 _: &mut Window,
7634 _: &mut Context<Workspace>,
7635 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7636 ) -> Subscription;
7637 fn create_shared_screen(
7638 &self,
7639 _: PeerId,
7640 _: &Entity<Pane>,
7641 _: &mut Window,
7642 _: &mut App,
7643 ) -> Option<Entity<SharedScreen>>;
7644}
7645
7646#[derive(Clone)]
7647pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7648impl Global for GlobalAnyActiveCall {}
7649
7650impl GlobalAnyActiveCall {
7651 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7652 cx.try_global()
7653 }
7654
7655 pub(crate) fn global(cx: &App) -> &Self {
7656 cx.global()
7657 }
7658}
7659
7660pub fn merge_conflict_notification_id() -> NotificationId {
7661 struct MergeConflictNotification;
7662 NotificationId::unique::<MergeConflictNotification>()
7663}
7664
7665/// Workspace-local view of a remote participant's location.
7666#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7667pub enum ParticipantLocation {
7668 SharedProject { project_id: u64 },
7669 UnsharedProject,
7670 External,
7671}
7672
7673impl ParticipantLocation {
7674 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7675 match location
7676 .and_then(|l| l.variant)
7677 .context("participant location was not provided")?
7678 {
7679 proto::participant_location::Variant::SharedProject(project) => {
7680 Ok(Self::SharedProject {
7681 project_id: project.id,
7682 })
7683 }
7684 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7685 proto::participant_location::Variant::External(_) => Ok(Self::External),
7686 }
7687 }
7688}
7689/// Workspace-local view of a remote collaborator's state.
7690/// This is the subset of `call::RemoteParticipant` that workspace needs.
7691#[derive(Clone)]
7692pub struct RemoteCollaborator {
7693 pub user: Arc<User>,
7694 pub peer_id: PeerId,
7695 pub location: ParticipantLocation,
7696 pub participant_index: ParticipantIndex,
7697}
7698
7699pub enum ActiveCallEvent {
7700 ParticipantLocationChanged { participant_id: PeerId },
7701 RemoteVideoTracksChanged { participant_id: PeerId },
7702}
7703
7704fn leader_border_for_pane(
7705 follower_states: &HashMap<CollaboratorId, FollowerState>,
7706 pane: &Entity<Pane>,
7707 _: &Window,
7708 cx: &App,
7709) -> Option<Div> {
7710 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7711 if state.pane() == pane {
7712 Some((*leader_id, state))
7713 } else {
7714 None
7715 }
7716 })?;
7717
7718 let mut leader_color = match leader_id {
7719 CollaboratorId::PeerId(leader_peer_id) => {
7720 let leader = GlobalAnyActiveCall::try_global(cx)?
7721 .0
7722 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7723
7724 cx.theme()
7725 .players()
7726 .color_for_participant(leader.participant_index.0)
7727 .cursor
7728 }
7729 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7730 };
7731 leader_color.fade_out(0.3);
7732 Some(
7733 div()
7734 .absolute()
7735 .size_full()
7736 .left_0()
7737 .top_0()
7738 .border_2()
7739 .border_color(leader_color),
7740 )
7741}
7742
7743fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7744 ZED_WINDOW_POSITION
7745 .zip(*ZED_WINDOW_SIZE)
7746 .map(|(position, size)| Bounds {
7747 origin: position,
7748 size,
7749 })
7750}
7751
7752fn open_items(
7753 serialized_workspace: Option<SerializedWorkspace>,
7754 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7755 window: &mut Window,
7756 cx: &mut Context<Workspace>,
7757) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7758 let restored_items = serialized_workspace.map(|serialized_workspace| {
7759 Workspace::load_workspace(
7760 serialized_workspace,
7761 project_paths_to_open
7762 .iter()
7763 .map(|(_, project_path)| project_path)
7764 .cloned()
7765 .collect(),
7766 window,
7767 cx,
7768 )
7769 });
7770
7771 cx.spawn_in(window, async move |workspace, cx| {
7772 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7773
7774 if let Some(restored_items) = restored_items {
7775 let restored_items = restored_items.await?;
7776
7777 let restored_project_paths = restored_items
7778 .iter()
7779 .filter_map(|item| {
7780 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7781 .ok()
7782 .flatten()
7783 })
7784 .collect::<HashSet<_>>();
7785
7786 for restored_item in restored_items {
7787 opened_items.push(restored_item.map(Ok));
7788 }
7789
7790 project_paths_to_open
7791 .iter_mut()
7792 .for_each(|(_, project_path)| {
7793 if let Some(project_path_to_open) = project_path
7794 && restored_project_paths.contains(project_path_to_open)
7795 {
7796 *project_path = None;
7797 }
7798 });
7799 } else {
7800 for _ in 0..project_paths_to_open.len() {
7801 opened_items.push(None);
7802 }
7803 }
7804 assert!(opened_items.len() == project_paths_to_open.len());
7805
7806 let tasks =
7807 project_paths_to_open
7808 .into_iter()
7809 .enumerate()
7810 .map(|(ix, (abs_path, project_path))| {
7811 let workspace = workspace.clone();
7812 cx.spawn(async move |cx| {
7813 let file_project_path = project_path?;
7814 let abs_path_task = workspace.update(cx, |workspace, cx| {
7815 workspace.project().update(cx, |project, cx| {
7816 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7817 })
7818 });
7819
7820 // We only want to open file paths here. If one of the items
7821 // here is a directory, it was already opened further above
7822 // with a `find_or_create_worktree`.
7823 if let Ok(task) = abs_path_task
7824 && task.await.is_none_or(|p| p.is_file())
7825 {
7826 return Some((
7827 ix,
7828 workspace
7829 .update_in(cx, |workspace, window, cx| {
7830 workspace.open_path(
7831 file_project_path,
7832 None,
7833 true,
7834 window,
7835 cx,
7836 )
7837 })
7838 .log_err()?
7839 .await,
7840 ));
7841 }
7842 None
7843 })
7844 });
7845
7846 let tasks = tasks.collect::<Vec<_>>();
7847
7848 let tasks = futures::future::join_all(tasks);
7849 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7850 opened_items[ix] = Some(path_open_result);
7851 }
7852
7853 Ok(opened_items)
7854 })
7855}
7856
7857#[derive(Clone)]
7858enum ActivateInDirectionTarget {
7859 Pane(Entity<Pane>),
7860 Dock(Entity<Dock>),
7861 Sidebar(FocusHandle),
7862}
7863
7864fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7865 window
7866 .update(cx, |multi_workspace, _, cx| {
7867 let workspace = multi_workspace.workspace().clone();
7868 workspace.update(cx, |workspace, cx| {
7869 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7870 struct DatabaseFailedNotification;
7871
7872 workspace.show_notification(
7873 NotificationId::unique::<DatabaseFailedNotification>(),
7874 cx,
7875 |cx| {
7876 cx.new(|cx| {
7877 MessageNotification::new("Failed to load the database file.", cx)
7878 .primary_message("File an Issue")
7879 .primary_icon(IconName::Plus)
7880 .primary_on_click(|window, cx| {
7881 window.dispatch_action(Box::new(FileBugReport), cx)
7882 })
7883 })
7884 },
7885 );
7886 }
7887 });
7888 })
7889 .log_err();
7890}
7891
7892fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7893 if val == 0 {
7894 ThemeSettings::get_global(cx).ui_font_size(cx)
7895 } else {
7896 px(val as f32)
7897 }
7898}
7899
7900fn adjust_active_dock_size_by_px(
7901 px: Pixels,
7902 workspace: &mut Workspace,
7903 window: &mut Window,
7904 cx: &mut Context<Workspace>,
7905) {
7906 let Some(active_dock) = workspace
7907 .all_docks()
7908 .into_iter()
7909 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7910 else {
7911 return;
7912 };
7913 let dock = active_dock.read(cx);
7914 let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
7915 return;
7916 };
7917 workspace.resize_dock(dock.position(), panel_size + px, window, cx);
7918}
7919
7920fn adjust_open_docks_size_by_px(
7921 px: Pixels,
7922 workspace: &mut Workspace,
7923 window: &mut Window,
7924 cx: &mut Context<Workspace>,
7925) {
7926 let docks = workspace
7927 .all_docks()
7928 .into_iter()
7929 .filter_map(|dock_entity| {
7930 let dock = dock_entity.read(cx);
7931 if dock.is_open() {
7932 let dock_pos = dock.position();
7933 let panel_size = workspace.dock_size(&dock, window, cx)?;
7934 Some((dock_pos, panel_size + px))
7935 } else {
7936 None
7937 }
7938 })
7939 .collect::<Vec<_>>();
7940
7941 for (position, new_size) in docks {
7942 workspace.resize_dock(position, new_size, window, cx);
7943 }
7944}
7945
7946impl Focusable for Workspace {
7947 fn focus_handle(&self, cx: &App) -> FocusHandle {
7948 self.active_pane.focus_handle(cx)
7949 }
7950}
7951
7952#[derive(Clone)]
7953struct DraggedDock(DockPosition);
7954
7955impl Render for DraggedDock {
7956 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7957 gpui::Empty
7958 }
7959}
7960
7961impl Render for Workspace {
7962 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7963 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7964 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7965 log::info!("Rendered first frame");
7966 }
7967
7968 let centered_layout = self.centered_layout
7969 && self.center.panes().len() == 1
7970 && self.active_item(cx).is_some();
7971 let render_padding = |size| {
7972 (size > 0.0).then(|| {
7973 div()
7974 .h_full()
7975 .w(relative(size))
7976 .bg(cx.theme().colors().editor_background)
7977 .border_color(cx.theme().colors().pane_group_border)
7978 })
7979 };
7980 let paddings = if centered_layout {
7981 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7982 (
7983 render_padding(Self::adjust_padding(
7984 settings.left_padding.map(|padding| padding.0),
7985 )),
7986 render_padding(Self::adjust_padding(
7987 settings.right_padding.map(|padding| padding.0),
7988 )),
7989 )
7990 } else {
7991 (None, None)
7992 };
7993 let ui_font = theme_settings::setup_ui_font(window, cx);
7994
7995 let theme = cx.theme().clone();
7996 let colors = theme.colors();
7997 let notification_entities = self
7998 .notifications
7999 .iter()
8000 .map(|(_, notification)| notification.entity_id())
8001 .collect::<Vec<_>>();
8002 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
8003
8004 div()
8005 .relative()
8006 .size_full()
8007 .flex()
8008 .flex_col()
8009 .font(ui_font)
8010 .gap_0()
8011 .justify_start()
8012 .items_start()
8013 .text_color(colors.text)
8014 .overflow_hidden()
8015 .children(self.titlebar_item.clone())
8016 .on_modifiers_changed(move |_, _, cx| {
8017 for &id in ¬ification_entities {
8018 cx.notify(id);
8019 }
8020 })
8021 .child(
8022 div()
8023 .size_full()
8024 .relative()
8025 .flex_1()
8026 .flex()
8027 .flex_col()
8028 .child(
8029 div()
8030 .id("workspace")
8031 .bg(colors.background)
8032 .relative()
8033 .flex_1()
8034 .w_full()
8035 .flex()
8036 .flex_col()
8037 .overflow_hidden()
8038 .border_t_1()
8039 .border_b_1()
8040 .border_color(colors.border)
8041 .child({
8042 let this = cx.entity();
8043 canvas(
8044 move |bounds, window, cx| {
8045 this.update(cx, |this, cx| {
8046 let bounds_changed = this.bounds != bounds;
8047 this.bounds = bounds;
8048
8049 if bounds_changed {
8050 this.left_dock.update(cx, |dock, cx| {
8051 dock.clamp_panel_size(
8052 bounds.size.width,
8053 window,
8054 cx,
8055 )
8056 });
8057
8058 this.right_dock.update(cx, |dock, cx| {
8059 dock.clamp_panel_size(
8060 bounds.size.width,
8061 window,
8062 cx,
8063 )
8064 });
8065
8066 this.bottom_dock.update(cx, |dock, cx| {
8067 dock.clamp_panel_size(
8068 bounds.size.height,
8069 window,
8070 cx,
8071 )
8072 });
8073 }
8074 })
8075 },
8076 |_, _, _, _| {},
8077 )
8078 .absolute()
8079 .size_full()
8080 })
8081 .when(self.zoomed.is_none(), |this| {
8082 this.on_drag_move(cx.listener(
8083 move |workspace,
8084 e: &DragMoveEvent<DraggedDock>,
8085 window,
8086 cx| {
8087 if workspace.previous_dock_drag_coordinates
8088 != Some(e.event.position)
8089 {
8090 workspace.previous_dock_drag_coordinates =
8091 Some(e.event.position);
8092
8093 match e.drag(cx).0 {
8094 DockPosition::Left => {
8095 workspace.resize_left_dock(
8096 e.event.position.x
8097 - workspace.bounds.left(),
8098 window,
8099 cx,
8100 );
8101 }
8102 DockPosition::Right => {
8103 workspace.resize_right_dock(
8104 workspace.bounds.right()
8105 - e.event.position.x,
8106 window,
8107 cx,
8108 );
8109 }
8110 DockPosition::Bottom => {
8111 workspace.resize_bottom_dock(
8112 workspace.bounds.bottom()
8113 - e.event.position.y,
8114 window,
8115 cx,
8116 );
8117 }
8118 };
8119 workspace.serialize_workspace(window, cx);
8120 }
8121 },
8122 ))
8123
8124 })
8125 .child({
8126 match bottom_dock_layout {
8127 BottomDockLayout::Full => div()
8128 .flex()
8129 .flex_col()
8130 .h_full()
8131 .child(
8132 div()
8133 .flex()
8134 .flex_row()
8135 .flex_1()
8136 .overflow_hidden()
8137 .children(self.render_dock(
8138 DockPosition::Left,
8139 &self.left_dock,
8140 window,
8141 cx,
8142 ))
8143
8144 .child(
8145 div()
8146 .flex()
8147 .flex_col()
8148 .flex_1()
8149 .overflow_hidden()
8150 .child(
8151 h_flex()
8152 .flex_1()
8153 .when_some(
8154 paddings.0,
8155 |this, p| {
8156 this.child(
8157 p.border_r_1(),
8158 )
8159 },
8160 )
8161 .child(self.center.render(
8162 self.zoomed.as_ref(),
8163 &PaneRenderContext {
8164 follower_states:
8165 &self.follower_states,
8166 active_call: self.active_call(),
8167 active_pane: &self.active_pane,
8168 app_state: &self.app_state,
8169 project: &self.project,
8170 workspace: &self.weak_self,
8171 },
8172 window,
8173 cx,
8174 ))
8175 .when_some(
8176 paddings.1,
8177 |this, p| {
8178 this.child(
8179 p.border_l_1(),
8180 )
8181 },
8182 ),
8183 ),
8184 )
8185
8186 .children(self.render_dock(
8187 DockPosition::Right,
8188 &self.right_dock,
8189 window,
8190 cx,
8191 )),
8192 )
8193 .child(div().w_full().children(self.render_dock(
8194 DockPosition::Bottom,
8195 &self.bottom_dock,
8196 window,
8197 cx
8198 ))),
8199
8200 BottomDockLayout::LeftAligned => div()
8201 .flex()
8202 .flex_row()
8203 .h_full()
8204 .child(
8205 div()
8206 .flex()
8207 .flex_col()
8208 .flex_1()
8209 .h_full()
8210 .child(
8211 div()
8212 .flex()
8213 .flex_row()
8214 .flex_1()
8215 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
8216
8217 .child(
8218 div()
8219 .flex()
8220 .flex_col()
8221 .flex_1()
8222 .overflow_hidden()
8223 .child(
8224 h_flex()
8225 .flex_1()
8226 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8227 .child(self.center.render(
8228 self.zoomed.as_ref(),
8229 &PaneRenderContext {
8230 follower_states:
8231 &self.follower_states,
8232 active_call: self.active_call(),
8233 active_pane: &self.active_pane,
8234 app_state: &self.app_state,
8235 project: &self.project,
8236 workspace: &self.weak_self,
8237 },
8238 window,
8239 cx,
8240 ))
8241 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8242 )
8243 )
8244
8245 )
8246 .child(
8247 div()
8248 .w_full()
8249 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8250 ),
8251 )
8252 .children(self.render_dock(
8253 DockPosition::Right,
8254 &self.right_dock,
8255 window,
8256 cx,
8257 )),
8258 BottomDockLayout::RightAligned => div()
8259 .flex()
8260 .flex_row()
8261 .h_full()
8262 .children(self.render_dock(
8263 DockPosition::Left,
8264 &self.left_dock,
8265 window,
8266 cx,
8267 ))
8268
8269 .child(
8270 div()
8271 .flex()
8272 .flex_col()
8273 .flex_1()
8274 .h_full()
8275 .child(
8276 div()
8277 .flex()
8278 .flex_row()
8279 .flex_1()
8280 .child(
8281 div()
8282 .flex()
8283 .flex_col()
8284 .flex_1()
8285 .overflow_hidden()
8286 .child(
8287 h_flex()
8288 .flex_1()
8289 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8290 .child(self.center.render(
8291 self.zoomed.as_ref(),
8292 &PaneRenderContext {
8293 follower_states:
8294 &self.follower_states,
8295 active_call: self.active_call(),
8296 active_pane: &self.active_pane,
8297 app_state: &self.app_state,
8298 project: &self.project,
8299 workspace: &self.weak_self,
8300 },
8301 window,
8302 cx,
8303 ))
8304 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8305 )
8306 )
8307
8308 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8309 )
8310 .child(
8311 div()
8312 .w_full()
8313 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8314 ),
8315 ),
8316 BottomDockLayout::Contained => div()
8317 .flex()
8318 .flex_row()
8319 .h_full()
8320 .children(self.render_dock(
8321 DockPosition::Left,
8322 &self.left_dock,
8323 window,
8324 cx,
8325 ))
8326
8327 .child(
8328 div()
8329 .flex()
8330 .flex_col()
8331 .flex_1()
8332 .overflow_hidden()
8333 .child(
8334 h_flex()
8335 .flex_1()
8336 .when_some(paddings.0, |this, p| {
8337 this.child(p.border_r_1())
8338 })
8339 .child(self.center.render(
8340 self.zoomed.as_ref(),
8341 &PaneRenderContext {
8342 follower_states:
8343 &self.follower_states,
8344 active_call: self.active_call(),
8345 active_pane: &self.active_pane,
8346 app_state: &self.app_state,
8347 project: &self.project,
8348 workspace: &self.weak_self,
8349 },
8350 window,
8351 cx,
8352 ))
8353 .when_some(paddings.1, |this, p| {
8354 this.child(p.border_l_1())
8355 }),
8356 )
8357 .children(self.render_dock(
8358 DockPosition::Bottom,
8359 &self.bottom_dock,
8360 window,
8361 cx,
8362 )),
8363 )
8364
8365 .children(self.render_dock(
8366 DockPosition::Right,
8367 &self.right_dock,
8368 window,
8369 cx,
8370 )),
8371 }
8372 })
8373 .children(self.zoomed.as_ref().and_then(|view| {
8374 let zoomed_view = view.upgrade()?;
8375 let div = div()
8376 .occlude()
8377 .absolute()
8378 .overflow_hidden()
8379 .border_color(colors.border)
8380 .bg(colors.background)
8381 .child(zoomed_view)
8382 .inset_0()
8383 .shadow_lg();
8384
8385 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8386 return Some(div);
8387 }
8388
8389 Some(match self.zoomed_position {
8390 Some(DockPosition::Left) => div.right_2().border_r_1(),
8391 Some(DockPosition::Right) => div.left_2().border_l_1(),
8392 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8393 None => {
8394 div.top_2().bottom_2().left_2().right_2().border_1()
8395 }
8396 })
8397 }))
8398 .children(self.render_notifications(window, cx)),
8399 )
8400 .when(self.status_bar_visible(cx), |parent| {
8401 parent.child(self.status_bar.clone())
8402 })
8403 .child(self.toast_layer.clone()),
8404 )
8405 }
8406}
8407
8408impl WorkspaceStore {
8409 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8410 Self {
8411 workspaces: Default::default(),
8412 _subscriptions: vec![
8413 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8414 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8415 ],
8416 client,
8417 }
8418 }
8419
8420 pub fn update_followers(
8421 &self,
8422 project_id: Option<u64>,
8423 update: proto::update_followers::Variant,
8424 cx: &App,
8425 ) -> Option<()> {
8426 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8427 let room_id = active_call.0.room_id(cx)?;
8428 self.client
8429 .send(proto::UpdateFollowers {
8430 room_id,
8431 project_id,
8432 variant: Some(update),
8433 })
8434 .log_err()
8435 }
8436
8437 pub async fn handle_follow(
8438 this: Entity<Self>,
8439 envelope: TypedEnvelope<proto::Follow>,
8440 mut cx: AsyncApp,
8441 ) -> Result<proto::FollowResponse> {
8442 this.update(&mut cx, |this, cx| {
8443 let follower = Follower {
8444 project_id: envelope.payload.project_id,
8445 peer_id: envelope.original_sender_id()?,
8446 };
8447
8448 let mut response = proto::FollowResponse::default();
8449
8450 this.workspaces.retain(|(window_handle, weak_workspace)| {
8451 let Some(workspace) = weak_workspace.upgrade() else {
8452 return false;
8453 };
8454 window_handle
8455 .update(cx, |_, window, cx| {
8456 workspace.update(cx, |workspace, cx| {
8457 let handler_response =
8458 workspace.handle_follow(follower.project_id, window, cx);
8459 if let Some(active_view) = handler_response.active_view
8460 && workspace.project.read(cx).remote_id() == follower.project_id
8461 {
8462 response.active_view = Some(active_view)
8463 }
8464 });
8465 })
8466 .is_ok()
8467 });
8468
8469 Ok(response)
8470 })
8471 }
8472
8473 async fn handle_update_followers(
8474 this: Entity<Self>,
8475 envelope: TypedEnvelope<proto::UpdateFollowers>,
8476 mut cx: AsyncApp,
8477 ) -> Result<()> {
8478 let leader_id = envelope.original_sender_id()?;
8479 let update = envelope.payload;
8480
8481 this.update(&mut cx, |this, cx| {
8482 this.workspaces.retain(|(window_handle, weak_workspace)| {
8483 let Some(workspace) = weak_workspace.upgrade() else {
8484 return false;
8485 };
8486 window_handle
8487 .update(cx, |_, window, cx| {
8488 workspace.update(cx, |workspace, cx| {
8489 let project_id = workspace.project.read(cx).remote_id();
8490 if update.project_id != project_id && update.project_id.is_some() {
8491 return;
8492 }
8493 workspace.handle_update_followers(
8494 leader_id,
8495 update.clone(),
8496 window,
8497 cx,
8498 );
8499 });
8500 })
8501 .is_ok()
8502 });
8503 Ok(())
8504 })
8505 }
8506
8507 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8508 self.workspaces.iter().map(|(_, weak)| weak)
8509 }
8510
8511 pub fn workspaces_with_windows(
8512 &self,
8513 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8514 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8515 }
8516}
8517
8518impl ViewId {
8519 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8520 Ok(Self {
8521 creator: message
8522 .creator
8523 .map(CollaboratorId::PeerId)
8524 .context("creator is missing")?,
8525 id: message.id,
8526 })
8527 }
8528
8529 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8530 if let CollaboratorId::PeerId(peer_id) = self.creator {
8531 Some(proto::ViewId {
8532 creator: Some(peer_id),
8533 id: self.id,
8534 })
8535 } else {
8536 None
8537 }
8538 }
8539}
8540
8541impl FollowerState {
8542 fn pane(&self) -> &Entity<Pane> {
8543 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8544 }
8545}
8546
8547pub trait WorkspaceHandle {
8548 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8549}
8550
8551impl WorkspaceHandle for Entity<Workspace> {
8552 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8553 self.read(cx)
8554 .worktrees(cx)
8555 .flat_map(|worktree| {
8556 let worktree_id = worktree.read(cx).id();
8557 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8558 worktree_id,
8559 path: f.path.clone(),
8560 })
8561 })
8562 .collect::<Vec<_>>()
8563 }
8564}
8565
8566pub async fn last_opened_workspace_location(
8567 db: &WorkspaceDb,
8568 fs: &dyn fs::Fs,
8569) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8570 db.last_workspace(fs)
8571 .await
8572 .log_err()
8573 .flatten()
8574 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8575}
8576
8577pub async fn last_session_workspace_locations(
8578 db: &WorkspaceDb,
8579 last_session_id: &str,
8580 last_session_window_stack: Option<Vec<WindowId>>,
8581 fs: &dyn fs::Fs,
8582) -> Option<Vec<SessionWorkspace>> {
8583 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8584 .await
8585 .log_err()
8586}
8587
8588pub struct MultiWorkspaceRestoreResult {
8589 pub window_handle: WindowHandle<MultiWorkspace>,
8590 pub errors: Vec<anyhow::Error>,
8591}
8592
8593pub async fn restore_multiworkspace(
8594 multi_workspace: SerializedMultiWorkspace,
8595 app_state: Arc<AppState>,
8596 cx: &mut AsyncApp,
8597) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8598 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
8599 let mut group_iter = workspaces.into_iter();
8600 let first = group_iter
8601 .next()
8602 .context("window group must not be empty")?;
8603
8604 let window_handle = if first.paths.is_empty() {
8605 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8606 .await?
8607 } else {
8608 let OpenResult { window, .. } = cx
8609 .update(|cx| {
8610 Workspace::new_local(
8611 first.paths.paths().to_vec(),
8612 app_state.clone(),
8613 None,
8614 None,
8615 None,
8616 OpenMode::Activate,
8617 cx,
8618 )
8619 })
8620 .await?;
8621 window
8622 };
8623
8624 let mut errors = Vec::new();
8625
8626 for session_workspace in group_iter {
8627 let error = if session_workspace.paths.is_empty() {
8628 cx.update(|cx| {
8629 open_workspace_by_id(
8630 session_workspace.workspace_id,
8631 app_state.clone(),
8632 Some(window_handle),
8633 cx,
8634 )
8635 })
8636 .await
8637 .err()
8638 } else {
8639 cx.update(|cx| {
8640 Workspace::new_local(
8641 session_workspace.paths.paths().to_vec(),
8642 app_state.clone(),
8643 Some(window_handle),
8644 None,
8645 None,
8646 OpenMode::Add,
8647 cx,
8648 )
8649 })
8650 .await
8651 .err()
8652 };
8653
8654 if let Some(error) = error {
8655 errors.push(error);
8656 }
8657 }
8658
8659 if let Some(target_id) = state.active_workspace_id {
8660 window_handle
8661 .update(cx, |multi_workspace, window, cx| {
8662 let target_index = multi_workspace
8663 .workspaces()
8664 .iter()
8665 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8666 let index = target_index.unwrap_or(0);
8667 if let Some(workspace) = multi_workspace.workspaces().get(index).cloned() {
8668 multi_workspace.activate(workspace, window, cx);
8669 }
8670 })
8671 .ok();
8672 } else {
8673 window_handle
8674 .update(cx, |multi_workspace, window, cx| {
8675 if let Some(workspace) = multi_workspace.workspaces().first().cloned() {
8676 multi_workspace.activate(workspace, window, cx);
8677 }
8678 })
8679 .ok();
8680 }
8681
8682 if state.sidebar_open {
8683 window_handle
8684 .update(cx, |multi_workspace, _, cx| {
8685 multi_workspace.open_sidebar(cx);
8686 })
8687 .ok();
8688 }
8689
8690 window_handle
8691 .update(cx, |_, window, _cx| {
8692 window.activate_window();
8693 })
8694 .ok();
8695
8696 Ok(MultiWorkspaceRestoreResult {
8697 window_handle,
8698 errors,
8699 })
8700}
8701
8702actions!(
8703 collab,
8704 [
8705 /// Opens the channel notes for the current call.
8706 ///
8707 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8708 /// channel in the collab panel.
8709 ///
8710 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8711 /// can be copied via "Copy link to section" in the context menu of the channel notes
8712 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8713 OpenChannelNotes,
8714 /// Mutes your microphone.
8715 Mute,
8716 /// Deafens yourself (mute both microphone and speakers).
8717 Deafen,
8718 /// Leaves the current call.
8719 LeaveCall,
8720 /// Shares the current project with collaborators.
8721 ShareProject,
8722 /// Shares your screen with collaborators.
8723 ScreenShare,
8724 /// Copies the current room name and session id for debugging purposes.
8725 CopyRoomId,
8726 ]
8727);
8728
8729/// Opens the channel notes for a specific channel by its ID.
8730#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8731#[action(namespace = collab)]
8732#[serde(deny_unknown_fields)]
8733pub struct OpenChannelNotesById {
8734 pub channel_id: u64,
8735}
8736
8737actions!(
8738 zed,
8739 [
8740 /// Opens the Zed log file.
8741 OpenLog,
8742 /// Reveals the Zed log file in the system file manager.
8743 RevealLogInFileManager
8744 ]
8745);
8746
8747async fn join_channel_internal(
8748 channel_id: ChannelId,
8749 app_state: &Arc<AppState>,
8750 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8751 requesting_workspace: Option<WeakEntity<Workspace>>,
8752 active_call: &dyn AnyActiveCall,
8753 cx: &mut AsyncApp,
8754) -> Result<bool> {
8755 let (should_prompt, already_in_channel) = cx.update(|cx| {
8756 if !active_call.is_in_room(cx) {
8757 return (false, false);
8758 }
8759
8760 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8761 let should_prompt = active_call.is_sharing_project(cx)
8762 && active_call.has_remote_participants(cx)
8763 && !already_in_channel;
8764 (should_prompt, already_in_channel)
8765 });
8766
8767 if already_in_channel {
8768 let task = cx.update(|cx| {
8769 if let Some((project, host)) = active_call.most_active_project(cx) {
8770 Some(join_in_room_project(project, host, app_state.clone(), cx))
8771 } else {
8772 None
8773 }
8774 });
8775 if let Some(task) = task {
8776 task.await?;
8777 }
8778 return anyhow::Ok(true);
8779 }
8780
8781 if should_prompt {
8782 if let Some(multi_workspace) = requesting_window {
8783 let answer = multi_workspace
8784 .update(cx, |_, window, cx| {
8785 window.prompt(
8786 PromptLevel::Warning,
8787 "Do you want to switch channels?",
8788 Some("Leaving this call will unshare your current project."),
8789 &["Yes, Join Channel", "Cancel"],
8790 cx,
8791 )
8792 })?
8793 .await;
8794
8795 if answer == Ok(1) {
8796 return Ok(false);
8797 }
8798 } else {
8799 return Ok(false);
8800 }
8801 }
8802
8803 let client = cx.update(|cx| active_call.client(cx));
8804
8805 let mut client_status = client.status();
8806
8807 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8808 'outer: loop {
8809 let Some(status) = client_status.recv().await else {
8810 anyhow::bail!("error connecting");
8811 };
8812
8813 match status {
8814 Status::Connecting
8815 | Status::Authenticating
8816 | Status::Authenticated
8817 | Status::Reconnecting
8818 | Status::Reauthenticating
8819 | Status::Reauthenticated => continue,
8820 Status::Connected { .. } => break 'outer,
8821 Status::SignedOut | Status::AuthenticationError => {
8822 return Err(ErrorCode::SignedOut.into());
8823 }
8824 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8825 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8826 return Err(ErrorCode::Disconnected.into());
8827 }
8828 }
8829 }
8830
8831 let joined = cx
8832 .update(|cx| active_call.join_channel(channel_id, cx))
8833 .await?;
8834
8835 if !joined {
8836 return anyhow::Ok(true);
8837 }
8838
8839 cx.update(|cx| active_call.room_update_completed(cx)).await;
8840
8841 let task = cx.update(|cx| {
8842 if let Some((project, host)) = active_call.most_active_project(cx) {
8843 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8844 }
8845
8846 // If you are the first to join a channel, see if you should share your project.
8847 if !active_call.has_remote_participants(cx)
8848 && !active_call.local_participant_is_guest(cx)
8849 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8850 {
8851 let project = workspace.update(cx, |workspace, cx| {
8852 let project = workspace.project.read(cx);
8853
8854 if !active_call.share_on_join(cx) {
8855 return None;
8856 }
8857
8858 if (project.is_local() || project.is_via_remote_server())
8859 && project.visible_worktrees(cx).any(|tree| {
8860 tree.read(cx)
8861 .root_entry()
8862 .is_some_and(|entry| entry.is_dir())
8863 })
8864 {
8865 Some(workspace.project.clone())
8866 } else {
8867 None
8868 }
8869 });
8870 if let Some(project) = project {
8871 let share_task = active_call.share_project(project, cx);
8872 return Some(cx.spawn(async move |_cx| -> Result<()> {
8873 share_task.await?;
8874 Ok(())
8875 }));
8876 }
8877 }
8878
8879 None
8880 });
8881 if let Some(task) = task {
8882 task.await?;
8883 return anyhow::Ok(true);
8884 }
8885 anyhow::Ok(false)
8886}
8887
8888pub fn join_channel(
8889 channel_id: ChannelId,
8890 app_state: Arc<AppState>,
8891 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8892 requesting_workspace: Option<WeakEntity<Workspace>>,
8893 cx: &mut App,
8894) -> Task<Result<()>> {
8895 let active_call = GlobalAnyActiveCall::global(cx).clone();
8896 cx.spawn(async move |cx| {
8897 let result = join_channel_internal(
8898 channel_id,
8899 &app_state,
8900 requesting_window,
8901 requesting_workspace,
8902 &*active_call.0,
8903 cx,
8904 )
8905 .await;
8906
8907 // join channel succeeded, and opened a window
8908 if matches!(result, Ok(true)) {
8909 return anyhow::Ok(());
8910 }
8911
8912 // find an existing workspace to focus and show call controls
8913 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8914 if active_window.is_none() {
8915 // no open workspaces, make one to show the error in (blergh)
8916 let OpenResult {
8917 window: window_handle,
8918 ..
8919 } = cx
8920 .update(|cx| {
8921 Workspace::new_local(
8922 vec![],
8923 app_state.clone(),
8924 requesting_window,
8925 None,
8926 None,
8927 OpenMode::Activate,
8928 cx,
8929 )
8930 })
8931 .await?;
8932
8933 window_handle
8934 .update(cx, |_, window, _cx| {
8935 window.activate_window();
8936 })
8937 .ok();
8938
8939 if result.is_ok() {
8940 cx.update(|cx| {
8941 cx.dispatch_action(&OpenChannelNotes);
8942 });
8943 }
8944
8945 active_window = Some(window_handle);
8946 }
8947
8948 if let Err(err) = result {
8949 log::error!("failed to join channel: {}", err);
8950 if let Some(active_window) = active_window {
8951 active_window
8952 .update(cx, |_, window, cx| {
8953 let detail: SharedString = match err.error_code() {
8954 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8955 ErrorCode::UpgradeRequired => concat!(
8956 "Your are running an unsupported version of Zed. ",
8957 "Please update to continue."
8958 )
8959 .into(),
8960 ErrorCode::NoSuchChannel => concat!(
8961 "No matching channel was found. ",
8962 "Please check the link and try again."
8963 )
8964 .into(),
8965 ErrorCode::Forbidden => concat!(
8966 "This channel is private, and you do not have access. ",
8967 "Please ask someone to add you and try again."
8968 )
8969 .into(),
8970 ErrorCode::Disconnected => {
8971 "Please check your internet connection and try again.".into()
8972 }
8973 _ => format!("{}\n\nPlease try again.", err).into(),
8974 };
8975 window.prompt(
8976 PromptLevel::Critical,
8977 "Failed to join channel",
8978 Some(&detail),
8979 &["Ok"],
8980 cx,
8981 )
8982 })?
8983 .await
8984 .ok();
8985 }
8986 }
8987
8988 // return ok, we showed the error to the user.
8989 anyhow::Ok(())
8990 })
8991}
8992
8993pub async fn get_any_active_multi_workspace(
8994 app_state: Arc<AppState>,
8995 mut cx: AsyncApp,
8996) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8997 // find an existing workspace to focus and show call controls
8998 let active_window = activate_any_workspace_window(&mut cx);
8999 if active_window.is_none() {
9000 cx.update(|cx| {
9001 Workspace::new_local(
9002 vec![],
9003 app_state.clone(),
9004 None,
9005 None,
9006 None,
9007 OpenMode::Activate,
9008 cx,
9009 )
9010 })
9011 .await?;
9012 }
9013 activate_any_workspace_window(&mut cx).context("could not open zed")
9014}
9015
9016fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
9017 cx.update(|cx| {
9018 if let Some(workspace_window) = cx
9019 .active_window()
9020 .and_then(|window| window.downcast::<MultiWorkspace>())
9021 {
9022 return Some(workspace_window);
9023 }
9024
9025 for window in cx.windows() {
9026 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
9027 workspace_window
9028 .update(cx, |_, window, _| window.activate_window())
9029 .ok();
9030 return Some(workspace_window);
9031 }
9032 }
9033 None
9034 })
9035}
9036
9037pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
9038 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
9039}
9040
9041pub fn workspace_windows_for_location(
9042 serialized_location: &SerializedWorkspaceLocation,
9043 cx: &App,
9044) -> Vec<WindowHandle<MultiWorkspace>> {
9045 cx.windows()
9046 .into_iter()
9047 .filter_map(|window| window.downcast::<MultiWorkspace>())
9048 .filter(|multi_workspace| {
9049 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
9050 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
9051 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
9052 }
9053 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
9054 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
9055 a.distro_name == b.distro_name
9056 }
9057 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
9058 a.container_id == b.container_id
9059 }
9060 #[cfg(any(test, feature = "test-support"))]
9061 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
9062 a.id == b.id
9063 }
9064 _ => false,
9065 };
9066
9067 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
9068 multi_workspace.workspaces().iter().any(|workspace| {
9069 match workspace.read(cx).workspace_location(cx) {
9070 WorkspaceLocation::Location(location, _) => {
9071 match (&location, serialized_location) {
9072 (
9073 SerializedWorkspaceLocation::Local,
9074 SerializedWorkspaceLocation::Local,
9075 ) => true,
9076 (
9077 SerializedWorkspaceLocation::Remote(a),
9078 SerializedWorkspaceLocation::Remote(b),
9079 ) => same_host(a, b),
9080 _ => false,
9081 }
9082 }
9083 _ => false,
9084 }
9085 })
9086 })
9087 })
9088 .collect()
9089}
9090
9091pub async fn find_existing_workspace(
9092 abs_paths: &[PathBuf],
9093 open_options: &OpenOptions,
9094 location: &SerializedWorkspaceLocation,
9095 cx: &mut AsyncApp,
9096) -> (
9097 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
9098 OpenVisible,
9099) {
9100 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
9101 let mut open_visible = OpenVisible::All;
9102 let mut best_match = None;
9103
9104 if open_options.open_new_workspace != Some(true) {
9105 cx.update(|cx| {
9106 for window in workspace_windows_for_location(location, cx) {
9107 if let Ok(multi_workspace) = window.read(cx) {
9108 for workspace in multi_workspace.workspaces() {
9109 let project = workspace.read(cx).project.read(cx);
9110 let m = project.visibility_for_paths(
9111 abs_paths,
9112 open_options.open_new_workspace == None,
9113 cx,
9114 );
9115 if m > best_match {
9116 existing = Some((window, workspace.clone()));
9117 best_match = m;
9118 } else if best_match.is_none()
9119 && open_options.open_new_workspace == Some(false)
9120 {
9121 existing = Some((window, workspace.clone()))
9122 }
9123 }
9124 }
9125 }
9126 });
9127
9128 let all_paths_are_files = existing
9129 .as_ref()
9130 .and_then(|(_, target_workspace)| {
9131 cx.update(|cx| {
9132 let workspace = target_workspace.read(cx);
9133 let project = workspace.project.read(cx);
9134 let path_style = workspace.path_style(cx);
9135 Some(!abs_paths.iter().any(|path| {
9136 let path = util::paths::SanitizedPath::new(path);
9137 project.worktrees(cx).any(|worktree| {
9138 let worktree = worktree.read(cx);
9139 let abs_path = worktree.abs_path();
9140 path_style
9141 .strip_prefix(path.as_ref(), abs_path.as_ref())
9142 .and_then(|rel| worktree.entry_for_path(&rel))
9143 .is_some_and(|e| e.is_dir())
9144 })
9145 }))
9146 })
9147 })
9148 .unwrap_or(false);
9149
9150 if open_options.open_new_workspace.is_none()
9151 && existing.is_some()
9152 && open_options.wait
9153 && all_paths_are_files
9154 {
9155 cx.update(|cx| {
9156 let windows = workspace_windows_for_location(location, cx);
9157 let window = cx
9158 .active_window()
9159 .and_then(|window| window.downcast::<MultiWorkspace>())
9160 .filter(|window| windows.contains(window))
9161 .or_else(|| windows.into_iter().next());
9162 if let Some(window) = window {
9163 if let Ok(multi_workspace) = window.read(cx) {
9164 let active_workspace = multi_workspace.workspace().clone();
9165 existing = Some((window, active_workspace));
9166 open_visible = OpenVisible::None;
9167 }
9168 }
9169 });
9170 }
9171 }
9172 (existing, open_visible)
9173}
9174
9175#[derive(Default, Clone)]
9176pub struct OpenOptions {
9177 pub visible: Option<OpenVisible>,
9178 pub focus: Option<bool>,
9179 pub open_new_workspace: Option<bool>,
9180 pub wait: bool,
9181 pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
9182 pub open_mode: OpenMode,
9183 pub env: Option<HashMap<String, String>>,
9184}
9185
9186/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
9187/// or [`Workspace::open_workspace_for_paths`].
9188pub struct OpenResult {
9189 pub window: WindowHandle<MultiWorkspace>,
9190 pub workspace: Entity<Workspace>,
9191 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
9192}
9193
9194/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
9195pub fn open_workspace_by_id(
9196 workspace_id: WorkspaceId,
9197 app_state: Arc<AppState>,
9198 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9199 cx: &mut App,
9200) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
9201 let project_handle = Project::local(
9202 app_state.client.clone(),
9203 app_state.node_runtime.clone(),
9204 app_state.user_store.clone(),
9205 app_state.languages.clone(),
9206 app_state.fs.clone(),
9207 None,
9208 project::LocalProjectFlags {
9209 init_worktree_trust: true,
9210 ..project::LocalProjectFlags::default()
9211 },
9212 cx,
9213 );
9214
9215 let db = WorkspaceDb::global(cx);
9216 let kvp = db::kvp::KeyValueStore::global(cx);
9217 cx.spawn(async move |cx| {
9218 let serialized_workspace = db
9219 .workspace_for_id(workspace_id)
9220 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
9221
9222 let centered_layout = serialized_workspace.centered_layout;
9223
9224 let (window, workspace) = if let Some(window) = requesting_window {
9225 let workspace = window.update(cx, |multi_workspace, window, cx| {
9226 let workspace = cx.new(|cx| {
9227 let mut workspace = Workspace::new(
9228 Some(workspace_id),
9229 project_handle.clone(),
9230 app_state.clone(),
9231 window,
9232 cx,
9233 );
9234 workspace.centered_layout = centered_layout;
9235 workspace
9236 });
9237 multi_workspace.add(workspace.clone(), &*window, cx);
9238 workspace
9239 })?;
9240 (window, workspace)
9241 } else {
9242 let window_bounds_override = window_bounds_env_override();
9243
9244 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
9245 (Some(WindowBounds::Windowed(bounds)), None)
9246 } else if let Some(display) = serialized_workspace.display
9247 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
9248 {
9249 (Some(bounds.0), Some(display))
9250 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
9251 (Some(bounds), Some(display))
9252 } else {
9253 (None, None)
9254 };
9255
9256 let options = cx.update(|cx| {
9257 let mut options = (app_state.build_window_options)(display, cx);
9258 options.window_bounds = window_bounds;
9259 options
9260 });
9261
9262 let window = cx.open_window(options, {
9263 let app_state = app_state.clone();
9264 let project_handle = project_handle.clone();
9265 move |window, cx| {
9266 let workspace = cx.new(|cx| {
9267 let mut workspace = Workspace::new(
9268 Some(workspace_id),
9269 project_handle,
9270 app_state,
9271 window,
9272 cx,
9273 );
9274 workspace.centered_layout = centered_layout;
9275 workspace
9276 });
9277 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9278 }
9279 })?;
9280
9281 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9282 multi_workspace.workspace().clone()
9283 })?;
9284
9285 (window, workspace)
9286 };
9287
9288 notify_if_database_failed(window, cx);
9289
9290 // Restore items from the serialized workspace
9291 window
9292 .update(cx, |_, window, cx| {
9293 workspace.update(cx, |_workspace, cx| {
9294 open_items(Some(serialized_workspace), vec![], window, cx)
9295 })
9296 })?
9297 .await?;
9298
9299 window.update(cx, |_, window, cx| {
9300 workspace.update(cx, |workspace, cx| {
9301 workspace.serialize_workspace(window, cx);
9302 });
9303 })?;
9304
9305 Ok(window)
9306 })
9307}
9308
9309#[allow(clippy::type_complexity)]
9310pub fn open_paths(
9311 abs_paths: &[PathBuf],
9312 app_state: Arc<AppState>,
9313 open_options: OpenOptions,
9314 cx: &mut App,
9315) -> Task<anyhow::Result<OpenResult>> {
9316 let abs_paths = abs_paths.to_vec();
9317 #[cfg(target_os = "windows")]
9318 let wsl_path = abs_paths
9319 .iter()
9320 .find_map(|p| util::paths::WslPath::from_path(p));
9321
9322 cx.spawn(async move |cx| {
9323 let (mut existing, mut open_visible) = find_existing_workspace(
9324 &abs_paths,
9325 &open_options,
9326 &SerializedWorkspaceLocation::Local,
9327 cx,
9328 )
9329 .await;
9330
9331 // Fallback: if no workspace contains the paths and all paths are files,
9332 // prefer an existing local workspace window (active window first).
9333 if open_options.open_new_workspace.is_none() && existing.is_none() {
9334 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9335 let all_metadatas = futures::future::join_all(all_paths)
9336 .await
9337 .into_iter()
9338 .filter_map(|result| result.ok().flatten())
9339 .collect::<Vec<_>>();
9340
9341 if all_metadatas.iter().all(|file| !file.is_dir) {
9342 cx.update(|cx| {
9343 let windows = workspace_windows_for_location(
9344 &SerializedWorkspaceLocation::Local,
9345 cx,
9346 );
9347 let window = cx
9348 .active_window()
9349 .and_then(|window| window.downcast::<MultiWorkspace>())
9350 .filter(|window| windows.contains(window))
9351 .or_else(|| windows.into_iter().next());
9352 if let Some(window) = window {
9353 if let Ok(multi_workspace) = window.read(cx) {
9354 let active_workspace = multi_workspace.workspace().clone();
9355 existing = Some((window, active_workspace));
9356 open_visible = OpenVisible::None;
9357 }
9358 }
9359 });
9360 }
9361 }
9362
9363 let result = if let Some((existing, target_workspace)) = existing {
9364 let open_task = existing
9365 .update(cx, |multi_workspace, window, cx| {
9366 window.activate_window();
9367 multi_workspace.activate(target_workspace.clone(), window, cx);
9368 target_workspace.update(cx, |workspace, cx| {
9369 workspace.open_paths(
9370 abs_paths,
9371 OpenOptions {
9372 visible: Some(open_visible),
9373 ..Default::default()
9374 },
9375 None,
9376 window,
9377 cx,
9378 )
9379 })
9380 })?
9381 .await;
9382
9383 _ = existing.update(cx, |multi_workspace, _, cx| {
9384 let workspace = multi_workspace.workspace().clone();
9385 workspace.update(cx, |workspace, cx| {
9386 for item in open_task.iter().flatten() {
9387 if let Err(e) = item {
9388 workspace.show_error(&e, cx);
9389 }
9390 }
9391 });
9392 });
9393
9394 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9395 } else {
9396 let result = cx
9397 .update(move |cx| {
9398 Workspace::new_local(
9399 abs_paths,
9400 app_state.clone(),
9401 open_options.requesting_window,
9402 open_options.env,
9403 None,
9404 open_options.open_mode,
9405 cx,
9406 )
9407 })
9408 .await;
9409
9410 if let Ok(ref result) = result {
9411 result.window
9412 .update(cx, |_, window, _cx| {
9413 window.activate_window();
9414 })
9415 .log_err();
9416 }
9417
9418 result
9419 };
9420
9421 #[cfg(target_os = "windows")]
9422 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9423 && let Ok(ref result) = result
9424 {
9425 result.window
9426 .update(cx, move |multi_workspace, _window, cx| {
9427 struct OpenInWsl;
9428 let workspace = multi_workspace.workspace().clone();
9429 workspace.update(cx, |workspace, cx| {
9430 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9431 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9432 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9433 cx.new(move |cx| {
9434 MessageNotification::new(msg, cx)
9435 .primary_message("Open in WSL")
9436 .primary_icon(IconName::FolderOpen)
9437 .primary_on_click(move |window, cx| {
9438 window.dispatch_action(Box::new(remote::OpenWslPath {
9439 distro: remote::WslConnectionOptions {
9440 distro_name: distro.clone(),
9441 user: None,
9442 },
9443 paths: vec![path.clone().into()],
9444 }), cx)
9445 })
9446 })
9447 });
9448 });
9449 })
9450 .unwrap();
9451 };
9452 result
9453 })
9454}
9455
9456pub fn open_new(
9457 open_options: OpenOptions,
9458 app_state: Arc<AppState>,
9459 cx: &mut App,
9460 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9461) -> Task<anyhow::Result<()>> {
9462 let addition = open_options.open_mode;
9463 let task = Workspace::new_local(
9464 Vec::new(),
9465 app_state,
9466 open_options.requesting_window,
9467 open_options.env,
9468 Some(Box::new(init)),
9469 addition,
9470 cx,
9471 );
9472 cx.spawn(async move |cx| {
9473 let OpenResult { window, .. } = task.await?;
9474 window
9475 .update(cx, |_, window, _cx| {
9476 window.activate_window();
9477 })
9478 .ok();
9479 Ok(())
9480 })
9481}
9482
9483pub fn create_and_open_local_file(
9484 path: &'static Path,
9485 window: &mut Window,
9486 cx: &mut Context<Workspace>,
9487 default_content: impl 'static + Send + FnOnce() -> Rope,
9488) -> Task<Result<Box<dyn ItemHandle>>> {
9489 cx.spawn_in(window, async move |workspace, cx| {
9490 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9491 if !fs.is_file(path).await {
9492 fs.create_file(path, Default::default()).await?;
9493 fs.save(path, &default_content(), Default::default())
9494 .await?;
9495 }
9496
9497 workspace
9498 .update_in(cx, |workspace, window, cx| {
9499 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9500 let path = workspace
9501 .project
9502 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9503 cx.spawn_in(window, async move |workspace, cx| {
9504 let path = path.await?;
9505
9506 let path = fs.canonicalize(&path).await.unwrap_or(path);
9507
9508 let mut items = workspace
9509 .update_in(cx, |workspace, window, cx| {
9510 workspace.open_paths(
9511 vec![path.to_path_buf()],
9512 OpenOptions {
9513 visible: Some(OpenVisible::None),
9514 ..Default::default()
9515 },
9516 None,
9517 window,
9518 cx,
9519 )
9520 })?
9521 .await;
9522 let item = items.pop().flatten();
9523 item.with_context(|| format!("path {path:?} is not a file"))?
9524 })
9525 })
9526 })?
9527 .await?
9528 .await
9529 })
9530}
9531
9532pub fn open_remote_project_with_new_connection(
9533 window: WindowHandle<MultiWorkspace>,
9534 remote_connection: Arc<dyn RemoteConnection>,
9535 cancel_rx: oneshot::Receiver<()>,
9536 delegate: Arc<dyn RemoteClientDelegate>,
9537 app_state: Arc<AppState>,
9538 paths: Vec<PathBuf>,
9539 cx: &mut App,
9540) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9541 cx.spawn(async move |cx| {
9542 let (workspace_id, serialized_workspace) =
9543 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9544 .await?;
9545
9546 let session = match cx
9547 .update(|cx| {
9548 remote::RemoteClient::new(
9549 ConnectionIdentifier::Workspace(workspace_id.0),
9550 remote_connection,
9551 cancel_rx,
9552 delegate,
9553 cx,
9554 )
9555 })
9556 .await?
9557 {
9558 Some(result) => result,
9559 None => return Ok(Vec::new()),
9560 };
9561
9562 let project = cx.update(|cx| {
9563 project::Project::remote(
9564 session,
9565 app_state.client.clone(),
9566 app_state.node_runtime.clone(),
9567 app_state.user_store.clone(),
9568 app_state.languages.clone(),
9569 app_state.fs.clone(),
9570 true,
9571 cx,
9572 )
9573 });
9574
9575 open_remote_project_inner(
9576 project,
9577 paths,
9578 workspace_id,
9579 serialized_workspace,
9580 app_state,
9581 window,
9582 cx,
9583 )
9584 .await
9585 })
9586}
9587
9588pub fn open_remote_project_with_existing_connection(
9589 connection_options: RemoteConnectionOptions,
9590 project: Entity<Project>,
9591 paths: Vec<PathBuf>,
9592 app_state: Arc<AppState>,
9593 window: WindowHandle<MultiWorkspace>,
9594 cx: &mut AsyncApp,
9595) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9596 cx.spawn(async move |cx| {
9597 let (workspace_id, serialized_workspace) =
9598 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9599
9600 open_remote_project_inner(
9601 project,
9602 paths,
9603 workspace_id,
9604 serialized_workspace,
9605 app_state,
9606 window,
9607 cx,
9608 )
9609 .await
9610 })
9611}
9612
9613async fn open_remote_project_inner(
9614 project: Entity<Project>,
9615 paths: Vec<PathBuf>,
9616 workspace_id: WorkspaceId,
9617 serialized_workspace: Option<SerializedWorkspace>,
9618 app_state: Arc<AppState>,
9619 window: WindowHandle<MultiWorkspace>,
9620 cx: &mut AsyncApp,
9621) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9622 let db = cx.update(|cx| WorkspaceDb::global(cx));
9623 let toolchains = db.toolchains(workspace_id).await?;
9624 for (toolchain, worktree_path, path) in toolchains {
9625 project
9626 .update(cx, |this, cx| {
9627 let Some(worktree_id) =
9628 this.find_worktree(&worktree_path, cx)
9629 .and_then(|(worktree, rel_path)| {
9630 if rel_path.is_empty() {
9631 Some(worktree.read(cx).id())
9632 } else {
9633 None
9634 }
9635 })
9636 else {
9637 return Task::ready(None);
9638 };
9639
9640 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9641 })
9642 .await;
9643 }
9644 let mut project_paths_to_open = vec![];
9645 let mut project_path_errors = vec![];
9646
9647 for path in paths {
9648 let result = cx
9649 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9650 .await;
9651 match result {
9652 Ok((_, project_path)) => {
9653 project_paths_to_open.push((path.clone(), Some(project_path)));
9654 }
9655 Err(error) => {
9656 project_path_errors.push(error);
9657 }
9658 };
9659 }
9660
9661 if project_paths_to_open.is_empty() {
9662 return Err(project_path_errors.pop().context("no paths given")?);
9663 }
9664
9665 let workspace = window.update(cx, |multi_workspace, window, cx| {
9666 telemetry::event!("SSH Project Opened");
9667
9668 let new_workspace = cx.new(|cx| {
9669 let mut workspace =
9670 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9671 workspace.update_history(cx);
9672
9673 if let Some(ref serialized) = serialized_workspace {
9674 workspace.centered_layout = serialized.centered_layout;
9675 }
9676
9677 workspace
9678 });
9679
9680 multi_workspace.activate(new_workspace.clone(), window, cx);
9681 new_workspace
9682 })?;
9683
9684 let items = window
9685 .update(cx, |_, window, cx| {
9686 window.activate_window();
9687 workspace.update(cx, |_workspace, cx| {
9688 open_items(serialized_workspace, project_paths_to_open, window, cx)
9689 })
9690 })?
9691 .await?;
9692
9693 workspace.update(cx, |workspace, cx| {
9694 for error in project_path_errors {
9695 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9696 if let Some(path) = error.error_tag("path") {
9697 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9698 }
9699 } else {
9700 workspace.show_error(&error, cx)
9701 }
9702 }
9703 });
9704
9705 Ok(items.into_iter().map(|item| item?.ok()).collect())
9706}
9707
9708fn deserialize_remote_project(
9709 connection_options: RemoteConnectionOptions,
9710 paths: Vec<PathBuf>,
9711 cx: &AsyncApp,
9712) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9713 let db = cx.update(|cx| WorkspaceDb::global(cx));
9714 cx.background_spawn(async move {
9715 let remote_connection_id = db
9716 .get_or_create_remote_connection(connection_options)
9717 .await?;
9718
9719 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9720
9721 let workspace_id = if let Some(workspace_id) =
9722 serialized_workspace.as_ref().map(|workspace| workspace.id)
9723 {
9724 workspace_id
9725 } else {
9726 db.next_id().await?
9727 };
9728
9729 Ok((workspace_id, serialized_workspace))
9730 })
9731}
9732
9733pub fn join_in_room_project(
9734 project_id: u64,
9735 follow_user_id: u64,
9736 app_state: Arc<AppState>,
9737 cx: &mut App,
9738) -> Task<Result<()>> {
9739 let windows = cx.windows();
9740 cx.spawn(async move |cx| {
9741 let existing_window_and_workspace: Option<(
9742 WindowHandle<MultiWorkspace>,
9743 Entity<Workspace>,
9744 )> = windows.into_iter().find_map(|window_handle| {
9745 window_handle
9746 .downcast::<MultiWorkspace>()
9747 .and_then(|window_handle| {
9748 window_handle
9749 .update(cx, |multi_workspace, _window, cx| {
9750 for workspace in multi_workspace.workspaces() {
9751 if workspace.read(cx).project().read(cx).remote_id()
9752 == Some(project_id)
9753 {
9754 return Some((window_handle, workspace.clone()));
9755 }
9756 }
9757 None
9758 })
9759 .unwrap_or(None)
9760 })
9761 });
9762
9763 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9764 existing_window_and_workspace
9765 {
9766 existing_window
9767 .update(cx, |multi_workspace, window, cx| {
9768 multi_workspace.activate(target_workspace, window, cx);
9769 })
9770 .ok();
9771 existing_window
9772 } else {
9773 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9774 let project = cx
9775 .update(|cx| {
9776 active_call.0.join_project(
9777 project_id,
9778 app_state.languages.clone(),
9779 app_state.fs.clone(),
9780 cx,
9781 )
9782 })
9783 .await?;
9784
9785 let window_bounds_override = window_bounds_env_override();
9786 cx.update(|cx| {
9787 let mut options = (app_state.build_window_options)(None, cx);
9788 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9789 cx.open_window(options, |window, cx| {
9790 let workspace = cx.new(|cx| {
9791 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9792 });
9793 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9794 })
9795 })?
9796 };
9797
9798 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9799 cx.activate(true);
9800 window.activate_window();
9801
9802 // We set the active workspace above, so this is the correct workspace.
9803 let workspace = multi_workspace.workspace().clone();
9804 workspace.update(cx, |workspace, cx| {
9805 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9806 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9807 .or_else(|| {
9808 // If we couldn't follow the given user, follow the host instead.
9809 let collaborator = workspace
9810 .project()
9811 .read(cx)
9812 .collaborators()
9813 .values()
9814 .find(|collaborator| collaborator.is_host)?;
9815 Some(collaborator.peer_id)
9816 });
9817
9818 if let Some(follow_peer_id) = follow_peer_id {
9819 workspace.follow(follow_peer_id, window, cx);
9820 }
9821 });
9822 })?;
9823
9824 anyhow::Ok(())
9825 })
9826}
9827
9828pub fn reload(cx: &mut App) {
9829 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9830 let mut workspace_windows = cx
9831 .windows()
9832 .into_iter()
9833 .filter_map(|window| window.downcast::<MultiWorkspace>())
9834 .collect::<Vec<_>>();
9835
9836 // If multiple windows have unsaved changes, and need a save prompt,
9837 // prompt in the active window before switching to a different window.
9838 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9839
9840 let mut prompt = None;
9841 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9842 prompt = window
9843 .update(cx, |_, window, cx| {
9844 window.prompt(
9845 PromptLevel::Info,
9846 "Are you sure you want to restart?",
9847 None,
9848 &["Restart", "Cancel"],
9849 cx,
9850 )
9851 })
9852 .ok();
9853 }
9854
9855 cx.spawn(async move |cx| {
9856 if let Some(prompt) = prompt {
9857 let answer = prompt.await?;
9858 if answer != 0 {
9859 return anyhow::Ok(());
9860 }
9861 }
9862
9863 // If the user cancels any save prompt, then keep the app open.
9864 for window in workspace_windows {
9865 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9866 let workspace = multi_workspace.workspace().clone();
9867 workspace.update(cx, |workspace, cx| {
9868 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9869 })
9870 }) && !should_close.await?
9871 {
9872 return anyhow::Ok(());
9873 }
9874 }
9875 cx.update(|cx| cx.restart());
9876 anyhow::Ok(())
9877 })
9878 .detach_and_log_err(cx);
9879}
9880
9881fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9882 let mut parts = value.split(',');
9883 let x: usize = parts.next()?.parse().ok()?;
9884 let y: usize = parts.next()?.parse().ok()?;
9885 Some(point(px(x as f32), px(y as f32)))
9886}
9887
9888fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9889 let mut parts = value.split(',');
9890 let width: usize = parts.next()?.parse().ok()?;
9891 let height: usize = parts.next()?.parse().ok()?;
9892 Some(size(px(width as f32), px(height as f32)))
9893}
9894
9895/// Add client-side decorations (rounded corners, shadows, resize handling) when
9896/// appropriate.
9897///
9898/// The `border_radius_tiling` parameter allows overriding which corners get
9899/// rounded, independently of the actual window tiling state. This is used
9900/// specifically for the workspace switcher sidebar: when the sidebar is open,
9901/// we want square corners on the left (so the sidebar appears flush with the
9902/// window edge) but we still need the shadow padding for proper visual
9903/// appearance. Unlike actual window tiling, this only affects border radius -
9904/// not padding or shadows.
9905pub fn client_side_decorations(
9906 element: impl IntoElement,
9907 window: &mut Window,
9908 cx: &mut App,
9909 border_radius_tiling: Tiling,
9910) -> Stateful<Div> {
9911 const BORDER_SIZE: Pixels = px(1.0);
9912 let decorations = window.window_decorations();
9913 let tiling = match decorations {
9914 Decorations::Server => Tiling::default(),
9915 Decorations::Client { tiling } => tiling,
9916 };
9917
9918 match decorations {
9919 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9920 Decorations::Server => window.set_client_inset(px(0.0)),
9921 }
9922
9923 struct GlobalResizeEdge(ResizeEdge);
9924 impl Global for GlobalResizeEdge {}
9925
9926 div()
9927 .id("window-backdrop")
9928 .bg(transparent_black())
9929 .map(|div| match decorations {
9930 Decorations::Server => div,
9931 Decorations::Client { .. } => div
9932 .when(
9933 !(tiling.top
9934 || tiling.right
9935 || border_radius_tiling.top
9936 || border_radius_tiling.right),
9937 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9938 )
9939 .when(
9940 !(tiling.top
9941 || tiling.left
9942 || border_radius_tiling.top
9943 || border_radius_tiling.left),
9944 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9945 )
9946 .when(
9947 !(tiling.bottom
9948 || tiling.right
9949 || border_radius_tiling.bottom
9950 || border_radius_tiling.right),
9951 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9952 )
9953 .when(
9954 !(tiling.bottom
9955 || tiling.left
9956 || border_radius_tiling.bottom
9957 || border_radius_tiling.left),
9958 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9959 )
9960 .when(!tiling.top, |div| {
9961 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9962 })
9963 .when(!tiling.bottom, |div| {
9964 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9965 })
9966 .when(!tiling.left, |div| {
9967 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9968 })
9969 .when(!tiling.right, |div| {
9970 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9971 })
9972 .on_mouse_move(move |e, window, cx| {
9973 let size = window.window_bounds().get_bounds().size;
9974 let pos = e.position;
9975
9976 let new_edge =
9977 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9978
9979 let edge = cx.try_global::<GlobalResizeEdge>();
9980 if new_edge != edge.map(|edge| edge.0) {
9981 window
9982 .window_handle()
9983 .update(cx, |workspace, _, cx| {
9984 cx.notify(workspace.entity_id());
9985 })
9986 .ok();
9987 }
9988 })
9989 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9990 let size = window.window_bounds().get_bounds().size;
9991 let pos = e.position;
9992
9993 let edge = match resize_edge(
9994 pos,
9995 theme::CLIENT_SIDE_DECORATION_SHADOW,
9996 size,
9997 tiling,
9998 ) {
9999 Some(value) => value,
10000 None => return,
10001 };
10002
10003 window.start_window_resize(edge);
10004 }),
10005 })
10006 .size_full()
10007 .child(
10008 div()
10009 .cursor(CursorStyle::Arrow)
10010 .map(|div| match decorations {
10011 Decorations::Server => div,
10012 Decorations::Client { .. } => div
10013 .border_color(cx.theme().colors().border)
10014 .when(
10015 !(tiling.top
10016 || tiling.right
10017 || border_radius_tiling.top
10018 || border_radius_tiling.right),
10019 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10020 )
10021 .when(
10022 !(tiling.top
10023 || tiling.left
10024 || border_radius_tiling.top
10025 || border_radius_tiling.left),
10026 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10027 )
10028 .when(
10029 !(tiling.bottom
10030 || tiling.right
10031 || border_radius_tiling.bottom
10032 || border_radius_tiling.right),
10033 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10034 )
10035 .when(
10036 !(tiling.bottom
10037 || tiling.left
10038 || border_radius_tiling.bottom
10039 || border_radius_tiling.left),
10040 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10041 )
10042 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10043 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10044 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10045 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10046 .when(!tiling.is_tiled(), |div| {
10047 div.shadow(vec![gpui::BoxShadow {
10048 color: Hsla {
10049 h: 0.,
10050 s: 0.,
10051 l: 0.,
10052 a: 0.4,
10053 },
10054 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10055 spread_radius: px(0.),
10056 offset: point(px(0.0), px(0.0)),
10057 }])
10058 }),
10059 })
10060 .on_mouse_move(|_e, _, cx| {
10061 cx.stop_propagation();
10062 })
10063 .size_full()
10064 .child(element),
10065 )
10066 .map(|div| match decorations {
10067 Decorations::Server => div,
10068 Decorations::Client { tiling, .. } => div.child(
10069 canvas(
10070 |_bounds, window, _| {
10071 window.insert_hitbox(
10072 Bounds::new(
10073 point(px(0.0), px(0.0)),
10074 window.window_bounds().get_bounds().size,
10075 ),
10076 HitboxBehavior::Normal,
10077 )
10078 },
10079 move |_bounds, hitbox, window, cx| {
10080 let mouse = window.mouse_position();
10081 let size = window.window_bounds().get_bounds().size;
10082 let Some(edge) =
10083 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10084 else {
10085 return;
10086 };
10087 cx.set_global(GlobalResizeEdge(edge));
10088 window.set_cursor_style(
10089 match edge {
10090 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10091 ResizeEdge::Left | ResizeEdge::Right => {
10092 CursorStyle::ResizeLeftRight
10093 }
10094 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10095 CursorStyle::ResizeUpLeftDownRight
10096 }
10097 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10098 CursorStyle::ResizeUpRightDownLeft
10099 }
10100 },
10101 &hitbox,
10102 );
10103 },
10104 )
10105 .size_full()
10106 .absolute(),
10107 ),
10108 })
10109}
10110
10111fn resize_edge(
10112 pos: Point<Pixels>,
10113 shadow_size: Pixels,
10114 window_size: Size<Pixels>,
10115 tiling: Tiling,
10116) -> Option<ResizeEdge> {
10117 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10118 if bounds.contains(&pos) {
10119 return None;
10120 }
10121
10122 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10123 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10124 if !tiling.top && top_left_bounds.contains(&pos) {
10125 return Some(ResizeEdge::TopLeft);
10126 }
10127
10128 let top_right_bounds = Bounds::new(
10129 Point::new(window_size.width - corner_size.width, px(0.)),
10130 corner_size,
10131 );
10132 if !tiling.top && top_right_bounds.contains(&pos) {
10133 return Some(ResizeEdge::TopRight);
10134 }
10135
10136 let bottom_left_bounds = Bounds::new(
10137 Point::new(px(0.), window_size.height - corner_size.height),
10138 corner_size,
10139 );
10140 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10141 return Some(ResizeEdge::BottomLeft);
10142 }
10143
10144 let bottom_right_bounds = Bounds::new(
10145 Point::new(
10146 window_size.width - corner_size.width,
10147 window_size.height - corner_size.height,
10148 ),
10149 corner_size,
10150 );
10151 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10152 return Some(ResizeEdge::BottomRight);
10153 }
10154
10155 if !tiling.top && pos.y < shadow_size {
10156 Some(ResizeEdge::Top)
10157 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10158 Some(ResizeEdge::Bottom)
10159 } else if !tiling.left && pos.x < shadow_size {
10160 Some(ResizeEdge::Left)
10161 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10162 Some(ResizeEdge::Right)
10163 } else {
10164 None
10165 }
10166}
10167
10168fn join_pane_into_active(
10169 active_pane: &Entity<Pane>,
10170 pane: &Entity<Pane>,
10171 window: &mut Window,
10172 cx: &mut App,
10173) {
10174 if pane == active_pane {
10175 } else if pane.read(cx).items_len() == 0 {
10176 pane.update(cx, |_, cx| {
10177 cx.emit(pane::Event::Remove {
10178 focus_on_pane: None,
10179 });
10180 })
10181 } else {
10182 move_all_items(pane, active_pane, window, cx);
10183 }
10184}
10185
10186fn move_all_items(
10187 from_pane: &Entity<Pane>,
10188 to_pane: &Entity<Pane>,
10189 window: &mut Window,
10190 cx: &mut App,
10191) {
10192 let destination_is_different = from_pane != to_pane;
10193 let mut moved_items = 0;
10194 for (item_ix, item_handle) in from_pane
10195 .read(cx)
10196 .items()
10197 .enumerate()
10198 .map(|(ix, item)| (ix, item.clone()))
10199 .collect::<Vec<_>>()
10200 {
10201 let ix = item_ix - moved_items;
10202 if destination_is_different {
10203 // Close item from previous pane
10204 from_pane.update(cx, |source, cx| {
10205 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10206 });
10207 moved_items += 1;
10208 }
10209
10210 // This automatically removes duplicate items in the pane
10211 to_pane.update(cx, |destination, cx| {
10212 destination.add_item(item_handle, true, true, None, window, cx);
10213 window.focus(&destination.focus_handle(cx), cx)
10214 });
10215 }
10216}
10217
10218pub fn move_item(
10219 source: &Entity<Pane>,
10220 destination: &Entity<Pane>,
10221 item_id_to_move: EntityId,
10222 destination_index: usize,
10223 activate: bool,
10224 window: &mut Window,
10225 cx: &mut App,
10226) {
10227 let Some((item_ix, item_handle)) = source
10228 .read(cx)
10229 .items()
10230 .enumerate()
10231 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10232 .map(|(ix, item)| (ix, item.clone()))
10233 else {
10234 // Tab was closed during drag
10235 return;
10236 };
10237
10238 if source != destination {
10239 // Close item from previous pane
10240 source.update(cx, |source, cx| {
10241 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10242 });
10243 }
10244
10245 // This automatically removes duplicate items in the pane
10246 destination.update(cx, |destination, cx| {
10247 destination.add_item_inner(
10248 item_handle,
10249 activate,
10250 activate,
10251 activate,
10252 Some(destination_index),
10253 window,
10254 cx,
10255 );
10256 if activate {
10257 window.focus(&destination.focus_handle(cx), cx)
10258 }
10259 });
10260}
10261
10262pub fn move_active_item(
10263 source: &Entity<Pane>,
10264 destination: &Entity<Pane>,
10265 focus_destination: bool,
10266 close_if_empty: bool,
10267 window: &mut Window,
10268 cx: &mut App,
10269) {
10270 if source == destination {
10271 return;
10272 }
10273 let Some(active_item) = source.read(cx).active_item() else {
10274 return;
10275 };
10276 source.update(cx, |source_pane, cx| {
10277 let item_id = active_item.item_id();
10278 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10279 destination.update(cx, |target_pane, cx| {
10280 target_pane.add_item(
10281 active_item,
10282 focus_destination,
10283 focus_destination,
10284 Some(target_pane.items_len()),
10285 window,
10286 cx,
10287 );
10288 });
10289 });
10290}
10291
10292pub fn clone_active_item(
10293 workspace_id: Option<WorkspaceId>,
10294 source: &Entity<Pane>,
10295 destination: &Entity<Pane>,
10296 focus_destination: bool,
10297 window: &mut Window,
10298 cx: &mut App,
10299) {
10300 if source == destination {
10301 return;
10302 }
10303 let Some(active_item) = source.read(cx).active_item() else {
10304 return;
10305 };
10306 if !active_item.can_split(cx) {
10307 return;
10308 }
10309 let destination = destination.downgrade();
10310 let task = active_item.clone_on_split(workspace_id, window, cx);
10311 window
10312 .spawn(cx, async move |cx| {
10313 let Some(clone) = task.await else {
10314 return;
10315 };
10316 destination
10317 .update_in(cx, |target_pane, window, cx| {
10318 target_pane.add_item(
10319 clone,
10320 focus_destination,
10321 focus_destination,
10322 Some(target_pane.items_len()),
10323 window,
10324 cx,
10325 );
10326 })
10327 .log_err();
10328 })
10329 .detach();
10330}
10331
10332#[derive(Debug)]
10333pub struct WorkspacePosition {
10334 pub window_bounds: Option<WindowBounds>,
10335 pub display: Option<Uuid>,
10336 pub centered_layout: bool,
10337}
10338
10339pub fn remote_workspace_position_from_db(
10340 connection_options: RemoteConnectionOptions,
10341 paths_to_open: &[PathBuf],
10342 cx: &App,
10343) -> Task<Result<WorkspacePosition>> {
10344 let paths = paths_to_open.to_vec();
10345 let db = WorkspaceDb::global(cx);
10346 let kvp = db::kvp::KeyValueStore::global(cx);
10347
10348 cx.background_spawn(async move {
10349 let remote_connection_id = db
10350 .get_or_create_remote_connection(connection_options)
10351 .await
10352 .context("fetching serialized ssh project")?;
10353 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10354
10355 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10356 (Some(WindowBounds::Windowed(bounds)), None)
10357 } else {
10358 let restorable_bounds = serialized_workspace
10359 .as_ref()
10360 .and_then(|workspace| {
10361 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10362 })
10363 .or_else(|| persistence::read_default_window_bounds(&kvp));
10364
10365 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10366 (Some(serialized_bounds), Some(serialized_display))
10367 } else {
10368 (None, None)
10369 }
10370 };
10371
10372 let centered_layout = serialized_workspace
10373 .as_ref()
10374 .map(|w| w.centered_layout)
10375 .unwrap_or(false);
10376
10377 Ok(WorkspacePosition {
10378 window_bounds,
10379 display,
10380 centered_layout,
10381 })
10382 })
10383}
10384
10385pub fn with_active_or_new_workspace(
10386 cx: &mut App,
10387 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10388) {
10389 match cx
10390 .active_window()
10391 .and_then(|w| w.downcast::<MultiWorkspace>())
10392 {
10393 Some(multi_workspace) => {
10394 cx.defer(move |cx| {
10395 multi_workspace
10396 .update(cx, |multi_workspace, window, cx| {
10397 let workspace = multi_workspace.workspace().clone();
10398 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10399 })
10400 .log_err();
10401 });
10402 }
10403 None => {
10404 let app_state = AppState::global(cx);
10405 open_new(
10406 OpenOptions::default(),
10407 app_state,
10408 cx,
10409 move |workspace, window, cx| f(workspace, window, cx),
10410 )
10411 .detach_and_log_err(cx);
10412 }
10413 }
10414}
10415
10416/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10417/// key. This migration path only runs once per panel per workspace.
10418fn load_legacy_panel_size(
10419 panel_key: &str,
10420 dock_position: DockPosition,
10421 workspace: &Workspace,
10422 cx: &mut App,
10423) -> Option<Pixels> {
10424 #[derive(Deserialize)]
10425 struct LegacyPanelState {
10426 #[serde(default)]
10427 width: Option<Pixels>,
10428 #[serde(default)]
10429 height: Option<Pixels>,
10430 }
10431
10432 let workspace_id = workspace
10433 .database_id()
10434 .map(|id| i64::from(id).to_string())
10435 .or_else(|| workspace.session_id())?;
10436
10437 let legacy_key = match panel_key {
10438 "ProjectPanel" => {
10439 format!("{}-{:?}", "ProjectPanel", workspace_id)
10440 }
10441 "OutlinePanel" => {
10442 format!("{}-{:?}", "OutlinePanel", workspace_id)
10443 }
10444 "GitPanel" => {
10445 format!("{}-{:?}", "GitPanel", workspace_id)
10446 }
10447 "TerminalPanel" => {
10448 format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10449 }
10450 _ => return None,
10451 };
10452
10453 let kvp = db::kvp::KeyValueStore::global(cx);
10454 let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10455 let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10456 let size = match dock_position {
10457 DockPosition::Bottom => state.height,
10458 DockPosition::Left | DockPosition::Right => state.width,
10459 }?;
10460
10461 cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10462 .detach_and_log_err(cx);
10463
10464 Some(size)
10465}
10466
10467#[cfg(test)]
10468mod tests {
10469 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10470
10471 use super::*;
10472 use crate::{
10473 dock::{PanelEvent, test::TestPanel},
10474 item::{
10475 ItemBufferKind, ItemEvent,
10476 test::{TestItem, TestProjectItem},
10477 },
10478 };
10479 use fs::FakeFs;
10480 use gpui::{
10481 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10482 UpdateGlobal, VisualTestContext, px,
10483 };
10484 use project::{Project, ProjectEntryId};
10485 use serde_json::json;
10486 use settings::SettingsStore;
10487 use util::path;
10488 use util::rel_path::rel_path;
10489
10490 #[gpui::test]
10491 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10492 init_test(cx);
10493
10494 let fs = FakeFs::new(cx.executor());
10495 let project = Project::test(fs, [], cx).await;
10496 let (workspace, cx) =
10497 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10498
10499 // Adding an item with no ambiguity renders the tab without detail.
10500 let item1 = cx.new(|cx| {
10501 let mut item = TestItem::new(cx);
10502 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10503 item
10504 });
10505 workspace.update_in(cx, |workspace, window, cx| {
10506 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10507 });
10508 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10509
10510 // Adding an item that creates ambiguity increases the level of detail on
10511 // both tabs.
10512 let item2 = cx.new_window_entity(|_window, cx| {
10513 let mut item = TestItem::new(cx);
10514 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10515 item
10516 });
10517 workspace.update_in(cx, |workspace, window, cx| {
10518 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10519 });
10520 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10521 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10522
10523 // Adding an item that creates ambiguity increases the level of detail only
10524 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10525 // we stop at the highest detail available.
10526 let item3 = cx.new(|cx| {
10527 let mut item = TestItem::new(cx);
10528 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10529 item
10530 });
10531 workspace.update_in(cx, |workspace, window, cx| {
10532 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10533 });
10534 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10535 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10536 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10537 }
10538
10539 #[gpui::test]
10540 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10541 init_test(cx);
10542
10543 let fs = FakeFs::new(cx.executor());
10544 fs.insert_tree(
10545 "/root1",
10546 json!({
10547 "one.txt": "",
10548 "two.txt": "",
10549 }),
10550 )
10551 .await;
10552 fs.insert_tree(
10553 "/root2",
10554 json!({
10555 "three.txt": "",
10556 }),
10557 )
10558 .await;
10559
10560 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10561 let (workspace, cx) =
10562 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10563 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10564 let worktree_id = project.update(cx, |project, cx| {
10565 project.worktrees(cx).next().unwrap().read(cx).id()
10566 });
10567
10568 let item1 = cx.new(|cx| {
10569 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10570 });
10571 let item2 = cx.new(|cx| {
10572 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10573 });
10574
10575 // Add an item to an empty pane
10576 workspace.update_in(cx, |workspace, window, cx| {
10577 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10578 });
10579 project.update(cx, |project, cx| {
10580 assert_eq!(
10581 project.active_entry(),
10582 project
10583 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10584 .map(|e| e.id)
10585 );
10586 });
10587 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10588
10589 // Add a second item to a non-empty pane
10590 workspace.update_in(cx, |workspace, window, cx| {
10591 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10592 });
10593 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10594 project.update(cx, |project, cx| {
10595 assert_eq!(
10596 project.active_entry(),
10597 project
10598 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10599 .map(|e| e.id)
10600 );
10601 });
10602
10603 // Close the active item
10604 pane.update_in(cx, |pane, window, cx| {
10605 pane.close_active_item(&Default::default(), window, cx)
10606 })
10607 .await
10608 .unwrap();
10609 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10610 project.update(cx, |project, cx| {
10611 assert_eq!(
10612 project.active_entry(),
10613 project
10614 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10615 .map(|e| e.id)
10616 );
10617 });
10618
10619 // Add a project folder
10620 project
10621 .update(cx, |project, cx| {
10622 project.find_or_create_worktree("root2", true, cx)
10623 })
10624 .await
10625 .unwrap();
10626 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10627
10628 // Remove a project folder
10629 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10630 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10631 }
10632
10633 #[gpui::test]
10634 async fn test_close_window(cx: &mut TestAppContext) {
10635 init_test(cx);
10636
10637 let fs = FakeFs::new(cx.executor());
10638 fs.insert_tree("/root", json!({ "one": "" })).await;
10639
10640 let project = Project::test(fs, ["root".as_ref()], cx).await;
10641 let (workspace, cx) =
10642 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10643
10644 // When there are no dirty items, there's nothing to do.
10645 let item1 = cx.new(TestItem::new);
10646 workspace.update_in(cx, |w, window, cx| {
10647 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10648 });
10649 let task = workspace.update_in(cx, |w, window, cx| {
10650 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10651 });
10652 assert!(task.await.unwrap());
10653
10654 // When there are dirty untitled items, prompt to save each one. If the user
10655 // cancels any prompt, then abort.
10656 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10657 let item3 = cx.new(|cx| {
10658 TestItem::new(cx)
10659 .with_dirty(true)
10660 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10661 });
10662 workspace.update_in(cx, |w, window, cx| {
10663 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10664 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10665 });
10666 let task = workspace.update_in(cx, |w, window, cx| {
10667 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10668 });
10669 cx.executor().run_until_parked();
10670 cx.simulate_prompt_answer("Cancel"); // cancel save all
10671 cx.executor().run_until_parked();
10672 assert!(!cx.has_pending_prompt());
10673 assert!(!task.await.unwrap());
10674 }
10675
10676 #[gpui::test]
10677 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10678 init_test(cx);
10679
10680 let fs = FakeFs::new(cx.executor());
10681 fs.insert_tree("/root", json!({ "one": "" })).await;
10682
10683 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10684 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10685 let multi_workspace_handle =
10686 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10687 cx.run_until_parked();
10688
10689 let workspace_a = multi_workspace_handle
10690 .read_with(cx, |mw, _| mw.workspace().clone())
10691 .unwrap();
10692
10693 let workspace_b = multi_workspace_handle
10694 .update(cx, |mw, window, cx| {
10695 mw.test_add_workspace(project_b, window, cx)
10696 })
10697 .unwrap();
10698
10699 // Activate workspace A
10700 multi_workspace_handle
10701 .update(cx, |mw, window, cx| {
10702 let workspace = mw.workspaces()[0].clone();
10703 mw.activate(workspace, window, cx);
10704 })
10705 .unwrap();
10706
10707 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10708
10709 // Workspace A has a clean item
10710 let item_a = cx.new(TestItem::new);
10711 workspace_a.update_in(cx, |w, window, cx| {
10712 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10713 });
10714
10715 // Workspace B has a dirty item
10716 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10717 workspace_b.update_in(cx, |w, window, cx| {
10718 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10719 });
10720
10721 // Verify workspace A is active
10722 multi_workspace_handle
10723 .read_with(cx, |mw, _| {
10724 assert_eq!(mw.active_workspace_index(), 0);
10725 })
10726 .unwrap();
10727
10728 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10729 multi_workspace_handle
10730 .update(cx, |mw, window, cx| {
10731 mw.close_window(&CloseWindow, window, cx);
10732 })
10733 .unwrap();
10734 cx.run_until_parked();
10735
10736 // Workspace B should now be active since it has dirty items that need attention
10737 multi_workspace_handle
10738 .read_with(cx, |mw, _| {
10739 assert_eq!(
10740 mw.active_workspace_index(),
10741 1,
10742 "workspace B should be activated when it prompts"
10743 );
10744 })
10745 .unwrap();
10746
10747 // User cancels the save prompt from workspace B
10748 cx.simulate_prompt_answer("Cancel");
10749 cx.run_until_parked();
10750
10751 // Window should still exist because workspace B's close was cancelled
10752 assert!(
10753 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10754 "window should still exist after cancelling one workspace's close"
10755 );
10756 }
10757
10758 #[gpui::test]
10759 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10760 init_test(cx);
10761
10762 // Register TestItem as a serializable item
10763 cx.update(|cx| {
10764 register_serializable_item::<TestItem>(cx);
10765 });
10766
10767 let fs = FakeFs::new(cx.executor());
10768 fs.insert_tree("/root", json!({ "one": "" })).await;
10769
10770 let project = Project::test(fs, ["root".as_ref()], cx).await;
10771 let (workspace, cx) =
10772 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10773
10774 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10775 let item1 = cx.new(|cx| {
10776 TestItem::new(cx)
10777 .with_dirty(true)
10778 .with_serialize(|| Some(Task::ready(Ok(()))))
10779 });
10780 let item2 = cx.new(|cx| {
10781 TestItem::new(cx)
10782 .with_dirty(true)
10783 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10784 .with_serialize(|| Some(Task::ready(Ok(()))))
10785 });
10786 workspace.update_in(cx, |w, window, cx| {
10787 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10788 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10789 });
10790 let task = workspace.update_in(cx, |w, window, cx| {
10791 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10792 });
10793 assert!(task.await.unwrap());
10794 }
10795
10796 #[gpui::test]
10797 async fn test_close_pane_items(cx: &mut TestAppContext) {
10798 init_test(cx);
10799
10800 let fs = FakeFs::new(cx.executor());
10801
10802 let project = Project::test(fs, None, cx).await;
10803 let (workspace, cx) =
10804 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10805
10806 let item1 = cx.new(|cx| {
10807 TestItem::new(cx)
10808 .with_dirty(true)
10809 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10810 });
10811 let item2 = cx.new(|cx| {
10812 TestItem::new(cx)
10813 .with_dirty(true)
10814 .with_conflict(true)
10815 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10816 });
10817 let item3 = cx.new(|cx| {
10818 TestItem::new(cx)
10819 .with_dirty(true)
10820 .with_conflict(true)
10821 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10822 });
10823 let item4 = cx.new(|cx| {
10824 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10825 let project_item = TestProjectItem::new_untitled(cx);
10826 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10827 project_item
10828 }])
10829 });
10830 let pane = workspace.update_in(cx, |workspace, window, cx| {
10831 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10832 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10833 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10834 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10835 workspace.active_pane().clone()
10836 });
10837
10838 let close_items = pane.update_in(cx, |pane, window, cx| {
10839 pane.activate_item(1, true, true, window, cx);
10840 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10841 let item1_id = item1.item_id();
10842 let item3_id = item3.item_id();
10843 let item4_id = item4.item_id();
10844 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10845 [item1_id, item3_id, item4_id].contains(&id)
10846 })
10847 });
10848 cx.executor().run_until_parked();
10849
10850 assert!(cx.has_pending_prompt());
10851 cx.simulate_prompt_answer("Save all");
10852
10853 cx.executor().run_until_parked();
10854
10855 // Item 1 is saved. There's a prompt to save item 3.
10856 pane.update(cx, |pane, cx| {
10857 assert_eq!(item1.read(cx).save_count, 1);
10858 assert_eq!(item1.read(cx).save_as_count, 0);
10859 assert_eq!(item1.read(cx).reload_count, 0);
10860 assert_eq!(pane.items_len(), 3);
10861 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10862 });
10863 assert!(cx.has_pending_prompt());
10864
10865 // Cancel saving item 3.
10866 cx.simulate_prompt_answer("Discard");
10867 cx.executor().run_until_parked();
10868
10869 // Item 3 is reloaded. There's a prompt to save item 4.
10870 pane.update(cx, |pane, cx| {
10871 assert_eq!(item3.read(cx).save_count, 0);
10872 assert_eq!(item3.read(cx).save_as_count, 0);
10873 assert_eq!(item3.read(cx).reload_count, 1);
10874 assert_eq!(pane.items_len(), 2);
10875 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10876 });
10877
10878 // There's a prompt for a path for item 4.
10879 cx.simulate_new_path_selection(|_| Some(Default::default()));
10880 close_items.await.unwrap();
10881
10882 // The requested items are closed.
10883 pane.update(cx, |pane, cx| {
10884 assert_eq!(item4.read(cx).save_count, 0);
10885 assert_eq!(item4.read(cx).save_as_count, 1);
10886 assert_eq!(item4.read(cx).reload_count, 0);
10887 assert_eq!(pane.items_len(), 1);
10888 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10889 });
10890 }
10891
10892 #[gpui::test]
10893 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10894 init_test(cx);
10895
10896 let fs = FakeFs::new(cx.executor());
10897 let project = Project::test(fs, [], cx).await;
10898 let (workspace, cx) =
10899 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10900
10901 // Create several workspace items with single project entries, and two
10902 // workspace items with multiple project entries.
10903 let single_entry_items = (0..=4)
10904 .map(|project_entry_id| {
10905 cx.new(|cx| {
10906 TestItem::new(cx)
10907 .with_dirty(true)
10908 .with_project_items(&[dirty_project_item(
10909 project_entry_id,
10910 &format!("{project_entry_id}.txt"),
10911 cx,
10912 )])
10913 })
10914 })
10915 .collect::<Vec<_>>();
10916 let item_2_3 = cx.new(|cx| {
10917 TestItem::new(cx)
10918 .with_dirty(true)
10919 .with_buffer_kind(ItemBufferKind::Multibuffer)
10920 .with_project_items(&[
10921 single_entry_items[2].read(cx).project_items[0].clone(),
10922 single_entry_items[3].read(cx).project_items[0].clone(),
10923 ])
10924 });
10925 let item_3_4 = cx.new(|cx| {
10926 TestItem::new(cx)
10927 .with_dirty(true)
10928 .with_buffer_kind(ItemBufferKind::Multibuffer)
10929 .with_project_items(&[
10930 single_entry_items[3].read(cx).project_items[0].clone(),
10931 single_entry_items[4].read(cx).project_items[0].clone(),
10932 ])
10933 });
10934
10935 // Create two panes that contain the following project entries:
10936 // left pane:
10937 // multi-entry items: (2, 3)
10938 // single-entry items: 0, 2, 3, 4
10939 // right pane:
10940 // single-entry items: 4, 1
10941 // multi-entry items: (3, 4)
10942 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10943 let left_pane = workspace.active_pane().clone();
10944 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10945 workspace.add_item_to_active_pane(
10946 single_entry_items[0].boxed_clone(),
10947 None,
10948 true,
10949 window,
10950 cx,
10951 );
10952 workspace.add_item_to_active_pane(
10953 single_entry_items[2].boxed_clone(),
10954 None,
10955 true,
10956 window,
10957 cx,
10958 );
10959 workspace.add_item_to_active_pane(
10960 single_entry_items[3].boxed_clone(),
10961 None,
10962 true,
10963 window,
10964 cx,
10965 );
10966 workspace.add_item_to_active_pane(
10967 single_entry_items[4].boxed_clone(),
10968 None,
10969 true,
10970 window,
10971 cx,
10972 );
10973
10974 let right_pane =
10975 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10976
10977 let boxed_clone = single_entry_items[1].boxed_clone();
10978 let right_pane = window.spawn(cx, async move |cx| {
10979 right_pane.await.inspect(|right_pane| {
10980 right_pane
10981 .update_in(cx, |pane, window, cx| {
10982 pane.add_item(boxed_clone, true, true, None, window, cx);
10983 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10984 })
10985 .unwrap();
10986 })
10987 });
10988
10989 (left_pane, right_pane)
10990 });
10991 let right_pane = right_pane.await.unwrap();
10992 cx.focus(&right_pane);
10993
10994 let close = right_pane.update_in(cx, |pane, window, cx| {
10995 pane.close_all_items(&CloseAllItems::default(), window, cx)
10996 .unwrap()
10997 });
10998 cx.executor().run_until_parked();
10999
11000 let msg = cx.pending_prompt().unwrap().0;
11001 assert!(msg.contains("1.txt"));
11002 assert!(!msg.contains("2.txt"));
11003 assert!(!msg.contains("3.txt"));
11004 assert!(!msg.contains("4.txt"));
11005
11006 // With best-effort close, cancelling item 1 keeps it open but items 4
11007 // and (3,4) still close since their entries exist in left pane.
11008 cx.simulate_prompt_answer("Cancel");
11009 close.await;
11010
11011 right_pane.read_with(cx, |pane, _| {
11012 assert_eq!(pane.items_len(), 1);
11013 });
11014
11015 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11016 left_pane
11017 .update_in(cx, |left_pane, window, cx| {
11018 left_pane.close_item_by_id(
11019 single_entry_items[3].entity_id(),
11020 SaveIntent::Skip,
11021 window,
11022 cx,
11023 )
11024 })
11025 .await
11026 .unwrap();
11027
11028 let close = left_pane.update_in(cx, |pane, window, cx| {
11029 pane.close_all_items(&CloseAllItems::default(), window, cx)
11030 .unwrap()
11031 });
11032 cx.executor().run_until_parked();
11033
11034 let details = cx.pending_prompt().unwrap().1;
11035 assert!(details.contains("0.txt"));
11036 assert!(details.contains("3.txt"));
11037 assert!(details.contains("4.txt"));
11038 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11039 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11040 // assert!(!details.contains("2.txt"));
11041
11042 cx.simulate_prompt_answer("Save all");
11043 cx.executor().run_until_parked();
11044 close.await;
11045
11046 left_pane.read_with(cx, |pane, _| {
11047 assert_eq!(pane.items_len(), 0);
11048 });
11049 }
11050
11051 #[gpui::test]
11052 async fn test_autosave(cx: &mut gpui::TestAppContext) {
11053 init_test(cx);
11054
11055 let fs = FakeFs::new(cx.executor());
11056 let project = Project::test(fs, [], cx).await;
11057 let (workspace, cx) =
11058 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11059 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11060
11061 let item = cx.new(|cx| {
11062 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11063 });
11064 let item_id = item.entity_id();
11065 workspace.update_in(cx, |workspace, window, cx| {
11066 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11067 });
11068
11069 // Autosave on window change.
11070 item.update(cx, |item, cx| {
11071 SettingsStore::update_global(cx, |settings, cx| {
11072 settings.update_user_settings(cx, |settings| {
11073 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11074 })
11075 });
11076 item.is_dirty = true;
11077 });
11078
11079 // Deactivating the window saves the file.
11080 cx.deactivate_window();
11081 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11082
11083 // Re-activating the window doesn't save the file.
11084 cx.update(|window, _| window.activate_window());
11085 cx.executor().run_until_parked();
11086 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11087
11088 // Autosave on focus change.
11089 item.update_in(cx, |item, window, cx| {
11090 cx.focus_self(window);
11091 SettingsStore::update_global(cx, |settings, cx| {
11092 settings.update_user_settings(cx, |settings| {
11093 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11094 })
11095 });
11096 item.is_dirty = true;
11097 });
11098 // Blurring the item saves the file.
11099 item.update_in(cx, |_, window, _| window.blur());
11100 cx.executor().run_until_parked();
11101 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11102
11103 // Deactivating the window still saves the file.
11104 item.update_in(cx, |item, window, cx| {
11105 cx.focus_self(window);
11106 item.is_dirty = true;
11107 });
11108 cx.deactivate_window();
11109 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11110
11111 // Autosave after delay.
11112 item.update(cx, |item, cx| {
11113 SettingsStore::update_global(cx, |settings, cx| {
11114 settings.update_user_settings(cx, |settings| {
11115 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11116 milliseconds: 500.into(),
11117 });
11118 })
11119 });
11120 item.is_dirty = true;
11121 cx.emit(ItemEvent::Edit);
11122 });
11123
11124 // Delay hasn't fully expired, so the file is still dirty and unsaved.
11125 cx.executor().advance_clock(Duration::from_millis(250));
11126 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11127
11128 // After delay expires, the file is saved.
11129 cx.executor().advance_clock(Duration::from_millis(250));
11130 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11131
11132 // Autosave after delay, should save earlier than delay if tab is closed
11133 item.update(cx, |item, cx| {
11134 item.is_dirty = true;
11135 cx.emit(ItemEvent::Edit);
11136 });
11137 cx.executor().advance_clock(Duration::from_millis(250));
11138 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11139
11140 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11141 pane.update_in(cx, |pane, window, cx| {
11142 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11143 })
11144 .await
11145 .unwrap();
11146 assert!(!cx.has_pending_prompt());
11147 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11148
11149 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11150 workspace.update_in(cx, |workspace, window, cx| {
11151 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11152 });
11153 item.update_in(cx, |item, _window, cx| {
11154 item.is_dirty = true;
11155 for project_item in &mut item.project_items {
11156 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11157 }
11158 });
11159 cx.run_until_parked();
11160 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11161
11162 // Autosave on focus change, ensuring closing the tab counts as such.
11163 item.update(cx, |item, cx| {
11164 SettingsStore::update_global(cx, |settings, cx| {
11165 settings.update_user_settings(cx, |settings| {
11166 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11167 })
11168 });
11169 item.is_dirty = true;
11170 for project_item in &mut item.project_items {
11171 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11172 }
11173 });
11174
11175 pane.update_in(cx, |pane, window, cx| {
11176 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11177 })
11178 .await
11179 .unwrap();
11180 assert!(!cx.has_pending_prompt());
11181 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11182
11183 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11184 workspace.update_in(cx, |workspace, window, cx| {
11185 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11186 });
11187 item.update_in(cx, |item, window, cx| {
11188 item.project_items[0].update(cx, |item, _| {
11189 item.entry_id = None;
11190 });
11191 item.is_dirty = true;
11192 window.blur();
11193 });
11194 cx.run_until_parked();
11195 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11196
11197 // Ensure autosave is prevented for deleted files also when closing the buffer.
11198 let _close_items = pane.update_in(cx, |pane, window, cx| {
11199 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11200 });
11201 cx.run_until_parked();
11202 assert!(cx.has_pending_prompt());
11203 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11204 }
11205
11206 #[gpui::test]
11207 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11208 init_test(cx);
11209
11210 let fs = FakeFs::new(cx.executor());
11211 let project = Project::test(fs, [], cx).await;
11212 let (workspace, cx) =
11213 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11214
11215 // Create a multibuffer-like item with two child focus handles,
11216 // simulating individual buffer editors within a multibuffer.
11217 let item = cx.new(|cx| {
11218 TestItem::new(cx)
11219 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11220 .with_child_focus_handles(2, cx)
11221 });
11222 workspace.update_in(cx, |workspace, window, cx| {
11223 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11224 });
11225
11226 // Set autosave to OnFocusChange and focus the first child handle,
11227 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11228 item.update_in(cx, |item, window, cx| {
11229 SettingsStore::update_global(cx, |settings, cx| {
11230 settings.update_user_settings(cx, |settings| {
11231 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11232 })
11233 });
11234 item.is_dirty = true;
11235 window.focus(&item.child_focus_handles[0], cx);
11236 });
11237 cx.executor().run_until_parked();
11238 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11239
11240 // Moving focus from one child to another within the same item should
11241 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11242 item.update_in(cx, |item, window, cx| {
11243 window.focus(&item.child_focus_handles[1], cx);
11244 });
11245 cx.executor().run_until_parked();
11246 item.read_with(cx, |item, _| {
11247 assert_eq!(
11248 item.save_count, 0,
11249 "Switching focus between children within the same item should not autosave"
11250 );
11251 });
11252
11253 // Blurring the item saves the file. This is the core regression scenario:
11254 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11255 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11256 // the leaf is always a child focus handle, so `on_blur` never detected
11257 // focus leaving the item.
11258 item.update_in(cx, |_, window, _| window.blur());
11259 cx.executor().run_until_parked();
11260 item.read_with(cx, |item, _| {
11261 assert_eq!(
11262 item.save_count, 1,
11263 "Blurring should trigger autosave when focus was on a child of the item"
11264 );
11265 });
11266
11267 // Deactivating the window should also trigger autosave when a child of
11268 // the multibuffer item currently owns focus.
11269 item.update_in(cx, |item, window, cx| {
11270 item.is_dirty = true;
11271 window.focus(&item.child_focus_handles[0], cx);
11272 });
11273 cx.executor().run_until_parked();
11274 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11275
11276 cx.deactivate_window();
11277 item.read_with(cx, |item, _| {
11278 assert_eq!(
11279 item.save_count, 2,
11280 "Deactivating window should trigger autosave when focus was on a child"
11281 );
11282 });
11283 }
11284
11285 #[gpui::test]
11286 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11287 init_test(cx);
11288
11289 let fs = FakeFs::new(cx.executor());
11290
11291 let project = Project::test(fs, [], cx).await;
11292 let (workspace, cx) =
11293 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11294
11295 let item = cx.new(|cx| {
11296 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11297 });
11298 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11299 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11300 let toolbar_notify_count = Rc::new(RefCell::new(0));
11301
11302 workspace.update_in(cx, |workspace, window, cx| {
11303 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11304 let toolbar_notification_count = toolbar_notify_count.clone();
11305 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11306 *toolbar_notification_count.borrow_mut() += 1
11307 })
11308 .detach();
11309 });
11310
11311 pane.read_with(cx, |pane, _| {
11312 assert!(!pane.can_navigate_backward());
11313 assert!(!pane.can_navigate_forward());
11314 });
11315
11316 item.update_in(cx, |item, _, cx| {
11317 item.set_state("one".to_string(), cx);
11318 });
11319
11320 // Toolbar must be notified to re-render the navigation buttons
11321 assert_eq!(*toolbar_notify_count.borrow(), 1);
11322
11323 pane.read_with(cx, |pane, _| {
11324 assert!(pane.can_navigate_backward());
11325 assert!(!pane.can_navigate_forward());
11326 });
11327
11328 workspace
11329 .update_in(cx, |workspace, window, cx| {
11330 workspace.go_back(pane.downgrade(), window, cx)
11331 })
11332 .await
11333 .unwrap();
11334
11335 assert_eq!(*toolbar_notify_count.borrow(), 2);
11336 pane.read_with(cx, |pane, _| {
11337 assert!(!pane.can_navigate_backward());
11338 assert!(pane.can_navigate_forward());
11339 });
11340 }
11341
11342 /// Tests that the navigation history deduplicates entries for the same item.
11343 ///
11344 /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11345 /// the navigation history deduplicates by keeping only the most recent visit to each item,
11346 /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11347 /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11348 /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11349 ///
11350 /// This behavior prevents the navigation history from growing unnecessarily large and provides
11351 /// a better user experience by eliminating redundant navigation steps when jumping between files.
11352 #[gpui::test]
11353 async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11354 init_test(cx);
11355
11356 let fs = FakeFs::new(cx.executor());
11357 let project = Project::test(fs, [], cx).await;
11358 let (workspace, cx) =
11359 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11360
11361 let item_a = cx.new(|cx| {
11362 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11363 });
11364 let item_b = cx.new(|cx| {
11365 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11366 });
11367 let item_c = cx.new(|cx| {
11368 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11369 });
11370
11371 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11372
11373 workspace.update_in(cx, |workspace, window, cx| {
11374 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11375 workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11376 workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11377 });
11378
11379 workspace.update_in(cx, |workspace, window, cx| {
11380 workspace.activate_item(&item_a, false, false, window, cx);
11381 });
11382 cx.run_until_parked();
11383
11384 workspace.update_in(cx, |workspace, window, cx| {
11385 workspace.activate_item(&item_b, false, false, window, cx);
11386 });
11387 cx.run_until_parked();
11388
11389 workspace.update_in(cx, |workspace, window, cx| {
11390 workspace.activate_item(&item_a, false, false, window, cx);
11391 });
11392 cx.run_until_parked();
11393
11394 workspace.update_in(cx, |workspace, window, cx| {
11395 workspace.activate_item(&item_b, false, false, window, cx);
11396 });
11397 cx.run_until_parked();
11398
11399 workspace.update_in(cx, |workspace, window, cx| {
11400 workspace.activate_item(&item_a, false, false, window, cx);
11401 });
11402 cx.run_until_parked();
11403
11404 workspace.update_in(cx, |workspace, window, cx| {
11405 workspace.activate_item(&item_b, false, false, window, cx);
11406 });
11407 cx.run_until_parked();
11408
11409 workspace.update_in(cx, |workspace, window, cx| {
11410 workspace.activate_item(&item_c, false, false, window, cx);
11411 });
11412 cx.run_until_parked();
11413
11414 let backward_count = pane.read_with(cx, |pane, cx| {
11415 let mut count = 0;
11416 pane.nav_history().for_each_entry(cx, &mut |_, _| {
11417 count += 1;
11418 });
11419 count
11420 });
11421 assert!(
11422 backward_count <= 4,
11423 "Should have at most 4 entries, got {}",
11424 backward_count
11425 );
11426
11427 workspace
11428 .update_in(cx, |workspace, window, cx| {
11429 workspace.go_back(pane.downgrade(), window, cx)
11430 })
11431 .await
11432 .unwrap();
11433
11434 let active_item = workspace.read_with(cx, |workspace, cx| {
11435 workspace.active_item(cx).unwrap().item_id()
11436 });
11437 assert_eq!(
11438 active_item,
11439 item_b.entity_id(),
11440 "After first go_back, should be at item B"
11441 );
11442
11443 workspace
11444 .update_in(cx, |workspace, window, cx| {
11445 workspace.go_back(pane.downgrade(), window, cx)
11446 })
11447 .await
11448 .unwrap();
11449
11450 let active_item = workspace.read_with(cx, |workspace, cx| {
11451 workspace.active_item(cx).unwrap().item_id()
11452 });
11453 assert_eq!(
11454 active_item,
11455 item_a.entity_id(),
11456 "After second go_back, should be at item A"
11457 );
11458
11459 pane.read_with(cx, |pane, _| {
11460 assert!(pane.can_navigate_forward(), "Should be able to go forward");
11461 });
11462 }
11463
11464 #[gpui::test]
11465 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11466 init_test(cx);
11467 let fs = FakeFs::new(cx.executor());
11468 let project = Project::test(fs, [], cx).await;
11469 let (multi_workspace, cx) =
11470 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11471 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11472
11473 workspace.update_in(cx, |workspace, window, cx| {
11474 let first_item = cx.new(|cx| {
11475 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11476 });
11477 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11478 workspace.split_pane(
11479 workspace.active_pane().clone(),
11480 SplitDirection::Right,
11481 window,
11482 cx,
11483 );
11484 workspace.split_pane(
11485 workspace.active_pane().clone(),
11486 SplitDirection::Right,
11487 window,
11488 cx,
11489 );
11490 });
11491
11492 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11493 let panes = workspace.center.panes();
11494 assert!(panes.len() >= 2);
11495 (
11496 panes.first().expect("at least one pane").entity_id(),
11497 panes.last().expect("at least one pane").entity_id(),
11498 )
11499 });
11500
11501 workspace.update_in(cx, |workspace, window, cx| {
11502 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11503 });
11504 workspace.update(cx, |workspace, _| {
11505 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11506 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11507 });
11508
11509 cx.dispatch_action(ActivateLastPane);
11510
11511 workspace.update(cx, |workspace, _| {
11512 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11513 });
11514 }
11515
11516 #[gpui::test]
11517 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11518 init_test(cx);
11519 let fs = FakeFs::new(cx.executor());
11520
11521 let project = Project::test(fs, [], cx).await;
11522 let (workspace, cx) =
11523 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11524
11525 let panel = workspace.update_in(cx, |workspace, window, cx| {
11526 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11527 workspace.add_panel(panel.clone(), window, cx);
11528
11529 workspace
11530 .right_dock()
11531 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11532
11533 panel
11534 });
11535
11536 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11537 pane.update_in(cx, |pane, window, cx| {
11538 let item = cx.new(TestItem::new);
11539 pane.add_item(Box::new(item), true, true, None, window, cx);
11540 });
11541
11542 // Transfer focus from center to panel
11543 workspace.update_in(cx, |workspace, window, cx| {
11544 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11545 });
11546
11547 workspace.update_in(cx, |workspace, window, cx| {
11548 assert!(workspace.right_dock().read(cx).is_open());
11549 assert!(!panel.is_zoomed(window, cx));
11550 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11551 });
11552
11553 // Transfer focus from panel to center
11554 workspace.update_in(cx, |workspace, window, cx| {
11555 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11556 });
11557
11558 workspace.update_in(cx, |workspace, window, cx| {
11559 assert!(workspace.right_dock().read(cx).is_open());
11560 assert!(!panel.is_zoomed(window, cx));
11561 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11562 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11563 });
11564
11565 // Close the dock
11566 workspace.update_in(cx, |workspace, window, cx| {
11567 workspace.toggle_dock(DockPosition::Right, window, cx);
11568 });
11569
11570 workspace.update_in(cx, |workspace, window, cx| {
11571 assert!(!workspace.right_dock().read(cx).is_open());
11572 assert!(!panel.is_zoomed(window, cx));
11573 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11574 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11575 });
11576
11577 // Open the dock
11578 workspace.update_in(cx, |workspace, window, cx| {
11579 workspace.toggle_dock(DockPosition::Right, window, cx);
11580 });
11581
11582 workspace.update_in(cx, |workspace, window, cx| {
11583 assert!(workspace.right_dock().read(cx).is_open());
11584 assert!(!panel.is_zoomed(window, cx));
11585 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11586 });
11587
11588 // Focus and zoom panel
11589 panel.update_in(cx, |panel, window, cx| {
11590 cx.focus_self(window);
11591 panel.set_zoomed(true, window, cx)
11592 });
11593
11594 workspace.update_in(cx, |workspace, window, cx| {
11595 assert!(workspace.right_dock().read(cx).is_open());
11596 assert!(panel.is_zoomed(window, cx));
11597 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11598 });
11599
11600 // Transfer focus to the center closes the dock
11601 workspace.update_in(cx, |workspace, window, cx| {
11602 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11603 });
11604
11605 workspace.update_in(cx, |workspace, window, cx| {
11606 assert!(!workspace.right_dock().read(cx).is_open());
11607 assert!(panel.is_zoomed(window, cx));
11608 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11609 });
11610
11611 // Transferring focus back to the panel keeps it zoomed
11612 workspace.update_in(cx, |workspace, window, cx| {
11613 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11614 });
11615
11616 workspace.update_in(cx, |workspace, window, cx| {
11617 assert!(workspace.right_dock().read(cx).is_open());
11618 assert!(panel.is_zoomed(window, cx));
11619 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11620 });
11621
11622 // Close the dock while it is zoomed
11623 workspace.update_in(cx, |workspace, window, cx| {
11624 workspace.toggle_dock(DockPosition::Right, window, cx)
11625 });
11626
11627 workspace.update_in(cx, |workspace, window, cx| {
11628 assert!(!workspace.right_dock().read(cx).is_open());
11629 assert!(panel.is_zoomed(window, cx));
11630 assert!(workspace.zoomed.is_none());
11631 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11632 });
11633
11634 // Opening the dock, when it's zoomed, retains focus
11635 workspace.update_in(cx, |workspace, window, cx| {
11636 workspace.toggle_dock(DockPosition::Right, window, cx)
11637 });
11638
11639 workspace.update_in(cx, |workspace, window, cx| {
11640 assert!(workspace.right_dock().read(cx).is_open());
11641 assert!(panel.is_zoomed(window, cx));
11642 assert!(workspace.zoomed.is_some());
11643 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11644 });
11645
11646 // Unzoom and close the panel, zoom the active pane.
11647 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11648 workspace.update_in(cx, |workspace, window, cx| {
11649 workspace.toggle_dock(DockPosition::Right, window, cx)
11650 });
11651 pane.update_in(cx, |pane, window, cx| {
11652 pane.toggle_zoom(&Default::default(), window, cx)
11653 });
11654
11655 // Opening a dock unzooms the pane.
11656 workspace.update_in(cx, |workspace, window, cx| {
11657 workspace.toggle_dock(DockPosition::Right, window, cx)
11658 });
11659 workspace.update_in(cx, |workspace, window, cx| {
11660 let pane = pane.read(cx);
11661 assert!(!pane.is_zoomed());
11662 assert!(!pane.focus_handle(cx).is_focused(window));
11663 assert!(workspace.right_dock().read(cx).is_open());
11664 assert!(workspace.zoomed.is_none());
11665 });
11666 }
11667
11668 #[gpui::test]
11669 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11670 init_test(cx);
11671 let fs = FakeFs::new(cx.executor());
11672
11673 let project = Project::test(fs, [], cx).await;
11674 let (workspace, cx) =
11675 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11676
11677 let panel = workspace.update_in(cx, |workspace, window, cx| {
11678 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11679 workspace.add_panel(panel.clone(), window, cx);
11680 panel
11681 });
11682
11683 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11684 pane.update_in(cx, |pane, window, cx| {
11685 let item = cx.new(TestItem::new);
11686 pane.add_item(Box::new(item), true, true, None, window, cx);
11687 });
11688
11689 // Enable close_panel_on_toggle
11690 cx.update_global(|store: &mut SettingsStore, cx| {
11691 store.update_user_settings(cx, |settings| {
11692 settings.workspace.close_panel_on_toggle = Some(true);
11693 });
11694 });
11695
11696 // Panel starts closed. Toggling should open and focus it.
11697 workspace.update_in(cx, |workspace, window, cx| {
11698 assert!(!workspace.right_dock().read(cx).is_open());
11699 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11700 });
11701
11702 workspace.update_in(cx, |workspace, window, cx| {
11703 assert!(
11704 workspace.right_dock().read(cx).is_open(),
11705 "Dock should be open after toggling from center"
11706 );
11707 assert!(
11708 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11709 "Panel should be focused after toggling from center"
11710 );
11711 });
11712
11713 // Panel is open and focused. Toggling should close the panel and
11714 // return focus to the center.
11715 workspace.update_in(cx, |workspace, window, cx| {
11716 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11717 });
11718
11719 workspace.update_in(cx, |workspace, window, cx| {
11720 assert!(
11721 !workspace.right_dock().read(cx).is_open(),
11722 "Dock should be closed after toggling from focused panel"
11723 );
11724 assert!(
11725 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11726 "Panel should not be focused after toggling from focused panel"
11727 );
11728 });
11729
11730 // Open the dock and focus something else so the panel is open but not
11731 // focused. Toggling should focus the panel (not close it).
11732 workspace.update_in(cx, |workspace, window, cx| {
11733 workspace
11734 .right_dock()
11735 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11736 window.focus(&pane.read(cx).focus_handle(cx), cx);
11737 });
11738
11739 workspace.update_in(cx, |workspace, window, cx| {
11740 assert!(workspace.right_dock().read(cx).is_open());
11741 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11742 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11743 });
11744
11745 workspace.update_in(cx, |workspace, window, cx| {
11746 assert!(
11747 workspace.right_dock().read(cx).is_open(),
11748 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11749 );
11750 assert!(
11751 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11752 "Panel should be focused after toggling an open-but-unfocused panel"
11753 );
11754 });
11755
11756 // Now disable the setting and verify the original behavior: toggling
11757 // from a focused panel moves focus to center but leaves the dock open.
11758 cx.update_global(|store: &mut SettingsStore, cx| {
11759 store.update_user_settings(cx, |settings| {
11760 settings.workspace.close_panel_on_toggle = Some(false);
11761 });
11762 });
11763
11764 workspace.update_in(cx, |workspace, window, cx| {
11765 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11766 });
11767
11768 workspace.update_in(cx, |workspace, window, cx| {
11769 assert!(
11770 workspace.right_dock().read(cx).is_open(),
11771 "Dock should remain open when setting is disabled"
11772 );
11773 assert!(
11774 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11775 "Panel should not be focused after toggling with setting disabled"
11776 );
11777 });
11778 }
11779
11780 #[gpui::test]
11781 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11782 init_test(cx);
11783 let fs = FakeFs::new(cx.executor());
11784
11785 let project = Project::test(fs, [], cx).await;
11786 let (workspace, cx) =
11787 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11788
11789 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11790 workspace.active_pane().clone()
11791 });
11792
11793 // Add an item to the pane so it can be zoomed
11794 workspace.update_in(cx, |workspace, window, cx| {
11795 let item = cx.new(TestItem::new);
11796 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11797 });
11798
11799 // Initially not zoomed
11800 workspace.update_in(cx, |workspace, _window, cx| {
11801 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11802 assert!(
11803 workspace.zoomed.is_none(),
11804 "Workspace should track no zoomed pane"
11805 );
11806 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11807 });
11808
11809 // Zoom In
11810 pane.update_in(cx, |pane, window, cx| {
11811 pane.zoom_in(&crate::ZoomIn, window, cx);
11812 });
11813
11814 workspace.update_in(cx, |workspace, window, cx| {
11815 assert!(
11816 pane.read(cx).is_zoomed(),
11817 "Pane should be zoomed after ZoomIn"
11818 );
11819 assert!(
11820 workspace.zoomed.is_some(),
11821 "Workspace should track the zoomed pane"
11822 );
11823 assert!(
11824 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11825 "ZoomIn should focus the pane"
11826 );
11827 });
11828
11829 // Zoom In again is a no-op
11830 pane.update_in(cx, |pane, window, cx| {
11831 pane.zoom_in(&crate::ZoomIn, window, cx);
11832 });
11833
11834 workspace.update_in(cx, |workspace, window, cx| {
11835 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11836 assert!(
11837 workspace.zoomed.is_some(),
11838 "Workspace still tracks zoomed pane"
11839 );
11840 assert!(
11841 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11842 "Pane remains focused after repeated ZoomIn"
11843 );
11844 });
11845
11846 // Zoom Out
11847 pane.update_in(cx, |pane, window, cx| {
11848 pane.zoom_out(&crate::ZoomOut, window, cx);
11849 });
11850
11851 workspace.update_in(cx, |workspace, _window, cx| {
11852 assert!(
11853 !pane.read(cx).is_zoomed(),
11854 "Pane should unzoom after ZoomOut"
11855 );
11856 assert!(
11857 workspace.zoomed.is_none(),
11858 "Workspace clears zoom tracking after ZoomOut"
11859 );
11860 });
11861
11862 // Zoom Out again is a no-op
11863 pane.update_in(cx, |pane, window, cx| {
11864 pane.zoom_out(&crate::ZoomOut, window, cx);
11865 });
11866
11867 workspace.update_in(cx, |workspace, _window, cx| {
11868 assert!(
11869 !pane.read(cx).is_zoomed(),
11870 "Second ZoomOut keeps pane unzoomed"
11871 );
11872 assert!(
11873 workspace.zoomed.is_none(),
11874 "Workspace remains without zoomed pane"
11875 );
11876 });
11877 }
11878
11879 #[gpui::test]
11880 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11881 init_test(cx);
11882 let fs = FakeFs::new(cx.executor());
11883
11884 let project = Project::test(fs, [], cx).await;
11885 let (workspace, cx) =
11886 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11887 workspace.update_in(cx, |workspace, window, cx| {
11888 // Open two docks
11889 let left_dock = workspace.dock_at_position(DockPosition::Left);
11890 let right_dock = workspace.dock_at_position(DockPosition::Right);
11891
11892 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11893 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11894
11895 assert!(left_dock.read(cx).is_open());
11896 assert!(right_dock.read(cx).is_open());
11897 });
11898
11899 workspace.update_in(cx, |workspace, window, cx| {
11900 // Toggle all docks - should close both
11901 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11902
11903 let left_dock = workspace.dock_at_position(DockPosition::Left);
11904 let right_dock = workspace.dock_at_position(DockPosition::Right);
11905 assert!(!left_dock.read(cx).is_open());
11906 assert!(!right_dock.read(cx).is_open());
11907 });
11908
11909 workspace.update_in(cx, |workspace, window, cx| {
11910 // Toggle again - should reopen both
11911 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11912
11913 let left_dock = workspace.dock_at_position(DockPosition::Left);
11914 let right_dock = workspace.dock_at_position(DockPosition::Right);
11915 assert!(left_dock.read(cx).is_open());
11916 assert!(right_dock.read(cx).is_open());
11917 });
11918 }
11919
11920 #[gpui::test]
11921 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11922 init_test(cx);
11923 let fs = FakeFs::new(cx.executor());
11924
11925 let project = Project::test(fs, [], cx).await;
11926 let (workspace, cx) =
11927 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11928 workspace.update_in(cx, |workspace, window, cx| {
11929 // Open two docks
11930 let left_dock = workspace.dock_at_position(DockPosition::Left);
11931 let right_dock = workspace.dock_at_position(DockPosition::Right);
11932
11933 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11934 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11935
11936 assert!(left_dock.read(cx).is_open());
11937 assert!(right_dock.read(cx).is_open());
11938 });
11939
11940 workspace.update_in(cx, |workspace, window, cx| {
11941 // Close them manually
11942 workspace.toggle_dock(DockPosition::Left, window, cx);
11943 workspace.toggle_dock(DockPosition::Right, window, cx);
11944
11945 let left_dock = workspace.dock_at_position(DockPosition::Left);
11946 let right_dock = workspace.dock_at_position(DockPosition::Right);
11947 assert!(!left_dock.read(cx).is_open());
11948 assert!(!right_dock.read(cx).is_open());
11949 });
11950
11951 workspace.update_in(cx, |workspace, window, cx| {
11952 // Toggle all docks - only last closed (right dock) should reopen
11953 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11954
11955 let left_dock = workspace.dock_at_position(DockPosition::Left);
11956 let right_dock = workspace.dock_at_position(DockPosition::Right);
11957 assert!(!left_dock.read(cx).is_open());
11958 assert!(right_dock.read(cx).is_open());
11959 });
11960 }
11961
11962 #[gpui::test]
11963 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11964 init_test(cx);
11965 let fs = FakeFs::new(cx.executor());
11966 let project = Project::test(fs, [], cx).await;
11967 let (multi_workspace, cx) =
11968 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11969 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11970
11971 // Open two docks (left and right) with one panel each
11972 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11973 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11974 workspace.add_panel(left_panel.clone(), window, cx);
11975
11976 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11977 workspace.add_panel(right_panel.clone(), window, cx);
11978
11979 workspace.toggle_dock(DockPosition::Left, window, cx);
11980 workspace.toggle_dock(DockPosition::Right, window, cx);
11981
11982 // Verify initial state
11983 assert!(
11984 workspace.left_dock().read(cx).is_open(),
11985 "Left dock should be open"
11986 );
11987 assert_eq!(
11988 workspace
11989 .left_dock()
11990 .read(cx)
11991 .visible_panel()
11992 .unwrap()
11993 .panel_id(),
11994 left_panel.panel_id(),
11995 "Left panel should be visible in left dock"
11996 );
11997 assert!(
11998 workspace.right_dock().read(cx).is_open(),
11999 "Right dock should be open"
12000 );
12001 assert_eq!(
12002 workspace
12003 .right_dock()
12004 .read(cx)
12005 .visible_panel()
12006 .unwrap()
12007 .panel_id(),
12008 right_panel.panel_id(),
12009 "Right panel should be visible in right dock"
12010 );
12011 assert!(
12012 !workspace.bottom_dock().read(cx).is_open(),
12013 "Bottom dock should be closed"
12014 );
12015
12016 (left_panel, right_panel)
12017 });
12018
12019 // Focus the left panel and move it to the next position (bottom dock)
12020 workspace.update_in(cx, |workspace, window, cx| {
12021 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12022 assert!(
12023 left_panel.read(cx).focus_handle(cx).is_focused(window),
12024 "Left panel should be focused"
12025 );
12026 });
12027
12028 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12029
12030 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12031 workspace.update(cx, |workspace, cx| {
12032 assert!(
12033 !workspace.left_dock().read(cx).is_open(),
12034 "Left dock should be closed"
12035 );
12036 assert!(
12037 workspace.bottom_dock().read(cx).is_open(),
12038 "Bottom dock should now be open"
12039 );
12040 assert_eq!(
12041 left_panel.read(cx).position,
12042 DockPosition::Bottom,
12043 "Left panel should now be in the bottom dock"
12044 );
12045 assert_eq!(
12046 workspace
12047 .bottom_dock()
12048 .read(cx)
12049 .visible_panel()
12050 .unwrap()
12051 .panel_id(),
12052 left_panel.panel_id(),
12053 "Left panel should be the visible panel in the bottom dock"
12054 );
12055 });
12056
12057 // Toggle all docks off
12058 workspace.update_in(cx, |workspace, window, cx| {
12059 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12060 assert!(
12061 !workspace.left_dock().read(cx).is_open(),
12062 "Left dock should be closed"
12063 );
12064 assert!(
12065 !workspace.right_dock().read(cx).is_open(),
12066 "Right dock should be closed"
12067 );
12068 assert!(
12069 !workspace.bottom_dock().read(cx).is_open(),
12070 "Bottom dock should be closed"
12071 );
12072 });
12073
12074 // Toggle all docks back on and verify positions are restored
12075 workspace.update_in(cx, |workspace, window, cx| {
12076 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12077 assert!(
12078 !workspace.left_dock().read(cx).is_open(),
12079 "Left dock should remain closed"
12080 );
12081 assert!(
12082 workspace.right_dock().read(cx).is_open(),
12083 "Right dock should remain open"
12084 );
12085 assert!(
12086 workspace.bottom_dock().read(cx).is_open(),
12087 "Bottom dock should remain open"
12088 );
12089 assert_eq!(
12090 left_panel.read(cx).position,
12091 DockPosition::Bottom,
12092 "Left panel should remain in the bottom dock"
12093 );
12094 assert_eq!(
12095 right_panel.read(cx).position,
12096 DockPosition::Right,
12097 "Right panel should remain in the right dock"
12098 );
12099 assert_eq!(
12100 workspace
12101 .bottom_dock()
12102 .read(cx)
12103 .visible_panel()
12104 .unwrap()
12105 .panel_id(),
12106 left_panel.panel_id(),
12107 "Left panel should be the visible panel in the right dock"
12108 );
12109 });
12110 }
12111
12112 #[gpui::test]
12113 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12114 init_test(cx);
12115
12116 let fs = FakeFs::new(cx.executor());
12117
12118 let project = Project::test(fs, None, cx).await;
12119 let (workspace, cx) =
12120 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12121
12122 // Let's arrange the panes like this:
12123 //
12124 // +-----------------------+
12125 // | top |
12126 // +------+--------+-------+
12127 // | left | center | right |
12128 // +------+--------+-------+
12129 // | bottom |
12130 // +-----------------------+
12131
12132 let top_item = cx.new(|cx| {
12133 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12134 });
12135 let bottom_item = cx.new(|cx| {
12136 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12137 });
12138 let left_item = cx.new(|cx| {
12139 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12140 });
12141 let right_item = cx.new(|cx| {
12142 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12143 });
12144 let center_item = cx.new(|cx| {
12145 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12146 });
12147
12148 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12149 let top_pane_id = workspace.active_pane().entity_id();
12150 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12151 workspace.split_pane(
12152 workspace.active_pane().clone(),
12153 SplitDirection::Down,
12154 window,
12155 cx,
12156 );
12157 top_pane_id
12158 });
12159 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12160 let bottom_pane_id = workspace.active_pane().entity_id();
12161 workspace.add_item_to_active_pane(
12162 Box::new(bottom_item.clone()),
12163 None,
12164 false,
12165 window,
12166 cx,
12167 );
12168 workspace.split_pane(
12169 workspace.active_pane().clone(),
12170 SplitDirection::Up,
12171 window,
12172 cx,
12173 );
12174 bottom_pane_id
12175 });
12176 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12177 let left_pane_id = workspace.active_pane().entity_id();
12178 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12179 workspace.split_pane(
12180 workspace.active_pane().clone(),
12181 SplitDirection::Right,
12182 window,
12183 cx,
12184 );
12185 left_pane_id
12186 });
12187 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12188 let right_pane_id = workspace.active_pane().entity_id();
12189 workspace.add_item_to_active_pane(
12190 Box::new(right_item.clone()),
12191 None,
12192 false,
12193 window,
12194 cx,
12195 );
12196 workspace.split_pane(
12197 workspace.active_pane().clone(),
12198 SplitDirection::Left,
12199 window,
12200 cx,
12201 );
12202 right_pane_id
12203 });
12204 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12205 let center_pane_id = workspace.active_pane().entity_id();
12206 workspace.add_item_to_active_pane(
12207 Box::new(center_item.clone()),
12208 None,
12209 false,
12210 window,
12211 cx,
12212 );
12213 center_pane_id
12214 });
12215 cx.executor().run_until_parked();
12216
12217 workspace.update_in(cx, |workspace, window, cx| {
12218 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12219
12220 // Join into next from center pane into right
12221 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12222 });
12223
12224 workspace.update_in(cx, |workspace, window, cx| {
12225 let active_pane = workspace.active_pane();
12226 assert_eq!(right_pane_id, active_pane.entity_id());
12227 assert_eq!(2, active_pane.read(cx).items_len());
12228 let item_ids_in_pane =
12229 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12230 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12231 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12232
12233 // Join into next from right pane into bottom
12234 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12235 });
12236
12237 workspace.update_in(cx, |workspace, window, cx| {
12238 let active_pane = workspace.active_pane();
12239 assert_eq!(bottom_pane_id, active_pane.entity_id());
12240 assert_eq!(3, active_pane.read(cx).items_len());
12241 let item_ids_in_pane =
12242 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12243 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12244 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12245 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12246
12247 // Join into next from bottom pane into left
12248 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12249 });
12250
12251 workspace.update_in(cx, |workspace, window, cx| {
12252 let active_pane = workspace.active_pane();
12253 assert_eq!(left_pane_id, active_pane.entity_id());
12254 assert_eq!(4, active_pane.read(cx).items_len());
12255 let item_ids_in_pane =
12256 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12257 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12258 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12259 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12260 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12261
12262 // Join into next from left pane into top
12263 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12264 });
12265
12266 workspace.update_in(cx, |workspace, window, cx| {
12267 let active_pane = workspace.active_pane();
12268 assert_eq!(top_pane_id, active_pane.entity_id());
12269 assert_eq!(5, active_pane.read(cx).items_len());
12270 let item_ids_in_pane =
12271 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12272 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12273 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12274 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12275 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12276 assert!(item_ids_in_pane.contains(&top_item.item_id()));
12277
12278 // Single pane left: no-op
12279 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12280 });
12281
12282 workspace.update(cx, |workspace, _cx| {
12283 let active_pane = workspace.active_pane();
12284 assert_eq!(top_pane_id, active_pane.entity_id());
12285 });
12286 }
12287
12288 fn add_an_item_to_active_pane(
12289 cx: &mut VisualTestContext,
12290 workspace: &Entity<Workspace>,
12291 item_id: u64,
12292 ) -> Entity<TestItem> {
12293 let item = cx.new(|cx| {
12294 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12295 item_id,
12296 "item{item_id}.txt",
12297 cx,
12298 )])
12299 });
12300 workspace.update_in(cx, |workspace, window, cx| {
12301 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12302 });
12303 item
12304 }
12305
12306 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12307 workspace.update_in(cx, |workspace, window, cx| {
12308 workspace.split_pane(
12309 workspace.active_pane().clone(),
12310 SplitDirection::Right,
12311 window,
12312 cx,
12313 )
12314 })
12315 }
12316
12317 #[gpui::test]
12318 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12319 init_test(cx);
12320 let fs = FakeFs::new(cx.executor());
12321 let project = Project::test(fs, None, cx).await;
12322 let (workspace, cx) =
12323 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12324
12325 add_an_item_to_active_pane(cx, &workspace, 1);
12326 split_pane(cx, &workspace);
12327 add_an_item_to_active_pane(cx, &workspace, 2);
12328 split_pane(cx, &workspace); // empty pane
12329 split_pane(cx, &workspace);
12330 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12331
12332 cx.executor().run_until_parked();
12333
12334 workspace.update(cx, |workspace, cx| {
12335 let num_panes = workspace.panes().len();
12336 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12337 let active_item = workspace
12338 .active_pane()
12339 .read(cx)
12340 .active_item()
12341 .expect("item is in focus");
12342
12343 assert_eq!(num_panes, 4);
12344 assert_eq!(num_items_in_current_pane, 1);
12345 assert_eq!(active_item.item_id(), last_item.item_id());
12346 });
12347
12348 workspace.update_in(cx, |workspace, window, cx| {
12349 workspace.join_all_panes(window, cx);
12350 });
12351
12352 workspace.update(cx, |workspace, cx| {
12353 let num_panes = workspace.panes().len();
12354 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12355 let active_item = workspace
12356 .active_pane()
12357 .read(cx)
12358 .active_item()
12359 .expect("item is in focus");
12360
12361 assert_eq!(num_panes, 1);
12362 assert_eq!(num_items_in_current_pane, 3);
12363 assert_eq!(active_item.item_id(), last_item.item_id());
12364 });
12365 }
12366
12367 #[gpui::test]
12368 async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12369 init_test(cx);
12370 let fs = FakeFs::new(cx.executor());
12371
12372 let project = Project::test(fs, [], cx).await;
12373 let (multi_workspace, cx) =
12374 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12375 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12376
12377 workspace.update(cx, |workspace, _cx| {
12378 workspace.bounds.size.width = px(800.);
12379 });
12380
12381 workspace.update_in(cx, |workspace, window, cx| {
12382 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12383 workspace.add_panel(panel, window, cx);
12384 workspace.toggle_dock(DockPosition::Right, window, cx);
12385 });
12386
12387 let (panel, resized_width, ratio_basis_width) =
12388 workspace.update_in(cx, |workspace, window, cx| {
12389 let item = cx.new(|cx| {
12390 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12391 });
12392 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12393
12394 let dock = workspace.right_dock().read(cx);
12395 let workspace_width = workspace.bounds.size.width;
12396 let initial_width = workspace
12397 .dock_size(&dock, window, cx)
12398 .expect("flexible dock should have an initial width");
12399
12400 assert_eq!(initial_width, workspace_width / 2.);
12401
12402 workspace.resize_right_dock(px(300.), window, cx);
12403
12404 let dock = workspace.right_dock().read(cx);
12405 let resized_width = workspace
12406 .dock_size(&dock, window, cx)
12407 .expect("flexible dock should keep its resized width");
12408
12409 assert_eq!(resized_width, px(300.));
12410
12411 let panel = workspace
12412 .right_dock()
12413 .read(cx)
12414 .visible_panel()
12415 .expect("flexible dock should have a visible panel")
12416 .panel_id();
12417
12418 (panel, resized_width, workspace_width)
12419 });
12420
12421 workspace.update_in(cx, |workspace, window, cx| {
12422 workspace.toggle_dock(DockPosition::Right, window, cx);
12423 workspace.toggle_dock(DockPosition::Right, window, cx);
12424
12425 let dock = workspace.right_dock().read(cx);
12426 let reopened_width = workspace
12427 .dock_size(&dock, window, cx)
12428 .expect("flexible dock should restore when reopened");
12429
12430 assert_eq!(reopened_width, resized_width);
12431
12432 let right_dock = workspace.right_dock().read(cx);
12433 let flexible_panel = right_dock
12434 .visible_panel()
12435 .expect("flexible dock should still have a visible panel");
12436 assert_eq!(flexible_panel.panel_id(), panel);
12437 assert_eq!(
12438 right_dock
12439 .stored_panel_size_state(flexible_panel.as_ref())
12440 .and_then(|size_state| size_state.flex),
12441 Some(
12442 resized_width.to_f64() as f32
12443 / (workspace.bounds.size.width - resized_width).to_f64() as f32
12444 )
12445 );
12446 });
12447
12448 workspace.update_in(cx, |workspace, window, cx| {
12449 workspace.split_pane(
12450 workspace.active_pane().clone(),
12451 SplitDirection::Right,
12452 window,
12453 cx,
12454 );
12455
12456 let dock = workspace.right_dock().read(cx);
12457 let split_width = workspace
12458 .dock_size(&dock, window, cx)
12459 .expect("flexible dock should keep its user-resized proportion");
12460
12461 assert_eq!(split_width, px(300.));
12462
12463 workspace.bounds.size.width = px(1600.);
12464
12465 let dock = workspace.right_dock().read(cx);
12466 let resized_window_width = workspace
12467 .dock_size(&dock, window, cx)
12468 .expect("flexible dock should preserve proportional size on window resize");
12469
12470 assert_eq!(
12471 resized_window_width,
12472 workspace.bounds.size.width
12473 * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12474 );
12475 });
12476 }
12477
12478 #[gpui::test]
12479 async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12480 init_test(cx);
12481 let fs = FakeFs::new(cx.executor());
12482
12483 // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12484 {
12485 let project = Project::test(fs.clone(), [], cx).await;
12486 let (multi_workspace, cx) =
12487 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12488 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12489
12490 workspace.update(cx, |workspace, _cx| {
12491 workspace.set_random_database_id();
12492 workspace.bounds.size.width = px(800.);
12493 });
12494
12495 let panel = workspace.update_in(cx, |workspace, window, cx| {
12496 let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12497 workspace.add_panel(panel.clone(), window, cx);
12498 workspace.toggle_dock(DockPosition::Left, window, cx);
12499 panel
12500 });
12501
12502 workspace.update_in(cx, |workspace, window, cx| {
12503 workspace.resize_left_dock(px(350.), window, cx);
12504 });
12505
12506 cx.run_until_parked();
12507
12508 let persisted = workspace.read_with(cx, |workspace, cx| {
12509 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12510 });
12511 assert_eq!(
12512 persisted.and_then(|s| s.size),
12513 Some(px(350.)),
12514 "fixed-width panel size should be persisted to KVP"
12515 );
12516
12517 // Remove the panel and re-add a fresh instance with the same key.
12518 // The new instance should have its size state restored from KVP.
12519 workspace.update_in(cx, |workspace, window, cx| {
12520 workspace.remove_panel(&panel, window, cx);
12521 });
12522
12523 workspace.update_in(cx, |workspace, window, cx| {
12524 let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12525 workspace.add_panel(new_panel, window, cx);
12526
12527 let left_dock = workspace.left_dock().read(cx);
12528 let size_state = left_dock
12529 .panel::<TestPanel>()
12530 .and_then(|p| left_dock.stored_panel_size_state(&p));
12531 assert_eq!(
12532 size_state.and_then(|s| s.size),
12533 Some(px(350.)),
12534 "re-added fixed-width panel should restore persisted size from KVP"
12535 );
12536 });
12537 }
12538
12539 // Flexible panel: both pixel size and ratio are persisted and restored.
12540 {
12541 let project = Project::test(fs.clone(), [], cx).await;
12542 let (multi_workspace, cx) =
12543 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12544 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12545
12546 workspace.update(cx, |workspace, _cx| {
12547 workspace.set_random_database_id();
12548 workspace.bounds.size.width = px(800.);
12549 });
12550
12551 let panel = workspace.update_in(cx, |workspace, window, cx| {
12552 let item = cx.new(|cx| {
12553 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12554 });
12555 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12556
12557 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12558 workspace.add_panel(panel.clone(), window, cx);
12559 workspace.toggle_dock(DockPosition::Right, window, cx);
12560 panel
12561 });
12562
12563 workspace.update_in(cx, |workspace, window, cx| {
12564 workspace.resize_right_dock(px(300.), window, cx);
12565 });
12566
12567 cx.run_until_parked();
12568
12569 let persisted = workspace
12570 .read_with(cx, |workspace, cx| {
12571 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12572 })
12573 .expect("flexible panel state should be persisted to KVP");
12574 assert_eq!(
12575 persisted.size, None,
12576 "flexible panel should not persist a redundant pixel size"
12577 );
12578 let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12579
12580 // Remove the panel and re-add: both size and ratio should be restored.
12581 workspace.update_in(cx, |workspace, window, cx| {
12582 workspace.remove_panel(&panel, window, cx);
12583 });
12584
12585 workspace.update_in(cx, |workspace, window, cx| {
12586 let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12587 workspace.add_panel(new_panel, window, cx);
12588
12589 let right_dock = workspace.right_dock().read(cx);
12590 let size_state = right_dock
12591 .panel::<TestPanel>()
12592 .and_then(|p| right_dock.stored_panel_size_state(&p))
12593 .expect("re-added flexible panel should have restored size state from KVP");
12594 assert_eq!(
12595 size_state.size, None,
12596 "re-added flexible panel should not have a persisted pixel size"
12597 );
12598 assert_eq!(
12599 size_state.flex,
12600 Some(original_ratio),
12601 "re-added flexible panel should restore persisted flex"
12602 );
12603 });
12604 }
12605 }
12606
12607 #[gpui::test]
12608 async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12609 init_test(cx);
12610 let fs = FakeFs::new(cx.executor());
12611
12612 let project = Project::test(fs, [], cx).await;
12613 let (multi_workspace, cx) =
12614 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12615 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12616
12617 workspace.update(cx, |workspace, _cx| {
12618 workspace.bounds.size.width = px(900.);
12619 });
12620
12621 // Step 1: Add a tab to the center pane then open a flexible panel in the left
12622 // dock. With one full-width center pane the default ratio is 0.5, so the panel
12623 // and the center pane each take half the workspace width.
12624 workspace.update_in(cx, |workspace, window, cx| {
12625 let item = cx.new(|cx| {
12626 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12627 });
12628 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12629
12630 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12631 workspace.add_panel(panel, window, cx);
12632 workspace.toggle_dock(DockPosition::Left, window, cx);
12633
12634 let left_dock = workspace.left_dock().read(cx);
12635 let left_width = workspace
12636 .dock_size(&left_dock, window, cx)
12637 .expect("left dock should have an active panel");
12638
12639 assert_eq!(
12640 left_width,
12641 workspace.bounds.size.width / 2.,
12642 "flexible left panel should split evenly with the center pane"
12643 );
12644 });
12645
12646 // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12647 // change horizontal width fractions, so the flexible panel stays at the same
12648 // width as each half of the split.
12649 workspace.update_in(cx, |workspace, window, cx| {
12650 workspace.split_pane(
12651 workspace.active_pane().clone(),
12652 SplitDirection::Down,
12653 window,
12654 cx,
12655 );
12656
12657 let left_dock = workspace.left_dock().read(cx);
12658 let left_width = workspace
12659 .dock_size(&left_dock, window, cx)
12660 .expect("left dock should still have an active panel after vertical split");
12661
12662 assert_eq!(
12663 left_width,
12664 workspace.bounds.size.width / 2.,
12665 "flexible left panel width should match each vertically-split pane"
12666 );
12667 });
12668
12669 // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12670 // size reduces the available width, so the flexible left panel and the center
12671 // panes all shrink proportionally to accommodate it.
12672 workspace.update_in(cx, |workspace, window, cx| {
12673 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12674 workspace.add_panel(panel, window, cx);
12675 workspace.toggle_dock(DockPosition::Right, window, cx);
12676
12677 let right_dock = workspace.right_dock().read(cx);
12678 let right_width = workspace
12679 .dock_size(&right_dock, window, cx)
12680 .expect("right dock should have an active panel");
12681
12682 let left_dock = workspace.left_dock().read(cx);
12683 let left_width = workspace
12684 .dock_size(&left_dock, window, cx)
12685 .expect("left dock should still have an active panel");
12686
12687 let available_width = workspace.bounds.size.width - right_width;
12688 assert_eq!(
12689 left_width,
12690 available_width / 2.,
12691 "flexible left panel should shrink proportionally as the right dock takes space"
12692 );
12693 });
12694
12695 // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12696 // flex sizing and the workspace width is divided among left-flex, center
12697 // (implicit flex 1.0), and right-flex.
12698 workspace.update_in(cx, |workspace, window, cx| {
12699 let right_dock = workspace.right_dock().clone();
12700 let right_panel = right_dock
12701 .read(cx)
12702 .visible_panel()
12703 .expect("right dock should have a visible panel")
12704 .clone();
12705 workspace.toggle_dock_panel_flexible_size(
12706 &right_dock,
12707 right_panel.as_ref(),
12708 window,
12709 cx,
12710 );
12711
12712 let right_dock = right_dock.read(cx);
12713 let right_panel = right_dock
12714 .visible_panel()
12715 .expect("right dock should still have a visible panel");
12716 assert!(
12717 right_panel.has_flexible_size(window, cx),
12718 "right panel should now be flexible"
12719 );
12720
12721 let right_size_state = right_dock
12722 .stored_panel_size_state(right_panel.as_ref())
12723 .expect("right panel should have a stored size state after toggling");
12724 let right_flex = right_size_state
12725 .flex
12726 .expect("right panel should have a flex value after toggling");
12727
12728 let left_dock = workspace.left_dock().read(cx);
12729 let left_width = workspace
12730 .dock_size(&left_dock, window, cx)
12731 .expect("left dock should still have an active panel");
12732 let right_width = workspace
12733 .dock_size(&right_dock, window, cx)
12734 .expect("right dock should still have an active panel");
12735
12736 let left_flex = workspace
12737 .default_dock_flex(DockPosition::Left)
12738 .expect("left dock should have a default flex");
12739
12740 let total_flex = left_flex + 1.0 + right_flex;
12741 let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12742 let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12743 assert_eq!(
12744 left_width, expected_left,
12745 "flexible left panel should share workspace width via flex ratios"
12746 );
12747 assert_eq!(
12748 right_width, expected_right,
12749 "flexible right panel should share workspace width via flex ratios"
12750 );
12751 });
12752 }
12753
12754 struct TestModal(FocusHandle);
12755
12756 impl TestModal {
12757 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12758 Self(cx.focus_handle())
12759 }
12760 }
12761
12762 impl EventEmitter<DismissEvent> for TestModal {}
12763
12764 impl Focusable for TestModal {
12765 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12766 self.0.clone()
12767 }
12768 }
12769
12770 impl ModalView for TestModal {}
12771
12772 impl Render for TestModal {
12773 fn render(
12774 &mut self,
12775 _window: &mut Window,
12776 _cx: &mut Context<TestModal>,
12777 ) -> impl IntoElement {
12778 div().track_focus(&self.0)
12779 }
12780 }
12781
12782 #[gpui::test]
12783 async fn test_panels(cx: &mut gpui::TestAppContext) {
12784 init_test(cx);
12785 let fs = FakeFs::new(cx.executor());
12786
12787 let project = Project::test(fs, [], cx).await;
12788 let (multi_workspace, cx) =
12789 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12790 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12791
12792 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12793 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12794 workspace.add_panel(panel_1.clone(), window, cx);
12795 workspace.toggle_dock(DockPosition::Left, window, cx);
12796 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12797 workspace.add_panel(panel_2.clone(), window, cx);
12798 workspace.toggle_dock(DockPosition::Right, window, cx);
12799
12800 let left_dock = workspace.left_dock();
12801 assert_eq!(
12802 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12803 panel_1.panel_id()
12804 );
12805 assert_eq!(
12806 workspace.dock_size(&left_dock.read(cx), window, cx),
12807 Some(px(300.))
12808 );
12809
12810 workspace.resize_left_dock(px(1337.), window, cx);
12811 assert_eq!(
12812 workspace
12813 .right_dock()
12814 .read(cx)
12815 .visible_panel()
12816 .unwrap()
12817 .panel_id(),
12818 panel_2.panel_id(),
12819 );
12820
12821 (panel_1, panel_2)
12822 });
12823
12824 // Move panel_1 to the right
12825 panel_1.update_in(cx, |panel_1, window, cx| {
12826 panel_1.set_position(DockPosition::Right, window, cx)
12827 });
12828
12829 workspace.update_in(cx, |workspace, window, cx| {
12830 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12831 // Since it was the only panel on the left, the left dock should now be closed.
12832 assert!(!workspace.left_dock().read(cx).is_open());
12833 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12834 let right_dock = workspace.right_dock();
12835 assert_eq!(
12836 right_dock.read(cx).visible_panel().unwrap().panel_id(),
12837 panel_1.panel_id()
12838 );
12839 assert_eq!(
12840 right_dock
12841 .read(cx)
12842 .active_panel_size()
12843 .unwrap()
12844 .size
12845 .unwrap(),
12846 px(1337.)
12847 );
12848
12849 // Now we move panel_2 to the left
12850 panel_2.set_position(DockPosition::Left, window, cx);
12851 });
12852
12853 workspace.update(cx, |workspace, cx| {
12854 // Since panel_2 was not visible on the right, we don't open the left dock.
12855 assert!(!workspace.left_dock().read(cx).is_open());
12856 // And the right dock is unaffected in its displaying of panel_1
12857 assert!(workspace.right_dock().read(cx).is_open());
12858 assert_eq!(
12859 workspace
12860 .right_dock()
12861 .read(cx)
12862 .visible_panel()
12863 .unwrap()
12864 .panel_id(),
12865 panel_1.panel_id(),
12866 );
12867 });
12868
12869 // Move panel_1 back to the left
12870 panel_1.update_in(cx, |panel_1, window, cx| {
12871 panel_1.set_position(DockPosition::Left, window, cx)
12872 });
12873
12874 workspace.update_in(cx, |workspace, window, cx| {
12875 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12876 let left_dock = workspace.left_dock();
12877 assert!(left_dock.read(cx).is_open());
12878 assert_eq!(
12879 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12880 panel_1.panel_id()
12881 );
12882 assert_eq!(
12883 workspace.dock_size(&left_dock.read(cx), window, cx),
12884 Some(px(1337.))
12885 );
12886 // And the right dock should be closed as it no longer has any panels.
12887 assert!(!workspace.right_dock().read(cx).is_open());
12888
12889 // Now we move panel_1 to the bottom
12890 panel_1.set_position(DockPosition::Bottom, window, cx);
12891 });
12892
12893 workspace.update_in(cx, |workspace, window, cx| {
12894 // Since panel_1 was visible on the left, we close the left dock.
12895 assert!(!workspace.left_dock().read(cx).is_open());
12896 // The bottom dock is sized based on the panel's default size,
12897 // since the panel orientation changed from vertical to horizontal.
12898 let bottom_dock = workspace.bottom_dock();
12899 assert_eq!(
12900 workspace.dock_size(&bottom_dock.read(cx), window, cx),
12901 Some(px(300.))
12902 );
12903 // Close bottom dock and move panel_1 back to the left.
12904 bottom_dock.update(cx, |bottom_dock, cx| {
12905 bottom_dock.set_open(false, window, cx)
12906 });
12907 panel_1.set_position(DockPosition::Left, window, cx);
12908 });
12909
12910 // Emit activated event on panel 1
12911 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12912
12913 // Now the left dock is open and panel_1 is active and focused.
12914 workspace.update_in(cx, |workspace, window, cx| {
12915 let left_dock = workspace.left_dock();
12916 assert!(left_dock.read(cx).is_open());
12917 assert_eq!(
12918 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12919 panel_1.panel_id(),
12920 );
12921 assert!(panel_1.focus_handle(cx).is_focused(window));
12922 });
12923
12924 // Emit closed event on panel 2, which is not active
12925 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12926
12927 // Wo don't close the left dock, because panel_2 wasn't the active panel
12928 workspace.update(cx, |workspace, cx| {
12929 let left_dock = workspace.left_dock();
12930 assert!(left_dock.read(cx).is_open());
12931 assert_eq!(
12932 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12933 panel_1.panel_id(),
12934 );
12935 });
12936
12937 // Emitting a ZoomIn event shows the panel as zoomed.
12938 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12939 workspace.read_with(cx, |workspace, _| {
12940 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12941 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12942 });
12943
12944 // Move panel to another dock while it is zoomed
12945 panel_1.update_in(cx, |panel, window, cx| {
12946 panel.set_position(DockPosition::Right, window, cx)
12947 });
12948 workspace.read_with(cx, |workspace, _| {
12949 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12950
12951 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12952 });
12953
12954 // This is a helper for getting a:
12955 // - valid focus on an element,
12956 // - that isn't a part of the panes and panels system of the Workspace,
12957 // - and doesn't trigger the 'on_focus_lost' API.
12958 let focus_other_view = {
12959 let workspace = workspace.clone();
12960 move |cx: &mut VisualTestContext| {
12961 workspace.update_in(cx, |workspace, window, cx| {
12962 if workspace.active_modal::<TestModal>(cx).is_some() {
12963 workspace.toggle_modal(window, cx, TestModal::new);
12964 workspace.toggle_modal(window, cx, TestModal::new);
12965 } else {
12966 workspace.toggle_modal(window, cx, TestModal::new);
12967 }
12968 })
12969 }
12970 };
12971
12972 // If focus is transferred to another view that's not a panel or another pane, we still show
12973 // the panel as zoomed.
12974 focus_other_view(cx);
12975 workspace.read_with(cx, |workspace, _| {
12976 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12977 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12978 });
12979
12980 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12981 workspace.update_in(cx, |_workspace, window, cx| {
12982 cx.focus_self(window);
12983 });
12984 workspace.read_with(cx, |workspace, _| {
12985 assert_eq!(workspace.zoomed, None);
12986 assert_eq!(workspace.zoomed_position, None);
12987 });
12988
12989 // If focus is transferred again to another view that's not a panel or a pane, we won't
12990 // show the panel as zoomed because it wasn't zoomed before.
12991 focus_other_view(cx);
12992 workspace.read_with(cx, |workspace, _| {
12993 assert_eq!(workspace.zoomed, None);
12994 assert_eq!(workspace.zoomed_position, None);
12995 });
12996
12997 // When the panel is activated, it is zoomed again.
12998 cx.dispatch_action(ToggleRightDock);
12999 workspace.read_with(cx, |workspace, _| {
13000 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13001 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13002 });
13003
13004 // Emitting a ZoomOut event unzooms the panel.
13005 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13006 workspace.read_with(cx, |workspace, _| {
13007 assert_eq!(workspace.zoomed, None);
13008 assert_eq!(workspace.zoomed_position, None);
13009 });
13010
13011 // Emit closed event on panel 1, which is active
13012 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13013
13014 // Now the left dock is closed, because panel_1 was the active panel
13015 workspace.update(cx, |workspace, cx| {
13016 let right_dock = workspace.right_dock();
13017 assert!(!right_dock.read(cx).is_open());
13018 });
13019 }
13020
13021 #[gpui::test]
13022 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13023 init_test(cx);
13024
13025 let fs = FakeFs::new(cx.background_executor.clone());
13026 let project = Project::test(fs, [], cx).await;
13027 let (workspace, cx) =
13028 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13029 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13030
13031 let dirty_regular_buffer = cx.new(|cx| {
13032 TestItem::new(cx)
13033 .with_dirty(true)
13034 .with_label("1.txt")
13035 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13036 });
13037 let dirty_regular_buffer_2 = cx.new(|cx| {
13038 TestItem::new(cx)
13039 .with_dirty(true)
13040 .with_label("2.txt")
13041 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13042 });
13043 let dirty_multi_buffer_with_both = cx.new(|cx| {
13044 TestItem::new(cx)
13045 .with_dirty(true)
13046 .with_buffer_kind(ItemBufferKind::Multibuffer)
13047 .with_label("Fake Project Search")
13048 .with_project_items(&[
13049 dirty_regular_buffer.read(cx).project_items[0].clone(),
13050 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13051 ])
13052 });
13053 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13054 workspace.update_in(cx, |workspace, window, cx| {
13055 workspace.add_item(
13056 pane.clone(),
13057 Box::new(dirty_regular_buffer.clone()),
13058 None,
13059 false,
13060 false,
13061 window,
13062 cx,
13063 );
13064 workspace.add_item(
13065 pane.clone(),
13066 Box::new(dirty_regular_buffer_2.clone()),
13067 None,
13068 false,
13069 false,
13070 window,
13071 cx,
13072 );
13073 workspace.add_item(
13074 pane.clone(),
13075 Box::new(dirty_multi_buffer_with_both.clone()),
13076 None,
13077 false,
13078 false,
13079 window,
13080 cx,
13081 );
13082 });
13083
13084 pane.update_in(cx, |pane, window, cx| {
13085 pane.activate_item(2, true, true, window, cx);
13086 assert_eq!(
13087 pane.active_item().unwrap().item_id(),
13088 multi_buffer_with_both_files_id,
13089 "Should select the multi buffer in the pane"
13090 );
13091 });
13092 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13093 pane.close_other_items(
13094 &CloseOtherItems {
13095 save_intent: Some(SaveIntent::Save),
13096 close_pinned: true,
13097 },
13098 None,
13099 window,
13100 cx,
13101 )
13102 });
13103 cx.background_executor.run_until_parked();
13104 assert!(!cx.has_pending_prompt());
13105 close_all_but_multi_buffer_task
13106 .await
13107 .expect("Closing all buffers but the multi buffer failed");
13108 pane.update(cx, |pane, cx| {
13109 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13110 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13111 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13112 assert_eq!(pane.items_len(), 1);
13113 assert_eq!(
13114 pane.active_item().unwrap().item_id(),
13115 multi_buffer_with_both_files_id,
13116 "Should have only the multi buffer left in the pane"
13117 );
13118 assert!(
13119 dirty_multi_buffer_with_both.read(cx).is_dirty,
13120 "The multi buffer containing the unsaved buffer should still be dirty"
13121 );
13122 });
13123
13124 dirty_regular_buffer.update(cx, |buffer, cx| {
13125 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13126 });
13127
13128 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13129 pane.close_active_item(
13130 &CloseActiveItem {
13131 save_intent: Some(SaveIntent::Close),
13132 close_pinned: false,
13133 },
13134 window,
13135 cx,
13136 )
13137 });
13138 cx.background_executor.run_until_parked();
13139 assert!(
13140 cx.has_pending_prompt(),
13141 "Dirty multi buffer should prompt a save dialog"
13142 );
13143 cx.simulate_prompt_answer("Save");
13144 cx.background_executor.run_until_parked();
13145 close_multi_buffer_task
13146 .await
13147 .expect("Closing the multi buffer failed");
13148 pane.update(cx, |pane, cx| {
13149 assert_eq!(
13150 dirty_multi_buffer_with_both.read(cx).save_count,
13151 1,
13152 "Multi buffer item should get be saved"
13153 );
13154 // Test impl does not save inner items, so we do not assert them
13155 assert_eq!(
13156 pane.items_len(),
13157 0,
13158 "No more items should be left in the pane"
13159 );
13160 assert!(pane.active_item().is_none());
13161 });
13162 }
13163
13164 #[gpui::test]
13165 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13166 cx: &mut TestAppContext,
13167 ) {
13168 init_test(cx);
13169
13170 let fs = FakeFs::new(cx.background_executor.clone());
13171 let project = Project::test(fs, [], cx).await;
13172 let (workspace, cx) =
13173 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13174 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13175
13176 let dirty_regular_buffer = cx.new(|cx| {
13177 TestItem::new(cx)
13178 .with_dirty(true)
13179 .with_label("1.txt")
13180 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13181 });
13182 let dirty_regular_buffer_2 = cx.new(|cx| {
13183 TestItem::new(cx)
13184 .with_dirty(true)
13185 .with_label("2.txt")
13186 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13187 });
13188 let clear_regular_buffer = cx.new(|cx| {
13189 TestItem::new(cx)
13190 .with_label("3.txt")
13191 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13192 });
13193
13194 let dirty_multi_buffer_with_both = cx.new(|cx| {
13195 TestItem::new(cx)
13196 .with_dirty(true)
13197 .with_buffer_kind(ItemBufferKind::Multibuffer)
13198 .with_label("Fake Project Search")
13199 .with_project_items(&[
13200 dirty_regular_buffer.read(cx).project_items[0].clone(),
13201 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13202 clear_regular_buffer.read(cx).project_items[0].clone(),
13203 ])
13204 });
13205 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13206 workspace.update_in(cx, |workspace, window, cx| {
13207 workspace.add_item(
13208 pane.clone(),
13209 Box::new(dirty_regular_buffer.clone()),
13210 None,
13211 false,
13212 false,
13213 window,
13214 cx,
13215 );
13216 workspace.add_item(
13217 pane.clone(),
13218 Box::new(dirty_multi_buffer_with_both.clone()),
13219 None,
13220 false,
13221 false,
13222 window,
13223 cx,
13224 );
13225 });
13226
13227 pane.update_in(cx, |pane, window, cx| {
13228 pane.activate_item(1, true, true, window, cx);
13229 assert_eq!(
13230 pane.active_item().unwrap().item_id(),
13231 multi_buffer_with_both_files_id,
13232 "Should select the multi buffer in the pane"
13233 );
13234 });
13235 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13236 pane.close_active_item(
13237 &CloseActiveItem {
13238 save_intent: None,
13239 close_pinned: false,
13240 },
13241 window,
13242 cx,
13243 )
13244 });
13245 cx.background_executor.run_until_parked();
13246 assert!(
13247 cx.has_pending_prompt(),
13248 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13249 );
13250 }
13251
13252 /// Tests that when `close_on_file_delete` is enabled, files are automatically
13253 /// closed when they are deleted from disk.
13254 #[gpui::test]
13255 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13256 init_test(cx);
13257
13258 // Enable the close_on_disk_deletion setting
13259 cx.update_global(|store: &mut SettingsStore, cx| {
13260 store.update_user_settings(cx, |settings| {
13261 settings.workspace.close_on_file_delete = Some(true);
13262 });
13263 });
13264
13265 let fs = FakeFs::new(cx.background_executor.clone());
13266 let project = Project::test(fs, [], cx).await;
13267 let (workspace, cx) =
13268 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13269 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13270
13271 // Create a test item that simulates a file
13272 let item = cx.new(|cx| {
13273 TestItem::new(cx)
13274 .with_label("test.txt")
13275 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13276 });
13277
13278 // Add item to workspace
13279 workspace.update_in(cx, |workspace, window, cx| {
13280 workspace.add_item(
13281 pane.clone(),
13282 Box::new(item.clone()),
13283 None,
13284 false,
13285 false,
13286 window,
13287 cx,
13288 );
13289 });
13290
13291 // Verify the item is in the pane
13292 pane.read_with(cx, |pane, _| {
13293 assert_eq!(pane.items().count(), 1);
13294 });
13295
13296 // Simulate file deletion by setting the item's deleted state
13297 item.update(cx, |item, _| {
13298 item.set_has_deleted_file(true);
13299 });
13300
13301 // Emit UpdateTab event to trigger the close behavior
13302 cx.run_until_parked();
13303 item.update(cx, |_, cx| {
13304 cx.emit(ItemEvent::UpdateTab);
13305 });
13306
13307 // Allow the close operation to complete
13308 cx.run_until_parked();
13309
13310 // Verify the item was automatically closed
13311 pane.read_with(cx, |pane, _| {
13312 assert_eq!(
13313 pane.items().count(),
13314 0,
13315 "Item should be automatically closed when file is deleted"
13316 );
13317 });
13318 }
13319
13320 /// Tests that when `close_on_file_delete` is disabled (default), files remain
13321 /// open with a strikethrough when they are deleted from disk.
13322 #[gpui::test]
13323 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13324 init_test(cx);
13325
13326 // Ensure close_on_disk_deletion is disabled (default)
13327 cx.update_global(|store: &mut SettingsStore, cx| {
13328 store.update_user_settings(cx, |settings| {
13329 settings.workspace.close_on_file_delete = Some(false);
13330 });
13331 });
13332
13333 let fs = FakeFs::new(cx.background_executor.clone());
13334 let project = Project::test(fs, [], cx).await;
13335 let (workspace, cx) =
13336 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13337 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13338
13339 // Create a test item that simulates a file
13340 let item = cx.new(|cx| {
13341 TestItem::new(cx)
13342 .with_label("test.txt")
13343 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13344 });
13345
13346 // Add item to workspace
13347 workspace.update_in(cx, |workspace, window, cx| {
13348 workspace.add_item(
13349 pane.clone(),
13350 Box::new(item.clone()),
13351 None,
13352 false,
13353 false,
13354 window,
13355 cx,
13356 );
13357 });
13358
13359 // Verify the item is in the pane
13360 pane.read_with(cx, |pane, _| {
13361 assert_eq!(pane.items().count(), 1);
13362 });
13363
13364 // Simulate file deletion
13365 item.update(cx, |item, _| {
13366 item.set_has_deleted_file(true);
13367 });
13368
13369 // Emit UpdateTab event
13370 cx.run_until_parked();
13371 item.update(cx, |_, cx| {
13372 cx.emit(ItemEvent::UpdateTab);
13373 });
13374
13375 // Allow any potential close operation to complete
13376 cx.run_until_parked();
13377
13378 // Verify the item remains open (with strikethrough)
13379 pane.read_with(cx, |pane, _| {
13380 assert_eq!(
13381 pane.items().count(),
13382 1,
13383 "Item should remain open when close_on_disk_deletion is disabled"
13384 );
13385 });
13386
13387 // Verify the item shows as deleted
13388 item.read_with(cx, |item, _| {
13389 assert!(
13390 item.has_deleted_file,
13391 "Item should be marked as having deleted file"
13392 );
13393 });
13394 }
13395
13396 /// Tests that dirty files are not automatically closed when deleted from disk,
13397 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13398 /// unsaved changes without being prompted.
13399 #[gpui::test]
13400 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13401 init_test(cx);
13402
13403 // Enable the close_on_file_delete setting
13404 cx.update_global(|store: &mut SettingsStore, cx| {
13405 store.update_user_settings(cx, |settings| {
13406 settings.workspace.close_on_file_delete = Some(true);
13407 });
13408 });
13409
13410 let fs = FakeFs::new(cx.background_executor.clone());
13411 let project = Project::test(fs, [], cx).await;
13412 let (workspace, cx) =
13413 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13414 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13415
13416 // Create a dirty test item
13417 let item = cx.new(|cx| {
13418 TestItem::new(cx)
13419 .with_dirty(true)
13420 .with_label("test.txt")
13421 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13422 });
13423
13424 // Add item to workspace
13425 workspace.update_in(cx, |workspace, window, cx| {
13426 workspace.add_item(
13427 pane.clone(),
13428 Box::new(item.clone()),
13429 None,
13430 false,
13431 false,
13432 window,
13433 cx,
13434 );
13435 });
13436
13437 // Simulate file deletion
13438 item.update(cx, |item, _| {
13439 item.set_has_deleted_file(true);
13440 });
13441
13442 // Emit UpdateTab event to trigger the close behavior
13443 cx.run_until_parked();
13444 item.update(cx, |_, cx| {
13445 cx.emit(ItemEvent::UpdateTab);
13446 });
13447
13448 // Allow any potential close operation to complete
13449 cx.run_until_parked();
13450
13451 // Verify the item remains open (dirty files are not auto-closed)
13452 pane.read_with(cx, |pane, _| {
13453 assert_eq!(
13454 pane.items().count(),
13455 1,
13456 "Dirty items should not be automatically closed even when file is deleted"
13457 );
13458 });
13459
13460 // Verify the item is marked as deleted and still dirty
13461 item.read_with(cx, |item, _| {
13462 assert!(
13463 item.has_deleted_file,
13464 "Item should be marked as having deleted file"
13465 );
13466 assert!(item.is_dirty, "Item should still be dirty");
13467 });
13468 }
13469
13470 /// Tests that navigation history is cleaned up when files are auto-closed
13471 /// due to deletion from disk.
13472 #[gpui::test]
13473 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13474 init_test(cx);
13475
13476 // Enable the close_on_file_delete setting
13477 cx.update_global(|store: &mut SettingsStore, cx| {
13478 store.update_user_settings(cx, |settings| {
13479 settings.workspace.close_on_file_delete = Some(true);
13480 });
13481 });
13482
13483 let fs = FakeFs::new(cx.background_executor.clone());
13484 let project = Project::test(fs, [], cx).await;
13485 let (workspace, cx) =
13486 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13487 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13488
13489 // Create test items
13490 let item1 = cx.new(|cx| {
13491 TestItem::new(cx)
13492 .with_label("test1.txt")
13493 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13494 });
13495 let item1_id = item1.item_id();
13496
13497 let item2 = cx.new(|cx| {
13498 TestItem::new(cx)
13499 .with_label("test2.txt")
13500 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13501 });
13502
13503 // Add items to workspace
13504 workspace.update_in(cx, |workspace, window, cx| {
13505 workspace.add_item(
13506 pane.clone(),
13507 Box::new(item1.clone()),
13508 None,
13509 false,
13510 false,
13511 window,
13512 cx,
13513 );
13514 workspace.add_item(
13515 pane.clone(),
13516 Box::new(item2.clone()),
13517 None,
13518 false,
13519 false,
13520 window,
13521 cx,
13522 );
13523 });
13524
13525 // Activate item1 to ensure it gets navigation entries
13526 pane.update_in(cx, |pane, window, cx| {
13527 pane.activate_item(0, true, true, window, cx);
13528 });
13529
13530 // Switch to item2 and back to create navigation history
13531 pane.update_in(cx, |pane, window, cx| {
13532 pane.activate_item(1, true, true, window, cx);
13533 });
13534 cx.run_until_parked();
13535
13536 pane.update_in(cx, |pane, window, cx| {
13537 pane.activate_item(0, true, true, window, cx);
13538 });
13539 cx.run_until_parked();
13540
13541 // Simulate file deletion for item1
13542 item1.update(cx, |item, _| {
13543 item.set_has_deleted_file(true);
13544 });
13545
13546 // Emit UpdateTab event to trigger the close behavior
13547 item1.update(cx, |_, cx| {
13548 cx.emit(ItemEvent::UpdateTab);
13549 });
13550 cx.run_until_parked();
13551
13552 // Verify item1 was closed
13553 pane.read_with(cx, |pane, _| {
13554 assert_eq!(
13555 pane.items().count(),
13556 1,
13557 "Should have 1 item remaining after auto-close"
13558 );
13559 });
13560
13561 // Check navigation history after close
13562 let has_item = pane.read_with(cx, |pane, cx| {
13563 let mut has_item = false;
13564 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13565 if entry.item.id() == item1_id {
13566 has_item = true;
13567 }
13568 });
13569 has_item
13570 });
13571
13572 assert!(
13573 !has_item,
13574 "Navigation history should not contain closed item entries"
13575 );
13576 }
13577
13578 #[gpui::test]
13579 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13580 cx: &mut TestAppContext,
13581 ) {
13582 init_test(cx);
13583
13584 let fs = FakeFs::new(cx.background_executor.clone());
13585 let project = Project::test(fs, [], cx).await;
13586 let (workspace, cx) =
13587 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13588 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13589
13590 let dirty_regular_buffer = cx.new(|cx| {
13591 TestItem::new(cx)
13592 .with_dirty(true)
13593 .with_label("1.txt")
13594 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13595 });
13596 let dirty_regular_buffer_2 = cx.new(|cx| {
13597 TestItem::new(cx)
13598 .with_dirty(true)
13599 .with_label("2.txt")
13600 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13601 });
13602 let clear_regular_buffer = cx.new(|cx| {
13603 TestItem::new(cx)
13604 .with_label("3.txt")
13605 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13606 });
13607
13608 let dirty_multi_buffer = cx.new(|cx| {
13609 TestItem::new(cx)
13610 .with_dirty(true)
13611 .with_buffer_kind(ItemBufferKind::Multibuffer)
13612 .with_label("Fake Project Search")
13613 .with_project_items(&[
13614 dirty_regular_buffer.read(cx).project_items[0].clone(),
13615 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13616 clear_regular_buffer.read(cx).project_items[0].clone(),
13617 ])
13618 });
13619 workspace.update_in(cx, |workspace, window, cx| {
13620 workspace.add_item(
13621 pane.clone(),
13622 Box::new(dirty_regular_buffer.clone()),
13623 None,
13624 false,
13625 false,
13626 window,
13627 cx,
13628 );
13629 workspace.add_item(
13630 pane.clone(),
13631 Box::new(dirty_regular_buffer_2.clone()),
13632 None,
13633 false,
13634 false,
13635 window,
13636 cx,
13637 );
13638 workspace.add_item(
13639 pane.clone(),
13640 Box::new(dirty_multi_buffer.clone()),
13641 None,
13642 false,
13643 false,
13644 window,
13645 cx,
13646 );
13647 });
13648
13649 pane.update_in(cx, |pane, window, cx| {
13650 pane.activate_item(2, true, true, window, cx);
13651 assert_eq!(
13652 pane.active_item().unwrap().item_id(),
13653 dirty_multi_buffer.item_id(),
13654 "Should select the multi buffer in the pane"
13655 );
13656 });
13657 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13658 pane.close_active_item(
13659 &CloseActiveItem {
13660 save_intent: None,
13661 close_pinned: false,
13662 },
13663 window,
13664 cx,
13665 )
13666 });
13667 cx.background_executor.run_until_parked();
13668 assert!(
13669 !cx.has_pending_prompt(),
13670 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13671 );
13672 close_multi_buffer_task
13673 .await
13674 .expect("Closing multi buffer failed");
13675 pane.update(cx, |pane, cx| {
13676 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13677 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13678 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13679 assert_eq!(
13680 pane.items()
13681 .map(|item| item.item_id())
13682 .sorted()
13683 .collect::<Vec<_>>(),
13684 vec![
13685 dirty_regular_buffer.item_id(),
13686 dirty_regular_buffer_2.item_id(),
13687 ],
13688 "Should have no multi buffer left in the pane"
13689 );
13690 assert!(dirty_regular_buffer.read(cx).is_dirty);
13691 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13692 });
13693 }
13694
13695 #[gpui::test]
13696 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13697 init_test(cx);
13698 let fs = FakeFs::new(cx.executor());
13699 let project = Project::test(fs, [], cx).await;
13700 let (multi_workspace, cx) =
13701 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13702 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13703
13704 // Add a new panel to the right dock, opening the dock and setting the
13705 // focus to the new panel.
13706 let panel = workspace.update_in(cx, |workspace, window, cx| {
13707 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13708 workspace.add_panel(panel.clone(), window, cx);
13709
13710 workspace
13711 .right_dock()
13712 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13713
13714 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13715
13716 panel
13717 });
13718
13719 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13720 // panel to the next valid position which, in this case, is the left
13721 // dock.
13722 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13723 workspace.update(cx, |workspace, cx| {
13724 assert!(workspace.left_dock().read(cx).is_open());
13725 assert_eq!(panel.read(cx).position, DockPosition::Left);
13726 });
13727
13728 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13729 // panel to the next valid position which, in this case, is the bottom
13730 // dock.
13731 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13732 workspace.update(cx, |workspace, cx| {
13733 assert!(workspace.bottom_dock().read(cx).is_open());
13734 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13735 });
13736
13737 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13738 // around moving the panel to its initial position, the right dock.
13739 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13740 workspace.update(cx, |workspace, cx| {
13741 assert!(workspace.right_dock().read(cx).is_open());
13742 assert_eq!(panel.read(cx).position, DockPosition::Right);
13743 });
13744
13745 // Remove focus from the panel, ensuring that, if the panel is not
13746 // focused, the `MoveFocusedPanelToNextPosition` action does not update
13747 // the panel's position, so the panel is still in the right dock.
13748 workspace.update_in(cx, |workspace, window, cx| {
13749 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13750 });
13751
13752 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13753 workspace.update(cx, |workspace, cx| {
13754 assert!(workspace.right_dock().read(cx).is_open());
13755 assert_eq!(panel.read(cx).position, DockPosition::Right);
13756 });
13757 }
13758
13759 #[gpui::test]
13760 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13761 init_test(cx);
13762
13763 let fs = FakeFs::new(cx.executor());
13764 let project = Project::test(fs, [], cx).await;
13765 let (workspace, cx) =
13766 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13767
13768 let item_1 = cx.new(|cx| {
13769 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13770 });
13771 workspace.update_in(cx, |workspace, window, cx| {
13772 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13773 workspace.move_item_to_pane_in_direction(
13774 &MoveItemToPaneInDirection {
13775 direction: SplitDirection::Right,
13776 focus: true,
13777 clone: false,
13778 },
13779 window,
13780 cx,
13781 );
13782 workspace.move_item_to_pane_at_index(
13783 &MoveItemToPane {
13784 destination: 3,
13785 focus: true,
13786 clone: false,
13787 },
13788 window,
13789 cx,
13790 );
13791
13792 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13793 assert_eq!(
13794 pane_items_paths(&workspace.active_pane, cx),
13795 vec!["first.txt".to_string()],
13796 "Single item was not moved anywhere"
13797 );
13798 });
13799
13800 let item_2 = cx.new(|cx| {
13801 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13802 });
13803 workspace.update_in(cx, |workspace, window, cx| {
13804 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13805 assert_eq!(
13806 pane_items_paths(&workspace.panes[0], cx),
13807 vec!["first.txt".to_string(), "second.txt".to_string()],
13808 );
13809 workspace.move_item_to_pane_in_direction(
13810 &MoveItemToPaneInDirection {
13811 direction: SplitDirection::Right,
13812 focus: true,
13813 clone: false,
13814 },
13815 window,
13816 cx,
13817 );
13818
13819 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13820 assert_eq!(
13821 pane_items_paths(&workspace.panes[0], cx),
13822 vec!["first.txt".to_string()],
13823 "After moving, one item should be left in the original pane"
13824 );
13825 assert_eq!(
13826 pane_items_paths(&workspace.panes[1], cx),
13827 vec!["second.txt".to_string()],
13828 "New item should have been moved to the new pane"
13829 );
13830 });
13831
13832 let item_3 = cx.new(|cx| {
13833 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13834 });
13835 workspace.update_in(cx, |workspace, window, cx| {
13836 let original_pane = workspace.panes[0].clone();
13837 workspace.set_active_pane(&original_pane, window, cx);
13838 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13839 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13840 assert_eq!(
13841 pane_items_paths(&workspace.active_pane, cx),
13842 vec!["first.txt".to_string(), "third.txt".to_string()],
13843 "New pane should be ready to move one item out"
13844 );
13845
13846 workspace.move_item_to_pane_at_index(
13847 &MoveItemToPane {
13848 destination: 3,
13849 focus: true,
13850 clone: false,
13851 },
13852 window,
13853 cx,
13854 );
13855 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13856 assert_eq!(
13857 pane_items_paths(&workspace.active_pane, cx),
13858 vec!["first.txt".to_string()],
13859 "After moving, one item should be left in the original pane"
13860 );
13861 assert_eq!(
13862 pane_items_paths(&workspace.panes[1], cx),
13863 vec!["second.txt".to_string()],
13864 "Previously created pane should be unchanged"
13865 );
13866 assert_eq!(
13867 pane_items_paths(&workspace.panes[2], cx),
13868 vec!["third.txt".to_string()],
13869 "New item should have been moved to the new pane"
13870 );
13871 });
13872 }
13873
13874 #[gpui::test]
13875 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13876 init_test(cx);
13877
13878 let fs = FakeFs::new(cx.executor());
13879 let project = Project::test(fs, [], cx).await;
13880 let (workspace, cx) =
13881 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13882
13883 let item_1 = cx.new(|cx| {
13884 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13885 });
13886 workspace.update_in(cx, |workspace, window, cx| {
13887 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13888 workspace.move_item_to_pane_in_direction(
13889 &MoveItemToPaneInDirection {
13890 direction: SplitDirection::Right,
13891 focus: true,
13892 clone: true,
13893 },
13894 window,
13895 cx,
13896 );
13897 });
13898 cx.run_until_parked();
13899 workspace.update_in(cx, |workspace, window, cx| {
13900 workspace.move_item_to_pane_at_index(
13901 &MoveItemToPane {
13902 destination: 3,
13903 focus: true,
13904 clone: true,
13905 },
13906 window,
13907 cx,
13908 );
13909 });
13910 cx.run_until_parked();
13911
13912 workspace.update(cx, |workspace, cx| {
13913 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13914 for pane in workspace.panes() {
13915 assert_eq!(
13916 pane_items_paths(pane, cx),
13917 vec!["first.txt".to_string()],
13918 "Single item exists in all panes"
13919 );
13920 }
13921 });
13922
13923 // verify that the active pane has been updated after waiting for the
13924 // pane focus event to fire and resolve
13925 workspace.read_with(cx, |workspace, _app| {
13926 assert_eq!(
13927 workspace.active_pane(),
13928 &workspace.panes[2],
13929 "The third pane should be the active one: {:?}",
13930 workspace.panes
13931 );
13932 })
13933 }
13934
13935 #[gpui::test]
13936 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13937 init_test(cx);
13938
13939 let fs = FakeFs::new(cx.executor());
13940 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13941
13942 let project = Project::test(fs, ["root".as_ref()], cx).await;
13943 let (workspace, cx) =
13944 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13945
13946 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13947 // Add item to pane A with project path
13948 let item_a = cx.new(|cx| {
13949 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13950 });
13951 workspace.update_in(cx, |workspace, window, cx| {
13952 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13953 });
13954
13955 // Split to create pane B
13956 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13957 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13958 });
13959
13960 // Add item with SAME project path to pane B, and pin it
13961 let item_b = cx.new(|cx| {
13962 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13963 });
13964 pane_b.update_in(cx, |pane, window, cx| {
13965 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13966 pane.set_pinned_count(1);
13967 });
13968
13969 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13970 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13971
13972 // close_pinned: false should only close the unpinned copy
13973 workspace.update_in(cx, |workspace, window, cx| {
13974 workspace.close_item_in_all_panes(
13975 &CloseItemInAllPanes {
13976 save_intent: Some(SaveIntent::Close),
13977 close_pinned: false,
13978 },
13979 window,
13980 cx,
13981 )
13982 });
13983 cx.executor().run_until_parked();
13984
13985 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13986 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13987 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13988 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13989
13990 // Split again, seeing as closing the previous item also closed its
13991 // pane, so only pane remains, which does not allow us to properly test
13992 // that both items close when `close_pinned: true`.
13993 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13994 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13995 });
13996
13997 // Add an item with the same project path to pane C so that
13998 // close_item_in_all_panes can determine what to close across all panes
13999 // (it reads the active item from the active pane, and split_pane
14000 // creates an empty pane).
14001 let item_c = cx.new(|cx| {
14002 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14003 });
14004 pane_c.update_in(cx, |pane, window, cx| {
14005 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14006 });
14007
14008 // close_pinned: true should close the pinned copy too
14009 workspace.update_in(cx, |workspace, window, cx| {
14010 let panes_count = workspace.panes().len();
14011 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14012
14013 workspace.close_item_in_all_panes(
14014 &CloseItemInAllPanes {
14015 save_intent: Some(SaveIntent::Close),
14016 close_pinned: true,
14017 },
14018 window,
14019 cx,
14020 )
14021 });
14022 cx.executor().run_until_parked();
14023
14024 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14025 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14026 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14027 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14028 }
14029
14030 mod register_project_item_tests {
14031
14032 use super::*;
14033
14034 // View
14035 struct TestPngItemView {
14036 focus_handle: FocusHandle,
14037 }
14038 // Model
14039 struct TestPngItem {}
14040
14041 impl project::ProjectItem for TestPngItem {
14042 fn try_open(
14043 _project: &Entity<Project>,
14044 path: &ProjectPath,
14045 cx: &mut App,
14046 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14047 if path.path.extension().unwrap() == "png" {
14048 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14049 } else {
14050 None
14051 }
14052 }
14053
14054 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14055 None
14056 }
14057
14058 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14059 None
14060 }
14061
14062 fn is_dirty(&self) -> bool {
14063 false
14064 }
14065 }
14066
14067 impl Item for TestPngItemView {
14068 type Event = ();
14069 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14070 "".into()
14071 }
14072 }
14073 impl EventEmitter<()> for TestPngItemView {}
14074 impl Focusable for TestPngItemView {
14075 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14076 self.focus_handle.clone()
14077 }
14078 }
14079
14080 impl Render for TestPngItemView {
14081 fn render(
14082 &mut self,
14083 _window: &mut Window,
14084 _cx: &mut Context<Self>,
14085 ) -> impl IntoElement {
14086 Empty
14087 }
14088 }
14089
14090 impl ProjectItem for TestPngItemView {
14091 type Item = TestPngItem;
14092
14093 fn for_project_item(
14094 _project: Entity<Project>,
14095 _pane: Option<&Pane>,
14096 _item: Entity<Self::Item>,
14097 _: &mut Window,
14098 cx: &mut Context<Self>,
14099 ) -> Self
14100 where
14101 Self: Sized,
14102 {
14103 Self {
14104 focus_handle: cx.focus_handle(),
14105 }
14106 }
14107 }
14108
14109 // View
14110 struct TestIpynbItemView {
14111 focus_handle: FocusHandle,
14112 }
14113 // Model
14114 struct TestIpynbItem {}
14115
14116 impl project::ProjectItem for TestIpynbItem {
14117 fn try_open(
14118 _project: &Entity<Project>,
14119 path: &ProjectPath,
14120 cx: &mut App,
14121 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14122 if path.path.extension().unwrap() == "ipynb" {
14123 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14124 } else {
14125 None
14126 }
14127 }
14128
14129 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14130 None
14131 }
14132
14133 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14134 None
14135 }
14136
14137 fn is_dirty(&self) -> bool {
14138 false
14139 }
14140 }
14141
14142 impl Item for TestIpynbItemView {
14143 type Event = ();
14144 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14145 "".into()
14146 }
14147 }
14148 impl EventEmitter<()> for TestIpynbItemView {}
14149 impl Focusable for TestIpynbItemView {
14150 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14151 self.focus_handle.clone()
14152 }
14153 }
14154
14155 impl Render for TestIpynbItemView {
14156 fn render(
14157 &mut self,
14158 _window: &mut Window,
14159 _cx: &mut Context<Self>,
14160 ) -> impl IntoElement {
14161 Empty
14162 }
14163 }
14164
14165 impl ProjectItem for TestIpynbItemView {
14166 type Item = TestIpynbItem;
14167
14168 fn for_project_item(
14169 _project: Entity<Project>,
14170 _pane: Option<&Pane>,
14171 _item: Entity<Self::Item>,
14172 _: &mut Window,
14173 cx: &mut Context<Self>,
14174 ) -> Self
14175 where
14176 Self: Sized,
14177 {
14178 Self {
14179 focus_handle: cx.focus_handle(),
14180 }
14181 }
14182 }
14183
14184 struct TestAlternatePngItemView {
14185 focus_handle: FocusHandle,
14186 }
14187
14188 impl Item for TestAlternatePngItemView {
14189 type Event = ();
14190 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14191 "".into()
14192 }
14193 }
14194
14195 impl EventEmitter<()> for TestAlternatePngItemView {}
14196 impl Focusable for TestAlternatePngItemView {
14197 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14198 self.focus_handle.clone()
14199 }
14200 }
14201
14202 impl Render for TestAlternatePngItemView {
14203 fn render(
14204 &mut self,
14205 _window: &mut Window,
14206 _cx: &mut Context<Self>,
14207 ) -> impl IntoElement {
14208 Empty
14209 }
14210 }
14211
14212 impl ProjectItem for TestAlternatePngItemView {
14213 type Item = TestPngItem;
14214
14215 fn for_project_item(
14216 _project: Entity<Project>,
14217 _pane: Option<&Pane>,
14218 _item: Entity<Self::Item>,
14219 _: &mut Window,
14220 cx: &mut Context<Self>,
14221 ) -> Self
14222 where
14223 Self: Sized,
14224 {
14225 Self {
14226 focus_handle: cx.focus_handle(),
14227 }
14228 }
14229 }
14230
14231 #[gpui::test]
14232 async fn test_register_project_item(cx: &mut TestAppContext) {
14233 init_test(cx);
14234
14235 cx.update(|cx| {
14236 register_project_item::<TestPngItemView>(cx);
14237 register_project_item::<TestIpynbItemView>(cx);
14238 });
14239
14240 let fs = FakeFs::new(cx.executor());
14241 fs.insert_tree(
14242 "/root1",
14243 json!({
14244 "one.png": "BINARYDATAHERE",
14245 "two.ipynb": "{ totally a notebook }",
14246 "three.txt": "editing text, sure why not?"
14247 }),
14248 )
14249 .await;
14250
14251 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14252 let (workspace, cx) =
14253 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14254
14255 let worktree_id = project.update(cx, |project, cx| {
14256 project.worktrees(cx).next().unwrap().read(cx).id()
14257 });
14258
14259 let handle = workspace
14260 .update_in(cx, |workspace, window, cx| {
14261 let project_path = (worktree_id, rel_path("one.png"));
14262 workspace.open_path(project_path, None, true, window, cx)
14263 })
14264 .await
14265 .unwrap();
14266
14267 // Now we can check if the handle we got back errored or not
14268 assert_eq!(
14269 handle.to_any_view().entity_type(),
14270 TypeId::of::<TestPngItemView>()
14271 );
14272
14273 let handle = workspace
14274 .update_in(cx, |workspace, window, cx| {
14275 let project_path = (worktree_id, rel_path("two.ipynb"));
14276 workspace.open_path(project_path, None, true, window, cx)
14277 })
14278 .await
14279 .unwrap();
14280
14281 assert_eq!(
14282 handle.to_any_view().entity_type(),
14283 TypeId::of::<TestIpynbItemView>()
14284 );
14285
14286 let handle = workspace
14287 .update_in(cx, |workspace, window, cx| {
14288 let project_path = (worktree_id, rel_path("three.txt"));
14289 workspace.open_path(project_path, None, true, window, cx)
14290 })
14291 .await;
14292 assert!(handle.is_err());
14293 }
14294
14295 #[gpui::test]
14296 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14297 init_test(cx);
14298
14299 cx.update(|cx| {
14300 register_project_item::<TestPngItemView>(cx);
14301 register_project_item::<TestAlternatePngItemView>(cx);
14302 });
14303
14304 let fs = FakeFs::new(cx.executor());
14305 fs.insert_tree(
14306 "/root1",
14307 json!({
14308 "one.png": "BINARYDATAHERE",
14309 "two.ipynb": "{ totally a notebook }",
14310 "three.txt": "editing text, sure why not?"
14311 }),
14312 )
14313 .await;
14314 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14315 let (workspace, cx) =
14316 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14317 let worktree_id = project.update(cx, |project, cx| {
14318 project.worktrees(cx).next().unwrap().read(cx).id()
14319 });
14320
14321 let handle = workspace
14322 .update_in(cx, |workspace, window, cx| {
14323 let project_path = (worktree_id, rel_path("one.png"));
14324 workspace.open_path(project_path, None, true, window, cx)
14325 })
14326 .await
14327 .unwrap();
14328
14329 // This _must_ be the second item registered
14330 assert_eq!(
14331 handle.to_any_view().entity_type(),
14332 TypeId::of::<TestAlternatePngItemView>()
14333 );
14334
14335 let handle = workspace
14336 .update_in(cx, |workspace, window, cx| {
14337 let project_path = (worktree_id, rel_path("three.txt"));
14338 workspace.open_path(project_path, None, true, window, cx)
14339 })
14340 .await;
14341 assert!(handle.is_err());
14342 }
14343 }
14344
14345 #[gpui::test]
14346 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14347 init_test(cx);
14348
14349 let fs = FakeFs::new(cx.executor());
14350 let project = Project::test(fs, [], cx).await;
14351 let (workspace, _cx) =
14352 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14353
14354 // Test with status bar shown (default)
14355 workspace.read_with(cx, |workspace, cx| {
14356 let visible = workspace.status_bar_visible(cx);
14357 assert!(visible, "Status bar should be visible by default");
14358 });
14359
14360 // Test with status bar hidden
14361 cx.update_global(|store: &mut SettingsStore, cx| {
14362 store.update_user_settings(cx, |settings| {
14363 settings.status_bar.get_or_insert_default().show = Some(false);
14364 });
14365 });
14366
14367 workspace.read_with(cx, |workspace, cx| {
14368 let visible = workspace.status_bar_visible(cx);
14369 assert!(!visible, "Status bar should be hidden when show is false");
14370 });
14371
14372 // Test with status bar shown explicitly
14373 cx.update_global(|store: &mut SettingsStore, cx| {
14374 store.update_user_settings(cx, |settings| {
14375 settings.status_bar.get_or_insert_default().show = Some(true);
14376 });
14377 });
14378
14379 workspace.read_with(cx, |workspace, cx| {
14380 let visible = workspace.status_bar_visible(cx);
14381 assert!(visible, "Status bar should be visible when show is true");
14382 });
14383 }
14384
14385 #[gpui::test]
14386 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14387 init_test(cx);
14388
14389 let fs = FakeFs::new(cx.executor());
14390 let project = Project::test(fs, [], cx).await;
14391 let (multi_workspace, cx) =
14392 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14393 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14394 let panel = workspace.update_in(cx, |workspace, window, cx| {
14395 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14396 workspace.add_panel(panel.clone(), window, cx);
14397
14398 workspace
14399 .right_dock()
14400 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14401
14402 panel
14403 });
14404
14405 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14406 let item_a = cx.new(TestItem::new);
14407 let item_b = cx.new(TestItem::new);
14408 let item_a_id = item_a.entity_id();
14409 let item_b_id = item_b.entity_id();
14410
14411 pane.update_in(cx, |pane, window, cx| {
14412 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14413 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14414 });
14415
14416 pane.read_with(cx, |pane, _| {
14417 assert_eq!(pane.items_len(), 2);
14418 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14419 });
14420
14421 workspace.update_in(cx, |workspace, window, cx| {
14422 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14423 });
14424
14425 workspace.update_in(cx, |_, window, cx| {
14426 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14427 });
14428
14429 // Assert that the `pane::CloseActiveItem` action is handled at the
14430 // workspace level when one of the dock panels is focused and, in that
14431 // case, the center pane's active item is closed but the focus is not
14432 // moved.
14433 cx.dispatch_action(pane::CloseActiveItem::default());
14434 cx.run_until_parked();
14435
14436 pane.read_with(cx, |pane, _| {
14437 assert_eq!(pane.items_len(), 1);
14438 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14439 });
14440
14441 workspace.update_in(cx, |workspace, window, cx| {
14442 assert!(workspace.right_dock().read(cx).is_open());
14443 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14444 });
14445 }
14446
14447 #[gpui::test]
14448 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14449 init_test(cx);
14450 let fs = FakeFs::new(cx.executor());
14451
14452 let project_a = Project::test(fs.clone(), [], cx).await;
14453 let project_b = Project::test(fs, [], cx).await;
14454
14455 let multi_workspace_handle =
14456 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14457 cx.run_until_parked();
14458
14459 let workspace_a = multi_workspace_handle
14460 .read_with(cx, |mw, _| mw.workspace().clone())
14461 .unwrap();
14462
14463 let _workspace_b = multi_workspace_handle
14464 .update(cx, |mw, window, cx| {
14465 mw.test_add_workspace(project_b, window, cx)
14466 })
14467 .unwrap();
14468
14469 // Switch to workspace A
14470 multi_workspace_handle
14471 .update(cx, |mw, window, cx| {
14472 let workspace = mw.workspaces()[0].clone();
14473 mw.activate(workspace, window, cx);
14474 })
14475 .unwrap();
14476
14477 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14478
14479 // Add a panel to workspace A's right dock and open the dock
14480 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14481 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14482 workspace.add_panel(panel.clone(), window, cx);
14483 workspace
14484 .right_dock()
14485 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14486 panel
14487 });
14488
14489 // Focus the panel through the workspace (matching existing test pattern)
14490 workspace_a.update_in(cx, |workspace, window, cx| {
14491 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14492 });
14493
14494 // Zoom the panel
14495 panel.update_in(cx, |panel, window, cx| {
14496 panel.set_zoomed(true, window, cx);
14497 });
14498
14499 // Verify the panel is zoomed and the dock is open
14500 workspace_a.update_in(cx, |workspace, window, cx| {
14501 assert!(
14502 workspace.right_dock().read(cx).is_open(),
14503 "dock should be open before switch"
14504 );
14505 assert!(
14506 panel.is_zoomed(window, cx),
14507 "panel should be zoomed before switch"
14508 );
14509 assert!(
14510 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14511 "panel should be focused before switch"
14512 );
14513 });
14514
14515 // Switch to workspace B
14516 multi_workspace_handle
14517 .update(cx, |mw, window, cx| {
14518 let workspace = mw.workspaces()[1].clone();
14519 mw.activate(workspace, window, cx);
14520 })
14521 .unwrap();
14522 cx.run_until_parked();
14523
14524 // Switch back to workspace A
14525 multi_workspace_handle
14526 .update(cx, |mw, window, cx| {
14527 let workspace = mw.workspaces()[0].clone();
14528 mw.activate(workspace, window, cx);
14529 })
14530 .unwrap();
14531 cx.run_until_parked();
14532
14533 // Verify the panel is still zoomed and the dock is still open
14534 workspace_a.update_in(cx, |workspace, window, cx| {
14535 assert!(
14536 workspace.right_dock().read(cx).is_open(),
14537 "dock should still be open after switching back"
14538 );
14539 assert!(
14540 panel.is_zoomed(window, cx),
14541 "panel should still be zoomed after switching back"
14542 );
14543 });
14544 }
14545
14546 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14547 pane.read(cx)
14548 .items()
14549 .flat_map(|item| {
14550 item.project_paths(cx)
14551 .into_iter()
14552 .map(|path| path.path.display(PathStyle::local()).into_owned())
14553 })
14554 .collect()
14555 }
14556
14557 pub fn init_test(cx: &mut TestAppContext) {
14558 cx.update(|cx| {
14559 let settings_store = SettingsStore::test(cx);
14560 cx.set_global(settings_store);
14561 cx.set_global(db::AppDatabase::test_new());
14562 theme_settings::init(theme::LoadThemes::JustBase, cx);
14563 });
14564 }
14565
14566 #[gpui::test]
14567 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14568 use settings::{ThemeName, ThemeSelection};
14569 use theme::SystemAppearance;
14570 use zed_actions::theme::ToggleMode;
14571
14572 init_test(cx);
14573
14574 let fs = FakeFs::new(cx.executor());
14575 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14576
14577 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14578 .await;
14579
14580 // Build a test project and workspace view so the test can invoke
14581 // the workspace action handler the same way the UI would.
14582 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14583 let (workspace, cx) =
14584 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14585
14586 // Seed the settings file with a plain static light theme so the
14587 // first toggle always starts from a known persisted state.
14588 workspace.update_in(cx, |_workspace, _window, cx| {
14589 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14590 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14591 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14592 });
14593 });
14594 cx.executor().advance_clock(Duration::from_millis(200));
14595 cx.run_until_parked();
14596
14597 // Confirm the initial persisted settings contain the static theme
14598 // we just wrote before any toggling happens.
14599 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14600 assert!(settings_text.contains(r#""theme": "One Light""#));
14601
14602 // Toggle once. This should migrate the persisted theme settings
14603 // into light/dark slots and enable system mode.
14604 workspace.update_in(cx, |workspace, window, cx| {
14605 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14606 });
14607 cx.executor().advance_clock(Duration::from_millis(200));
14608 cx.run_until_parked();
14609
14610 // 1. Static -> Dynamic
14611 // this assertion checks theme changed from static to dynamic.
14612 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14613 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14614 assert_eq!(
14615 parsed["theme"],
14616 serde_json::json!({
14617 "mode": "system",
14618 "light": "One Light",
14619 "dark": "One Dark"
14620 })
14621 );
14622
14623 // 2. Toggle again, suppose it will change the mode to light
14624 workspace.update_in(cx, |workspace, window, cx| {
14625 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14626 });
14627 cx.executor().advance_clock(Duration::from_millis(200));
14628 cx.run_until_parked();
14629
14630 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14631 assert!(settings_text.contains(r#""mode": "light""#));
14632 }
14633
14634 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14635 let item = TestProjectItem::new(id, path, cx);
14636 item.update(cx, |item, _| {
14637 item.is_dirty = true;
14638 });
14639 item
14640 }
14641
14642 #[gpui::test]
14643 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14644 cx: &mut gpui::TestAppContext,
14645 ) {
14646 init_test(cx);
14647 let fs = FakeFs::new(cx.executor());
14648
14649 let project = Project::test(fs, [], cx).await;
14650 let (workspace, cx) =
14651 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14652
14653 let panel = workspace.update_in(cx, |workspace, window, cx| {
14654 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14655 workspace.add_panel(panel.clone(), window, cx);
14656 workspace
14657 .right_dock()
14658 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14659 panel
14660 });
14661
14662 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14663 pane.update_in(cx, |pane, window, cx| {
14664 let item = cx.new(TestItem::new);
14665 pane.add_item(Box::new(item), true, true, None, window, cx);
14666 });
14667
14668 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14669 // mirrors the real-world flow and avoids side effects from directly
14670 // focusing the panel while the center pane is active.
14671 workspace.update_in(cx, |workspace, window, cx| {
14672 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14673 });
14674
14675 panel.update_in(cx, |panel, window, cx| {
14676 panel.set_zoomed(true, window, cx);
14677 });
14678
14679 workspace.update_in(cx, |workspace, window, cx| {
14680 assert!(workspace.right_dock().read(cx).is_open());
14681 assert!(panel.is_zoomed(window, cx));
14682 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14683 });
14684
14685 // Simulate a spurious pane::Event::Focus on the center pane while the
14686 // panel still has focus. This mirrors what happens during macOS window
14687 // activation: the center pane fires a focus event even though actual
14688 // focus remains on the dock panel.
14689 pane.update_in(cx, |_, _, cx| {
14690 cx.emit(pane::Event::Focus);
14691 });
14692
14693 // The dock must remain open because the panel had focus at the time the
14694 // event was processed. Before the fix, dock_to_preserve was None for
14695 // panels that don't implement pane(), causing the dock to close.
14696 workspace.update_in(cx, |workspace, window, cx| {
14697 assert!(
14698 workspace.right_dock().read(cx).is_open(),
14699 "Dock should stay open when its zoomed panel (without pane()) still has focus"
14700 );
14701 assert!(panel.is_zoomed(window, cx));
14702 });
14703 }
14704
14705 #[gpui::test]
14706 async fn test_panels_stay_open_after_position_change_and_settings_update(
14707 cx: &mut gpui::TestAppContext,
14708 ) {
14709 init_test(cx);
14710 let fs = FakeFs::new(cx.executor());
14711 let project = Project::test(fs, [], cx).await;
14712 let (workspace, cx) =
14713 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14714
14715 // Add two panels to the left dock and open it.
14716 let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14717 let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14718 let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14719 workspace.add_panel(panel_a.clone(), window, cx);
14720 workspace.add_panel(panel_b.clone(), window, cx);
14721 workspace.left_dock().update(cx, |dock, cx| {
14722 dock.set_open(true, window, cx);
14723 dock.activate_panel(0, window, cx);
14724 });
14725 (panel_a, panel_b)
14726 });
14727
14728 workspace.update_in(cx, |workspace, _, cx| {
14729 assert!(workspace.left_dock().read(cx).is_open());
14730 });
14731
14732 // Simulate a feature flag changing default dock positions: both panels
14733 // move from Left to Right.
14734 workspace.update_in(cx, |_workspace, _window, cx| {
14735 panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14736 panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14737 cx.update_global::<SettingsStore, _>(|_, _| {});
14738 });
14739
14740 // Both panels should now be in the right dock.
14741 workspace.update_in(cx, |workspace, _, cx| {
14742 let right_dock = workspace.right_dock().read(cx);
14743 assert_eq!(right_dock.panels_len(), 2);
14744 });
14745
14746 // Open the right dock and activate panel_b (simulating the user
14747 // opening the panel after it moved).
14748 workspace.update_in(cx, |workspace, window, cx| {
14749 workspace.right_dock().update(cx, |dock, cx| {
14750 dock.set_open(true, window, cx);
14751 dock.activate_panel(1, window, cx);
14752 });
14753 });
14754
14755 // Now trigger another SettingsStore change
14756 workspace.update_in(cx, |_workspace, _window, cx| {
14757 cx.update_global::<SettingsStore, _>(|_, _| {});
14758 });
14759
14760 workspace.update_in(cx, |workspace, _, cx| {
14761 assert!(
14762 workspace.right_dock().read(cx).is_open(),
14763 "Right dock should still be open after a settings change"
14764 );
14765 assert_eq!(
14766 workspace.right_dock().read(cx).panels_len(),
14767 2,
14768 "Both panels should still be in the right dock"
14769 );
14770 });
14771 }
14772}