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, SidebarEvent, 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 /// Open the panel of the given type, dismissing any zoomed items that
4191 /// would obscure it (e.g. a zoomed terminal).
4192 pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4193 let dock_position = self.all_docks().iter().find_map(|dock| {
4194 let dock = dock.read(cx);
4195 dock.panel_index_for_type::<T>().map(|_| dock.position())
4196 });
4197 self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
4198 self.open_panel::<T>(window, cx);
4199 }
4200
4201 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
4202 for dock in self.all_docks().iter() {
4203 dock.update(cx, |dock, cx| {
4204 if dock.panel::<T>().is_some() {
4205 dock.set_open(false, window, cx)
4206 }
4207 })
4208 }
4209 }
4210
4211 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
4212 self.all_docks()
4213 .iter()
4214 .find_map(|dock| dock.read(cx).panel::<T>())
4215 }
4216
4217 fn dismiss_zoomed_items_to_reveal(
4218 &mut self,
4219 dock_to_reveal: Option<DockPosition>,
4220 window: &mut Window,
4221 cx: &mut Context<Self>,
4222 ) {
4223 // If a center pane is zoomed, unzoom it.
4224 for pane in &self.panes {
4225 if pane != &self.active_pane || dock_to_reveal.is_some() {
4226 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4227 }
4228 }
4229
4230 // If another dock is zoomed, hide it.
4231 let mut focus_center = false;
4232 for dock in self.all_docks() {
4233 dock.update(cx, |dock, cx| {
4234 if Some(dock.position()) != dock_to_reveal
4235 && let Some(panel) = dock.active_panel()
4236 && panel.is_zoomed(window, cx)
4237 {
4238 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
4239 dock.set_open(false, window, cx);
4240 }
4241 });
4242 }
4243
4244 if focus_center {
4245 self.active_pane
4246 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4247 }
4248
4249 if self.zoomed_position != dock_to_reveal {
4250 self.zoomed = None;
4251 self.zoomed_position = None;
4252 cx.emit(Event::ZoomChanged);
4253 }
4254
4255 cx.notify();
4256 }
4257
4258 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4259 let pane = cx.new(|cx| {
4260 let mut pane = Pane::new(
4261 self.weak_handle(),
4262 self.project.clone(),
4263 self.pane_history_timestamp.clone(),
4264 None,
4265 NewFile.boxed_clone(),
4266 true,
4267 window,
4268 cx,
4269 );
4270 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4271 pane
4272 });
4273 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4274 .detach();
4275 self.panes.push(pane.clone());
4276
4277 window.focus(&pane.focus_handle(cx), cx);
4278
4279 cx.emit(Event::PaneAdded(pane.clone()));
4280 pane
4281 }
4282
4283 pub fn add_item_to_center(
4284 &mut self,
4285 item: Box<dyn ItemHandle>,
4286 window: &mut Window,
4287 cx: &mut Context<Self>,
4288 ) -> bool {
4289 if let Some(center_pane) = self.last_active_center_pane.clone() {
4290 if let Some(center_pane) = center_pane.upgrade() {
4291 center_pane.update(cx, |pane, cx| {
4292 pane.add_item(item, true, true, None, window, cx)
4293 });
4294 true
4295 } else {
4296 false
4297 }
4298 } else {
4299 false
4300 }
4301 }
4302
4303 pub fn add_item_to_active_pane(
4304 &mut self,
4305 item: Box<dyn ItemHandle>,
4306 destination_index: Option<usize>,
4307 focus_item: bool,
4308 window: &mut Window,
4309 cx: &mut App,
4310 ) {
4311 self.add_item(
4312 self.active_pane.clone(),
4313 item,
4314 destination_index,
4315 false,
4316 focus_item,
4317 window,
4318 cx,
4319 )
4320 }
4321
4322 pub fn add_item(
4323 &mut self,
4324 pane: Entity<Pane>,
4325 item: Box<dyn ItemHandle>,
4326 destination_index: Option<usize>,
4327 activate_pane: bool,
4328 focus_item: bool,
4329 window: &mut Window,
4330 cx: &mut App,
4331 ) {
4332 pane.update(cx, |pane, cx| {
4333 pane.add_item(
4334 item,
4335 activate_pane,
4336 focus_item,
4337 destination_index,
4338 window,
4339 cx,
4340 )
4341 });
4342 }
4343
4344 pub fn split_item(
4345 &mut self,
4346 split_direction: SplitDirection,
4347 item: Box<dyn ItemHandle>,
4348 window: &mut Window,
4349 cx: &mut Context<Self>,
4350 ) {
4351 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4352 self.add_item(new_pane, item, None, true, true, window, cx);
4353 }
4354
4355 pub fn open_abs_path(
4356 &mut self,
4357 abs_path: PathBuf,
4358 options: OpenOptions,
4359 window: &mut Window,
4360 cx: &mut Context<Self>,
4361 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4362 cx.spawn_in(window, async move |workspace, cx| {
4363 let open_paths_task_result = workspace
4364 .update_in(cx, |workspace, window, cx| {
4365 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4366 })
4367 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4368 .await;
4369 anyhow::ensure!(
4370 open_paths_task_result.len() == 1,
4371 "open abs path {abs_path:?} task returned incorrect number of results"
4372 );
4373 match open_paths_task_result
4374 .into_iter()
4375 .next()
4376 .expect("ensured single task result")
4377 {
4378 Some(open_result) => {
4379 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4380 }
4381 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4382 }
4383 })
4384 }
4385
4386 pub fn split_abs_path(
4387 &mut self,
4388 abs_path: PathBuf,
4389 visible: bool,
4390 window: &mut Window,
4391 cx: &mut Context<Self>,
4392 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4393 let project_path_task =
4394 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4395 cx.spawn_in(window, async move |this, cx| {
4396 let (_, path) = project_path_task.await?;
4397 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4398 .await
4399 })
4400 }
4401
4402 pub fn open_path(
4403 &mut self,
4404 path: impl Into<ProjectPath>,
4405 pane: Option<WeakEntity<Pane>>,
4406 focus_item: bool,
4407 window: &mut Window,
4408 cx: &mut App,
4409 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4410 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4411 }
4412
4413 pub fn open_path_preview(
4414 &mut self,
4415 path: impl Into<ProjectPath>,
4416 pane: Option<WeakEntity<Pane>>,
4417 focus_item: bool,
4418 allow_preview: bool,
4419 activate: bool,
4420 window: &mut Window,
4421 cx: &mut App,
4422 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4423 let pane = pane.unwrap_or_else(|| {
4424 self.last_active_center_pane.clone().unwrap_or_else(|| {
4425 self.panes
4426 .first()
4427 .expect("There must be an active pane")
4428 .downgrade()
4429 })
4430 });
4431
4432 let project_path = path.into();
4433 let task = self.load_path(project_path.clone(), window, cx);
4434 window.spawn(cx, async move |cx| {
4435 let (project_entry_id, build_item) = task.await?;
4436
4437 pane.update_in(cx, |pane, window, cx| {
4438 pane.open_item(
4439 project_entry_id,
4440 project_path,
4441 focus_item,
4442 allow_preview,
4443 activate,
4444 None,
4445 window,
4446 cx,
4447 build_item,
4448 )
4449 })
4450 })
4451 }
4452
4453 pub fn split_path(
4454 &mut self,
4455 path: impl Into<ProjectPath>,
4456 window: &mut Window,
4457 cx: &mut Context<Self>,
4458 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4459 self.split_path_preview(path, false, None, window, cx)
4460 }
4461
4462 pub fn split_path_preview(
4463 &mut self,
4464 path: impl Into<ProjectPath>,
4465 allow_preview: bool,
4466 split_direction: Option<SplitDirection>,
4467 window: &mut Window,
4468 cx: &mut Context<Self>,
4469 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4470 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4471 self.panes
4472 .first()
4473 .expect("There must be an active pane")
4474 .downgrade()
4475 });
4476
4477 if let Member::Pane(center_pane) = &self.center.root
4478 && center_pane.read(cx).items_len() == 0
4479 {
4480 return self.open_path(path, Some(pane), true, window, cx);
4481 }
4482
4483 let project_path = path.into();
4484 let task = self.load_path(project_path.clone(), window, cx);
4485 cx.spawn_in(window, async move |this, cx| {
4486 let (project_entry_id, build_item) = task.await?;
4487 this.update_in(cx, move |this, window, cx| -> Option<_> {
4488 let pane = pane.upgrade()?;
4489 let new_pane = this.split_pane(
4490 pane,
4491 split_direction.unwrap_or(SplitDirection::Right),
4492 window,
4493 cx,
4494 );
4495 new_pane.update(cx, |new_pane, cx| {
4496 Some(new_pane.open_item(
4497 project_entry_id,
4498 project_path,
4499 true,
4500 allow_preview,
4501 true,
4502 None,
4503 window,
4504 cx,
4505 build_item,
4506 ))
4507 })
4508 })
4509 .map(|option| option.context("pane was dropped"))?
4510 })
4511 }
4512
4513 fn load_path(
4514 &mut self,
4515 path: ProjectPath,
4516 window: &mut Window,
4517 cx: &mut App,
4518 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4519 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4520 registry.open_path(self.project(), &path, window, cx)
4521 }
4522
4523 pub fn find_project_item<T>(
4524 &self,
4525 pane: &Entity<Pane>,
4526 project_item: &Entity<T::Item>,
4527 cx: &App,
4528 ) -> Option<Entity<T>>
4529 where
4530 T: ProjectItem,
4531 {
4532 use project::ProjectItem as _;
4533 let project_item = project_item.read(cx);
4534 let entry_id = project_item.entry_id(cx);
4535 let project_path = project_item.project_path(cx);
4536
4537 let mut item = None;
4538 if let Some(entry_id) = entry_id {
4539 item = pane.read(cx).item_for_entry(entry_id, cx);
4540 }
4541 if item.is_none()
4542 && let Some(project_path) = project_path
4543 {
4544 item = pane.read(cx).item_for_path(project_path, cx);
4545 }
4546
4547 item.and_then(|item| item.downcast::<T>())
4548 }
4549
4550 pub fn is_project_item_open<T>(
4551 &self,
4552 pane: &Entity<Pane>,
4553 project_item: &Entity<T::Item>,
4554 cx: &App,
4555 ) -> bool
4556 where
4557 T: ProjectItem,
4558 {
4559 self.find_project_item::<T>(pane, project_item, cx)
4560 .is_some()
4561 }
4562
4563 pub fn open_project_item<T>(
4564 &mut self,
4565 pane: Entity<Pane>,
4566 project_item: Entity<T::Item>,
4567 activate_pane: bool,
4568 focus_item: bool,
4569 keep_old_preview: bool,
4570 allow_new_preview: bool,
4571 window: &mut Window,
4572 cx: &mut Context<Self>,
4573 ) -> Entity<T>
4574 where
4575 T: ProjectItem,
4576 {
4577 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4578
4579 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4580 if !keep_old_preview
4581 && let Some(old_id) = old_item_id
4582 && old_id != item.item_id()
4583 {
4584 // switching to a different item, so unpreview old active item
4585 pane.update(cx, |pane, _| {
4586 pane.unpreview_item_if_preview(old_id);
4587 });
4588 }
4589
4590 self.activate_item(&item, activate_pane, focus_item, window, cx);
4591 if !allow_new_preview {
4592 pane.update(cx, |pane, _| {
4593 pane.unpreview_item_if_preview(item.item_id());
4594 });
4595 }
4596 return item;
4597 }
4598
4599 let item = pane.update(cx, |pane, cx| {
4600 cx.new(|cx| {
4601 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4602 })
4603 });
4604 let mut destination_index = None;
4605 pane.update(cx, |pane, cx| {
4606 if !keep_old_preview && let Some(old_id) = old_item_id {
4607 pane.unpreview_item_if_preview(old_id);
4608 }
4609 if allow_new_preview {
4610 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4611 }
4612 });
4613
4614 self.add_item(
4615 pane,
4616 Box::new(item.clone()),
4617 destination_index,
4618 activate_pane,
4619 focus_item,
4620 window,
4621 cx,
4622 );
4623 item
4624 }
4625
4626 pub fn open_shared_screen(
4627 &mut self,
4628 peer_id: PeerId,
4629 window: &mut Window,
4630 cx: &mut Context<Self>,
4631 ) {
4632 if let Some(shared_screen) =
4633 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4634 {
4635 self.active_pane.update(cx, |pane, cx| {
4636 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4637 });
4638 }
4639 }
4640
4641 pub fn activate_item(
4642 &mut self,
4643 item: &dyn ItemHandle,
4644 activate_pane: bool,
4645 focus_item: bool,
4646 window: &mut Window,
4647 cx: &mut App,
4648 ) -> bool {
4649 let result = self.panes.iter().find_map(|pane| {
4650 pane.read(cx)
4651 .index_for_item(item)
4652 .map(|ix| (pane.clone(), ix))
4653 });
4654 if let Some((pane, ix)) = result {
4655 pane.update(cx, |pane, cx| {
4656 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4657 });
4658 true
4659 } else {
4660 false
4661 }
4662 }
4663
4664 fn activate_pane_at_index(
4665 &mut self,
4666 action: &ActivatePane,
4667 window: &mut Window,
4668 cx: &mut Context<Self>,
4669 ) {
4670 let panes = self.center.panes();
4671 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4672 window.focus(&pane.focus_handle(cx), cx);
4673 } else {
4674 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4675 .detach();
4676 }
4677 }
4678
4679 fn move_item_to_pane_at_index(
4680 &mut self,
4681 action: &MoveItemToPane,
4682 window: &mut Window,
4683 cx: &mut Context<Self>,
4684 ) {
4685 let panes = self.center.panes();
4686 let destination = match panes.get(action.destination) {
4687 Some(&destination) => destination.clone(),
4688 None => {
4689 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4690 return;
4691 }
4692 let direction = SplitDirection::Right;
4693 let split_off_pane = self
4694 .find_pane_in_direction(direction, cx)
4695 .unwrap_or_else(|| self.active_pane.clone());
4696 let new_pane = self.add_pane(window, cx);
4697 self.center.split(&split_off_pane, &new_pane, direction, cx);
4698 new_pane
4699 }
4700 };
4701
4702 if action.clone {
4703 if self
4704 .active_pane
4705 .read(cx)
4706 .active_item()
4707 .is_some_and(|item| item.can_split(cx))
4708 {
4709 clone_active_item(
4710 self.database_id(),
4711 &self.active_pane,
4712 &destination,
4713 action.focus,
4714 window,
4715 cx,
4716 );
4717 return;
4718 }
4719 }
4720 move_active_item(
4721 &self.active_pane,
4722 &destination,
4723 action.focus,
4724 true,
4725 window,
4726 cx,
4727 )
4728 }
4729
4730 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4731 let panes = self.center.panes();
4732 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4733 let next_ix = (ix + 1) % panes.len();
4734 let next_pane = panes[next_ix].clone();
4735 window.focus(&next_pane.focus_handle(cx), cx);
4736 }
4737 }
4738
4739 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4740 let panes = self.center.panes();
4741 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4742 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4743 let prev_pane = panes[prev_ix].clone();
4744 window.focus(&prev_pane.focus_handle(cx), cx);
4745 }
4746 }
4747
4748 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4749 let last_pane = self.center.last_pane();
4750 window.focus(&last_pane.focus_handle(cx), cx);
4751 }
4752
4753 pub fn activate_pane_in_direction(
4754 &mut self,
4755 direction: SplitDirection,
4756 window: &mut Window,
4757 cx: &mut App,
4758 ) {
4759 use ActivateInDirectionTarget as Target;
4760 enum Origin {
4761 Sidebar,
4762 LeftDock,
4763 RightDock,
4764 BottomDock,
4765 Center,
4766 }
4767
4768 let origin: Origin = if self
4769 .sidebar_focus_handle
4770 .as_ref()
4771 .is_some_and(|h| h.contains_focused(window, cx))
4772 {
4773 Origin::Sidebar
4774 } else {
4775 [
4776 (&self.left_dock, Origin::LeftDock),
4777 (&self.right_dock, Origin::RightDock),
4778 (&self.bottom_dock, Origin::BottomDock),
4779 ]
4780 .into_iter()
4781 .find_map(|(dock, origin)| {
4782 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4783 Some(origin)
4784 } else {
4785 None
4786 }
4787 })
4788 .unwrap_or(Origin::Center)
4789 };
4790
4791 let get_last_active_pane = || {
4792 let pane = self
4793 .last_active_center_pane
4794 .clone()
4795 .unwrap_or_else(|| {
4796 self.panes
4797 .first()
4798 .expect("There must be an active pane")
4799 .downgrade()
4800 })
4801 .upgrade()?;
4802 (pane.read(cx).items_len() != 0).then_some(pane)
4803 };
4804
4805 let try_dock =
4806 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4807
4808 let sidebar_target = self
4809 .sidebar_focus_handle
4810 .as_ref()
4811 .map(|h| Target::Sidebar(h.clone()));
4812
4813 let target = match (origin, direction) {
4814 // From the sidebar, only Right navigates into the workspace.
4815 (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
4816 .or_else(|| get_last_active_pane().map(Target::Pane))
4817 .or_else(|| try_dock(&self.bottom_dock))
4818 .or_else(|| try_dock(&self.right_dock)),
4819
4820 (Origin::Sidebar, _) => None,
4821
4822 // We're in the center, so we first try to go to a different pane,
4823 // otherwise try to go to a dock.
4824 (Origin::Center, direction) => {
4825 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4826 Some(Target::Pane(pane))
4827 } else {
4828 match direction {
4829 SplitDirection::Up => None,
4830 SplitDirection::Down => try_dock(&self.bottom_dock),
4831 SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
4832 SplitDirection::Right => try_dock(&self.right_dock),
4833 }
4834 }
4835 }
4836
4837 (Origin::LeftDock, SplitDirection::Right) => {
4838 if let Some(last_active_pane) = get_last_active_pane() {
4839 Some(Target::Pane(last_active_pane))
4840 } else {
4841 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4842 }
4843 }
4844
4845 (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
4846
4847 (Origin::LeftDock, SplitDirection::Down)
4848 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4849
4850 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4851 (Origin::BottomDock, SplitDirection::Left) => {
4852 try_dock(&self.left_dock).or(sidebar_target)
4853 }
4854 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4855
4856 (Origin::RightDock, SplitDirection::Left) => {
4857 if let Some(last_active_pane) = get_last_active_pane() {
4858 Some(Target::Pane(last_active_pane))
4859 } else {
4860 try_dock(&self.bottom_dock)
4861 .or_else(|| try_dock(&self.left_dock))
4862 .or(sidebar_target)
4863 }
4864 }
4865
4866 _ => None,
4867 };
4868
4869 match target {
4870 Some(ActivateInDirectionTarget::Pane(pane)) => {
4871 let pane = pane.read(cx);
4872 if let Some(item) = pane.active_item() {
4873 item.item_focus_handle(cx).focus(window, cx);
4874 } else {
4875 log::error!(
4876 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4877 );
4878 }
4879 }
4880 Some(ActivateInDirectionTarget::Dock(dock)) => {
4881 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4882 window.defer(cx, move |window, cx| {
4883 let dock = dock.read(cx);
4884 if let Some(panel) = dock.active_panel() {
4885 panel.panel_focus_handle(cx).focus(window, cx);
4886 } else {
4887 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4888 }
4889 })
4890 }
4891 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4892 focus_handle.focus(window, cx);
4893 }
4894 None => {}
4895 }
4896 }
4897
4898 pub fn move_item_to_pane_in_direction(
4899 &mut self,
4900 action: &MoveItemToPaneInDirection,
4901 window: &mut Window,
4902 cx: &mut Context<Self>,
4903 ) {
4904 let destination = match self.find_pane_in_direction(action.direction, cx) {
4905 Some(destination) => destination,
4906 None => {
4907 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4908 return;
4909 }
4910 let new_pane = self.add_pane(window, cx);
4911 self.center
4912 .split(&self.active_pane, &new_pane, action.direction, cx);
4913 new_pane
4914 }
4915 };
4916
4917 if action.clone {
4918 if self
4919 .active_pane
4920 .read(cx)
4921 .active_item()
4922 .is_some_and(|item| item.can_split(cx))
4923 {
4924 clone_active_item(
4925 self.database_id(),
4926 &self.active_pane,
4927 &destination,
4928 action.focus,
4929 window,
4930 cx,
4931 );
4932 return;
4933 }
4934 }
4935 move_active_item(
4936 &self.active_pane,
4937 &destination,
4938 action.focus,
4939 true,
4940 window,
4941 cx,
4942 );
4943 }
4944
4945 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4946 self.center.bounding_box_for_pane(pane)
4947 }
4948
4949 pub fn find_pane_in_direction(
4950 &mut self,
4951 direction: SplitDirection,
4952 cx: &App,
4953 ) -> Option<Entity<Pane>> {
4954 self.center
4955 .find_pane_in_direction(&self.active_pane, direction, cx)
4956 .cloned()
4957 }
4958
4959 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4960 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4961 self.center.swap(&self.active_pane, &to, cx);
4962 cx.notify();
4963 }
4964 }
4965
4966 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4967 if self
4968 .center
4969 .move_to_border(&self.active_pane, direction, cx)
4970 .unwrap()
4971 {
4972 cx.notify();
4973 }
4974 }
4975
4976 pub fn resize_pane(
4977 &mut self,
4978 axis: gpui::Axis,
4979 amount: Pixels,
4980 window: &mut Window,
4981 cx: &mut Context<Self>,
4982 ) {
4983 let docks = self.all_docks();
4984 let active_dock = docks
4985 .into_iter()
4986 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4987
4988 if let Some(dock_entity) = active_dock {
4989 let dock = dock_entity.read(cx);
4990 let Some(panel_size) = self.dock_size(&dock, window, cx) else {
4991 return;
4992 };
4993 match dock.position() {
4994 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4995 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4996 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4997 }
4998 } else {
4999 self.center
5000 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
5001 }
5002 cx.notify();
5003 }
5004
5005 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
5006 self.center.reset_pane_sizes(cx);
5007 cx.notify();
5008 }
5009
5010 fn handle_pane_focused(
5011 &mut self,
5012 pane: Entity<Pane>,
5013 window: &mut Window,
5014 cx: &mut Context<Self>,
5015 ) {
5016 // This is explicitly hoisted out of the following check for pane identity as
5017 // terminal panel panes are not registered as a center panes.
5018 self.status_bar.update(cx, |status_bar, cx| {
5019 status_bar.set_active_pane(&pane, window, cx);
5020 });
5021 if self.active_pane != pane {
5022 self.set_active_pane(&pane, window, cx);
5023 }
5024
5025 if self.last_active_center_pane.is_none() {
5026 self.last_active_center_pane = Some(pane.downgrade());
5027 }
5028
5029 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
5030 // This prevents the dock from closing when focus events fire during window activation.
5031 // We also preserve any dock whose active panel itself has focus — this covers
5032 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
5033 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
5034 let dock_read = dock.read(cx);
5035 if let Some(panel) = dock_read.active_panel() {
5036 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
5037 || panel.panel_focus_handle(cx).contains_focused(window, cx)
5038 {
5039 return Some(dock_read.position());
5040 }
5041 }
5042 None
5043 });
5044
5045 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
5046 if pane.read(cx).is_zoomed() {
5047 self.zoomed = Some(pane.downgrade().into());
5048 } else {
5049 self.zoomed = None;
5050 }
5051 self.zoomed_position = None;
5052 cx.emit(Event::ZoomChanged);
5053 self.update_active_view_for_followers(window, cx);
5054 pane.update(cx, |pane, _| {
5055 pane.track_alternate_file_items();
5056 });
5057
5058 cx.notify();
5059 }
5060
5061 fn set_active_pane(
5062 &mut self,
5063 pane: &Entity<Pane>,
5064 window: &mut Window,
5065 cx: &mut Context<Self>,
5066 ) {
5067 self.active_pane = pane.clone();
5068 self.active_item_path_changed(true, window, cx);
5069 self.last_active_center_pane = Some(pane.downgrade());
5070 }
5071
5072 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5073 self.update_active_view_for_followers(window, cx);
5074 }
5075
5076 fn handle_pane_event(
5077 &mut self,
5078 pane: &Entity<Pane>,
5079 event: &pane::Event,
5080 window: &mut Window,
5081 cx: &mut Context<Self>,
5082 ) {
5083 let mut serialize_workspace = true;
5084 match event {
5085 pane::Event::AddItem { item } => {
5086 item.added_to_pane(self, pane.clone(), window, cx);
5087 cx.emit(Event::ItemAdded {
5088 item: item.boxed_clone(),
5089 });
5090 }
5091 pane::Event::Split { direction, mode } => {
5092 match mode {
5093 SplitMode::ClonePane => {
5094 self.split_and_clone(pane.clone(), *direction, window, cx)
5095 .detach();
5096 }
5097 SplitMode::EmptyPane => {
5098 self.split_pane(pane.clone(), *direction, window, cx);
5099 }
5100 SplitMode::MovePane => {
5101 self.split_and_move(pane.clone(), *direction, window, cx);
5102 }
5103 };
5104 }
5105 pane::Event::JoinIntoNext => {
5106 self.join_pane_into_next(pane.clone(), window, cx);
5107 }
5108 pane::Event::JoinAll => {
5109 self.join_all_panes(window, cx);
5110 }
5111 pane::Event::Remove { focus_on_pane } => {
5112 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
5113 }
5114 pane::Event::ActivateItem {
5115 local,
5116 focus_changed,
5117 } => {
5118 window.invalidate_character_coordinates();
5119
5120 pane.update(cx, |pane, _| {
5121 pane.track_alternate_file_items();
5122 });
5123 if *local {
5124 self.unfollow_in_pane(pane, window, cx);
5125 }
5126 serialize_workspace = *focus_changed || pane != self.active_pane();
5127 if pane == self.active_pane() {
5128 self.active_item_path_changed(*focus_changed, window, cx);
5129 self.update_active_view_for_followers(window, cx);
5130 } else if *local {
5131 self.set_active_pane(pane, window, cx);
5132 }
5133 }
5134 pane::Event::UserSavedItem { item, save_intent } => {
5135 cx.emit(Event::UserSavedItem {
5136 pane: pane.downgrade(),
5137 item: item.boxed_clone(),
5138 save_intent: *save_intent,
5139 });
5140 serialize_workspace = false;
5141 }
5142 pane::Event::ChangeItemTitle => {
5143 if *pane == self.active_pane {
5144 self.active_item_path_changed(false, window, cx);
5145 }
5146 serialize_workspace = false;
5147 }
5148 pane::Event::RemovedItem { item } => {
5149 cx.emit(Event::ActiveItemChanged);
5150 self.update_window_edited(window, cx);
5151 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
5152 && entry.get().entity_id() == pane.entity_id()
5153 {
5154 entry.remove();
5155 }
5156 cx.emit(Event::ItemRemoved {
5157 item_id: item.item_id(),
5158 });
5159 }
5160 pane::Event::Focus => {
5161 window.invalidate_character_coordinates();
5162 self.handle_pane_focused(pane.clone(), window, cx);
5163 }
5164 pane::Event::ZoomIn => {
5165 if *pane == self.active_pane {
5166 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
5167 if pane.read(cx).has_focus(window, cx) {
5168 self.zoomed = Some(pane.downgrade().into());
5169 self.zoomed_position = None;
5170 cx.emit(Event::ZoomChanged);
5171 }
5172 cx.notify();
5173 }
5174 }
5175 pane::Event::ZoomOut => {
5176 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
5177 if self.zoomed_position.is_none() {
5178 self.zoomed = None;
5179 cx.emit(Event::ZoomChanged);
5180 }
5181 cx.notify();
5182 }
5183 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
5184 }
5185
5186 if serialize_workspace {
5187 self.serialize_workspace(window, cx);
5188 }
5189 }
5190
5191 pub fn unfollow_in_pane(
5192 &mut self,
5193 pane: &Entity<Pane>,
5194 window: &mut Window,
5195 cx: &mut Context<Workspace>,
5196 ) -> Option<CollaboratorId> {
5197 let leader_id = self.leader_for_pane(pane)?;
5198 self.unfollow(leader_id, window, cx);
5199 Some(leader_id)
5200 }
5201
5202 pub fn split_pane(
5203 &mut self,
5204 pane_to_split: Entity<Pane>,
5205 split_direction: SplitDirection,
5206 window: &mut Window,
5207 cx: &mut Context<Self>,
5208 ) -> Entity<Pane> {
5209 let new_pane = self.add_pane(window, cx);
5210 self.center
5211 .split(&pane_to_split, &new_pane, split_direction, cx);
5212 cx.notify();
5213 new_pane
5214 }
5215
5216 pub fn split_and_move(
5217 &mut self,
5218 pane: Entity<Pane>,
5219 direction: SplitDirection,
5220 window: &mut Window,
5221 cx: &mut Context<Self>,
5222 ) {
5223 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
5224 return;
5225 };
5226 let new_pane = self.add_pane(window, cx);
5227 new_pane.update(cx, |pane, cx| {
5228 pane.add_item(item, true, true, None, window, cx)
5229 });
5230 self.center.split(&pane, &new_pane, direction, cx);
5231 cx.notify();
5232 }
5233
5234 pub fn split_and_clone(
5235 &mut self,
5236 pane: Entity<Pane>,
5237 direction: SplitDirection,
5238 window: &mut Window,
5239 cx: &mut Context<Self>,
5240 ) -> Task<Option<Entity<Pane>>> {
5241 let Some(item) = pane.read(cx).active_item() else {
5242 return Task::ready(None);
5243 };
5244 if !item.can_split(cx) {
5245 return Task::ready(None);
5246 }
5247 let task = item.clone_on_split(self.database_id(), window, cx);
5248 cx.spawn_in(window, async move |this, cx| {
5249 if let Some(clone) = task.await {
5250 this.update_in(cx, |this, window, cx| {
5251 let new_pane = this.add_pane(window, cx);
5252 let nav_history = pane.read(cx).fork_nav_history();
5253 new_pane.update(cx, |pane, cx| {
5254 pane.set_nav_history(nav_history, cx);
5255 pane.add_item(clone, true, true, None, window, cx)
5256 });
5257 this.center.split(&pane, &new_pane, direction, cx);
5258 cx.notify();
5259 new_pane
5260 })
5261 .ok()
5262 } else {
5263 None
5264 }
5265 })
5266 }
5267
5268 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5269 let active_item = self.active_pane.read(cx).active_item();
5270 for pane in &self.panes {
5271 join_pane_into_active(&self.active_pane, pane, window, cx);
5272 }
5273 if let Some(active_item) = active_item {
5274 self.activate_item(active_item.as_ref(), true, true, window, cx);
5275 }
5276 cx.notify();
5277 }
5278
5279 pub fn join_pane_into_next(
5280 &mut self,
5281 pane: Entity<Pane>,
5282 window: &mut Window,
5283 cx: &mut Context<Self>,
5284 ) {
5285 let next_pane = self
5286 .find_pane_in_direction(SplitDirection::Right, cx)
5287 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5288 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5289 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5290 let Some(next_pane) = next_pane else {
5291 return;
5292 };
5293 move_all_items(&pane, &next_pane, window, cx);
5294 cx.notify();
5295 }
5296
5297 fn remove_pane(
5298 &mut self,
5299 pane: Entity<Pane>,
5300 focus_on: Option<Entity<Pane>>,
5301 window: &mut Window,
5302 cx: &mut Context<Self>,
5303 ) {
5304 if self.center.remove(&pane, cx).unwrap() {
5305 self.force_remove_pane(&pane, &focus_on, window, cx);
5306 self.unfollow_in_pane(&pane, window, cx);
5307 self.last_leaders_by_pane.remove(&pane.downgrade());
5308 for removed_item in pane.read(cx).items() {
5309 self.panes_by_item.remove(&removed_item.item_id());
5310 }
5311
5312 cx.notify();
5313 } else {
5314 self.active_item_path_changed(true, window, cx);
5315 }
5316 cx.emit(Event::PaneRemoved);
5317 }
5318
5319 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5320 &mut self.panes
5321 }
5322
5323 pub fn panes(&self) -> &[Entity<Pane>] {
5324 &self.panes
5325 }
5326
5327 pub fn active_pane(&self) -> &Entity<Pane> {
5328 &self.active_pane
5329 }
5330
5331 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5332 for dock in self.all_docks() {
5333 if dock.focus_handle(cx).contains_focused(window, cx)
5334 && let Some(pane) = dock
5335 .read(cx)
5336 .active_panel()
5337 .and_then(|panel| panel.pane(cx))
5338 {
5339 return pane;
5340 }
5341 }
5342 self.active_pane().clone()
5343 }
5344
5345 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5346 self.find_pane_in_direction(SplitDirection::Right, cx)
5347 .unwrap_or_else(|| {
5348 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5349 })
5350 }
5351
5352 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5353 self.pane_for_item_id(handle.item_id())
5354 }
5355
5356 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5357 let weak_pane = self.panes_by_item.get(&item_id)?;
5358 weak_pane.upgrade()
5359 }
5360
5361 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5362 self.panes
5363 .iter()
5364 .find(|pane| pane.entity_id() == entity_id)
5365 .cloned()
5366 }
5367
5368 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5369 self.follower_states.retain(|leader_id, state| {
5370 if *leader_id == CollaboratorId::PeerId(peer_id) {
5371 for item in state.items_by_leader_view_id.values() {
5372 item.view.set_leader_id(None, window, cx);
5373 }
5374 false
5375 } else {
5376 true
5377 }
5378 });
5379 cx.notify();
5380 }
5381
5382 pub fn start_following(
5383 &mut self,
5384 leader_id: impl Into<CollaboratorId>,
5385 window: &mut Window,
5386 cx: &mut Context<Self>,
5387 ) -> Option<Task<Result<()>>> {
5388 let leader_id = leader_id.into();
5389 let pane = self.active_pane().clone();
5390
5391 self.last_leaders_by_pane
5392 .insert(pane.downgrade(), leader_id);
5393 self.unfollow(leader_id, window, cx);
5394 self.unfollow_in_pane(&pane, window, cx);
5395 self.follower_states.insert(
5396 leader_id,
5397 FollowerState {
5398 center_pane: pane.clone(),
5399 dock_pane: None,
5400 active_view_id: None,
5401 items_by_leader_view_id: Default::default(),
5402 },
5403 );
5404 cx.notify();
5405
5406 match leader_id {
5407 CollaboratorId::PeerId(leader_peer_id) => {
5408 let room_id = self.active_call()?.room_id(cx)?;
5409 let project_id = self.project.read(cx).remote_id();
5410 let request = self.app_state.client.request(proto::Follow {
5411 room_id,
5412 project_id,
5413 leader_id: Some(leader_peer_id),
5414 });
5415
5416 Some(cx.spawn_in(window, async move |this, cx| {
5417 let response = request.await?;
5418 this.update(cx, |this, _| {
5419 let state = this
5420 .follower_states
5421 .get_mut(&leader_id)
5422 .context("following interrupted")?;
5423 state.active_view_id = response
5424 .active_view
5425 .as_ref()
5426 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5427 anyhow::Ok(())
5428 })??;
5429 if let Some(view) = response.active_view {
5430 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5431 }
5432 this.update_in(cx, |this, window, cx| {
5433 this.leader_updated(leader_id, window, cx)
5434 })?;
5435 Ok(())
5436 }))
5437 }
5438 CollaboratorId::Agent => {
5439 self.leader_updated(leader_id, window, cx)?;
5440 Some(Task::ready(Ok(())))
5441 }
5442 }
5443 }
5444
5445 pub fn follow_next_collaborator(
5446 &mut self,
5447 _: &FollowNextCollaborator,
5448 window: &mut Window,
5449 cx: &mut Context<Self>,
5450 ) {
5451 let collaborators = self.project.read(cx).collaborators();
5452 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5453 let mut collaborators = collaborators.keys().copied();
5454 for peer_id in collaborators.by_ref() {
5455 if CollaboratorId::PeerId(peer_id) == leader_id {
5456 break;
5457 }
5458 }
5459 collaborators.next().map(CollaboratorId::PeerId)
5460 } else if let Some(last_leader_id) =
5461 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5462 {
5463 match last_leader_id {
5464 CollaboratorId::PeerId(peer_id) => {
5465 if collaborators.contains_key(peer_id) {
5466 Some(*last_leader_id)
5467 } else {
5468 None
5469 }
5470 }
5471 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5472 }
5473 } else {
5474 None
5475 };
5476
5477 let pane = self.active_pane.clone();
5478 let Some(leader_id) = next_leader_id.or_else(|| {
5479 Some(CollaboratorId::PeerId(
5480 collaborators.keys().copied().next()?,
5481 ))
5482 }) else {
5483 return;
5484 };
5485 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5486 return;
5487 }
5488 if let Some(task) = self.start_following(leader_id, window, cx) {
5489 task.detach_and_log_err(cx)
5490 }
5491 }
5492
5493 pub fn follow(
5494 &mut self,
5495 leader_id: impl Into<CollaboratorId>,
5496 window: &mut Window,
5497 cx: &mut Context<Self>,
5498 ) {
5499 let leader_id = leader_id.into();
5500
5501 if let CollaboratorId::PeerId(peer_id) = leader_id {
5502 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5503 return;
5504 };
5505 let Some(remote_participant) =
5506 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5507 else {
5508 return;
5509 };
5510
5511 let project = self.project.read(cx);
5512
5513 let other_project_id = match remote_participant.location {
5514 ParticipantLocation::External => None,
5515 ParticipantLocation::UnsharedProject => None,
5516 ParticipantLocation::SharedProject { project_id } => {
5517 if Some(project_id) == project.remote_id() {
5518 None
5519 } else {
5520 Some(project_id)
5521 }
5522 }
5523 };
5524
5525 // if they are active in another project, follow there.
5526 if let Some(project_id) = other_project_id {
5527 let app_state = self.app_state.clone();
5528 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5529 .detach_and_log_err(cx);
5530 }
5531 }
5532
5533 // if you're already following, find the right pane and focus it.
5534 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5535 window.focus(&follower_state.pane().focus_handle(cx), cx);
5536
5537 return;
5538 }
5539
5540 // Otherwise, follow.
5541 if let Some(task) = self.start_following(leader_id, window, cx) {
5542 task.detach_and_log_err(cx)
5543 }
5544 }
5545
5546 pub fn unfollow(
5547 &mut self,
5548 leader_id: impl Into<CollaboratorId>,
5549 window: &mut Window,
5550 cx: &mut Context<Self>,
5551 ) -> Option<()> {
5552 cx.notify();
5553
5554 let leader_id = leader_id.into();
5555 let state = self.follower_states.remove(&leader_id)?;
5556 for (_, item) in state.items_by_leader_view_id {
5557 item.view.set_leader_id(None, window, cx);
5558 }
5559
5560 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5561 let project_id = self.project.read(cx).remote_id();
5562 let room_id = self.active_call()?.room_id(cx)?;
5563 self.app_state
5564 .client
5565 .send(proto::Unfollow {
5566 room_id,
5567 project_id,
5568 leader_id: Some(leader_peer_id),
5569 })
5570 .log_err();
5571 }
5572
5573 Some(())
5574 }
5575
5576 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5577 self.follower_states.contains_key(&id.into())
5578 }
5579
5580 fn active_item_path_changed(
5581 &mut self,
5582 focus_changed: bool,
5583 window: &mut Window,
5584 cx: &mut Context<Self>,
5585 ) {
5586 cx.emit(Event::ActiveItemChanged);
5587 let active_entry = self.active_project_path(cx);
5588 self.project.update(cx, |project, cx| {
5589 project.set_active_path(active_entry.clone(), cx)
5590 });
5591
5592 if focus_changed && let Some(project_path) = &active_entry {
5593 let git_store_entity = self.project.read(cx).git_store().clone();
5594 git_store_entity.update(cx, |git_store, cx| {
5595 git_store.set_active_repo_for_path(project_path, cx);
5596 });
5597 }
5598
5599 self.update_window_title(window, cx);
5600 }
5601
5602 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5603 let project = self.project().read(cx);
5604 let mut title = String::new();
5605
5606 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5607 let name = {
5608 let settings_location = SettingsLocation {
5609 worktree_id: worktree.read(cx).id(),
5610 path: RelPath::empty(),
5611 };
5612
5613 let settings = WorktreeSettings::get(Some(settings_location), cx);
5614 match &settings.project_name {
5615 Some(name) => name.as_str(),
5616 None => worktree.read(cx).root_name_str(),
5617 }
5618 };
5619 if i > 0 {
5620 title.push_str(", ");
5621 }
5622 title.push_str(name);
5623 }
5624
5625 if title.is_empty() {
5626 title = "empty project".to_string();
5627 }
5628
5629 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5630 let filename = path.path.file_name().or_else(|| {
5631 Some(
5632 project
5633 .worktree_for_id(path.worktree_id, cx)?
5634 .read(cx)
5635 .root_name_str(),
5636 )
5637 });
5638
5639 if let Some(filename) = filename {
5640 title.push_str(" — ");
5641 title.push_str(filename.as_ref());
5642 }
5643 }
5644
5645 if project.is_via_collab() {
5646 title.push_str(" ↙");
5647 } else if project.is_shared() {
5648 title.push_str(" ↗");
5649 }
5650
5651 if let Some(last_title) = self.last_window_title.as_ref()
5652 && &title == last_title
5653 {
5654 return;
5655 }
5656 window.set_window_title(&title);
5657 SystemWindowTabController::update_tab_title(
5658 cx,
5659 window.window_handle().window_id(),
5660 SharedString::from(&title),
5661 );
5662 self.last_window_title = Some(title);
5663 }
5664
5665 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5666 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5667 if is_edited != self.window_edited {
5668 self.window_edited = is_edited;
5669 window.set_window_edited(self.window_edited)
5670 }
5671 }
5672
5673 fn update_item_dirty_state(
5674 &mut self,
5675 item: &dyn ItemHandle,
5676 window: &mut Window,
5677 cx: &mut App,
5678 ) {
5679 let is_dirty = item.is_dirty(cx);
5680 let item_id = item.item_id();
5681 let was_dirty = self.dirty_items.contains_key(&item_id);
5682 if is_dirty == was_dirty {
5683 return;
5684 }
5685 if was_dirty {
5686 self.dirty_items.remove(&item_id);
5687 self.update_window_edited(window, cx);
5688 return;
5689 }
5690
5691 let workspace = self.weak_handle();
5692 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5693 return;
5694 };
5695 let on_release_callback = Box::new(move |cx: &mut App| {
5696 window_handle
5697 .update(cx, |_, window, cx| {
5698 workspace
5699 .update(cx, |workspace, cx| {
5700 workspace.dirty_items.remove(&item_id);
5701 workspace.update_window_edited(window, cx)
5702 })
5703 .ok();
5704 })
5705 .ok();
5706 });
5707
5708 let s = item.on_release(cx, on_release_callback);
5709 self.dirty_items.insert(item_id, s);
5710 self.update_window_edited(window, cx);
5711 }
5712
5713 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5714 if self.notifications.is_empty() {
5715 None
5716 } else {
5717 Some(
5718 div()
5719 .absolute()
5720 .right_3()
5721 .bottom_3()
5722 .w_112()
5723 .h_full()
5724 .flex()
5725 .flex_col()
5726 .justify_end()
5727 .gap_2()
5728 .children(
5729 self.notifications
5730 .iter()
5731 .map(|(_, notification)| notification.clone().into_any()),
5732 ),
5733 )
5734 }
5735 }
5736
5737 // RPC handlers
5738
5739 fn active_view_for_follower(
5740 &self,
5741 follower_project_id: Option<u64>,
5742 window: &mut Window,
5743 cx: &mut Context<Self>,
5744 ) -> Option<proto::View> {
5745 let (item, panel_id) = self.active_item_for_followers(window, cx);
5746 let item = item?;
5747 let leader_id = self
5748 .pane_for(&*item)
5749 .and_then(|pane| self.leader_for_pane(&pane));
5750 let leader_peer_id = match leader_id {
5751 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5752 Some(CollaboratorId::Agent) | None => None,
5753 };
5754
5755 let item_handle = item.to_followable_item_handle(cx)?;
5756 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5757 let variant = item_handle.to_state_proto(window, cx)?;
5758
5759 if item_handle.is_project_item(window, cx)
5760 && (follower_project_id.is_none()
5761 || follower_project_id != self.project.read(cx).remote_id())
5762 {
5763 return None;
5764 }
5765
5766 Some(proto::View {
5767 id: id.to_proto(),
5768 leader_id: leader_peer_id,
5769 variant: Some(variant),
5770 panel_id: panel_id.map(|id| id as i32),
5771 })
5772 }
5773
5774 fn handle_follow(
5775 &mut self,
5776 follower_project_id: Option<u64>,
5777 window: &mut Window,
5778 cx: &mut Context<Self>,
5779 ) -> proto::FollowResponse {
5780 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5781
5782 cx.notify();
5783 proto::FollowResponse {
5784 views: active_view.iter().cloned().collect(),
5785 active_view,
5786 }
5787 }
5788
5789 fn handle_update_followers(
5790 &mut self,
5791 leader_id: PeerId,
5792 message: proto::UpdateFollowers,
5793 _window: &mut Window,
5794 _cx: &mut Context<Self>,
5795 ) {
5796 self.leader_updates_tx
5797 .unbounded_send((leader_id, message))
5798 .ok();
5799 }
5800
5801 async fn process_leader_update(
5802 this: &WeakEntity<Self>,
5803 leader_id: PeerId,
5804 update: proto::UpdateFollowers,
5805 cx: &mut AsyncWindowContext,
5806 ) -> Result<()> {
5807 match update.variant.context("invalid update")? {
5808 proto::update_followers::Variant::CreateView(view) => {
5809 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5810 let should_add_view = this.update(cx, |this, _| {
5811 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5812 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5813 } else {
5814 anyhow::Ok(false)
5815 }
5816 })??;
5817
5818 if should_add_view {
5819 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5820 }
5821 }
5822 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5823 let should_add_view = this.update(cx, |this, _| {
5824 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5825 state.active_view_id = update_active_view
5826 .view
5827 .as_ref()
5828 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5829
5830 if state.active_view_id.is_some_and(|view_id| {
5831 !state.items_by_leader_view_id.contains_key(&view_id)
5832 }) {
5833 anyhow::Ok(true)
5834 } else {
5835 anyhow::Ok(false)
5836 }
5837 } else {
5838 anyhow::Ok(false)
5839 }
5840 })??;
5841
5842 if should_add_view && let Some(view) = update_active_view.view {
5843 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5844 }
5845 }
5846 proto::update_followers::Variant::UpdateView(update_view) => {
5847 let variant = update_view.variant.context("missing update view variant")?;
5848 let id = update_view.id.context("missing update view id")?;
5849 let mut tasks = Vec::new();
5850 this.update_in(cx, |this, window, cx| {
5851 let project = this.project.clone();
5852 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5853 let view_id = ViewId::from_proto(id.clone())?;
5854 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5855 tasks.push(item.view.apply_update_proto(
5856 &project,
5857 variant.clone(),
5858 window,
5859 cx,
5860 ));
5861 }
5862 }
5863 anyhow::Ok(())
5864 })??;
5865 try_join_all(tasks).await.log_err();
5866 }
5867 }
5868 this.update_in(cx, |this, window, cx| {
5869 this.leader_updated(leader_id, window, cx)
5870 })?;
5871 Ok(())
5872 }
5873
5874 async fn add_view_from_leader(
5875 this: WeakEntity<Self>,
5876 leader_id: PeerId,
5877 view: &proto::View,
5878 cx: &mut AsyncWindowContext,
5879 ) -> Result<()> {
5880 let this = this.upgrade().context("workspace dropped")?;
5881
5882 let Some(id) = view.id.clone() else {
5883 anyhow::bail!("no id for view");
5884 };
5885 let id = ViewId::from_proto(id)?;
5886 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5887
5888 let pane = this.update(cx, |this, _cx| {
5889 let state = this
5890 .follower_states
5891 .get(&leader_id.into())
5892 .context("stopped following")?;
5893 anyhow::Ok(state.pane().clone())
5894 })?;
5895 let existing_item = pane.update_in(cx, |pane, window, cx| {
5896 let client = this.read(cx).client().clone();
5897 pane.items().find_map(|item| {
5898 let item = item.to_followable_item_handle(cx)?;
5899 if item.remote_id(&client, window, cx) == Some(id) {
5900 Some(item)
5901 } else {
5902 None
5903 }
5904 })
5905 })?;
5906 let item = if let Some(existing_item) = existing_item {
5907 existing_item
5908 } else {
5909 let variant = view.variant.clone();
5910 anyhow::ensure!(variant.is_some(), "missing view variant");
5911
5912 let task = cx.update(|window, cx| {
5913 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5914 })?;
5915
5916 let Some(task) = task else {
5917 anyhow::bail!(
5918 "failed to construct view from leader (maybe from a different version of zed?)"
5919 );
5920 };
5921
5922 let mut new_item = task.await?;
5923 pane.update_in(cx, |pane, window, cx| {
5924 let mut item_to_remove = None;
5925 for (ix, item) in pane.items().enumerate() {
5926 if let Some(item) = item.to_followable_item_handle(cx) {
5927 match new_item.dedup(item.as_ref(), window, cx) {
5928 Some(item::Dedup::KeepExisting) => {
5929 new_item =
5930 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5931 break;
5932 }
5933 Some(item::Dedup::ReplaceExisting) => {
5934 item_to_remove = Some((ix, item.item_id()));
5935 break;
5936 }
5937 None => {}
5938 }
5939 }
5940 }
5941
5942 if let Some((ix, id)) = item_to_remove {
5943 pane.remove_item(id, false, false, window, cx);
5944 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5945 }
5946 })?;
5947
5948 new_item
5949 };
5950
5951 this.update_in(cx, |this, window, cx| {
5952 let state = this.follower_states.get_mut(&leader_id.into())?;
5953 item.set_leader_id(Some(leader_id.into()), window, cx);
5954 state.items_by_leader_view_id.insert(
5955 id,
5956 FollowerView {
5957 view: item,
5958 location: panel_id,
5959 },
5960 );
5961
5962 Some(())
5963 })
5964 .context("no follower state")?;
5965
5966 Ok(())
5967 }
5968
5969 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5970 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5971 return;
5972 };
5973
5974 if let Some(agent_location) = self.project.read(cx).agent_location() {
5975 let buffer_entity_id = agent_location.buffer.entity_id();
5976 let view_id = ViewId {
5977 creator: CollaboratorId::Agent,
5978 id: buffer_entity_id.as_u64(),
5979 };
5980 follower_state.active_view_id = Some(view_id);
5981
5982 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5983 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5984 hash_map::Entry::Vacant(entry) => {
5985 let existing_view =
5986 follower_state
5987 .center_pane
5988 .read(cx)
5989 .items()
5990 .find_map(|item| {
5991 let item = item.to_followable_item_handle(cx)?;
5992 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5993 && item.project_item_model_ids(cx).as_slice()
5994 == [buffer_entity_id]
5995 {
5996 Some(item)
5997 } else {
5998 None
5999 }
6000 });
6001 let view = existing_view.or_else(|| {
6002 agent_location.buffer.upgrade().and_then(|buffer| {
6003 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
6004 registry.build_item(buffer, self.project.clone(), None, window, cx)
6005 })?
6006 .to_followable_item_handle(cx)
6007 })
6008 });
6009
6010 view.map(|view| {
6011 entry.insert(FollowerView {
6012 view,
6013 location: None,
6014 })
6015 })
6016 }
6017 };
6018
6019 if let Some(item) = item {
6020 item.view
6021 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
6022 item.view
6023 .update_agent_location(agent_location.position, window, cx);
6024 }
6025 } else {
6026 follower_state.active_view_id = None;
6027 }
6028
6029 self.leader_updated(CollaboratorId::Agent, window, cx);
6030 }
6031
6032 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
6033 let mut is_project_item = true;
6034 let mut update = proto::UpdateActiveView::default();
6035 if window.is_window_active() {
6036 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
6037
6038 if let Some(item) = active_item
6039 && item.item_focus_handle(cx).contains_focused(window, cx)
6040 {
6041 let leader_id = self
6042 .pane_for(&*item)
6043 .and_then(|pane| self.leader_for_pane(&pane));
6044 let leader_peer_id = match leader_id {
6045 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
6046 Some(CollaboratorId::Agent) | None => None,
6047 };
6048
6049 if let Some(item) = item.to_followable_item_handle(cx) {
6050 let id = item
6051 .remote_id(&self.app_state.client, window, cx)
6052 .map(|id| id.to_proto());
6053
6054 if let Some(id) = id
6055 && let Some(variant) = item.to_state_proto(window, cx)
6056 {
6057 let view = Some(proto::View {
6058 id,
6059 leader_id: leader_peer_id,
6060 variant: Some(variant),
6061 panel_id: panel_id.map(|id| id as i32),
6062 });
6063
6064 is_project_item = item.is_project_item(window, cx);
6065 update = proto::UpdateActiveView { view };
6066 };
6067 }
6068 }
6069 }
6070
6071 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
6072 if active_view_id != self.last_active_view_id.as_ref() {
6073 self.last_active_view_id = active_view_id.cloned();
6074 self.update_followers(
6075 is_project_item,
6076 proto::update_followers::Variant::UpdateActiveView(update),
6077 window,
6078 cx,
6079 );
6080 }
6081 }
6082
6083 fn active_item_for_followers(
6084 &self,
6085 window: &mut Window,
6086 cx: &mut App,
6087 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
6088 let mut active_item = None;
6089 let mut panel_id = None;
6090 for dock in self.all_docks() {
6091 if dock.focus_handle(cx).contains_focused(window, cx)
6092 && let Some(panel) = dock.read(cx).active_panel()
6093 && let Some(pane) = panel.pane(cx)
6094 && let Some(item) = pane.read(cx).active_item()
6095 {
6096 active_item = Some(item);
6097 panel_id = panel.remote_id();
6098 break;
6099 }
6100 }
6101
6102 if active_item.is_none() {
6103 active_item = self.active_pane().read(cx).active_item();
6104 }
6105 (active_item, panel_id)
6106 }
6107
6108 fn update_followers(
6109 &self,
6110 project_only: bool,
6111 update: proto::update_followers::Variant,
6112 _: &mut Window,
6113 cx: &mut App,
6114 ) -> Option<()> {
6115 // If this update only applies to for followers in the current project,
6116 // then skip it unless this project is shared. If it applies to all
6117 // followers, regardless of project, then set `project_id` to none,
6118 // indicating that it goes to all followers.
6119 let project_id = if project_only {
6120 Some(self.project.read(cx).remote_id()?)
6121 } else {
6122 None
6123 };
6124 self.app_state().workspace_store.update(cx, |store, cx| {
6125 store.update_followers(project_id, update, cx)
6126 })
6127 }
6128
6129 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
6130 self.follower_states.iter().find_map(|(leader_id, state)| {
6131 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
6132 Some(*leader_id)
6133 } else {
6134 None
6135 }
6136 })
6137 }
6138
6139 fn leader_updated(
6140 &mut self,
6141 leader_id: impl Into<CollaboratorId>,
6142 window: &mut Window,
6143 cx: &mut Context<Self>,
6144 ) -> Option<Box<dyn ItemHandle>> {
6145 cx.notify();
6146
6147 let leader_id = leader_id.into();
6148 let (panel_id, item) = match leader_id {
6149 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
6150 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
6151 };
6152
6153 let state = self.follower_states.get(&leader_id)?;
6154 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
6155 let pane;
6156 if let Some(panel_id) = panel_id {
6157 pane = self
6158 .activate_panel_for_proto_id(panel_id, window, cx)?
6159 .pane(cx)?;
6160 let state = self.follower_states.get_mut(&leader_id)?;
6161 state.dock_pane = Some(pane.clone());
6162 } else {
6163 pane = state.center_pane.clone();
6164 let state = self.follower_states.get_mut(&leader_id)?;
6165 if let Some(dock_pane) = state.dock_pane.take() {
6166 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
6167 }
6168 }
6169
6170 pane.update(cx, |pane, cx| {
6171 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
6172 if let Some(index) = pane.index_for_item(item.as_ref()) {
6173 pane.activate_item(index, false, false, window, cx);
6174 } else {
6175 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
6176 }
6177
6178 if focus_active_item {
6179 pane.focus_active_item(window, cx)
6180 }
6181 });
6182
6183 Some(item)
6184 }
6185
6186 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
6187 let state = self.follower_states.get(&CollaboratorId::Agent)?;
6188 let active_view_id = state.active_view_id?;
6189 Some(
6190 state
6191 .items_by_leader_view_id
6192 .get(&active_view_id)?
6193 .view
6194 .boxed_clone(),
6195 )
6196 }
6197
6198 fn active_item_for_peer(
6199 &self,
6200 peer_id: PeerId,
6201 window: &mut Window,
6202 cx: &mut Context<Self>,
6203 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
6204 let call = self.active_call()?;
6205 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
6206 let leader_in_this_app;
6207 let leader_in_this_project;
6208 match participant.location {
6209 ParticipantLocation::SharedProject { project_id } => {
6210 leader_in_this_app = true;
6211 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
6212 }
6213 ParticipantLocation::UnsharedProject => {
6214 leader_in_this_app = true;
6215 leader_in_this_project = false;
6216 }
6217 ParticipantLocation::External => {
6218 leader_in_this_app = false;
6219 leader_in_this_project = false;
6220 }
6221 };
6222 let state = self.follower_states.get(&peer_id.into())?;
6223 let mut item_to_activate = None;
6224 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
6225 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
6226 && (leader_in_this_project || !item.view.is_project_item(window, cx))
6227 {
6228 item_to_activate = Some((item.location, item.view.boxed_clone()));
6229 }
6230 } else if let Some(shared_screen) =
6231 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
6232 {
6233 item_to_activate = Some((None, Box::new(shared_screen)));
6234 }
6235 item_to_activate
6236 }
6237
6238 fn shared_screen_for_peer(
6239 &self,
6240 peer_id: PeerId,
6241 pane: &Entity<Pane>,
6242 window: &mut Window,
6243 cx: &mut App,
6244 ) -> Option<Entity<SharedScreen>> {
6245 self.active_call()?
6246 .create_shared_screen(peer_id, pane, window, cx)
6247 }
6248
6249 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6250 if window.is_window_active() {
6251 self.update_active_view_for_followers(window, cx);
6252
6253 if let Some(database_id) = self.database_id {
6254 let db = WorkspaceDb::global(cx);
6255 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6256 .detach();
6257 }
6258 } else {
6259 for pane in &self.panes {
6260 pane.update(cx, |pane, cx| {
6261 if let Some(item) = pane.active_item() {
6262 item.workspace_deactivated(window, cx);
6263 }
6264 for item in pane.items() {
6265 if matches!(
6266 item.workspace_settings(cx).autosave,
6267 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6268 ) {
6269 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6270 .detach_and_log_err(cx);
6271 }
6272 }
6273 });
6274 }
6275 }
6276 }
6277
6278 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6279 self.active_call.as_ref().map(|(call, _)| &*call.0)
6280 }
6281
6282 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6283 self.active_call.as_ref().map(|(call, _)| call.clone())
6284 }
6285
6286 fn on_active_call_event(
6287 &mut self,
6288 event: &ActiveCallEvent,
6289 window: &mut Window,
6290 cx: &mut Context<Self>,
6291 ) {
6292 match event {
6293 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6294 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6295 self.leader_updated(participant_id, window, cx);
6296 }
6297 }
6298 }
6299
6300 pub fn database_id(&self) -> Option<WorkspaceId> {
6301 self.database_id
6302 }
6303
6304 #[cfg(any(test, feature = "test-support"))]
6305 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6306 self.database_id = Some(id);
6307 }
6308
6309 pub fn session_id(&self) -> Option<String> {
6310 self.session_id.clone()
6311 }
6312
6313 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6314 let Some(display) = window.display(cx) else {
6315 return Task::ready(());
6316 };
6317 let Ok(display_uuid) = display.uuid() else {
6318 return Task::ready(());
6319 };
6320
6321 let window_bounds = window.inner_window_bounds();
6322 let database_id = self.database_id;
6323 let has_paths = !self.root_paths(cx).is_empty();
6324 let db = WorkspaceDb::global(cx);
6325 let kvp = db::kvp::KeyValueStore::global(cx);
6326
6327 cx.background_executor().spawn(async move {
6328 if !has_paths {
6329 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6330 .await
6331 .log_err();
6332 }
6333 if let Some(database_id) = database_id {
6334 db.set_window_open_status(
6335 database_id,
6336 SerializedWindowBounds(window_bounds),
6337 display_uuid,
6338 )
6339 .await
6340 .log_err();
6341 } else {
6342 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6343 .await
6344 .log_err();
6345 }
6346 })
6347 }
6348
6349 /// Bypass the 200ms serialization throttle and write workspace state to
6350 /// the DB immediately. Returns a task the caller can await to ensure the
6351 /// write completes. Used by the quit handler so the most recent state
6352 /// isn't lost to a pending throttle timer when the process exits.
6353 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6354 self._schedule_serialize_workspace.take();
6355 self._serialize_workspace_task.take();
6356 self.bounds_save_task_queued.take();
6357
6358 let bounds_task = self.save_window_bounds(window, cx);
6359 let serialize_task = self.serialize_workspace_internal(window, cx);
6360 cx.spawn(async move |_| {
6361 bounds_task.await;
6362 serialize_task.await;
6363 })
6364 }
6365
6366 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6367 let project = self.project().read(cx);
6368 project
6369 .visible_worktrees(cx)
6370 .map(|worktree| worktree.read(cx).abs_path())
6371 .collect::<Vec<_>>()
6372 }
6373
6374 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6375 match member {
6376 Member::Axis(PaneAxis { members, .. }) => {
6377 for child in members.iter() {
6378 self.remove_panes(child.clone(), window, cx)
6379 }
6380 }
6381 Member::Pane(pane) => {
6382 self.force_remove_pane(&pane, &None, window, cx);
6383 }
6384 }
6385 }
6386
6387 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6388 self.session_id.take();
6389 self.serialize_workspace_internal(window, cx)
6390 }
6391
6392 fn force_remove_pane(
6393 &mut self,
6394 pane: &Entity<Pane>,
6395 focus_on: &Option<Entity<Pane>>,
6396 window: &mut Window,
6397 cx: &mut Context<Workspace>,
6398 ) {
6399 self.panes.retain(|p| p != pane);
6400 if let Some(focus_on) = focus_on {
6401 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6402 } else if self.active_pane() == pane {
6403 self.panes
6404 .last()
6405 .unwrap()
6406 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6407 }
6408 if self.last_active_center_pane == Some(pane.downgrade()) {
6409 self.last_active_center_pane = None;
6410 }
6411 cx.notify();
6412 }
6413
6414 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6415 if self._schedule_serialize_workspace.is_none() {
6416 self._schedule_serialize_workspace =
6417 Some(cx.spawn_in(window, async move |this, cx| {
6418 cx.background_executor()
6419 .timer(SERIALIZATION_THROTTLE_TIME)
6420 .await;
6421 this.update_in(cx, |this, window, cx| {
6422 this._serialize_workspace_task =
6423 Some(this.serialize_workspace_internal(window, cx));
6424 this._schedule_serialize_workspace.take();
6425 })
6426 .log_err();
6427 }));
6428 }
6429 }
6430
6431 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6432 let Some(database_id) = self.database_id() else {
6433 return Task::ready(());
6434 };
6435
6436 fn serialize_pane_handle(
6437 pane_handle: &Entity<Pane>,
6438 window: &mut Window,
6439 cx: &mut App,
6440 ) -> SerializedPane {
6441 let (items, active, pinned_count) = {
6442 let pane = pane_handle.read(cx);
6443 let active_item_id = pane.active_item().map(|item| item.item_id());
6444 (
6445 pane.items()
6446 .filter_map(|handle| {
6447 let handle = handle.to_serializable_item_handle(cx)?;
6448
6449 Some(SerializedItem {
6450 kind: Arc::from(handle.serialized_item_kind()),
6451 item_id: handle.item_id().as_u64(),
6452 active: Some(handle.item_id()) == active_item_id,
6453 preview: pane.is_active_preview_item(handle.item_id()),
6454 })
6455 })
6456 .collect::<Vec<_>>(),
6457 pane.has_focus(window, cx),
6458 pane.pinned_count(),
6459 )
6460 };
6461
6462 SerializedPane::new(items, active, pinned_count)
6463 }
6464
6465 fn build_serialized_pane_group(
6466 pane_group: &Member,
6467 window: &mut Window,
6468 cx: &mut App,
6469 ) -> SerializedPaneGroup {
6470 match pane_group {
6471 Member::Axis(PaneAxis {
6472 axis,
6473 members,
6474 flexes,
6475 bounding_boxes: _,
6476 }) => SerializedPaneGroup::Group {
6477 axis: SerializedAxis(*axis),
6478 children: members
6479 .iter()
6480 .map(|member| build_serialized_pane_group(member, window, cx))
6481 .collect::<Vec<_>>(),
6482 flexes: Some(flexes.lock().clone()),
6483 },
6484 Member::Pane(pane_handle) => {
6485 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6486 }
6487 }
6488 }
6489
6490 fn build_serialized_docks(
6491 this: &Workspace,
6492 window: &mut Window,
6493 cx: &mut App,
6494 ) -> DockStructure {
6495 this.capture_dock_state(window, cx)
6496 }
6497
6498 match self.workspace_location(cx) {
6499 WorkspaceLocation::Location(location, paths) => {
6500 let breakpoints = self.project.update(cx, |project, cx| {
6501 project
6502 .breakpoint_store()
6503 .read(cx)
6504 .all_source_breakpoints(cx)
6505 });
6506 let user_toolchains = self
6507 .project
6508 .read(cx)
6509 .user_toolchains(cx)
6510 .unwrap_or_default();
6511
6512 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6513 let docks = build_serialized_docks(self, window, cx);
6514 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6515
6516 let serialized_workspace = SerializedWorkspace {
6517 id: database_id,
6518 location,
6519 paths,
6520 center_group,
6521 window_bounds,
6522 display: Default::default(),
6523 docks,
6524 centered_layout: self.centered_layout,
6525 session_id: self.session_id.clone(),
6526 breakpoints,
6527 window_id: Some(window.window_handle().window_id().as_u64()),
6528 user_toolchains,
6529 };
6530
6531 let db = WorkspaceDb::global(cx);
6532 window.spawn(cx, async move |_| {
6533 db.save_workspace(serialized_workspace).await;
6534 })
6535 }
6536 WorkspaceLocation::DetachFromSession => {
6537 let window_bounds = SerializedWindowBounds(window.window_bounds());
6538 let display = window.display(cx).and_then(|d| d.uuid().ok());
6539 // Save dock state for empty local workspaces
6540 let docks = build_serialized_docks(self, window, cx);
6541 let db = WorkspaceDb::global(cx);
6542 let kvp = db::kvp::KeyValueStore::global(cx);
6543 window.spawn(cx, async move |_| {
6544 db.set_window_open_status(
6545 database_id,
6546 window_bounds,
6547 display.unwrap_or_default(),
6548 )
6549 .await
6550 .log_err();
6551 db.set_session_id(database_id, None).await.log_err();
6552 persistence::write_default_dock_state(&kvp, docks)
6553 .await
6554 .log_err();
6555 })
6556 }
6557 WorkspaceLocation::None => {
6558 // Save dock state for empty non-local workspaces
6559 let docks = build_serialized_docks(self, window, cx);
6560 let kvp = db::kvp::KeyValueStore::global(cx);
6561 window.spawn(cx, async move |_| {
6562 persistence::write_default_dock_state(&kvp, docks)
6563 .await
6564 .log_err();
6565 })
6566 }
6567 }
6568 }
6569
6570 fn has_any_items_open(&self, cx: &App) -> bool {
6571 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6572 }
6573
6574 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6575 let paths = PathList::new(&self.root_paths(cx));
6576 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6577 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6578 } else if self.project.read(cx).is_local() {
6579 if !paths.is_empty() || self.has_any_items_open(cx) {
6580 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6581 } else {
6582 WorkspaceLocation::DetachFromSession
6583 }
6584 } else {
6585 WorkspaceLocation::None
6586 }
6587 }
6588
6589 fn update_history(&self, cx: &mut App) {
6590 let Some(id) = self.database_id() else {
6591 return;
6592 };
6593 if !self.project.read(cx).is_local() {
6594 return;
6595 }
6596 if let Some(manager) = HistoryManager::global(cx) {
6597 let paths = PathList::new(&self.root_paths(cx));
6598 manager.update(cx, |this, cx| {
6599 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6600 });
6601 }
6602 }
6603
6604 async fn serialize_items(
6605 this: &WeakEntity<Self>,
6606 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6607 cx: &mut AsyncWindowContext,
6608 ) -> Result<()> {
6609 const CHUNK_SIZE: usize = 200;
6610
6611 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6612
6613 while let Some(items_received) = serializable_items.next().await {
6614 let unique_items =
6615 items_received
6616 .into_iter()
6617 .fold(HashMap::default(), |mut acc, item| {
6618 acc.entry(item.item_id()).or_insert(item);
6619 acc
6620 });
6621
6622 // We use into_iter() here so that the references to the items are moved into
6623 // the tasks and not kept alive while we're sleeping.
6624 for (_, item) in unique_items.into_iter() {
6625 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6626 item.serialize(workspace, false, window, cx)
6627 }) {
6628 cx.background_spawn(async move { task.await.log_err() })
6629 .detach();
6630 }
6631 }
6632
6633 cx.background_executor()
6634 .timer(SERIALIZATION_THROTTLE_TIME)
6635 .await;
6636 }
6637
6638 Ok(())
6639 }
6640
6641 pub(crate) fn enqueue_item_serialization(
6642 &mut self,
6643 item: Box<dyn SerializableItemHandle>,
6644 ) -> Result<()> {
6645 self.serializable_items_tx
6646 .unbounded_send(item)
6647 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6648 }
6649
6650 pub(crate) fn load_workspace(
6651 serialized_workspace: SerializedWorkspace,
6652 paths_to_open: Vec<Option<ProjectPath>>,
6653 window: &mut Window,
6654 cx: &mut Context<Workspace>,
6655 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6656 cx.spawn_in(window, async move |workspace, cx| {
6657 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6658
6659 let mut center_group = None;
6660 let mut center_items = None;
6661
6662 // Traverse the splits tree and add to things
6663 if let Some((group, active_pane, items)) = serialized_workspace
6664 .center_group
6665 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6666 .await
6667 {
6668 center_items = Some(items);
6669 center_group = Some((group, active_pane))
6670 }
6671
6672 let mut items_by_project_path = HashMap::default();
6673 let mut item_ids_by_kind = HashMap::default();
6674 let mut all_deserialized_items = Vec::default();
6675 cx.update(|_, cx| {
6676 for item in center_items.unwrap_or_default().into_iter().flatten() {
6677 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6678 item_ids_by_kind
6679 .entry(serializable_item_handle.serialized_item_kind())
6680 .or_insert(Vec::new())
6681 .push(item.item_id().as_u64() as ItemId);
6682 }
6683
6684 if let Some(project_path) = item.project_path(cx) {
6685 items_by_project_path.insert(project_path, item.clone());
6686 }
6687 all_deserialized_items.push(item);
6688 }
6689 })?;
6690
6691 let opened_items = paths_to_open
6692 .into_iter()
6693 .map(|path_to_open| {
6694 path_to_open
6695 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6696 })
6697 .collect::<Vec<_>>();
6698
6699 // Remove old panes from workspace panes list
6700 workspace.update_in(cx, |workspace, window, cx| {
6701 if let Some((center_group, active_pane)) = center_group {
6702 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6703
6704 // Swap workspace center group
6705 workspace.center = PaneGroup::with_root(center_group);
6706 workspace.center.set_is_center(true);
6707 workspace.center.mark_positions(cx);
6708
6709 if let Some(active_pane) = active_pane {
6710 workspace.set_active_pane(&active_pane, window, cx);
6711 cx.focus_self(window);
6712 } else {
6713 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6714 }
6715 }
6716
6717 let docks = serialized_workspace.docks;
6718
6719 for (dock, serialized_dock) in [
6720 (&mut workspace.right_dock, docks.right),
6721 (&mut workspace.left_dock, docks.left),
6722 (&mut workspace.bottom_dock, docks.bottom),
6723 ]
6724 .iter_mut()
6725 {
6726 dock.update(cx, |dock, cx| {
6727 dock.serialized_dock = Some(serialized_dock.clone());
6728 dock.restore_state(window, cx);
6729 });
6730 }
6731
6732 cx.notify();
6733 })?;
6734
6735 let _ = project
6736 .update(cx, |project, cx| {
6737 project
6738 .breakpoint_store()
6739 .update(cx, |breakpoint_store, cx| {
6740 breakpoint_store
6741 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6742 })
6743 })
6744 .await;
6745
6746 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6747 // after loading the items, we might have different items and in order to avoid
6748 // the database filling up, we delete items that haven't been loaded now.
6749 //
6750 // The items that have been loaded, have been saved after they've been added to the workspace.
6751 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6752 item_ids_by_kind
6753 .into_iter()
6754 .map(|(item_kind, loaded_items)| {
6755 SerializableItemRegistry::cleanup(
6756 item_kind,
6757 serialized_workspace.id,
6758 loaded_items,
6759 window,
6760 cx,
6761 )
6762 .log_err()
6763 })
6764 .collect::<Vec<_>>()
6765 })?;
6766
6767 futures::future::join_all(clean_up_tasks).await;
6768
6769 workspace
6770 .update_in(cx, |workspace, window, cx| {
6771 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6772 workspace.serialize_workspace_internal(window, cx).detach();
6773
6774 // Ensure that we mark the window as edited if we did load dirty items
6775 workspace.update_window_edited(window, cx);
6776 })
6777 .ok();
6778
6779 Ok(opened_items)
6780 })
6781 }
6782
6783 pub fn key_context(&self, cx: &App) -> KeyContext {
6784 let mut context = KeyContext::new_with_defaults();
6785 context.add("Workspace");
6786 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6787 if let Some(status) = self
6788 .debugger_provider
6789 .as_ref()
6790 .and_then(|provider| provider.active_thread_state(cx))
6791 {
6792 match status {
6793 ThreadStatus::Running | ThreadStatus::Stepping => {
6794 context.add("debugger_running");
6795 }
6796 ThreadStatus::Stopped => context.add("debugger_stopped"),
6797 ThreadStatus::Exited | ThreadStatus::Ended => {}
6798 }
6799 }
6800
6801 if self.left_dock.read(cx).is_open() {
6802 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6803 context.set("left_dock", active_panel.panel_key());
6804 }
6805 }
6806
6807 if self.right_dock.read(cx).is_open() {
6808 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6809 context.set("right_dock", active_panel.panel_key());
6810 }
6811 }
6812
6813 if self.bottom_dock.read(cx).is_open() {
6814 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6815 context.set("bottom_dock", active_panel.panel_key());
6816 }
6817 }
6818
6819 context
6820 }
6821
6822 /// Multiworkspace uses this to add workspace action handling to itself
6823 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6824 self.add_workspace_actions_listeners(div, window, cx)
6825 .on_action(cx.listener(
6826 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6827 for action in &action_sequence.0 {
6828 window.dispatch_action(action.boxed_clone(), cx);
6829 }
6830 },
6831 ))
6832 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6833 .on_action(cx.listener(Self::close_all_items_and_panes))
6834 .on_action(cx.listener(Self::close_item_in_all_panes))
6835 .on_action(cx.listener(Self::save_all))
6836 .on_action(cx.listener(Self::send_keystrokes))
6837 .on_action(cx.listener(Self::add_folder_to_project))
6838 .on_action(cx.listener(Self::follow_next_collaborator))
6839 .on_action(cx.listener(Self::activate_pane_at_index))
6840 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6841 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6842 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6843 .on_action(cx.listener(Self::toggle_theme_mode))
6844 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6845 let pane = workspace.active_pane().clone();
6846 workspace.unfollow_in_pane(&pane, window, cx);
6847 }))
6848 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6849 workspace
6850 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6851 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6852 }))
6853 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6854 workspace
6855 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6856 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6857 }))
6858 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6859 workspace
6860 .save_active_item(SaveIntent::SaveAs, window, cx)
6861 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6862 }))
6863 .on_action(
6864 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6865 workspace.activate_previous_pane(window, cx)
6866 }),
6867 )
6868 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6869 workspace.activate_next_pane(window, cx)
6870 }))
6871 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6872 workspace.activate_last_pane(window, cx)
6873 }))
6874 .on_action(
6875 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6876 workspace.activate_next_window(cx)
6877 }),
6878 )
6879 .on_action(
6880 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6881 workspace.activate_previous_window(cx)
6882 }),
6883 )
6884 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6885 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6886 }))
6887 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6888 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6889 }))
6890 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6891 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6892 }))
6893 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6894 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6895 }))
6896 .on_action(cx.listener(
6897 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6898 workspace.move_item_to_pane_in_direction(action, window, cx)
6899 },
6900 ))
6901 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6902 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6903 }))
6904 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6905 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6906 }))
6907 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6908 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6909 }))
6910 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6911 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6912 }))
6913 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6914 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6915 SplitDirection::Down,
6916 SplitDirection::Up,
6917 SplitDirection::Right,
6918 SplitDirection::Left,
6919 ];
6920 for dir in DIRECTION_PRIORITY {
6921 if workspace.find_pane_in_direction(dir, cx).is_some() {
6922 workspace.swap_pane_in_direction(dir, cx);
6923 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6924 break;
6925 }
6926 }
6927 }))
6928 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6929 workspace.move_pane_to_border(SplitDirection::Left, cx)
6930 }))
6931 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6932 workspace.move_pane_to_border(SplitDirection::Right, cx)
6933 }))
6934 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6935 workspace.move_pane_to_border(SplitDirection::Up, cx)
6936 }))
6937 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6938 workspace.move_pane_to_border(SplitDirection::Down, cx)
6939 }))
6940 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6941 this.toggle_dock(DockPosition::Left, window, cx);
6942 }))
6943 .on_action(cx.listener(
6944 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6945 workspace.toggle_dock(DockPosition::Right, window, cx);
6946 },
6947 ))
6948 .on_action(cx.listener(
6949 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6950 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6951 },
6952 ))
6953 .on_action(cx.listener(
6954 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6955 if !workspace.close_active_dock(window, cx) {
6956 cx.propagate();
6957 }
6958 },
6959 ))
6960 .on_action(
6961 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6962 workspace.close_all_docks(window, cx);
6963 }),
6964 )
6965 .on_action(cx.listener(Self::toggle_all_docks))
6966 .on_action(cx.listener(
6967 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6968 workspace.clear_all_notifications(cx);
6969 },
6970 ))
6971 .on_action(cx.listener(
6972 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6973 workspace.clear_navigation_history(window, cx);
6974 },
6975 ))
6976 .on_action(cx.listener(
6977 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6978 if let Some((notification_id, _)) = workspace.notifications.pop() {
6979 workspace.suppress_notification(¬ification_id, cx);
6980 }
6981 },
6982 ))
6983 .on_action(cx.listener(
6984 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6985 workspace.show_worktree_trust_security_modal(true, window, cx);
6986 },
6987 ))
6988 .on_action(
6989 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6990 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6991 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6992 trusted_worktrees.clear_trusted_paths()
6993 });
6994 let db = WorkspaceDb::global(cx);
6995 cx.spawn(async move |_, cx| {
6996 if db.clear_trusted_worktrees().await.log_err().is_some() {
6997 cx.update(|cx| reload(cx));
6998 }
6999 })
7000 .detach();
7001 }
7002 }),
7003 )
7004 .on_action(cx.listener(
7005 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
7006 workspace.reopen_closed_item(window, cx).detach();
7007 },
7008 ))
7009 .on_action(cx.listener(
7010 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
7011 for dock in workspace.all_docks() {
7012 if dock.focus_handle(cx).contains_focused(window, cx) {
7013 let panel = dock.read(cx).active_panel().cloned();
7014 if let Some(panel) = panel {
7015 dock.update(cx, |dock, cx| {
7016 dock.set_panel_size_state(
7017 panel.as_ref(),
7018 dock::PanelSizeState::default(),
7019 cx,
7020 );
7021 });
7022 }
7023 return;
7024 }
7025 }
7026 },
7027 ))
7028 .on_action(cx.listener(
7029 |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
7030 for dock in workspace.all_docks() {
7031 let panel = dock.read(cx).visible_panel().cloned();
7032 if let Some(panel) = panel {
7033 dock.update(cx, |dock, cx| {
7034 dock.set_panel_size_state(
7035 panel.as_ref(),
7036 dock::PanelSizeState::default(),
7037 cx,
7038 );
7039 });
7040 }
7041 }
7042 },
7043 ))
7044 .on_action(cx.listener(
7045 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
7046 adjust_active_dock_size_by_px(
7047 px_with_ui_font_fallback(act.px, cx),
7048 workspace,
7049 window,
7050 cx,
7051 );
7052 },
7053 ))
7054 .on_action(cx.listener(
7055 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
7056 adjust_active_dock_size_by_px(
7057 px_with_ui_font_fallback(act.px, cx) * -1.,
7058 workspace,
7059 window,
7060 cx,
7061 );
7062 },
7063 ))
7064 .on_action(cx.listener(
7065 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
7066 adjust_open_docks_size_by_px(
7067 px_with_ui_font_fallback(act.px, cx),
7068 workspace,
7069 window,
7070 cx,
7071 );
7072 },
7073 ))
7074 .on_action(cx.listener(
7075 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
7076 adjust_open_docks_size_by_px(
7077 px_with_ui_font_fallback(act.px, cx) * -1.,
7078 workspace,
7079 window,
7080 cx,
7081 );
7082 },
7083 ))
7084 .on_action(cx.listener(Workspace::toggle_centered_layout))
7085 .on_action(cx.listener(
7086 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
7087 if let Some(active_dock) = workspace.active_dock(window, cx) {
7088 let dock = active_dock.read(cx);
7089 if let Some(active_panel) = dock.active_panel() {
7090 if active_panel.pane(cx).is_none() {
7091 let mut recent_pane: Option<Entity<Pane>> = None;
7092 let mut recent_timestamp = 0;
7093 for pane_handle in workspace.panes() {
7094 let pane = pane_handle.read(cx);
7095 for entry in pane.activation_history() {
7096 if entry.timestamp > recent_timestamp {
7097 recent_timestamp = entry.timestamp;
7098 recent_pane = Some(pane_handle.clone());
7099 }
7100 }
7101 }
7102
7103 if let Some(pane) = recent_pane {
7104 pane.update(cx, |pane, cx| {
7105 let current_index = pane.active_item_index();
7106 let items_len = pane.items_len();
7107 if items_len > 0 {
7108 let next_index = if current_index + 1 < items_len {
7109 current_index + 1
7110 } else {
7111 0
7112 };
7113 pane.activate_item(
7114 next_index, false, false, window, cx,
7115 );
7116 }
7117 });
7118 return;
7119 }
7120 }
7121 }
7122 }
7123 cx.propagate();
7124 },
7125 ))
7126 .on_action(cx.listener(
7127 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
7128 if let Some(active_dock) = workspace.active_dock(window, cx) {
7129 let dock = active_dock.read(cx);
7130 if let Some(active_panel) = dock.active_panel() {
7131 if active_panel.pane(cx).is_none() {
7132 let mut recent_pane: Option<Entity<Pane>> = None;
7133 let mut recent_timestamp = 0;
7134 for pane_handle in workspace.panes() {
7135 let pane = pane_handle.read(cx);
7136 for entry in pane.activation_history() {
7137 if entry.timestamp > recent_timestamp {
7138 recent_timestamp = entry.timestamp;
7139 recent_pane = Some(pane_handle.clone());
7140 }
7141 }
7142 }
7143
7144 if let Some(pane) = recent_pane {
7145 pane.update(cx, |pane, cx| {
7146 let current_index = pane.active_item_index();
7147 let items_len = pane.items_len();
7148 if items_len > 0 {
7149 let prev_index = if current_index > 0 {
7150 current_index - 1
7151 } else {
7152 items_len.saturating_sub(1)
7153 };
7154 pane.activate_item(
7155 prev_index, false, false, window, cx,
7156 );
7157 }
7158 });
7159 return;
7160 }
7161 }
7162 }
7163 }
7164 cx.propagate();
7165 },
7166 ))
7167 .on_action(cx.listener(
7168 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
7169 if let Some(active_dock) = workspace.active_dock(window, cx) {
7170 let dock = active_dock.read(cx);
7171 if let Some(active_panel) = dock.active_panel() {
7172 if active_panel.pane(cx).is_none() {
7173 let active_pane = workspace.active_pane().clone();
7174 active_pane.update(cx, |pane, cx| {
7175 pane.close_active_item(action, window, cx)
7176 .detach_and_log_err(cx);
7177 });
7178 return;
7179 }
7180 }
7181 }
7182 cx.propagate();
7183 },
7184 ))
7185 .on_action(
7186 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
7187 let pane = workspace.active_pane().clone();
7188 if let Some(item) = pane.read(cx).active_item() {
7189 item.toggle_read_only(window, cx);
7190 }
7191 }),
7192 )
7193 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
7194 workspace.focus_center_pane(window, cx);
7195 }))
7196 .on_action(cx.listener(Workspace::cancel))
7197 }
7198
7199 #[cfg(any(test, feature = "test-support"))]
7200 pub fn set_random_database_id(&mut self) {
7201 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
7202 }
7203
7204 #[cfg(any(test, feature = "test-support"))]
7205 pub(crate) fn test_new(
7206 project: Entity<Project>,
7207 window: &mut Window,
7208 cx: &mut Context<Self>,
7209 ) -> Self {
7210 use node_runtime::NodeRuntime;
7211 use session::Session;
7212
7213 let client = project.read(cx).client();
7214 let user_store = project.read(cx).user_store();
7215 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
7216 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
7217 window.activate_window();
7218 let app_state = Arc::new(AppState {
7219 languages: project.read(cx).languages().clone(),
7220 workspace_store,
7221 client,
7222 user_store,
7223 fs: project.read(cx).fs().clone(),
7224 build_window_options: |_, _| Default::default(),
7225 node_runtime: NodeRuntime::unavailable(),
7226 session,
7227 });
7228 let workspace = Self::new(Default::default(), project, app_state, window, cx);
7229 workspace
7230 .active_pane
7231 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
7232 workspace
7233 }
7234
7235 pub fn register_action<A: Action>(
7236 &mut self,
7237 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
7238 ) -> &mut Self {
7239 let callback = Arc::new(callback);
7240
7241 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
7242 let callback = callback.clone();
7243 div.on_action(cx.listener(move |workspace, event, window, cx| {
7244 (callback)(workspace, event, window, cx)
7245 }))
7246 }));
7247 self
7248 }
7249 pub fn register_action_renderer(
7250 &mut self,
7251 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
7252 ) -> &mut Self {
7253 self.workspace_actions.push(Box::new(callback));
7254 self
7255 }
7256
7257 fn add_workspace_actions_listeners(
7258 &self,
7259 mut div: Div,
7260 window: &mut Window,
7261 cx: &mut Context<Self>,
7262 ) -> Div {
7263 for action in self.workspace_actions.iter() {
7264 div = (action)(div, self, window, cx)
7265 }
7266 div
7267 }
7268
7269 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7270 self.modal_layer.read(cx).has_active_modal()
7271 }
7272
7273 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7274 self.modal_layer
7275 .read(cx)
7276 .is_active_modal_command_palette(cx)
7277 }
7278
7279 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7280 self.modal_layer.read(cx).active_modal()
7281 }
7282
7283 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7284 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7285 /// If no modal is active, the new modal will be shown.
7286 ///
7287 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7288 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7289 /// will not be shown.
7290 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7291 where
7292 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7293 {
7294 self.modal_layer.update(cx, |modal_layer, cx| {
7295 modal_layer.toggle_modal(window, cx, build)
7296 })
7297 }
7298
7299 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7300 self.modal_layer
7301 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7302 }
7303
7304 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7305 self.toast_layer
7306 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7307 }
7308
7309 pub fn toggle_centered_layout(
7310 &mut self,
7311 _: &ToggleCenteredLayout,
7312 _: &mut Window,
7313 cx: &mut Context<Self>,
7314 ) {
7315 self.centered_layout = !self.centered_layout;
7316 if let Some(database_id) = self.database_id() {
7317 let db = WorkspaceDb::global(cx);
7318 let centered_layout = self.centered_layout;
7319 cx.background_spawn(async move {
7320 db.set_centered_layout(database_id, centered_layout).await
7321 })
7322 .detach_and_log_err(cx);
7323 }
7324 cx.notify();
7325 }
7326
7327 fn adjust_padding(padding: Option<f32>) -> f32 {
7328 padding
7329 .unwrap_or(CenteredPaddingSettings::default().0)
7330 .clamp(
7331 CenteredPaddingSettings::MIN_PADDING,
7332 CenteredPaddingSettings::MAX_PADDING,
7333 )
7334 }
7335
7336 fn render_dock(
7337 &self,
7338 position: DockPosition,
7339 dock: &Entity<Dock>,
7340 window: &mut Window,
7341 cx: &mut App,
7342 ) -> Option<Div> {
7343 if self.zoomed_position == Some(position) {
7344 return None;
7345 }
7346
7347 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7348 let pane = panel.pane(cx)?;
7349 let follower_states = &self.follower_states;
7350 leader_border_for_pane(follower_states, &pane, window, cx)
7351 });
7352
7353 let mut container = div()
7354 .flex()
7355 .overflow_hidden()
7356 .flex_none()
7357 .child(dock.clone())
7358 .children(leader_border);
7359
7360 // Apply sizing only when the dock is open. When closed the dock is still
7361 // included in the element tree so its focus handle remains mounted — without
7362 // this, toggle_panel_focus cannot focus the panel when the dock is closed.
7363 let dock = dock.read(cx);
7364 if let Some(panel) = dock.visible_panel() {
7365 let size_state = dock.stored_panel_size_state(panel.as_ref());
7366 if position.axis() == Axis::Horizontal {
7367 let use_flexible = panel.has_flexible_size(window, cx);
7368 let flex_grow = if use_flexible {
7369 size_state
7370 .and_then(|state| state.flex)
7371 .or_else(|| self.default_dock_flex(position))
7372 } else {
7373 None
7374 };
7375 if let Some(grow) = flex_grow {
7376 let grow = grow.max(0.001);
7377 let style = container.style();
7378 style.flex_grow = Some(grow);
7379 style.flex_shrink = Some(1.0);
7380 style.flex_basis = Some(relative(0.).into());
7381 } else {
7382 let size = size_state
7383 .and_then(|state| state.size)
7384 .unwrap_or_else(|| panel.default_size(window, cx));
7385 container = container.w(size);
7386 }
7387 } else {
7388 let size = size_state
7389 .and_then(|state| state.size)
7390 .unwrap_or_else(|| panel.default_size(window, cx));
7391 container = container.h(size);
7392 }
7393 }
7394
7395 Some(container)
7396 }
7397
7398 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7399 window
7400 .root::<MultiWorkspace>()
7401 .flatten()
7402 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7403 }
7404
7405 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7406 self.zoomed.as_ref()
7407 }
7408
7409 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7410 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7411 return;
7412 };
7413 let windows = cx.windows();
7414 let next_window =
7415 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7416 || {
7417 windows
7418 .iter()
7419 .cycle()
7420 .skip_while(|window| window.window_id() != current_window_id)
7421 .nth(1)
7422 },
7423 );
7424
7425 if let Some(window) = next_window {
7426 window
7427 .update(cx, |_, window, _| window.activate_window())
7428 .ok();
7429 }
7430 }
7431
7432 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7433 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7434 return;
7435 };
7436 let windows = cx.windows();
7437 let prev_window =
7438 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7439 || {
7440 windows
7441 .iter()
7442 .rev()
7443 .cycle()
7444 .skip_while(|window| window.window_id() != current_window_id)
7445 .nth(1)
7446 },
7447 );
7448
7449 if let Some(window) = prev_window {
7450 window
7451 .update(cx, |_, window, _| window.activate_window())
7452 .ok();
7453 }
7454 }
7455
7456 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7457 if cx.stop_active_drag(window) {
7458 } else if let Some((notification_id, _)) = self.notifications.pop() {
7459 dismiss_app_notification(¬ification_id, cx);
7460 } else {
7461 cx.propagate();
7462 }
7463 }
7464
7465 fn resize_dock(
7466 &mut self,
7467 dock_pos: DockPosition,
7468 new_size: Pixels,
7469 window: &mut Window,
7470 cx: &mut Context<Self>,
7471 ) {
7472 match dock_pos {
7473 DockPosition::Left => self.resize_left_dock(new_size, window, cx),
7474 DockPosition::Right => self.resize_right_dock(new_size, window, cx),
7475 DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
7476 }
7477 }
7478
7479 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7480 let workspace_width = self.bounds.size.width;
7481 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7482
7483 self.right_dock.read_with(cx, |right_dock, cx| {
7484 let right_dock_size = right_dock
7485 .stored_active_panel_size(window, cx)
7486 .unwrap_or(Pixels::ZERO);
7487 if right_dock_size + size > workspace_width {
7488 size = workspace_width - right_dock_size
7489 }
7490 });
7491
7492 let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
7493 self.left_dock.update(cx, |left_dock, cx| {
7494 if WorkspaceSettings::get_global(cx)
7495 .resize_all_panels_in_dock
7496 .contains(&DockPosition::Left)
7497 {
7498 left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7499 } else {
7500 left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7501 }
7502 });
7503 }
7504
7505 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7506 let workspace_width = self.bounds.size.width;
7507 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7508 self.left_dock.read_with(cx, |left_dock, cx| {
7509 let left_dock_size = left_dock
7510 .stored_active_panel_size(window, cx)
7511 .unwrap_or(Pixels::ZERO);
7512 if left_dock_size + size > workspace_width {
7513 size = workspace_width - left_dock_size
7514 }
7515 });
7516 let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
7517 self.right_dock.update(cx, |right_dock, cx| {
7518 if WorkspaceSettings::get_global(cx)
7519 .resize_all_panels_in_dock
7520 .contains(&DockPosition::Right)
7521 {
7522 right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7523 } else {
7524 right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7525 }
7526 });
7527 }
7528
7529 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7530 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7531 self.bottom_dock.update(cx, |bottom_dock, cx| {
7532 if WorkspaceSettings::get_global(cx)
7533 .resize_all_panels_in_dock
7534 .contains(&DockPosition::Bottom)
7535 {
7536 bottom_dock.resize_all_panels(Some(size), None, window, cx);
7537 } else {
7538 bottom_dock.resize_active_panel(Some(size), None, window, cx);
7539 }
7540 });
7541 }
7542
7543 fn toggle_edit_predictions_all_files(
7544 &mut self,
7545 _: &ToggleEditPrediction,
7546 _window: &mut Window,
7547 cx: &mut Context<Self>,
7548 ) {
7549 let fs = self.project().read(cx).fs().clone();
7550 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7551 update_settings_file(fs, cx, move |file, _| {
7552 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7553 });
7554 }
7555
7556 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7557 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7558 let next_mode = match current_mode {
7559 Some(theme_settings::ThemeAppearanceMode::Light) => {
7560 theme_settings::ThemeAppearanceMode::Dark
7561 }
7562 Some(theme_settings::ThemeAppearanceMode::Dark) => {
7563 theme_settings::ThemeAppearanceMode::Light
7564 }
7565 Some(theme_settings::ThemeAppearanceMode::System) | None => {
7566 match cx.theme().appearance() {
7567 theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
7568 theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
7569 }
7570 }
7571 };
7572
7573 let fs = self.project().read(cx).fs().clone();
7574 settings::update_settings_file(fs, cx, move |settings, _cx| {
7575 theme_settings::set_mode(settings, next_mode);
7576 });
7577 }
7578
7579 pub fn show_worktree_trust_security_modal(
7580 &mut self,
7581 toggle: bool,
7582 window: &mut Window,
7583 cx: &mut Context<Self>,
7584 ) {
7585 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7586 if toggle {
7587 security_modal.update(cx, |security_modal, cx| {
7588 security_modal.dismiss(cx);
7589 })
7590 } else {
7591 security_modal.update(cx, |security_modal, cx| {
7592 security_modal.refresh_restricted_paths(cx);
7593 });
7594 }
7595 } else {
7596 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7597 .map(|trusted_worktrees| {
7598 trusted_worktrees
7599 .read(cx)
7600 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7601 })
7602 .unwrap_or(false);
7603 if has_restricted_worktrees {
7604 let project = self.project().read(cx);
7605 let remote_host = project
7606 .remote_connection_options(cx)
7607 .map(RemoteHostLocation::from);
7608 let worktree_store = project.worktree_store().downgrade();
7609 self.toggle_modal(window, cx, |_, cx| {
7610 SecurityModal::new(worktree_store, remote_host, cx)
7611 });
7612 }
7613 }
7614 }
7615}
7616
7617pub trait AnyActiveCall {
7618 fn entity(&self) -> AnyEntity;
7619 fn is_in_room(&self, _: &App) -> bool;
7620 fn room_id(&self, _: &App) -> Option<u64>;
7621 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7622 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7623 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7624 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7625 fn is_sharing_project(&self, _: &App) -> bool;
7626 fn has_remote_participants(&self, _: &App) -> bool;
7627 fn local_participant_is_guest(&self, _: &App) -> bool;
7628 fn client(&self, _: &App) -> Arc<Client>;
7629 fn share_on_join(&self, _: &App) -> bool;
7630 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7631 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7632 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7633 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7634 fn join_project(
7635 &self,
7636 _: u64,
7637 _: Arc<LanguageRegistry>,
7638 _: Arc<dyn Fs>,
7639 _: &mut App,
7640 ) -> Task<Result<Entity<Project>>>;
7641 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7642 fn subscribe(
7643 &self,
7644 _: &mut Window,
7645 _: &mut Context<Workspace>,
7646 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7647 ) -> Subscription;
7648 fn create_shared_screen(
7649 &self,
7650 _: PeerId,
7651 _: &Entity<Pane>,
7652 _: &mut Window,
7653 _: &mut App,
7654 ) -> Option<Entity<SharedScreen>>;
7655}
7656
7657#[derive(Clone)]
7658pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7659impl Global for GlobalAnyActiveCall {}
7660
7661impl GlobalAnyActiveCall {
7662 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7663 cx.try_global()
7664 }
7665
7666 pub(crate) fn global(cx: &App) -> &Self {
7667 cx.global()
7668 }
7669}
7670
7671pub fn merge_conflict_notification_id() -> NotificationId {
7672 struct MergeConflictNotification;
7673 NotificationId::unique::<MergeConflictNotification>()
7674}
7675
7676/// Workspace-local view of a remote participant's location.
7677#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7678pub enum ParticipantLocation {
7679 SharedProject { project_id: u64 },
7680 UnsharedProject,
7681 External,
7682}
7683
7684impl ParticipantLocation {
7685 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7686 match location
7687 .and_then(|l| l.variant)
7688 .context("participant location was not provided")?
7689 {
7690 proto::participant_location::Variant::SharedProject(project) => {
7691 Ok(Self::SharedProject {
7692 project_id: project.id,
7693 })
7694 }
7695 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7696 proto::participant_location::Variant::External(_) => Ok(Self::External),
7697 }
7698 }
7699}
7700/// Workspace-local view of a remote collaborator's state.
7701/// This is the subset of `call::RemoteParticipant` that workspace needs.
7702#[derive(Clone)]
7703pub struct RemoteCollaborator {
7704 pub user: Arc<User>,
7705 pub peer_id: PeerId,
7706 pub location: ParticipantLocation,
7707 pub participant_index: ParticipantIndex,
7708}
7709
7710pub enum ActiveCallEvent {
7711 ParticipantLocationChanged { participant_id: PeerId },
7712 RemoteVideoTracksChanged { participant_id: PeerId },
7713}
7714
7715fn leader_border_for_pane(
7716 follower_states: &HashMap<CollaboratorId, FollowerState>,
7717 pane: &Entity<Pane>,
7718 _: &Window,
7719 cx: &App,
7720) -> Option<Div> {
7721 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7722 if state.pane() == pane {
7723 Some((*leader_id, state))
7724 } else {
7725 None
7726 }
7727 })?;
7728
7729 let mut leader_color = match leader_id {
7730 CollaboratorId::PeerId(leader_peer_id) => {
7731 let leader = GlobalAnyActiveCall::try_global(cx)?
7732 .0
7733 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7734
7735 cx.theme()
7736 .players()
7737 .color_for_participant(leader.participant_index.0)
7738 .cursor
7739 }
7740 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7741 };
7742 leader_color.fade_out(0.3);
7743 Some(
7744 div()
7745 .absolute()
7746 .size_full()
7747 .left_0()
7748 .top_0()
7749 .border_2()
7750 .border_color(leader_color),
7751 )
7752}
7753
7754fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7755 ZED_WINDOW_POSITION
7756 .zip(*ZED_WINDOW_SIZE)
7757 .map(|(position, size)| Bounds {
7758 origin: position,
7759 size,
7760 })
7761}
7762
7763fn open_items(
7764 serialized_workspace: Option<SerializedWorkspace>,
7765 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7766 window: &mut Window,
7767 cx: &mut Context<Workspace>,
7768) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7769 let restored_items = serialized_workspace.map(|serialized_workspace| {
7770 Workspace::load_workspace(
7771 serialized_workspace,
7772 project_paths_to_open
7773 .iter()
7774 .map(|(_, project_path)| project_path)
7775 .cloned()
7776 .collect(),
7777 window,
7778 cx,
7779 )
7780 });
7781
7782 cx.spawn_in(window, async move |workspace, cx| {
7783 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7784
7785 if let Some(restored_items) = restored_items {
7786 let restored_items = restored_items.await?;
7787
7788 let restored_project_paths = restored_items
7789 .iter()
7790 .filter_map(|item| {
7791 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7792 .ok()
7793 .flatten()
7794 })
7795 .collect::<HashSet<_>>();
7796
7797 for restored_item in restored_items {
7798 opened_items.push(restored_item.map(Ok));
7799 }
7800
7801 project_paths_to_open
7802 .iter_mut()
7803 .for_each(|(_, project_path)| {
7804 if let Some(project_path_to_open) = project_path
7805 && restored_project_paths.contains(project_path_to_open)
7806 {
7807 *project_path = None;
7808 }
7809 });
7810 } else {
7811 for _ in 0..project_paths_to_open.len() {
7812 opened_items.push(None);
7813 }
7814 }
7815 assert!(opened_items.len() == project_paths_to_open.len());
7816
7817 let tasks =
7818 project_paths_to_open
7819 .into_iter()
7820 .enumerate()
7821 .map(|(ix, (abs_path, project_path))| {
7822 let workspace = workspace.clone();
7823 cx.spawn(async move |cx| {
7824 let file_project_path = project_path?;
7825 let abs_path_task = workspace.update(cx, |workspace, cx| {
7826 workspace.project().update(cx, |project, cx| {
7827 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7828 })
7829 });
7830
7831 // We only want to open file paths here. If one of the items
7832 // here is a directory, it was already opened further above
7833 // with a `find_or_create_worktree`.
7834 if let Ok(task) = abs_path_task
7835 && task.await.is_none_or(|p| p.is_file())
7836 {
7837 return Some((
7838 ix,
7839 workspace
7840 .update_in(cx, |workspace, window, cx| {
7841 workspace.open_path(
7842 file_project_path,
7843 None,
7844 true,
7845 window,
7846 cx,
7847 )
7848 })
7849 .log_err()?
7850 .await,
7851 ));
7852 }
7853 None
7854 })
7855 });
7856
7857 let tasks = tasks.collect::<Vec<_>>();
7858
7859 let tasks = futures::future::join_all(tasks);
7860 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7861 opened_items[ix] = Some(path_open_result);
7862 }
7863
7864 Ok(opened_items)
7865 })
7866}
7867
7868#[derive(Clone)]
7869enum ActivateInDirectionTarget {
7870 Pane(Entity<Pane>),
7871 Dock(Entity<Dock>),
7872 Sidebar(FocusHandle),
7873}
7874
7875fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7876 window
7877 .update(cx, |multi_workspace, _, cx| {
7878 let workspace = multi_workspace.workspace().clone();
7879 workspace.update(cx, |workspace, cx| {
7880 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7881 struct DatabaseFailedNotification;
7882
7883 workspace.show_notification(
7884 NotificationId::unique::<DatabaseFailedNotification>(),
7885 cx,
7886 |cx| {
7887 cx.new(|cx| {
7888 MessageNotification::new("Failed to load the database file.", cx)
7889 .primary_message("File an Issue")
7890 .primary_icon(IconName::Plus)
7891 .primary_on_click(|window, cx| {
7892 window.dispatch_action(Box::new(FileBugReport), cx)
7893 })
7894 })
7895 },
7896 );
7897 }
7898 });
7899 })
7900 .log_err();
7901}
7902
7903fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7904 if val == 0 {
7905 ThemeSettings::get_global(cx).ui_font_size(cx)
7906 } else {
7907 px(val as f32)
7908 }
7909}
7910
7911fn adjust_active_dock_size_by_px(
7912 px: Pixels,
7913 workspace: &mut Workspace,
7914 window: &mut Window,
7915 cx: &mut Context<Workspace>,
7916) {
7917 let Some(active_dock) = workspace
7918 .all_docks()
7919 .into_iter()
7920 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7921 else {
7922 return;
7923 };
7924 let dock = active_dock.read(cx);
7925 let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
7926 return;
7927 };
7928 workspace.resize_dock(dock.position(), panel_size + px, window, cx);
7929}
7930
7931fn adjust_open_docks_size_by_px(
7932 px: Pixels,
7933 workspace: &mut Workspace,
7934 window: &mut Window,
7935 cx: &mut Context<Workspace>,
7936) {
7937 let docks = workspace
7938 .all_docks()
7939 .into_iter()
7940 .filter_map(|dock_entity| {
7941 let dock = dock_entity.read(cx);
7942 if dock.is_open() {
7943 let dock_pos = dock.position();
7944 let panel_size = workspace.dock_size(&dock, window, cx)?;
7945 Some((dock_pos, panel_size + px))
7946 } else {
7947 None
7948 }
7949 })
7950 .collect::<Vec<_>>();
7951
7952 for (position, new_size) in docks {
7953 workspace.resize_dock(position, new_size, window, cx);
7954 }
7955}
7956
7957impl Focusable for Workspace {
7958 fn focus_handle(&self, cx: &App) -> FocusHandle {
7959 self.active_pane.focus_handle(cx)
7960 }
7961}
7962
7963#[derive(Clone)]
7964struct DraggedDock(DockPosition);
7965
7966impl Render for DraggedDock {
7967 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7968 gpui::Empty
7969 }
7970}
7971
7972impl Render for Workspace {
7973 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7974 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7975 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7976 log::info!("Rendered first frame");
7977 }
7978
7979 let centered_layout = self.centered_layout
7980 && self.center.panes().len() == 1
7981 && self.active_item(cx).is_some();
7982 let render_padding = |size| {
7983 (size > 0.0).then(|| {
7984 div()
7985 .h_full()
7986 .w(relative(size))
7987 .bg(cx.theme().colors().editor_background)
7988 .border_color(cx.theme().colors().pane_group_border)
7989 })
7990 };
7991 let paddings = if centered_layout {
7992 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7993 (
7994 render_padding(Self::adjust_padding(
7995 settings.left_padding.map(|padding| padding.0),
7996 )),
7997 render_padding(Self::adjust_padding(
7998 settings.right_padding.map(|padding| padding.0),
7999 )),
8000 )
8001 } else {
8002 (None, None)
8003 };
8004 let ui_font = theme_settings::setup_ui_font(window, cx);
8005
8006 let theme = cx.theme().clone();
8007 let colors = theme.colors();
8008 let notification_entities = self
8009 .notifications
8010 .iter()
8011 .map(|(_, notification)| notification.entity_id())
8012 .collect::<Vec<_>>();
8013 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
8014
8015 div()
8016 .relative()
8017 .size_full()
8018 .flex()
8019 .flex_col()
8020 .font(ui_font)
8021 .gap_0()
8022 .justify_start()
8023 .items_start()
8024 .text_color(colors.text)
8025 .overflow_hidden()
8026 .children(self.titlebar_item.clone())
8027 .on_modifiers_changed(move |_, _, cx| {
8028 for &id in ¬ification_entities {
8029 cx.notify(id);
8030 }
8031 })
8032 .child(
8033 div()
8034 .size_full()
8035 .relative()
8036 .flex_1()
8037 .flex()
8038 .flex_col()
8039 .child(
8040 div()
8041 .id("workspace")
8042 .bg(colors.background)
8043 .relative()
8044 .flex_1()
8045 .w_full()
8046 .flex()
8047 .flex_col()
8048 .overflow_hidden()
8049 .border_t_1()
8050 .border_b_1()
8051 .border_color(colors.border)
8052 .child({
8053 let this = cx.entity();
8054 canvas(
8055 move |bounds, window, cx| {
8056 this.update(cx, |this, cx| {
8057 let bounds_changed = this.bounds != bounds;
8058 this.bounds = bounds;
8059
8060 if bounds_changed {
8061 this.left_dock.update(cx, |dock, cx| {
8062 dock.clamp_panel_size(
8063 bounds.size.width,
8064 window,
8065 cx,
8066 )
8067 });
8068
8069 this.right_dock.update(cx, |dock, cx| {
8070 dock.clamp_panel_size(
8071 bounds.size.width,
8072 window,
8073 cx,
8074 )
8075 });
8076
8077 this.bottom_dock.update(cx, |dock, cx| {
8078 dock.clamp_panel_size(
8079 bounds.size.height,
8080 window,
8081 cx,
8082 )
8083 });
8084 }
8085 })
8086 },
8087 |_, _, _, _| {},
8088 )
8089 .absolute()
8090 .size_full()
8091 })
8092 .when(self.zoomed.is_none(), |this| {
8093 this.on_drag_move(cx.listener(
8094 move |workspace,
8095 e: &DragMoveEvent<DraggedDock>,
8096 window,
8097 cx| {
8098 if workspace.previous_dock_drag_coordinates
8099 != Some(e.event.position)
8100 {
8101 workspace.previous_dock_drag_coordinates =
8102 Some(e.event.position);
8103
8104 match e.drag(cx).0 {
8105 DockPosition::Left => {
8106 workspace.resize_left_dock(
8107 e.event.position.x
8108 - workspace.bounds.left(),
8109 window,
8110 cx,
8111 );
8112 }
8113 DockPosition::Right => {
8114 workspace.resize_right_dock(
8115 workspace.bounds.right()
8116 - e.event.position.x,
8117 window,
8118 cx,
8119 );
8120 }
8121 DockPosition::Bottom => {
8122 workspace.resize_bottom_dock(
8123 workspace.bounds.bottom()
8124 - e.event.position.y,
8125 window,
8126 cx,
8127 );
8128 }
8129 };
8130 workspace.serialize_workspace(window, cx);
8131 }
8132 },
8133 ))
8134
8135 })
8136 .child({
8137 match bottom_dock_layout {
8138 BottomDockLayout::Full => div()
8139 .flex()
8140 .flex_col()
8141 .h_full()
8142 .child(
8143 div()
8144 .flex()
8145 .flex_row()
8146 .flex_1()
8147 .overflow_hidden()
8148 .children(self.render_dock(
8149 DockPosition::Left,
8150 &self.left_dock,
8151 window,
8152 cx,
8153 ))
8154
8155 .child(
8156 div()
8157 .flex()
8158 .flex_col()
8159 .flex_1()
8160 .overflow_hidden()
8161 .child(
8162 h_flex()
8163 .flex_1()
8164 .when_some(
8165 paddings.0,
8166 |this, p| {
8167 this.child(
8168 p.border_r_1(),
8169 )
8170 },
8171 )
8172 .child(self.center.render(
8173 self.zoomed.as_ref(),
8174 &PaneRenderContext {
8175 follower_states:
8176 &self.follower_states,
8177 active_call: self.active_call(),
8178 active_pane: &self.active_pane,
8179 app_state: &self.app_state,
8180 project: &self.project,
8181 workspace: &self.weak_self,
8182 },
8183 window,
8184 cx,
8185 ))
8186 .when_some(
8187 paddings.1,
8188 |this, p| {
8189 this.child(
8190 p.border_l_1(),
8191 )
8192 },
8193 ),
8194 ),
8195 )
8196
8197 .children(self.render_dock(
8198 DockPosition::Right,
8199 &self.right_dock,
8200 window,
8201 cx,
8202 )),
8203 )
8204 .child(div().w_full().children(self.render_dock(
8205 DockPosition::Bottom,
8206 &self.bottom_dock,
8207 window,
8208 cx
8209 ))),
8210
8211 BottomDockLayout::LeftAligned => div()
8212 .flex()
8213 .flex_row()
8214 .h_full()
8215 .child(
8216 div()
8217 .flex()
8218 .flex_col()
8219 .flex_1()
8220 .h_full()
8221 .child(
8222 div()
8223 .flex()
8224 .flex_row()
8225 .flex_1()
8226 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
8227
8228 .child(
8229 div()
8230 .flex()
8231 .flex_col()
8232 .flex_1()
8233 .overflow_hidden()
8234 .child(
8235 h_flex()
8236 .flex_1()
8237 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8238 .child(self.center.render(
8239 self.zoomed.as_ref(),
8240 &PaneRenderContext {
8241 follower_states:
8242 &self.follower_states,
8243 active_call: self.active_call(),
8244 active_pane: &self.active_pane,
8245 app_state: &self.app_state,
8246 project: &self.project,
8247 workspace: &self.weak_self,
8248 },
8249 window,
8250 cx,
8251 ))
8252 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8253 )
8254 )
8255
8256 )
8257 .child(
8258 div()
8259 .w_full()
8260 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8261 ),
8262 )
8263 .children(self.render_dock(
8264 DockPosition::Right,
8265 &self.right_dock,
8266 window,
8267 cx,
8268 )),
8269 BottomDockLayout::RightAligned => div()
8270 .flex()
8271 .flex_row()
8272 .h_full()
8273 .children(self.render_dock(
8274 DockPosition::Left,
8275 &self.left_dock,
8276 window,
8277 cx,
8278 ))
8279
8280 .child(
8281 div()
8282 .flex()
8283 .flex_col()
8284 .flex_1()
8285 .h_full()
8286 .child(
8287 div()
8288 .flex()
8289 .flex_row()
8290 .flex_1()
8291 .child(
8292 div()
8293 .flex()
8294 .flex_col()
8295 .flex_1()
8296 .overflow_hidden()
8297 .child(
8298 h_flex()
8299 .flex_1()
8300 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8301 .child(self.center.render(
8302 self.zoomed.as_ref(),
8303 &PaneRenderContext {
8304 follower_states:
8305 &self.follower_states,
8306 active_call: self.active_call(),
8307 active_pane: &self.active_pane,
8308 app_state: &self.app_state,
8309 project: &self.project,
8310 workspace: &self.weak_self,
8311 },
8312 window,
8313 cx,
8314 ))
8315 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8316 )
8317 )
8318
8319 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8320 )
8321 .child(
8322 div()
8323 .w_full()
8324 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8325 ),
8326 ),
8327 BottomDockLayout::Contained => div()
8328 .flex()
8329 .flex_row()
8330 .h_full()
8331 .children(self.render_dock(
8332 DockPosition::Left,
8333 &self.left_dock,
8334 window,
8335 cx,
8336 ))
8337
8338 .child(
8339 div()
8340 .flex()
8341 .flex_col()
8342 .flex_1()
8343 .overflow_hidden()
8344 .child(
8345 h_flex()
8346 .flex_1()
8347 .when_some(paddings.0, |this, p| {
8348 this.child(p.border_r_1())
8349 })
8350 .child(self.center.render(
8351 self.zoomed.as_ref(),
8352 &PaneRenderContext {
8353 follower_states:
8354 &self.follower_states,
8355 active_call: self.active_call(),
8356 active_pane: &self.active_pane,
8357 app_state: &self.app_state,
8358 project: &self.project,
8359 workspace: &self.weak_self,
8360 },
8361 window,
8362 cx,
8363 ))
8364 .when_some(paddings.1, |this, p| {
8365 this.child(p.border_l_1())
8366 }),
8367 )
8368 .children(self.render_dock(
8369 DockPosition::Bottom,
8370 &self.bottom_dock,
8371 window,
8372 cx,
8373 )),
8374 )
8375
8376 .children(self.render_dock(
8377 DockPosition::Right,
8378 &self.right_dock,
8379 window,
8380 cx,
8381 )),
8382 }
8383 })
8384 .children(self.zoomed.as_ref().and_then(|view| {
8385 let zoomed_view = view.upgrade()?;
8386 let div = div()
8387 .occlude()
8388 .absolute()
8389 .overflow_hidden()
8390 .border_color(colors.border)
8391 .bg(colors.background)
8392 .child(zoomed_view)
8393 .inset_0()
8394 .shadow_lg();
8395
8396 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8397 return Some(div);
8398 }
8399
8400 Some(match self.zoomed_position {
8401 Some(DockPosition::Left) => div.right_2().border_r_1(),
8402 Some(DockPosition::Right) => div.left_2().border_l_1(),
8403 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8404 None => {
8405 div.top_2().bottom_2().left_2().right_2().border_1()
8406 }
8407 })
8408 }))
8409 .children(self.render_notifications(window, cx)),
8410 )
8411 .when(self.status_bar_visible(cx), |parent| {
8412 parent.child(self.status_bar.clone())
8413 })
8414 .child(self.toast_layer.clone()),
8415 )
8416 }
8417}
8418
8419impl WorkspaceStore {
8420 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8421 Self {
8422 workspaces: Default::default(),
8423 _subscriptions: vec![
8424 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8425 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8426 ],
8427 client,
8428 }
8429 }
8430
8431 pub fn update_followers(
8432 &self,
8433 project_id: Option<u64>,
8434 update: proto::update_followers::Variant,
8435 cx: &App,
8436 ) -> Option<()> {
8437 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8438 let room_id = active_call.0.room_id(cx)?;
8439 self.client
8440 .send(proto::UpdateFollowers {
8441 room_id,
8442 project_id,
8443 variant: Some(update),
8444 })
8445 .log_err()
8446 }
8447
8448 pub async fn handle_follow(
8449 this: Entity<Self>,
8450 envelope: TypedEnvelope<proto::Follow>,
8451 mut cx: AsyncApp,
8452 ) -> Result<proto::FollowResponse> {
8453 this.update(&mut cx, |this, cx| {
8454 let follower = Follower {
8455 project_id: envelope.payload.project_id,
8456 peer_id: envelope.original_sender_id()?,
8457 };
8458
8459 let mut response = proto::FollowResponse::default();
8460
8461 this.workspaces.retain(|(window_handle, weak_workspace)| {
8462 let Some(workspace) = weak_workspace.upgrade() else {
8463 return false;
8464 };
8465 window_handle
8466 .update(cx, |_, window, cx| {
8467 workspace.update(cx, |workspace, cx| {
8468 let handler_response =
8469 workspace.handle_follow(follower.project_id, window, cx);
8470 if let Some(active_view) = handler_response.active_view
8471 && workspace.project.read(cx).remote_id() == follower.project_id
8472 {
8473 response.active_view = Some(active_view)
8474 }
8475 });
8476 })
8477 .is_ok()
8478 });
8479
8480 Ok(response)
8481 })
8482 }
8483
8484 async fn handle_update_followers(
8485 this: Entity<Self>,
8486 envelope: TypedEnvelope<proto::UpdateFollowers>,
8487 mut cx: AsyncApp,
8488 ) -> Result<()> {
8489 let leader_id = envelope.original_sender_id()?;
8490 let update = envelope.payload;
8491
8492 this.update(&mut cx, |this, cx| {
8493 this.workspaces.retain(|(window_handle, weak_workspace)| {
8494 let Some(workspace) = weak_workspace.upgrade() else {
8495 return false;
8496 };
8497 window_handle
8498 .update(cx, |_, window, cx| {
8499 workspace.update(cx, |workspace, cx| {
8500 let project_id = workspace.project.read(cx).remote_id();
8501 if update.project_id != project_id && update.project_id.is_some() {
8502 return;
8503 }
8504 workspace.handle_update_followers(
8505 leader_id,
8506 update.clone(),
8507 window,
8508 cx,
8509 );
8510 });
8511 })
8512 .is_ok()
8513 });
8514 Ok(())
8515 })
8516 }
8517
8518 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8519 self.workspaces.iter().map(|(_, weak)| weak)
8520 }
8521
8522 pub fn workspaces_with_windows(
8523 &self,
8524 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8525 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8526 }
8527}
8528
8529impl ViewId {
8530 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8531 Ok(Self {
8532 creator: message
8533 .creator
8534 .map(CollaboratorId::PeerId)
8535 .context("creator is missing")?,
8536 id: message.id,
8537 })
8538 }
8539
8540 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8541 if let CollaboratorId::PeerId(peer_id) = self.creator {
8542 Some(proto::ViewId {
8543 creator: Some(peer_id),
8544 id: self.id,
8545 })
8546 } else {
8547 None
8548 }
8549 }
8550}
8551
8552impl FollowerState {
8553 fn pane(&self) -> &Entity<Pane> {
8554 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8555 }
8556}
8557
8558pub trait WorkspaceHandle {
8559 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8560}
8561
8562impl WorkspaceHandle for Entity<Workspace> {
8563 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8564 self.read(cx)
8565 .worktrees(cx)
8566 .flat_map(|worktree| {
8567 let worktree_id = worktree.read(cx).id();
8568 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8569 worktree_id,
8570 path: f.path.clone(),
8571 })
8572 })
8573 .collect::<Vec<_>>()
8574 }
8575}
8576
8577pub async fn last_opened_workspace_location(
8578 db: &WorkspaceDb,
8579 fs: &dyn fs::Fs,
8580) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8581 db.last_workspace(fs)
8582 .await
8583 .log_err()
8584 .flatten()
8585 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8586}
8587
8588pub async fn last_session_workspace_locations(
8589 db: &WorkspaceDb,
8590 last_session_id: &str,
8591 last_session_window_stack: Option<Vec<WindowId>>,
8592 fs: &dyn fs::Fs,
8593) -> Option<Vec<SessionWorkspace>> {
8594 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8595 .await
8596 .log_err()
8597}
8598
8599pub struct MultiWorkspaceRestoreResult {
8600 pub window_handle: WindowHandle<MultiWorkspace>,
8601 pub errors: Vec<anyhow::Error>,
8602}
8603
8604pub async fn restore_multiworkspace(
8605 multi_workspace: SerializedMultiWorkspace,
8606 app_state: Arc<AppState>,
8607 cx: &mut AsyncApp,
8608) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8609 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
8610 let mut group_iter = workspaces.into_iter();
8611 let first = group_iter
8612 .next()
8613 .context("window group must not be empty")?;
8614
8615 let window_handle = if first.paths.is_empty() {
8616 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8617 .await?
8618 } else {
8619 let OpenResult { window, .. } = cx
8620 .update(|cx| {
8621 Workspace::new_local(
8622 first.paths.paths().to_vec(),
8623 app_state.clone(),
8624 None,
8625 None,
8626 None,
8627 OpenMode::Activate,
8628 cx,
8629 )
8630 })
8631 .await?;
8632 window
8633 };
8634
8635 let mut errors = Vec::new();
8636
8637 for session_workspace in group_iter {
8638 let error = if session_workspace.paths.is_empty() {
8639 cx.update(|cx| {
8640 open_workspace_by_id(
8641 session_workspace.workspace_id,
8642 app_state.clone(),
8643 Some(window_handle),
8644 cx,
8645 )
8646 })
8647 .await
8648 .err()
8649 } else {
8650 cx.update(|cx| {
8651 Workspace::new_local(
8652 session_workspace.paths.paths().to_vec(),
8653 app_state.clone(),
8654 Some(window_handle),
8655 None,
8656 None,
8657 OpenMode::Add,
8658 cx,
8659 )
8660 })
8661 .await
8662 .err()
8663 };
8664
8665 if let Some(error) = error {
8666 errors.push(error);
8667 }
8668 }
8669
8670 if let Some(target_id) = state.active_workspace_id {
8671 window_handle
8672 .update(cx, |multi_workspace, window, cx| {
8673 let target_index = multi_workspace
8674 .workspaces()
8675 .iter()
8676 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8677 let index = target_index.unwrap_or(0);
8678 if let Some(workspace) = multi_workspace.workspaces().get(index).cloned() {
8679 multi_workspace.activate(workspace, window, cx);
8680 }
8681 })
8682 .ok();
8683 } else {
8684 window_handle
8685 .update(cx, |multi_workspace, window, cx| {
8686 if let Some(workspace) = multi_workspace.workspaces().first().cloned() {
8687 multi_workspace.activate(workspace, window, cx);
8688 }
8689 })
8690 .ok();
8691 }
8692
8693 if state.sidebar_open {
8694 window_handle
8695 .update(cx, |multi_workspace, _, cx| {
8696 multi_workspace.open_sidebar(cx);
8697 })
8698 .ok();
8699 }
8700
8701 if let Some(sidebar_state) = &state.sidebar_state {
8702 let sidebar_state = sidebar_state.clone();
8703 window_handle
8704 .update(cx, |multi_workspace, window, cx| {
8705 if let Some(sidebar) = multi_workspace.sidebar() {
8706 sidebar.restore_serialized_state(&sidebar_state, window, cx);
8707 }
8708 multi_workspace.serialize(cx);
8709 })
8710 .ok();
8711 }
8712
8713 window_handle
8714 .update(cx, |_, window, _cx| {
8715 window.activate_window();
8716 })
8717 .ok();
8718
8719 Ok(MultiWorkspaceRestoreResult {
8720 window_handle,
8721 errors,
8722 })
8723}
8724
8725actions!(
8726 collab,
8727 [
8728 /// Opens the channel notes for the current call.
8729 ///
8730 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8731 /// channel in the collab panel.
8732 ///
8733 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8734 /// can be copied via "Copy link to section" in the context menu of the channel notes
8735 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8736 OpenChannelNotes,
8737 /// Mutes your microphone.
8738 Mute,
8739 /// Deafens yourself (mute both microphone and speakers).
8740 Deafen,
8741 /// Leaves the current call.
8742 LeaveCall,
8743 /// Shares the current project with collaborators.
8744 ShareProject,
8745 /// Shares your screen with collaborators.
8746 ScreenShare,
8747 /// Copies the current room name and session id for debugging purposes.
8748 CopyRoomId,
8749 ]
8750);
8751
8752/// Opens the channel notes for a specific channel by its ID.
8753#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8754#[action(namespace = collab)]
8755#[serde(deny_unknown_fields)]
8756pub struct OpenChannelNotesById {
8757 pub channel_id: u64,
8758}
8759
8760actions!(
8761 zed,
8762 [
8763 /// Opens the Zed log file.
8764 OpenLog,
8765 /// Reveals the Zed log file in the system file manager.
8766 RevealLogInFileManager
8767 ]
8768);
8769
8770async fn join_channel_internal(
8771 channel_id: ChannelId,
8772 app_state: &Arc<AppState>,
8773 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8774 requesting_workspace: Option<WeakEntity<Workspace>>,
8775 active_call: &dyn AnyActiveCall,
8776 cx: &mut AsyncApp,
8777) -> Result<bool> {
8778 let (should_prompt, already_in_channel) = cx.update(|cx| {
8779 if !active_call.is_in_room(cx) {
8780 return (false, false);
8781 }
8782
8783 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8784 let should_prompt = active_call.is_sharing_project(cx)
8785 && active_call.has_remote_participants(cx)
8786 && !already_in_channel;
8787 (should_prompt, already_in_channel)
8788 });
8789
8790 if already_in_channel {
8791 let task = cx.update(|cx| {
8792 if let Some((project, host)) = active_call.most_active_project(cx) {
8793 Some(join_in_room_project(project, host, app_state.clone(), cx))
8794 } else {
8795 None
8796 }
8797 });
8798 if let Some(task) = task {
8799 task.await?;
8800 }
8801 return anyhow::Ok(true);
8802 }
8803
8804 if should_prompt {
8805 if let Some(multi_workspace) = requesting_window {
8806 let answer = multi_workspace
8807 .update(cx, |_, window, cx| {
8808 window.prompt(
8809 PromptLevel::Warning,
8810 "Do you want to switch channels?",
8811 Some("Leaving this call will unshare your current project."),
8812 &["Yes, Join Channel", "Cancel"],
8813 cx,
8814 )
8815 })?
8816 .await;
8817
8818 if answer == Ok(1) {
8819 return Ok(false);
8820 }
8821 } else {
8822 return Ok(false);
8823 }
8824 }
8825
8826 let client = cx.update(|cx| active_call.client(cx));
8827
8828 let mut client_status = client.status();
8829
8830 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8831 'outer: loop {
8832 let Some(status) = client_status.recv().await else {
8833 anyhow::bail!("error connecting");
8834 };
8835
8836 match status {
8837 Status::Connecting
8838 | Status::Authenticating
8839 | Status::Authenticated
8840 | Status::Reconnecting
8841 | Status::Reauthenticating
8842 | Status::Reauthenticated => continue,
8843 Status::Connected { .. } => break 'outer,
8844 Status::SignedOut | Status::AuthenticationError => {
8845 return Err(ErrorCode::SignedOut.into());
8846 }
8847 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8848 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8849 return Err(ErrorCode::Disconnected.into());
8850 }
8851 }
8852 }
8853
8854 let joined = cx
8855 .update(|cx| active_call.join_channel(channel_id, cx))
8856 .await?;
8857
8858 if !joined {
8859 return anyhow::Ok(true);
8860 }
8861
8862 cx.update(|cx| active_call.room_update_completed(cx)).await;
8863
8864 let task = cx.update(|cx| {
8865 if let Some((project, host)) = active_call.most_active_project(cx) {
8866 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8867 }
8868
8869 // If you are the first to join a channel, see if you should share your project.
8870 if !active_call.has_remote_participants(cx)
8871 && !active_call.local_participant_is_guest(cx)
8872 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8873 {
8874 let project = workspace.update(cx, |workspace, cx| {
8875 let project = workspace.project.read(cx);
8876
8877 if !active_call.share_on_join(cx) {
8878 return None;
8879 }
8880
8881 if (project.is_local() || project.is_via_remote_server())
8882 && project.visible_worktrees(cx).any(|tree| {
8883 tree.read(cx)
8884 .root_entry()
8885 .is_some_and(|entry| entry.is_dir())
8886 })
8887 {
8888 Some(workspace.project.clone())
8889 } else {
8890 None
8891 }
8892 });
8893 if let Some(project) = project {
8894 let share_task = active_call.share_project(project, cx);
8895 return Some(cx.spawn(async move |_cx| -> Result<()> {
8896 share_task.await?;
8897 Ok(())
8898 }));
8899 }
8900 }
8901
8902 None
8903 });
8904 if let Some(task) = task {
8905 task.await?;
8906 return anyhow::Ok(true);
8907 }
8908 anyhow::Ok(false)
8909}
8910
8911pub fn join_channel(
8912 channel_id: ChannelId,
8913 app_state: Arc<AppState>,
8914 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8915 requesting_workspace: Option<WeakEntity<Workspace>>,
8916 cx: &mut App,
8917) -> Task<Result<()>> {
8918 let active_call = GlobalAnyActiveCall::global(cx).clone();
8919 cx.spawn(async move |cx| {
8920 let result = join_channel_internal(
8921 channel_id,
8922 &app_state,
8923 requesting_window,
8924 requesting_workspace,
8925 &*active_call.0,
8926 cx,
8927 )
8928 .await;
8929
8930 // join channel succeeded, and opened a window
8931 if matches!(result, Ok(true)) {
8932 return anyhow::Ok(());
8933 }
8934
8935 // find an existing workspace to focus and show call controls
8936 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8937 if active_window.is_none() {
8938 // no open workspaces, make one to show the error in (blergh)
8939 let OpenResult {
8940 window: window_handle,
8941 ..
8942 } = cx
8943 .update(|cx| {
8944 Workspace::new_local(
8945 vec![],
8946 app_state.clone(),
8947 requesting_window,
8948 None,
8949 None,
8950 OpenMode::Activate,
8951 cx,
8952 )
8953 })
8954 .await?;
8955
8956 window_handle
8957 .update(cx, |_, window, _cx| {
8958 window.activate_window();
8959 })
8960 .ok();
8961
8962 if result.is_ok() {
8963 cx.update(|cx| {
8964 cx.dispatch_action(&OpenChannelNotes);
8965 });
8966 }
8967
8968 active_window = Some(window_handle);
8969 }
8970
8971 if let Err(err) = result {
8972 log::error!("failed to join channel: {}", err);
8973 if let Some(active_window) = active_window {
8974 active_window
8975 .update(cx, |_, window, cx| {
8976 let detail: SharedString = match err.error_code() {
8977 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8978 ErrorCode::UpgradeRequired => concat!(
8979 "Your are running an unsupported version of Zed. ",
8980 "Please update to continue."
8981 )
8982 .into(),
8983 ErrorCode::NoSuchChannel => concat!(
8984 "No matching channel was found. ",
8985 "Please check the link and try again."
8986 )
8987 .into(),
8988 ErrorCode::Forbidden => concat!(
8989 "This channel is private, and you do not have access. ",
8990 "Please ask someone to add you and try again."
8991 )
8992 .into(),
8993 ErrorCode::Disconnected => {
8994 "Please check your internet connection and try again.".into()
8995 }
8996 _ => format!("{}\n\nPlease try again.", err).into(),
8997 };
8998 window.prompt(
8999 PromptLevel::Critical,
9000 "Failed to join channel",
9001 Some(&detail),
9002 &["Ok"],
9003 cx,
9004 )
9005 })?
9006 .await
9007 .ok();
9008 }
9009 }
9010
9011 // return ok, we showed the error to the user.
9012 anyhow::Ok(())
9013 })
9014}
9015
9016pub async fn get_any_active_multi_workspace(
9017 app_state: Arc<AppState>,
9018 mut cx: AsyncApp,
9019) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
9020 // find an existing workspace to focus and show call controls
9021 let active_window = activate_any_workspace_window(&mut cx);
9022 if active_window.is_none() {
9023 cx.update(|cx| {
9024 Workspace::new_local(
9025 vec![],
9026 app_state.clone(),
9027 None,
9028 None,
9029 None,
9030 OpenMode::Activate,
9031 cx,
9032 )
9033 })
9034 .await?;
9035 }
9036 activate_any_workspace_window(&mut cx).context("could not open zed")
9037}
9038
9039fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
9040 cx.update(|cx| {
9041 if let Some(workspace_window) = cx
9042 .active_window()
9043 .and_then(|window| window.downcast::<MultiWorkspace>())
9044 {
9045 return Some(workspace_window);
9046 }
9047
9048 for window in cx.windows() {
9049 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
9050 workspace_window
9051 .update(cx, |_, window, _| window.activate_window())
9052 .ok();
9053 return Some(workspace_window);
9054 }
9055 }
9056 None
9057 })
9058}
9059
9060pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
9061 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
9062}
9063
9064pub fn workspace_windows_for_location(
9065 serialized_location: &SerializedWorkspaceLocation,
9066 cx: &App,
9067) -> Vec<WindowHandle<MultiWorkspace>> {
9068 cx.windows()
9069 .into_iter()
9070 .filter_map(|window| window.downcast::<MultiWorkspace>())
9071 .filter(|multi_workspace| {
9072 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
9073 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
9074 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
9075 }
9076 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
9077 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
9078 a.distro_name == b.distro_name
9079 }
9080 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
9081 a.container_id == b.container_id
9082 }
9083 #[cfg(any(test, feature = "test-support"))]
9084 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
9085 a.id == b.id
9086 }
9087 _ => false,
9088 };
9089
9090 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
9091 multi_workspace.workspaces().iter().any(|workspace| {
9092 match workspace.read(cx).workspace_location(cx) {
9093 WorkspaceLocation::Location(location, _) => {
9094 match (&location, serialized_location) {
9095 (
9096 SerializedWorkspaceLocation::Local,
9097 SerializedWorkspaceLocation::Local,
9098 ) => true,
9099 (
9100 SerializedWorkspaceLocation::Remote(a),
9101 SerializedWorkspaceLocation::Remote(b),
9102 ) => same_host(a, b),
9103 _ => false,
9104 }
9105 }
9106 _ => false,
9107 }
9108 })
9109 })
9110 })
9111 .collect()
9112}
9113
9114pub async fn find_existing_workspace(
9115 abs_paths: &[PathBuf],
9116 open_options: &OpenOptions,
9117 location: &SerializedWorkspaceLocation,
9118 cx: &mut AsyncApp,
9119) -> (
9120 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
9121 OpenVisible,
9122) {
9123 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
9124 let mut open_visible = OpenVisible::All;
9125 let mut best_match = None;
9126
9127 if open_options.open_new_workspace != Some(true) {
9128 cx.update(|cx| {
9129 for window in workspace_windows_for_location(location, cx) {
9130 if let Ok(multi_workspace) = window.read(cx) {
9131 for workspace in multi_workspace.workspaces() {
9132 let project = workspace.read(cx).project.read(cx);
9133 let m = project.visibility_for_paths(
9134 abs_paths,
9135 open_options.open_new_workspace == None,
9136 cx,
9137 );
9138 if m > best_match {
9139 existing = Some((window, workspace.clone()));
9140 best_match = m;
9141 } else if best_match.is_none()
9142 && open_options.open_new_workspace == Some(false)
9143 {
9144 existing = Some((window, workspace.clone()))
9145 }
9146 }
9147 }
9148 }
9149 });
9150
9151 let all_paths_are_files = existing
9152 .as_ref()
9153 .and_then(|(_, target_workspace)| {
9154 cx.update(|cx| {
9155 let workspace = target_workspace.read(cx);
9156 let project = workspace.project.read(cx);
9157 let path_style = workspace.path_style(cx);
9158 Some(!abs_paths.iter().any(|path| {
9159 let path = util::paths::SanitizedPath::new(path);
9160 project.worktrees(cx).any(|worktree| {
9161 let worktree = worktree.read(cx);
9162 let abs_path = worktree.abs_path();
9163 path_style
9164 .strip_prefix(path.as_ref(), abs_path.as_ref())
9165 .and_then(|rel| worktree.entry_for_path(&rel))
9166 .is_some_and(|e| e.is_dir())
9167 })
9168 }))
9169 })
9170 })
9171 .unwrap_or(false);
9172
9173 if open_options.open_new_workspace.is_none()
9174 && existing.is_some()
9175 && open_options.wait
9176 && all_paths_are_files
9177 {
9178 cx.update(|cx| {
9179 let windows = workspace_windows_for_location(location, cx);
9180 let window = cx
9181 .active_window()
9182 .and_then(|window| window.downcast::<MultiWorkspace>())
9183 .filter(|window| windows.contains(window))
9184 .or_else(|| windows.into_iter().next());
9185 if let Some(window) = window {
9186 if let Ok(multi_workspace) = window.read(cx) {
9187 let active_workspace = multi_workspace.workspace().clone();
9188 existing = Some((window, active_workspace));
9189 open_visible = OpenVisible::None;
9190 }
9191 }
9192 });
9193 }
9194 }
9195 (existing, open_visible)
9196}
9197
9198#[derive(Default, Clone)]
9199pub struct OpenOptions {
9200 pub visible: Option<OpenVisible>,
9201 pub focus: Option<bool>,
9202 pub open_new_workspace: Option<bool>,
9203 pub wait: bool,
9204 pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
9205 pub open_mode: OpenMode,
9206 pub env: Option<HashMap<String, String>>,
9207}
9208
9209/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
9210/// or [`Workspace::open_workspace_for_paths`].
9211pub struct OpenResult {
9212 pub window: WindowHandle<MultiWorkspace>,
9213 pub workspace: Entity<Workspace>,
9214 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
9215}
9216
9217/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
9218pub fn open_workspace_by_id(
9219 workspace_id: WorkspaceId,
9220 app_state: Arc<AppState>,
9221 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9222 cx: &mut App,
9223) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
9224 let project_handle = Project::local(
9225 app_state.client.clone(),
9226 app_state.node_runtime.clone(),
9227 app_state.user_store.clone(),
9228 app_state.languages.clone(),
9229 app_state.fs.clone(),
9230 None,
9231 project::LocalProjectFlags {
9232 init_worktree_trust: true,
9233 ..project::LocalProjectFlags::default()
9234 },
9235 cx,
9236 );
9237
9238 let db = WorkspaceDb::global(cx);
9239 let kvp = db::kvp::KeyValueStore::global(cx);
9240 cx.spawn(async move |cx| {
9241 let serialized_workspace = db
9242 .workspace_for_id(workspace_id)
9243 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
9244
9245 let centered_layout = serialized_workspace.centered_layout;
9246
9247 let (window, workspace) = if let Some(window) = requesting_window {
9248 let workspace = window.update(cx, |multi_workspace, window, cx| {
9249 let workspace = cx.new(|cx| {
9250 let mut workspace = Workspace::new(
9251 Some(workspace_id),
9252 project_handle.clone(),
9253 app_state.clone(),
9254 window,
9255 cx,
9256 );
9257 workspace.centered_layout = centered_layout;
9258 workspace
9259 });
9260 multi_workspace.add(workspace.clone(), &*window, cx);
9261 workspace
9262 })?;
9263 (window, workspace)
9264 } else {
9265 let window_bounds_override = window_bounds_env_override();
9266
9267 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
9268 (Some(WindowBounds::Windowed(bounds)), None)
9269 } else if let Some(display) = serialized_workspace.display
9270 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
9271 {
9272 (Some(bounds.0), Some(display))
9273 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
9274 (Some(bounds), Some(display))
9275 } else {
9276 (None, None)
9277 };
9278
9279 let options = cx.update(|cx| {
9280 let mut options = (app_state.build_window_options)(display, cx);
9281 options.window_bounds = window_bounds;
9282 options
9283 });
9284
9285 let window = cx.open_window(options, {
9286 let app_state = app_state.clone();
9287 let project_handle = project_handle.clone();
9288 move |window, cx| {
9289 let workspace = cx.new(|cx| {
9290 let mut workspace = Workspace::new(
9291 Some(workspace_id),
9292 project_handle,
9293 app_state,
9294 window,
9295 cx,
9296 );
9297 workspace.centered_layout = centered_layout;
9298 workspace
9299 });
9300 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9301 }
9302 })?;
9303
9304 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9305 multi_workspace.workspace().clone()
9306 })?;
9307
9308 (window, workspace)
9309 };
9310
9311 notify_if_database_failed(window, cx);
9312
9313 // Restore items from the serialized workspace
9314 window
9315 .update(cx, |_, window, cx| {
9316 workspace.update(cx, |_workspace, cx| {
9317 open_items(Some(serialized_workspace), vec![], window, cx)
9318 })
9319 })?
9320 .await?;
9321
9322 window.update(cx, |_, window, cx| {
9323 workspace.update(cx, |workspace, cx| {
9324 workspace.serialize_workspace(window, cx);
9325 });
9326 })?;
9327
9328 Ok(window)
9329 })
9330}
9331
9332#[allow(clippy::type_complexity)]
9333pub fn open_paths(
9334 abs_paths: &[PathBuf],
9335 app_state: Arc<AppState>,
9336 open_options: OpenOptions,
9337 cx: &mut App,
9338) -> Task<anyhow::Result<OpenResult>> {
9339 let abs_paths = abs_paths.to_vec();
9340 #[cfg(target_os = "windows")]
9341 let wsl_path = abs_paths
9342 .iter()
9343 .find_map(|p| util::paths::WslPath::from_path(p));
9344
9345 cx.spawn(async move |cx| {
9346 let (mut existing, mut open_visible) = find_existing_workspace(
9347 &abs_paths,
9348 &open_options,
9349 &SerializedWorkspaceLocation::Local,
9350 cx,
9351 )
9352 .await;
9353
9354 // Fallback: if no workspace contains the paths and all paths are files,
9355 // prefer an existing local workspace window (active window first).
9356 if open_options.open_new_workspace.is_none() && existing.is_none() {
9357 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9358 let all_metadatas = futures::future::join_all(all_paths)
9359 .await
9360 .into_iter()
9361 .filter_map(|result| result.ok().flatten())
9362 .collect::<Vec<_>>();
9363
9364 if all_metadatas.iter().all(|file| !file.is_dir) {
9365 cx.update(|cx| {
9366 let windows = workspace_windows_for_location(
9367 &SerializedWorkspaceLocation::Local,
9368 cx,
9369 );
9370 let window = cx
9371 .active_window()
9372 .and_then(|window| window.downcast::<MultiWorkspace>())
9373 .filter(|window| windows.contains(window))
9374 .or_else(|| windows.into_iter().next());
9375 if let Some(window) = window {
9376 if let Ok(multi_workspace) = window.read(cx) {
9377 let active_workspace = multi_workspace.workspace().clone();
9378 existing = Some((window, active_workspace));
9379 open_visible = OpenVisible::None;
9380 }
9381 }
9382 });
9383 }
9384 }
9385
9386 let result = if let Some((existing, target_workspace)) = existing {
9387 let open_task = existing
9388 .update(cx, |multi_workspace, window, cx| {
9389 window.activate_window();
9390 multi_workspace.activate(target_workspace.clone(), window, cx);
9391 target_workspace.update(cx, |workspace, cx| {
9392 workspace.open_paths(
9393 abs_paths,
9394 OpenOptions {
9395 visible: Some(open_visible),
9396 ..Default::default()
9397 },
9398 None,
9399 window,
9400 cx,
9401 )
9402 })
9403 })?
9404 .await;
9405
9406 _ = existing.update(cx, |multi_workspace, _, cx| {
9407 let workspace = multi_workspace.workspace().clone();
9408 workspace.update(cx, |workspace, cx| {
9409 for item in open_task.iter().flatten() {
9410 if let Err(e) = item {
9411 workspace.show_error(&e, cx);
9412 }
9413 }
9414 });
9415 });
9416
9417 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9418 } else {
9419 let result = cx
9420 .update(move |cx| {
9421 Workspace::new_local(
9422 abs_paths,
9423 app_state.clone(),
9424 open_options.requesting_window,
9425 open_options.env,
9426 None,
9427 open_options.open_mode,
9428 cx,
9429 )
9430 })
9431 .await;
9432
9433 if let Ok(ref result) = result {
9434 result.window
9435 .update(cx, |_, window, _cx| {
9436 window.activate_window();
9437 })
9438 .log_err();
9439 }
9440
9441 result
9442 };
9443
9444 #[cfg(target_os = "windows")]
9445 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9446 && let Ok(ref result) = result
9447 {
9448 result.window
9449 .update(cx, move |multi_workspace, _window, cx| {
9450 struct OpenInWsl;
9451 let workspace = multi_workspace.workspace().clone();
9452 workspace.update(cx, |workspace, cx| {
9453 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9454 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9455 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9456 cx.new(move |cx| {
9457 MessageNotification::new(msg, cx)
9458 .primary_message("Open in WSL")
9459 .primary_icon(IconName::FolderOpen)
9460 .primary_on_click(move |window, cx| {
9461 window.dispatch_action(Box::new(remote::OpenWslPath {
9462 distro: remote::WslConnectionOptions {
9463 distro_name: distro.clone(),
9464 user: None,
9465 },
9466 paths: vec![path.clone().into()],
9467 }), cx)
9468 })
9469 })
9470 });
9471 });
9472 })
9473 .unwrap();
9474 };
9475 result
9476 })
9477}
9478
9479pub fn open_new(
9480 open_options: OpenOptions,
9481 app_state: Arc<AppState>,
9482 cx: &mut App,
9483 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9484) -> Task<anyhow::Result<()>> {
9485 let addition = open_options.open_mode;
9486 let task = Workspace::new_local(
9487 Vec::new(),
9488 app_state,
9489 open_options.requesting_window,
9490 open_options.env,
9491 Some(Box::new(init)),
9492 addition,
9493 cx,
9494 );
9495 cx.spawn(async move |cx| {
9496 let OpenResult { window, .. } = task.await?;
9497 window
9498 .update(cx, |_, window, _cx| {
9499 window.activate_window();
9500 })
9501 .ok();
9502 Ok(())
9503 })
9504}
9505
9506pub fn create_and_open_local_file(
9507 path: &'static Path,
9508 window: &mut Window,
9509 cx: &mut Context<Workspace>,
9510 default_content: impl 'static + Send + FnOnce() -> Rope,
9511) -> Task<Result<Box<dyn ItemHandle>>> {
9512 cx.spawn_in(window, async move |workspace, cx| {
9513 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9514 if !fs.is_file(path).await {
9515 fs.create_file(path, Default::default()).await?;
9516 fs.save(path, &default_content(), Default::default())
9517 .await?;
9518 }
9519
9520 workspace
9521 .update_in(cx, |workspace, window, cx| {
9522 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9523 let path = workspace
9524 .project
9525 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9526 cx.spawn_in(window, async move |workspace, cx| {
9527 let path = path.await?;
9528
9529 let path = fs.canonicalize(&path).await.unwrap_or(path);
9530
9531 let mut items = workspace
9532 .update_in(cx, |workspace, window, cx| {
9533 workspace.open_paths(
9534 vec![path.to_path_buf()],
9535 OpenOptions {
9536 visible: Some(OpenVisible::None),
9537 ..Default::default()
9538 },
9539 None,
9540 window,
9541 cx,
9542 )
9543 })?
9544 .await;
9545 let item = items.pop().flatten();
9546 item.with_context(|| format!("path {path:?} is not a file"))?
9547 })
9548 })
9549 })?
9550 .await?
9551 .await
9552 })
9553}
9554
9555pub fn open_remote_project_with_new_connection(
9556 window: WindowHandle<MultiWorkspace>,
9557 remote_connection: Arc<dyn RemoteConnection>,
9558 cancel_rx: oneshot::Receiver<()>,
9559 delegate: Arc<dyn RemoteClientDelegate>,
9560 app_state: Arc<AppState>,
9561 paths: Vec<PathBuf>,
9562 cx: &mut App,
9563) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9564 cx.spawn(async move |cx| {
9565 let (workspace_id, serialized_workspace) =
9566 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9567 .await?;
9568
9569 let session = match cx
9570 .update(|cx| {
9571 remote::RemoteClient::new(
9572 ConnectionIdentifier::Workspace(workspace_id.0),
9573 remote_connection,
9574 cancel_rx,
9575 delegate,
9576 cx,
9577 )
9578 })
9579 .await?
9580 {
9581 Some(result) => result,
9582 None => return Ok(Vec::new()),
9583 };
9584
9585 let project = cx.update(|cx| {
9586 project::Project::remote(
9587 session,
9588 app_state.client.clone(),
9589 app_state.node_runtime.clone(),
9590 app_state.user_store.clone(),
9591 app_state.languages.clone(),
9592 app_state.fs.clone(),
9593 true,
9594 cx,
9595 )
9596 });
9597
9598 open_remote_project_inner(
9599 project,
9600 paths,
9601 workspace_id,
9602 serialized_workspace,
9603 app_state,
9604 window,
9605 cx,
9606 )
9607 .await
9608 })
9609}
9610
9611pub fn open_remote_project_with_existing_connection(
9612 connection_options: RemoteConnectionOptions,
9613 project: Entity<Project>,
9614 paths: Vec<PathBuf>,
9615 app_state: Arc<AppState>,
9616 window: WindowHandle<MultiWorkspace>,
9617 cx: &mut AsyncApp,
9618) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9619 cx.spawn(async move |cx| {
9620 let (workspace_id, serialized_workspace) =
9621 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9622
9623 open_remote_project_inner(
9624 project,
9625 paths,
9626 workspace_id,
9627 serialized_workspace,
9628 app_state,
9629 window,
9630 cx,
9631 )
9632 .await
9633 })
9634}
9635
9636async fn open_remote_project_inner(
9637 project: Entity<Project>,
9638 paths: Vec<PathBuf>,
9639 workspace_id: WorkspaceId,
9640 serialized_workspace: Option<SerializedWorkspace>,
9641 app_state: Arc<AppState>,
9642 window: WindowHandle<MultiWorkspace>,
9643 cx: &mut AsyncApp,
9644) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9645 let db = cx.update(|cx| WorkspaceDb::global(cx));
9646 let toolchains = db.toolchains(workspace_id).await?;
9647 for (toolchain, worktree_path, path) in toolchains {
9648 project
9649 .update(cx, |this, cx| {
9650 let Some(worktree_id) =
9651 this.find_worktree(&worktree_path, cx)
9652 .and_then(|(worktree, rel_path)| {
9653 if rel_path.is_empty() {
9654 Some(worktree.read(cx).id())
9655 } else {
9656 None
9657 }
9658 })
9659 else {
9660 return Task::ready(None);
9661 };
9662
9663 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9664 })
9665 .await;
9666 }
9667 let mut project_paths_to_open = vec![];
9668 let mut project_path_errors = vec![];
9669
9670 for path in paths {
9671 let result = cx
9672 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9673 .await;
9674 match result {
9675 Ok((_, project_path)) => {
9676 project_paths_to_open.push((path.clone(), Some(project_path)));
9677 }
9678 Err(error) => {
9679 project_path_errors.push(error);
9680 }
9681 };
9682 }
9683
9684 if project_paths_to_open.is_empty() {
9685 return Err(project_path_errors.pop().context("no paths given")?);
9686 }
9687
9688 let workspace = window.update(cx, |multi_workspace, window, cx| {
9689 telemetry::event!("SSH Project Opened");
9690
9691 let new_workspace = cx.new(|cx| {
9692 let mut workspace =
9693 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9694 workspace.update_history(cx);
9695
9696 if let Some(ref serialized) = serialized_workspace {
9697 workspace.centered_layout = serialized.centered_layout;
9698 }
9699
9700 workspace
9701 });
9702
9703 multi_workspace.activate(new_workspace.clone(), window, cx);
9704 new_workspace
9705 })?;
9706
9707 let items = window
9708 .update(cx, |_, window, cx| {
9709 window.activate_window();
9710 workspace.update(cx, |_workspace, cx| {
9711 open_items(serialized_workspace, project_paths_to_open, window, cx)
9712 })
9713 })?
9714 .await?;
9715
9716 workspace.update(cx, |workspace, cx| {
9717 for error in project_path_errors {
9718 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9719 if let Some(path) = error.error_tag("path") {
9720 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9721 }
9722 } else {
9723 workspace.show_error(&error, cx)
9724 }
9725 }
9726 });
9727
9728 Ok(items.into_iter().map(|item| item?.ok()).collect())
9729}
9730
9731fn deserialize_remote_project(
9732 connection_options: RemoteConnectionOptions,
9733 paths: Vec<PathBuf>,
9734 cx: &AsyncApp,
9735) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9736 let db = cx.update(|cx| WorkspaceDb::global(cx));
9737 cx.background_spawn(async move {
9738 let remote_connection_id = db
9739 .get_or_create_remote_connection(connection_options)
9740 .await?;
9741
9742 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9743
9744 let workspace_id = if let Some(workspace_id) =
9745 serialized_workspace.as_ref().map(|workspace| workspace.id)
9746 {
9747 workspace_id
9748 } else {
9749 db.next_id().await?
9750 };
9751
9752 Ok((workspace_id, serialized_workspace))
9753 })
9754}
9755
9756pub fn join_in_room_project(
9757 project_id: u64,
9758 follow_user_id: u64,
9759 app_state: Arc<AppState>,
9760 cx: &mut App,
9761) -> Task<Result<()>> {
9762 let windows = cx.windows();
9763 cx.spawn(async move |cx| {
9764 let existing_window_and_workspace: Option<(
9765 WindowHandle<MultiWorkspace>,
9766 Entity<Workspace>,
9767 )> = windows.into_iter().find_map(|window_handle| {
9768 window_handle
9769 .downcast::<MultiWorkspace>()
9770 .and_then(|window_handle| {
9771 window_handle
9772 .update(cx, |multi_workspace, _window, cx| {
9773 for workspace in multi_workspace.workspaces() {
9774 if workspace.read(cx).project().read(cx).remote_id()
9775 == Some(project_id)
9776 {
9777 return Some((window_handle, workspace.clone()));
9778 }
9779 }
9780 None
9781 })
9782 .unwrap_or(None)
9783 })
9784 });
9785
9786 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9787 existing_window_and_workspace
9788 {
9789 existing_window
9790 .update(cx, |multi_workspace, window, cx| {
9791 multi_workspace.activate(target_workspace, window, cx);
9792 })
9793 .ok();
9794 existing_window
9795 } else {
9796 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9797 let project = cx
9798 .update(|cx| {
9799 active_call.0.join_project(
9800 project_id,
9801 app_state.languages.clone(),
9802 app_state.fs.clone(),
9803 cx,
9804 )
9805 })
9806 .await?;
9807
9808 let window_bounds_override = window_bounds_env_override();
9809 cx.update(|cx| {
9810 let mut options = (app_state.build_window_options)(None, cx);
9811 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9812 cx.open_window(options, |window, cx| {
9813 let workspace = cx.new(|cx| {
9814 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9815 });
9816 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9817 })
9818 })?
9819 };
9820
9821 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9822 cx.activate(true);
9823 window.activate_window();
9824
9825 // We set the active workspace above, so this is the correct workspace.
9826 let workspace = multi_workspace.workspace().clone();
9827 workspace.update(cx, |workspace, cx| {
9828 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9829 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9830 .or_else(|| {
9831 // If we couldn't follow the given user, follow the host instead.
9832 let collaborator = workspace
9833 .project()
9834 .read(cx)
9835 .collaborators()
9836 .values()
9837 .find(|collaborator| collaborator.is_host)?;
9838 Some(collaborator.peer_id)
9839 });
9840
9841 if let Some(follow_peer_id) = follow_peer_id {
9842 workspace.follow(follow_peer_id, window, cx);
9843 }
9844 });
9845 })?;
9846
9847 anyhow::Ok(())
9848 })
9849}
9850
9851pub fn reload(cx: &mut App) {
9852 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9853 let mut workspace_windows = cx
9854 .windows()
9855 .into_iter()
9856 .filter_map(|window| window.downcast::<MultiWorkspace>())
9857 .collect::<Vec<_>>();
9858
9859 // If multiple windows have unsaved changes, and need a save prompt,
9860 // prompt in the active window before switching to a different window.
9861 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9862
9863 let mut prompt = None;
9864 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9865 prompt = window
9866 .update(cx, |_, window, cx| {
9867 window.prompt(
9868 PromptLevel::Info,
9869 "Are you sure you want to restart?",
9870 None,
9871 &["Restart", "Cancel"],
9872 cx,
9873 )
9874 })
9875 .ok();
9876 }
9877
9878 cx.spawn(async move |cx| {
9879 if let Some(prompt) = prompt {
9880 let answer = prompt.await?;
9881 if answer != 0 {
9882 return anyhow::Ok(());
9883 }
9884 }
9885
9886 // If the user cancels any save prompt, then keep the app open.
9887 for window in workspace_windows {
9888 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9889 let workspace = multi_workspace.workspace().clone();
9890 workspace.update(cx, |workspace, cx| {
9891 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9892 })
9893 }) && !should_close.await?
9894 {
9895 return anyhow::Ok(());
9896 }
9897 }
9898 cx.update(|cx| cx.restart());
9899 anyhow::Ok(())
9900 })
9901 .detach_and_log_err(cx);
9902}
9903
9904fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9905 let mut parts = value.split(',');
9906 let x: usize = parts.next()?.parse().ok()?;
9907 let y: usize = parts.next()?.parse().ok()?;
9908 Some(point(px(x as f32), px(y as f32)))
9909}
9910
9911fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9912 let mut parts = value.split(',');
9913 let width: usize = parts.next()?.parse().ok()?;
9914 let height: usize = parts.next()?.parse().ok()?;
9915 Some(size(px(width as f32), px(height as f32)))
9916}
9917
9918/// Add client-side decorations (rounded corners, shadows, resize handling) when
9919/// appropriate.
9920///
9921/// The `border_radius_tiling` parameter allows overriding which corners get
9922/// rounded, independently of the actual window tiling state. This is used
9923/// specifically for the workspace switcher sidebar: when the sidebar is open,
9924/// we want square corners on the left (so the sidebar appears flush with the
9925/// window edge) but we still need the shadow padding for proper visual
9926/// appearance. Unlike actual window tiling, this only affects border radius -
9927/// not padding or shadows.
9928pub fn client_side_decorations(
9929 element: impl IntoElement,
9930 window: &mut Window,
9931 cx: &mut App,
9932 border_radius_tiling: Tiling,
9933) -> Stateful<Div> {
9934 const BORDER_SIZE: Pixels = px(1.0);
9935 let decorations = window.window_decorations();
9936 let tiling = match decorations {
9937 Decorations::Server => Tiling::default(),
9938 Decorations::Client { tiling } => tiling,
9939 };
9940
9941 match decorations {
9942 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9943 Decorations::Server => window.set_client_inset(px(0.0)),
9944 }
9945
9946 struct GlobalResizeEdge(ResizeEdge);
9947 impl Global for GlobalResizeEdge {}
9948
9949 div()
9950 .id("window-backdrop")
9951 .bg(transparent_black())
9952 .map(|div| match decorations {
9953 Decorations::Server => div,
9954 Decorations::Client { .. } => div
9955 .when(
9956 !(tiling.top
9957 || tiling.right
9958 || border_radius_tiling.top
9959 || border_radius_tiling.right),
9960 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9961 )
9962 .when(
9963 !(tiling.top
9964 || tiling.left
9965 || border_radius_tiling.top
9966 || border_radius_tiling.left),
9967 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9968 )
9969 .when(
9970 !(tiling.bottom
9971 || tiling.right
9972 || border_radius_tiling.bottom
9973 || border_radius_tiling.right),
9974 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9975 )
9976 .when(
9977 !(tiling.bottom
9978 || tiling.left
9979 || border_radius_tiling.bottom
9980 || border_radius_tiling.left),
9981 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9982 )
9983 .when(!tiling.top, |div| {
9984 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9985 })
9986 .when(!tiling.bottom, |div| {
9987 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9988 })
9989 .when(!tiling.left, |div| {
9990 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9991 })
9992 .when(!tiling.right, |div| {
9993 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9994 })
9995 .on_mouse_move(move |e, window, cx| {
9996 let size = window.window_bounds().get_bounds().size;
9997 let pos = e.position;
9998
9999 let new_edge =
10000 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10001
10002 let edge = cx.try_global::<GlobalResizeEdge>();
10003 if new_edge != edge.map(|edge| edge.0) {
10004 window
10005 .window_handle()
10006 .update(cx, |workspace, _, cx| {
10007 cx.notify(workspace.entity_id());
10008 })
10009 .ok();
10010 }
10011 })
10012 .on_mouse_down(MouseButton::Left, move |e, window, _| {
10013 let size = window.window_bounds().get_bounds().size;
10014 let pos = e.position;
10015
10016 let edge = match resize_edge(
10017 pos,
10018 theme::CLIENT_SIDE_DECORATION_SHADOW,
10019 size,
10020 tiling,
10021 ) {
10022 Some(value) => value,
10023 None => return,
10024 };
10025
10026 window.start_window_resize(edge);
10027 }),
10028 })
10029 .size_full()
10030 .child(
10031 div()
10032 .cursor(CursorStyle::Arrow)
10033 .map(|div| match decorations {
10034 Decorations::Server => div,
10035 Decorations::Client { .. } => div
10036 .border_color(cx.theme().colors().border)
10037 .when(
10038 !(tiling.top
10039 || tiling.right
10040 || border_radius_tiling.top
10041 || border_radius_tiling.right),
10042 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10043 )
10044 .when(
10045 !(tiling.top
10046 || tiling.left
10047 || border_radius_tiling.top
10048 || border_radius_tiling.left),
10049 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10050 )
10051 .when(
10052 !(tiling.bottom
10053 || tiling.right
10054 || border_radius_tiling.bottom
10055 || border_radius_tiling.right),
10056 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10057 )
10058 .when(
10059 !(tiling.bottom
10060 || tiling.left
10061 || border_radius_tiling.bottom
10062 || border_radius_tiling.left),
10063 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10064 )
10065 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10066 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10067 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10068 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10069 .when(!tiling.is_tiled(), |div| {
10070 div.shadow(vec![gpui::BoxShadow {
10071 color: Hsla {
10072 h: 0.,
10073 s: 0.,
10074 l: 0.,
10075 a: 0.4,
10076 },
10077 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10078 spread_radius: px(0.),
10079 offset: point(px(0.0), px(0.0)),
10080 }])
10081 }),
10082 })
10083 .on_mouse_move(|_e, _, cx| {
10084 cx.stop_propagation();
10085 })
10086 .size_full()
10087 .child(element),
10088 )
10089 .map(|div| match decorations {
10090 Decorations::Server => div,
10091 Decorations::Client { tiling, .. } => div.child(
10092 canvas(
10093 |_bounds, window, _| {
10094 window.insert_hitbox(
10095 Bounds::new(
10096 point(px(0.0), px(0.0)),
10097 window.window_bounds().get_bounds().size,
10098 ),
10099 HitboxBehavior::Normal,
10100 )
10101 },
10102 move |_bounds, hitbox, window, cx| {
10103 let mouse = window.mouse_position();
10104 let size = window.window_bounds().get_bounds().size;
10105 let Some(edge) =
10106 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10107 else {
10108 return;
10109 };
10110 cx.set_global(GlobalResizeEdge(edge));
10111 window.set_cursor_style(
10112 match edge {
10113 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10114 ResizeEdge::Left | ResizeEdge::Right => {
10115 CursorStyle::ResizeLeftRight
10116 }
10117 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10118 CursorStyle::ResizeUpLeftDownRight
10119 }
10120 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10121 CursorStyle::ResizeUpRightDownLeft
10122 }
10123 },
10124 &hitbox,
10125 );
10126 },
10127 )
10128 .size_full()
10129 .absolute(),
10130 ),
10131 })
10132}
10133
10134fn resize_edge(
10135 pos: Point<Pixels>,
10136 shadow_size: Pixels,
10137 window_size: Size<Pixels>,
10138 tiling: Tiling,
10139) -> Option<ResizeEdge> {
10140 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10141 if bounds.contains(&pos) {
10142 return None;
10143 }
10144
10145 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10146 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10147 if !tiling.top && top_left_bounds.contains(&pos) {
10148 return Some(ResizeEdge::TopLeft);
10149 }
10150
10151 let top_right_bounds = Bounds::new(
10152 Point::new(window_size.width - corner_size.width, px(0.)),
10153 corner_size,
10154 );
10155 if !tiling.top && top_right_bounds.contains(&pos) {
10156 return Some(ResizeEdge::TopRight);
10157 }
10158
10159 let bottom_left_bounds = Bounds::new(
10160 Point::new(px(0.), window_size.height - corner_size.height),
10161 corner_size,
10162 );
10163 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10164 return Some(ResizeEdge::BottomLeft);
10165 }
10166
10167 let bottom_right_bounds = Bounds::new(
10168 Point::new(
10169 window_size.width - corner_size.width,
10170 window_size.height - corner_size.height,
10171 ),
10172 corner_size,
10173 );
10174 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10175 return Some(ResizeEdge::BottomRight);
10176 }
10177
10178 if !tiling.top && pos.y < shadow_size {
10179 Some(ResizeEdge::Top)
10180 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10181 Some(ResizeEdge::Bottom)
10182 } else if !tiling.left && pos.x < shadow_size {
10183 Some(ResizeEdge::Left)
10184 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10185 Some(ResizeEdge::Right)
10186 } else {
10187 None
10188 }
10189}
10190
10191fn join_pane_into_active(
10192 active_pane: &Entity<Pane>,
10193 pane: &Entity<Pane>,
10194 window: &mut Window,
10195 cx: &mut App,
10196) {
10197 if pane == active_pane {
10198 } else if pane.read(cx).items_len() == 0 {
10199 pane.update(cx, |_, cx| {
10200 cx.emit(pane::Event::Remove {
10201 focus_on_pane: None,
10202 });
10203 })
10204 } else {
10205 move_all_items(pane, active_pane, window, cx);
10206 }
10207}
10208
10209fn move_all_items(
10210 from_pane: &Entity<Pane>,
10211 to_pane: &Entity<Pane>,
10212 window: &mut Window,
10213 cx: &mut App,
10214) {
10215 let destination_is_different = from_pane != to_pane;
10216 let mut moved_items = 0;
10217 for (item_ix, item_handle) in from_pane
10218 .read(cx)
10219 .items()
10220 .enumerate()
10221 .map(|(ix, item)| (ix, item.clone()))
10222 .collect::<Vec<_>>()
10223 {
10224 let ix = item_ix - moved_items;
10225 if destination_is_different {
10226 // Close item from previous pane
10227 from_pane.update(cx, |source, cx| {
10228 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10229 });
10230 moved_items += 1;
10231 }
10232
10233 // This automatically removes duplicate items in the pane
10234 to_pane.update(cx, |destination, cx| {
10235 destination.add_item(item_handle, true, true, None, window, cx);
10236 window.focus(&destination.focus_handle(cx), cx)
10237 });
10238 }
10239}
10240
10241pub fn move_item(
10242 source: &Entity<Pane>,
10243 destination: &Entity<Pane>,
10244 item_id_to_move: EntityId,
10245 destination_index: usize,
10246 activate: bool,
10247 window: &mut Window,
10248 cx: &mut App,
10249) {
10250 let Some((item_ix, item_handle)) = source
10251 .read(cx)
10252 .items()
10253 .enumerate()
10254 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10255 .map(|(ix, item)| (ix, item.clone()))
10256 else {
10257 // Tab was closed during drag
10258 return;
10259 };
10260
10261 if source != destination {
10262 // Close item from previous pane
10263 source.update(cx, |source, cx| {
10264 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10265 });
10266 }
10267
10268 // This automatically removes duplicate items in the pane
10269 destination.update(cx, |destination, cx| {
10270 destination.add_item_inner(
10271 item_handle,
10272 activate,
10273 activate,
10274 activate,
10275 Some(destination_index),
10276 window,
10277 cx,
10278 );
10279 if activate {
10280 window.focus(&destination.focus_handle(cx), cx)
10281 }
10282 });
10283}
10284
10285pub fn move_active_item(
10286 source: &Entity<Pane>,
10287 destination: &Entity<Pane>,
10288 focus_destination: bool,
10289 close_if_empty: bool,
10290 window: &mut Window,
10291 cx: &mut App,
10292) {
10293 if source == destination {
10294 return;
10295 }
10296 let Some(active_item) = source.read(cx).active_item() else {
10297 return;
10298 };
10299 source.update(cx, |source_pane, cx| {
10300 let item_id = active_item.item_id();
10301 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10302 destination.update(cx, |target_pane, cx| {
10303 target_pane.add_item(
10304 active_item,
10305 focus_destination,
10306 focus_destination,
10307 Some(target_pane.items_len()),
10308 window,
10309 cx,
10310 );
10311 });
10312 });
10313}
10314
10315pub fn clone_active_item(
10316 workspace_id: Option<WorkspaceId>,
10317 source: &Entity<Pane>,
10318 destination: &Entity<Pane>,
10319 focus_destination: bool,
10320 window: &mut Window,
10321 cx: &mut App,
10322) {
10323 if source == destination {
10324 return;
10325 }
10326 let Some(active_item) = source.read(cx).active_item() else {
10327 return;
10328 };
10329 if !active_item.can_split(cx) {
10330 return;
10331 }
10332 let destination = destination.downgrade();
10333 let task = active_item.clone_on_split(workspace_id, window, cx);
10334 window
10335 .spawn(cx, async move |cx| {
10336 let Some(clone) = task.await else {
10337 return;
10338 };
10339 destination
10340 .update_in(cx, |target_pane, window, cx| {
10341 target_pane.add_item(
10342 clone,
10343 focus_destination,
10344 focus_destination,
10345 Some(target_pane.items_len()),
10346 window,
10347 cx,
10348 );
10349 })
10350 .log_err();
10351 })
10352 .detach();
10353}
10354
10355#[derive(Debug)]
10356pub struct WorkspacePosition {
10357 pub window_bounds: Option<WindowBounds>,
10358 pub display: Option<Uuid>,
10359 pub centered_layout: bool,
10360}
10361
10362pub fn remote_workspace_position_from_db(
10363 connection_options: RemoteConnectionOptions,
10364 paths_to_open: &[PathBuf],
10365 cx: &App,
10366) -> Task<Result<WorkspacePosition>> {
10367 let paths = paths_to_open.to_vec();
10368 let db = WorkspaceDb::global(cx);
10369 let kvp = db::kvp::KeyValueStore::global(cx);
10370
10371 cx.background_spawn(async move {
10372 let remote_connection_id = db
10373 .get_or_create_remote_connection(connection_options)
10374 .await
10375 .context("fetching serialized ssh project")?;
10376 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10377
10378 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10379 (Some(WindowBounds::Windowed(bounds)), None)
10380 } else {
10381 let restorable_bounds = serialized_workspace
10382 .as_ref()
10383 .and_then(|workspace| {
10384 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10385 })
10386 .or_else(|| persistence::read_default_window_bounds(&kvp));
10387
10388 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10389 (Some(serialized_bounds), Some(serialized_display))
10390 } else {
10391 (None, None)
10392 }
10393 };
10394
10395 let centered_layout = serialized_workspace
10396 .as_ref()
10397 .map(|w| w.centered_layout)
10398 .unwrap_or(false);
10399
10400 Ok(WorkspacePosition {
10401 window_bounds,
10402 display,
10403 centered_layout,
10404 })
10405 })
10406}
10407
10408pub fn with_active_or_new_workspace(
10409 cx: &mut App,
10410 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10411) {
10412 match cx
10413 .active_window()
10414 .and_then(|w| w.downcast::<MultiWorkspace>())
10415 {
10416 Some(multi_workspace) => {
10417 cx.defer(move |cx| {
10418 multi_workspace
10419 .update(cx, |multi_workspace, window, cx| {
10420 let workspace = multi_workspace.workspace().clone();
10421 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10422 })
10423 .log_err();
10424 });
10425 }
10426 None => {
10427 let app_state = AppState::global(cx);
10428 open_new(
10429 OpenOptions::default(),
10430 app_state,
10431 cx,
10432 move |workspace, window, cx| f(workspace, window, cx),
10433 )
10434 .detach_and_log_err(cx);
10435 }
10436 }
10437}
10438
10439/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10440/// key. This migration path only runs once per panel per workspace.
10441fn load_legacy_panel_size(
10442 panel_key: &str,
10443 dock_position: DockPosition,
10444 workspace: &Workspace,
10445 cx: &mut App,
10446) -> Option<Pixels> {
10447 #[derive(Deserialize)]
10448 struct LegacyPanelState {
10449 #[serde(default)]
10450 width: Option<Pixels>,
10451 #[serde(default)]
10452 height: Option<Pixels>,
10453 }
10454
10455 let workspace_id = workspace
10456 .database_id()
10457 .map(|id| i64::from(id).to_string())
10458 .or_else(|| workspace.session_id())?;
10459
10460 let legacy_key = match panel_key {
10461 "ProjectPanel" => {
10462 format!("{}-{:?}", "ProjectPanel", workspace_id)
10463 }
10464 "OutlinePanel" => {
10465 format!("{}-{:?}", "OutlinePanel", workspace_id)
10466 }
10467 "GitPanel" => {
10468 format!("{}-{:?}", "GitPanel", workspace_id)
10469 }
10470 "TerminalPanel" => {
10471 format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10472 }
10473 _ => return None,
10474 };
10475
10476 let kvp = db::kvp::KeyValueStore::global(cx);
10477 let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10478 let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10479 let size = match dock_position {
10480 DockPosition::Bottom => state.height,
10481 DockPosition::Left | DockPosition::Right => state.width,
10482 }?;
10483
10484 cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10485 .detach_and_log_err(cx);
10486
10487 Some(size)
10488}
10489
10490#[cfg(test)]
10491mod tests {
10492 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10493
10494 use super::*;
10495 use crate::{
10496 dock::{PanelEvent, test::TestPanel},
10497 item::{
10498 ItemBufferKind, ItemEvent,
10499 test::{TestItem, TestProjectItem},
10500 },
10501 };
10502 use fs::FakeFs;
10503 use gpui::{
10504 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10505 UpdateGlobal, VisualTestContext, px,
10506 };
10507 use project::{Project, ProjectEntryId};
10508 use serde_json::json;
10509 use settings::SettingsStore;
10510 use util::path;
10511 use util::rel_path::rel_path;
10512
10513 #[gpui::test]
10514 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10515 init_test(cx);
10516
10517 let fs = FakeFs::new(cx.executor());
10518 let project = Project::test(fs, [], cx).await;
10519 let (workspace, cx) =
10520 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10521
10522 // Adding an item with no ambiguity renders the tab without detail.
10523 let item1 = cx.new(|cx| {
10524 let mut item = TestItem::new(cx);
10525 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10526 item
10527 });
10528 workspace.update_in(cx, |workspace, window, cx| {
10529 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10530 });
10531 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10532
10533 // Adding an item that creates ambiguity increases the level of detail on
10534 // both tabs.
10535 let item2 = cx.new_window_entity(|_window, cx| {
10536 let mut item = TestItem::new(cx);
10537 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10538 item
10539 });
10540 workspace.update_in(cx, |workspace, window, cx| {
10541 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10542 });
10543 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10544 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10545
10546 // Adding an item that creates ambiguity increases the level of detail only
10547 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10548 // we stop at the highest detail available.
10549 let item3 = cx.new(|cx| {
10550 let mut item = TestItem::new(cx);
10551 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10552 item
10553 });
10554 workspace.update_in(cx, |workspace, window, cx| {
10555 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10556 });
10557 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10558 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10559 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10560 }
10561
10562 #[gpui::test]
10563 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10564 init_test(cx);
10565
10566 let fs = FakeFs::new(cx.executor());
10567 fs.insert_tree(
10568 "/root1",
10569 json!({
10570 "one.txt": "",
10571 "two.txt": "",
10572 }),
10573 )
10574 .await;
10575 fs.insert_tree(
10576 "/root2",
10577 json!({
10578 "three.txt": "",
10579 }),
10580 )
10581 .await;
10582
10583 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10584 let (workspace, cx) =
10585 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10586 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10587 let worktree_id = project.update(cx, |project, cx| {
10588 project.worktrees(cx).next().unwrap().read(cx).id()
10589 });
10590
10591 let item1 = cx.new(|cx| {
10592 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10593 });
10594 let item2 = cx.new(|cx| {
10595 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10596 });
10597
10598 // Add an item to an empty pane
10599 workspace.update_in(cx, |workspace, window, cx| {
10600 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10601 });
10602 project.update(cx, |project, cx| {
10603 assert_eq!(
10604 project.active_entry(),
10605 project
10606 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10607 .map(|e| e.id)
10608 );
10609 });
10610 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10611
10612 // Add a second item to a non-empty pane
10613 workspace.update_in(cx, |workspace, window, cx| {
10614 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10615 });
10616 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10617 project.update(cx, |project, cx| {
10618 assert_eq!(
10619 project.active_entry(),
10620 project
10621 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10622 .map(|e| e.id)
10623 );
10624 });
10625
10626 // Close the active item
10627 pane.update_in(cx, |pane, window, cx| {
10628 pane.close_active_item(&Default::default(), window, cx)
10629 })
10630 .await
10631 .unwrap();
10632 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10633 project.update(cx, |project, cx| {
10634 assert_eq!(
10635 project.active_entry(),
10636 project
10637 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10638 .map(|e| e.id)
10639 );
10640 });
10641
10642 // Add a project folder
10643 project
10644 .update(cx, |project, cx| {
10645 project.find_or_create_worktree("root2", true, cx)
10646 })
10647 .await
10648 .unwrap();
10649 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10650
10651 // Remove a project folder
10652 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10653 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10654 }
10655
10656 #[gpui::test]
10657 async fn test_close_window(cx: &mut TestAppContext) {
10658 init_test(cx);
10659
10660 let fs = FakeFs::new(cx.executor());
10661 fs.insert_tree("/root", json!({ "one": "" })).await;
10662
10663 let project = Project::test(fs, ["root".as_ref()], cx).await;
10664 let (workspace, cx) =
10665 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10666
10667 // When there are no dirty items, there's nothing to do.
10668 let item1 = cx.new(TestItem::new);
10669 workspace.update_in(cx, |w, window, cx| {
10670 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10671 });
10672 let task = workspace.update_in(cx, |w, window, cx| {
10673 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10674 });
10675 assert!(task.await.unwrap());
10676
10677 // When there are dirty untitled items, prompt to save each one. If the user
10678 // cancels any prompt, then abort.
10679 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10680 let item3 = cx.new(|cx| {
10681 TestItem::new(cx)
10682 .with_dirty(true)
10683 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10684 });
10685 workspace.update_in(cx, |w, window, cx| {
10686 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10687 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10688 });
10689 let task = workspace.update_in(cx, |w, window, cx| {
10690 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10691 });
10692 cx.executor().run_until_parked();
10693 cx.simulate_prompt_answer("Cancel"); // cancel save all
10694 cx.executor().run_until_parked();
10695 assert!(!cx.has_pending_prompt());
10696 assert!(!task.await.unwrap());
10697 }
10698
10699 #[gpui::test]
10700 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10701 init_test(cx);
10702
10703 let fs = FakeFs::new(cx.executor());
10704 fs.insert_tree("/root", json!({ "one": "" })).await;
10705
10706 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10707 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10708 let multi_workspace_handle =
10709 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10710 cx.run_until_parked();
10711
10712 let workspace_a = multi_workspace_handle
10713 .read_with(cx, |mw, _| mw.workspace().clone())
10714 .unwrap();
10715
10716 let workspace_b = multi_workspace_handle
10717 .update(cx, |mw, window, cx| {
10718 mw.test_add_workspace(project_b, window, cx)
10719 })
10720 .unwrap();
10721
10722 // Activate workspace A
10723 multi_workspace_handle
10724 .update(cx, |mw, window, cx| {
10725 let workspace = mw.workspaces()[0].clone();
10726 mw.activate(workspace, window, cx);
10727 })
10728 .unwrap();
10729
10730 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10731
10732 // Workspace A has a clean item
10733 let item_a = cx.new(TestItem::new);
10734 workspace_a.update_in(cx, |w, window, cx| {
10735 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10736 });
10737
10738 // Workspace B has a dirty item
10739 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10740 workspace_b.update_in(cx, |w, window, cx| {
10741 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10742 });
10743
10744 // Verify workspace A is active
10745 multi_workspace_handle
10746 .read_with(cx, |mw, _| {
10747 assert_eq!(mw.active_workspace_index(), 0);
10748 })
10749 .unwrap();
10750
10751 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10752 multi_workspace_handle
10753 .update(cx, |mw, window, cx| {
10754 mw.close_window(&CloseWindow, window, cx);
10755 })
10756 .unwrap();
10757 cx.run_until_parked();
10758
10759 // Workspace B should now be active since it has dirty items that need attention
10760 multi_workspace_handle
10761 .read_with(cx, |mw, _| {
10762 assert_eq!(
10763 mw.active_workspace_index(),
10764 1,
10765 "workspace B should be activated when it prompts"
10766 );
10767 })
10768 .unwrap();
10769
10770 // User cancels the save prompt from workspace B
10771 cx.simulate_prompt_answer("Cancel");
10772 cx.run_until_parked();
10773
10774 // Window should still exist because workspace B's close was cancelled
10775 assert!(
10776 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10777 "window should still exist after cancelling one workspace's close"
10778 );
10779 }
10780
10781 #[gpui::test]
10782 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10783 init_test(cx);
10784
10785 // Register TestItem as a serializable item
10786 cx.update(|cx| {
10787 register_serializable_item::<TestItem>(cx);
10788 });
10789
10790 let fs = FakeFs::new(cx.executor());
10791 fs.insert_tree("/root", json!({ "one": "" })).await;
10792
10793 let project = Project::test(fs, ["root".as_ref()], cx).await;
10794 let (workspace, cx) =
10795 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10796
10797 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10798 let item1 = cx.new(|cx| {
10799 TestItem::new(cx)
10800 .with_dirty(true)
10801 .with_serialize(|| Some(Task::ready(Ok(()))))
10802 });
10803 let item2 = cx.new(|cx| {
10804 TestItem::new(cx)
10805 .with_dirty(true)
10806 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10807 .with_serialize(|| Some(Task::ready(Ok(()))))
10808 });
10809 workspace.update_in(cx, |w, window, cx| {
10810 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10811 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10812 });
10813 let task = workspace.update_in(cx, |w, window, cx| {
10814 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10815 });
10816 assert!(task.await.unwrap());
10817 }
10818
10819 #[gpui::test]
10820 async fn test_close_pane_items(cx: &mut TestAppContext) {
10821 init_test(cx);
10822
10823 let fs = FakeFs::new(cx.executor());
10824
10825 let project = Project::test(fs, None, cx).await;
10826 let (workspace, cx) =
10827 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10828
10829 let item1 = cx.new(|cx| {
10830 TestItem::new(cx)
10831 .with_dirty(true)
10832 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10833 });
10834 let item2 = cx.new(|cx| {
10835 TestItem::new(cx)
10836 .with_dirty(true)
10837 .with_conflict(true)
10838 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10839 });
10840 let item3 = cx.new(|cx| {
10841 TestItem::new(cx)
10842 .with_dirty(true)
10843 .with_conflict(true)
10844 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10845 });
10846 let item4 = cx.new(|cx| {
10847 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10848 let project_item = TestProjectItem::new_untitled(cx);
10849 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10850 project_item
10851 }])
10852 });
10853 let pane = workspace.update_in(cx, |workspace, window, cx| {
10854 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10855 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10856 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10857 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10858 workspace.active_pane().clone()
10859 });
10860
10861 let close_items = pane.update_in(cx, |pane, window, cx| {
10862 pane.activate_item(1, true, true, window, cx);
10863 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10864 let item1_id = item1.item_id();
10865 let item3_id = item3.item_id();
10866 let item4_id = item4.item_id();
10867 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10868 [item1_id, item3_id, item4_id].contains(&id)
10869 })
10870 });
10871 cx.executor().run_until_parked();
10872
10873 assert!(cx.has_pending_prompt());
10874 cx.simulate_prompt_answer("Save all");
10875
10876 cx.executor().run_until_parked();
10877
10878 // Item 1 is saved. There's a prompt to save item 3.
10879 pane.update(cx, |pane, cx| {
10880 assert_eq!(item1.read(cx).save_count, 1);
10881 assert_eq!(item1.read(cx).save_as_count, 0);
10882 assert_eq!(item1.read(cx).reload_count, 0);
10883 assert_eq!(pane.items_len(), 3);
10884 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10885 });
10886 assert!(cx.has_pending_prompt());
10887
10888 // Cancel saving item 3.
10889 cx.simulate_prompt_answer("Discard");
10890 cx.executor().run_until_parked();
10891
10892 // Item 3 is reloaded. There's a prompt to save item 4.
10893 pane.update(cx, |pane, cx| {
10894 assert_eq!(item3.read(cx).save_count, 0);
10895 assert_eq!(item3.read(cx).save_as_count, 0);
10896 assert_eq!(item3.read(cx).reload_count, 1);
10897 assert_eq!(pane.items_len(), 2);
10898 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10899 });
10900
10901 // There's a prompt for a path for item 4.
10902 cx.simulate_new_path_selection(|_| Some(Default::default()));
10903 close_items.await.unwrap();
10904
10905 // The requested items are closed.
10906 pane.update(cx, |pane, cx| {
10907 assert_eq!(item4.read(cx).save_count, 0);
10908 assert_eq!(item4.read(cx).save_as_count, 1);
10909 assert_eq!(item4.read(cx).reload_count, 0);
10910 assert_eq!(pane.items_len(), 1);
10911 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10912 });
10913 }
10914
10915 #[gpui::test]
10916 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10917 init_test(cx);
10918
10919 let fs = FakeFs::new(cx.executor());
10920 let project = Project::test(fs, [], cx).await;
10921 let (workspace, cx) =
10922 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10923
10924 // Create several workspace items with single project entries, and two
10925 // workspace items with multiple project entries.
10926 let single_entry_items = (0..=4)
10927 .map(|project_entry_id| {
10928 cx.new(|cx| {
10929 TestItem::new(cx)
10930 .with_dirty(true)
10931 .with_project_items(&[dirty_project_item(
10932 project_entry_id,
10933 &format!("{project_entry_id}.txt"),
10934 cx,
10935 )])
10936 })
10937 })
10938 .collect::<Vec<_>>();
10939 let item_2_3 = cx.new(|cx| {
10940 TestItem::new(cx)
10941 .with_dirty(true)
10942 .with_buffer_kind(ItemBufferKind::Multibuffer)
10943 .with_project_items(&[
10944 single_entry_items[2].read(cx).project_items[0].clone(),
10945 single_entry_items[3].read(cx).project_items[0].clone(),
10946 ])
10947 });
10948 let item_3_4 = cx.new(|cx| {
10949 TestItem::new(cx)
10950 .with_dirty(true)
10951 .with_buffer_kind(ItemBufferKind::Multibuffer)
10952 .with_project_items(&[
10953 single_entry_items[3].read(cx).project_items[0].clone(),
10954 single_entry_items[4].read(cx).project_items[0].clone(),
10955 ])
10956 });
10957
10958 // Create two panes that contain the following project entries:
10959 // left pane:
10960 // multi-entry items: (2, 3)
10961 // single-entry items: 0, 2, 3, 4
10962 // right pane:
10963 // single-entry items: 4, 1
10964 // multi-entry items: (3, 4)
10965 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10966 let left_pane = workspace.active_pane().clone();
10967 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10968 workspace.add_item_to_active_pane(
10969 single_entry_items[0].boxed_clone(),
10970 None,
10971 true,
10972 window,
10973 cx,
10974 );
10975 workspace.add_item_to_active_pane(
10976 single_entry_items[2].boxed_clone(),
10977 None,
10978 true,
10979 window,
10980 cx,
10981 );
10982 workspace.add_item_to_active_pane(
10983 single_entry_items[3].boxed_clone(),
10984 None,
10985 true,
10986 window,
10987 cx,
10988 );
10989 workspace.add_item_to_active_pane(
10990 single_entry_items[4].boxed_clone(),
10991 None,
10992 true,
10993 window,
10994 cx,
10995 );
10996
10997 let right_pane =
10998 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10999
11000 let boxed_clone = single_entry_items[1].boxed_clone();
11001 let right_pane = window.spawn(cx, async move |cx| {
11002 right_pane.await.inspect(|right_pane| {
11003 right_pane
11004 .update_in(cx, |pane, window, cx| {
11005 pane.add_item(boxed_clone, true, true, None, window, cx);
11006 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11007 })
11008 .unwrap();
11009 })
11010 });
11011
11012 (left_pane, right_pane)
11013 });
11014 let right_pane = right_pane.await.unwrap();
11015 cx.focus(&right_pane);
11016
11017 let close = right_pane.update_in(cx, |pane, window, cx| {
11018 pane.close_all_items(&CloseAllItems::default(), window, cx)
11019 .unwrap()
11020 });
11021 cx.executor().run_until_parked();
11022
11023 let msg = cx.pending_prompt().unwrap().0;
11024 assert!(msg.contains("1.txt"));
11025 assert!(!msg.contains("2.txt"));
11026 assert!(!msg.contains("3.txt"));
11027 assert!(!msg.contains("4.txt"));
11028
11029 // With best-effort close, cancelling item 1 keeps it open but items 4
11030 // and (3,4) still close since their entries exist in left pane.
11031 cx.simulate_prompt_answer("Cancel");
11032 close.await;
11033
11034 right_pane.read_with(cx, |pane, _| {
11035 assert_eq!(pane.items_len(), 1);
11036 });
11037
11038 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11039 left_pane
11040 .update_in(cx, |left_pane, window, cx| {
11041 left_pane.close_item_by_id(
11042 single_entry_items[3].entity_id(),
11043 SaveIntent::Skip,
11044 window,
11045 cx,
11046 )
11047 })
11048 .await
11049 .unwrap();
11050
11051 let close = left_pane.update_in(cx, |pane, window, cx| {
11052 pane.close_all_items(&CloseAllItems::default(), window, cx)
11053 .unwrap()
11054 });
11055 cx.executor().run_until_parked();
11056
11057 let details = cx.pending_prompt().unwrap().1;
11058 assert!(details.contains("0.txt"));
11059 assert!(details.contains("3.txt"));
11060 assert!(details.contains("4.txt"));
11061 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11062 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11063 // assert!(!details.contains("2.txt"));
11064
11065 cx.simulate_prompt_answer("Save all");
11066 cx.executor().run_until_parked();
11067 close.await;
11068
11069 left_pane.read_with(cx, |pane, _| {
11070 assert_eq!(pane.items_len(), 0);
11071 });
11072 }
11073
11074 #[gpui::test]
11075 async fn test_autosave(cx: &mut gpui::TestAppContext) {
11076 init_test(cx);
11077
11078 let fs = FakeFs::new(cx.executor());
11079 let project = Project::test(fs, [], cx).await;
11080 let (workspace, cx) =
11081 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11082 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11083
11084 let item = cx.new(|cx| {
11085 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11086 });
11087 let item_id = item.entity_id();
11088 workspace.update_in(cx, |workspace, window, cx| {
11089 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11090 });
11091
11092 // Autosave on window change.
11093 item.update(cx, |item, cx| {
11094 SettingsStore::update_global(cx, |settings, cx| {
11095 settings.update_user_settings(cx, |settings| {
11096 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11097 })
11098 });
11099 item.is_dirty = true;
11100 });
11101
11102 // Deactivating the window saves the file.
11103 cx.deactivate_window();
11104 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11105
11106 // Re-activating the window doesn't save the file.
11107 cx.update(|window, _| window.activate_window());
11108 cx.executor().run_until_parked();
11109 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11110
11111 // Autosave on focus change.
11112 item.update_in(cx, |item, window, cx| {
11113 cx.focus_self(window);
11114 SettingsStore::update_global(cx, |settings, cx| {
11115 settings.update_user_settings(cx, |settings| {
11116 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11117 })
11118 });
11119 item.is_dirty = true;
11120 });
11121 // Blurring the item saves the file.
11122 item.update_in(cx, |_, window, _| window.blur());
11123 cx.executor().run_until_parked();
11124 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11125
11126 // Deactivating the window still saves the file.
11127 item.update_in(cx, |item, window, cx| {
11128 cx.focus_self(window);
11129 item.is_dirty = true;
11130 });
11131 cx.deactivate_window();
11132 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11133
11134 // Autosave after delay.
11135 item.update(cx, |item, cx| {
11136 SettingsStore::update_global(cx, |settings, cx| {
11137 settings.update_user_settings(cx, |settings| {
11138 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11139 milliseconds: 500.into(),
11140 });
11141 })
11142 });
11143 item.is_dirty = true;
11144 cx.emit(ItemEvent::Edit);
11145 });
11146
11147 // Delay hasn't fully expired, so the file is still dirty and unsaved.
11148 cx.executor().advance_clock(Duration::from_millis(250));
11149 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11150
11151 // After delay expires, the file is saved.
11152 cx.executor().advance_clock(Duration::from_millis(250));
11153 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11154
11155 // Autosave after delay, should save earlier than delay if tab is closed
11156 item.update(cx, |item, cx| {
11157 item.is_dirty = true;
11158 cx.emit(ItemEvent::Edit);
11159 });
11160 cx.executor().advance_clock(Duration::from_millis(250));
11161 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11162
11163 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11164 pane.update_in(cx, |pane, window, cx| {
11165 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11166 })
11167 .await
11168 .unwrap();
11169 assert!(!cx.has_pending_prompt());
11170 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11171
11172 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11173 workspace.update_in(cx, |workspace, window, cx| {
11174 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11175 });
11176 item.update_in(cx, |item, _window, cx| {
11177 item.is_dirty = true;
11178 for project_item in &mut item.project_items {
11179 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11180 }
11181 });
11182 cx.run_until_parked();
11183 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11184
11185 // Autosave on focus change, ensuring closing the tab counts as such.
11186 item.update(cx, |item, cx| {
11187 SettingsStore::update_global(cx, |settings, cx| {
11188 settings.update_user_settings(cx, |settings| {
11189 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11190 })
11191 });
11192 item.is_dirty = true;
11193 for project_item in &mut item.project_items {
11194 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11195 }
11196 });
11197
11198 pane.update_in(cx, |pane, window, cx| {
11199 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11200 })
11201 .await
11202 .unwrap();
11203 assert!(!cx.has_pending_prompt());
11204 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11205
11206 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11207 workspace.update_in(cx, |workspace, window, cx| {
11208 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11209 });
11210 item.update_in(cx, |item, window, cx| {
11211 item.project_items[0].update(cx, |item, _| {
11212 item.entry_id = None;
11213 });
11214 item.is_dirty = true;
11215 window.blur();
11216 });
11217 cx.run_until_parked();
11218 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11219
11220 // Ensure autosave is prevented for deleted files also when closing the buffer.
11221 let _close_items = pane.update_in(cx, |pane, window, cx| {
11222 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11223 });
11224 cx.run_until_parked();
11225 assert!(cx.has_pending_prompt());
11226 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11227 }
11228
11229 #[gpui::test]
11230 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11231 init_test(cx);
11232
11233 let fs = FakeFs::new(cx.executor());
11234 let project = Project::test(fs, [], cx).await;
11235 let (workspace, cx) =
11236 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11237
11238 // Create a multibuffer-like item with two child focus handles,
11239 // simulating individual buffer editors within a multibuffer.
11240 let item = cx.new(|cx| {
11241 TestItem::new(cx)
11242 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11243 .with_child_focus_handles(2, cx)
11244 });
11245 workspace.update_in(cx, |workspace, window, cx| {
11246 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11247 });
11248
11249 // Set autosave to OnFocusChange and focus the first child handle,
11250 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11251 item.update_in(cx, |item, window, cx| {
11252 SettingsStore::update_global(cx, |settings, cx| {
11253 settings.update_user_settings(cx, |settings| {
11254 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11255 })
11256 });
11257 item.is_dirty = true;
11258 window.focus(&item.child_focus_handles[0], cx);
11259 });
11260 cx.executor().run_until_parked();
11261 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11262
11263 // Moving focus from one child to another within the same item should
11264 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11265 item.update_in(cx, |item, window, cx| {
11266 window.focus(&item.child_focus_handles[1], cx);
11267 });
11268 cx.executor().run_until_parked();
11269 item.read_with(cx, |item, _| {
11270 assert_eq!(
11271 item.save_count, 0,
11272 "Switching focus between children within the same item should not autosave"
11273 );
11274 });
11275
11276 // Blurring the item saves the file. This is the core regression scenario:
11277 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11278 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11279 // the leaf is always a child focus handle, so `on_blur` never detected
11280 // focus leaving the item.
11281 item.update_in(cx, |_, window, _| window.blur());
11282 cx.executor().run_until_parked();
11283 item.read_with(cx, |item, _| {
11284 assert_eq!(
11285 item.save_count, 1,
11286 "Blurring should trigger autosave when focus was on a child of the item"
11287 );
11288 });
11289
11290 // Deactivating the window should also trigger autosave when a child of
11291 // the multibuffer item currently owns focus.
11292 item.update_in(cx, |item, window, cx| {
11293 item.is_dirty = true;
11294 window.focus(&item.child_focus_handles[0], cx);
11295 });
11296 cx.executor().run_until_parked();
11297 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11298
11299 cx.deactivate_window();
11300 item.read_with(cx, |item, _| {
11301 assert_eq!(
11302 item.save_count, 2,
11303 "Deactivating window should trigger autosave when focus was on a child"
11304 );
11305 });
11306 }
11307
11308 #[gpui::test]
11309 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11310 init_test(cx);
11311
11312 let fs = FakeFs::new(cx.executor());
11313
11314 let project = Project::test(fs, [], cx).await;
11315 let (workspace, cx) =
11316 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11317
11318 let item = cx.new(|cx| {
11319 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11320 });
11321 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11322 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11323 let toolbar_notify_count = Rc::new(RefCell::new(0));
11324
11325 workspace.update_in(cx, |workspace, window, cx| {
11326 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11327 let toolbar_notification_count = toolbar_notify_count.clone();
11328 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11329 *toolbar_notification_count.borrow_mut() += 1
11330 })
11331 .detach();
11332 });
11333
11334 pane.read_with(cx, |pane, _| {
11335 assert!(!pane.can_navigate_backward());
11336 assert!(!pane.can_navigate_forward());
11337 });
11338
11339 item.update_in(cx, |item, _, cx| {
11340 item.set_state("one".to_string(), cx);
11341 });
11342
11343 // Toolbar must be notified to re-render the navigation buttons
11344 assert_eq!(*toolbar_notify_count.borrow(), 1);
11345
11346 pane.read_with(cx, |pane, _| {
11347 assert!(pane.can_navigate_backward());
11348 assert!(!pane.can_navigate_forward());
11349 });
11350
11351 workspace
11352 .update_in(cx, |workspace, window, cx| {
11353 workspace.go_back(pane.downgrade(), window, cx)
11354 })
11355 .await
11356 .unwrap();
11357
11358 assert_eq!(*toolbar_notify_count.borrow(), 2);
11359 pane.read_with(cx, |pane, _| {
11360 assert!(!pane.can_navigate_backward());
11361 assert!(pane.can_navigate_forward());
11362 });
11363 }
11364
11365 /// Tests that the navigation history deduplicates entries for the same item.
11366 ///
11367 /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11368 /// the navigation history deduplicates by keeping only the most recent visit to each item,
11369 /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11370 /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11371 /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11372 ///
11373 /// This behavior prevents the navigation history from growing unnecessarily large and provides
11374 /// a better user experience by eliminating redundant navigation steps when jumping between files.
11375 #[gpui::test]
11376 async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11377 init_test(cx);
11378
11379 let fs = FakeFs::new(cx.executor());
11380 let project = Project::test(fs, [], cx).await;
11381 let (workspace, cx) =
11382 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11383
11384 let item_a = cx.new(|cx| {
11385 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11386 });
11387 let item_b = cx.new(|cx| {
11388 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11389 });
11390 let item_c = cx.new(|cx| {
11391 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11392 });
11393
11394 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11395
11396 workspace.update_in(cx, |workspace, window, cx| {
11397 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11398 workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11399 workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11400 });
11401
11402 workspace.update_in(cx, |workspace, window, cx| {
11403 workspace.activate_item(&item_a, false, false, window, cx);
11404 });
11405 cx.run_until_parked();
11406
11407 workspace.update_in(cx, |workspace, window, cx| {
11408 workspace.activate_item(&item_b, false, false, window, cx);
11409 });
11410 cx.run_until_parked();
11411
11412 workspace.update_in(cx, |workspace, window, cx| {
11413 workspace.activate_item(&item_a, false, false, window, cx);
11414 });
11415 cx.run_until_parked();
11416
11417 workspace.update_in(cx, |workspace, window, cx| {
11418 workspace.activate_item(&item_b, false, false, window, cx);
11419 });
11420 cx.run_until_parked();
11421
11422 workspace.update_in(cx, |workspace, window, cx| {
11423 workspace.activate_item(&item_a, false, false, window, cx);
11424 });
11425 cx.run_until_parked();
11426
11427 workspace.update_in(cx, |workspace, window, cx| {
11428 workspace.activate_item(&item_b, false, false, window, cx);
11429 });
11430 cx.run_until_parked();
11431
11432 workspace.update_in(cx, |workspace, window, cx| {
11433 workspace.activate_item(&item_c, false, false, window, cx);
11434 });
11435 cx.run_until_parked();
11436
11437 let backward_count = pane.read_with(cx, |pane, cx| {
11438 let mut count = 0;
11439 pane.nav_history().for_each_entry(cx, &mut |_, _| {
11440 count += 1;
11441 });
11442 count
11443 });
11444 assert!(
11445 backward_count <= 4,
11446 "Should have at most 4 entries, got {}",
11447 backward_count
11448 );
11449
11450 workspace
11451 .update_in(cx, |workspace, window, cx| {
11452 workspace.go_back(pane.downgrade(), window, cx)
11453 })
11454 .await
11455 .unwrap();
11456
11457 let active_item = workspace.read_with(cx, |workspace, cx| {
11458 workspace.active_item(cx).unwrap().item_id()
11459 });
11460 assert_eq!(
11461 active_item,
11462 item_b.entity_id(),
11463 "After first go_back, should be at item B"
11464 );
11465
11466 workspace
11467 .update_in(cx, |workspace, window, cx| {
11468 workspace.go_back(pane.downgrade(), window, cx)
11469 })
11470 .await
11471 .unwrap();
11472
11473 let active_item = workspace.read_with(cx, |workspace, cx| {
11474 workspace.active_item(cx).unwrap().item_id()
11475 });
11476 assert_eq!(
11477 active_item,
11478 item_a.entity_id(),
11479 "After second go_back, should be at item A"
11480 );
11481
11482 pane.read_with(cx, |pane, _| {
11483 assert!(pane.can_navigate_forward(), "Should be able to go forward");
11484 });
11485 }
11486
11487 #[gpui::test]
11488 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11489 init_test(cx);
11490 let fs = FakeFs::new(cx.executor());
11491 let project = Project::test(fs, [], cx).await;
11492 let (multi_workspace, cx) =
11493 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11494 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11495
11496 workspace.update_in(cx, |workspace, window, cx| {
11497 let first_item = cx.new(|cx| {
11498 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11499 });
11500 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11501 workspace.split_pane(
11502 workspace.active_pane().clone(),
11503 SplitDirection::Right,
11504 window,
11505 cx,
11506 );
11507 workspace.split_pane(
11508 workspace.active_pane().clone(),
11509 SplitDirection::Right,
11510 window,
11511 cx,
11512 );
11513 });
11514
11515 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11516 let panes = workspace.center.panes();
11517 assert!(panes.len() >= 2);
11518 (
11519 panes.first().expect("at least one pane").entity_id(),
11520 panes.last().expect("at least one pane").entity_id(),
11521 )
11522 });
11523
11524 workspace.update_in(cx, |workspace, window, cx| {
11525 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11526 });
11527 workspace.update(cx, |workspace, _| {
11528 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11529 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11530 });
11531
11532 cx.dispatch_action(ActivateLastPane);
11533
11534 workspace.update(cx, |workspace, _| {
11535 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11536 });
11537 }
11538
11539 #[gpui::test]
11540 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11541 init_test(cx);
11542 let fs = FakeFs::new(cx.executor());
11543
11544 let project = Project::test(fs, [], cx).await;
11545 let (workspace, cx) =
11546 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11547
11548 let panel = workspace.update_in(cx, |workspace, window, cx| {
11549 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11550 workspace.add_panel(panel.clone(), window, cx);
11551
11552 workspace
11553 .right_dock()
11554 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11555
11556 panel
11557 });
11558
11559 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11560 pane.update_in(cx, |pane, window, cx| {
11561 let item = cx.new(TestItem::new);
11562 pane.add_item(Box::new(item), true, true, None, window, cx);
11563 });
11564
11565 // Transfer focus from center to panel
11566 workspace.update_in(cx, |workspace, window, cx| {
11567 workspace.toggle_panel_focus::<TestPanel>(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 });
11575
11576 // Transfer focus from panel to center
11577 workspace.update_in(cx, |workspace, window, cx| {
11578 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11579 });
11580
11581 workspace.update_in(cx, |workspace, window, cx| {
11582 assert!(workspace.right_dock().read(cx).is_open());
11583 assert!(!panel.is_zoomed(window, cx));
11584 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11585 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11586 });
11587
11588 // Close the dock
11589 workspace.update_in(cx, |workspace, window, cx| {
11590 workspace.toggle_dock(DockPosition::Right, window, cx);
11591 });
11592
11593 workspace.update_in(cx, |workspace, window, cx| {
11594 assert!(!workspace.right_dock().read(cx).is_open());
11595 assert!(!panel.is_zoomed(window, cx));
11596 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11597 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11598 });
11599
11600 // Open the dock
11601 workspace.update_in(cx, |workspace, window, cx| {
11602 workspace.toggle_dock(DockPosition::Right, 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 // Focus and zoom panel
11612 panel.update_in(cx, |panel, window, cx| {
11613 cx.focus_self(window);
11614 panel.set_zoomed(true, window, cx)
11615 });
11616
11617 workspace.update_in(cx, |workspace, window, cx| {
11618 assert!(workspace.right_dock().read(cx).is_open());
11619 assert!(panel.is_zoomed(window, cx));
11620 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11621 });
11622
11623 // Transfer focus to the center closes the dock
11624 workspace.update_in(cx, |workspace, window, cx| {
11625 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11626 });
11627
11628 workspace.update_in(cx, |workspace, window, cx| {
11629 assert!(!workspace.right_dock().read(cx).is_open());
11630 assert!(panel.is_zoomed(window, cx));
11631 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11632 });
11633
11634 // Transferring focus back to the panel keeps it zoomed
11635 workspace.update_in(cx, |workspace, window, cx| {
11636 workspace.toggle_panel_focus::<TestPanel>(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!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11643 });
11644
11645 // Close the dock while it is zoomed
11646 workspace.update_in(cx, |workspace, window, cx| {
11647 workspace.toggle_dock(DockPosition::Right, window, cx)
11648 });
11649
11650 workspace.update_in(cx, |workspace, window, cx| {
11651 assert!(!workspace.right_dock().read(cx).is_open());
11652 assert!(panel.is_zoomed(window, cx));
11653 assert!(workspace.zoomed.is_none());
11654 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11655 });
11656
11657 // Opening the dock, when it's zoomed, retains focus
11658 workspace.update_in(cx, |workspace, window, cx| {
11659 workspace.toggle_dock(DockPosition::Right, window, cx)
11660 });
11661
11662 workspace.update_in(cx, |workspace, window, cx| {
11663 assert!(workspace.right_dock().read(cx).is_open());
11664 assert!(panel.is_zoomed(window, cx));
11665 assert!(workspace.zoomed.is_some());
11666 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11667 });
11668
11669 // Unzoom and close the panel, zoom the active pane.
11670 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11671 workspace.update_in(cx, |workspace, window, cx| {
11672 workspace.toggle_dock(DockPosition::Right, window, cx)
11673 });
11674 pane.update_in(cx, |pane, window, cx| {
11675 pane.toggle_zoom(&Default::default(), window, cx)
11676 });
11677
11678 // Opening a dock unzooms the pane.
11679 workspace.update_in(cx, |workspace, window, cx| {
11680 workspace.toggle_dock(DockPosition::Right, window, cx)
11681 });
11682 workspace.update_in(cx, |workspace, window, cx| {
11683 let pane = pane.read(cx);
11684 assert!(!pane.is_zoomed());
11685 assert!(!pane.focus_handle(cx).is_focused(window));
11686 assert!(workspace.right_dock().read(cx).is_open());
11687 assert!(workspace.zoomed.is_none());
11688 });
11689 }
11690
11691 #[gpui::test]
11692 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11693 init_test(cx);
11694 let fs = FakeFs::new(cx.executor());
11695
11696 let project = Project::test(fs, [], cx).await;
11697 let (workspace, cx) =
11698 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11699
11700 let panel = workspace.update_in(cx, |workspace, window, cx| {
11701 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11702 workspace.add_panel(panel.clone(), window, cx);
11703 panel
11704 });
11705
11706 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11707 pane.update_in(cx, |pane, window, cx| {
11708 let item = cx.new(TestItem::new);
11709 pane.add_item(Box::new(item), true, true, None, window, cx);
11710 });
11711
11712 // Enable close_panel_on_toggle
11713 cx.update_global(|store: &mut SettingsStore, cx| {
11714 store.update_user_settings(cx, |settings| {
11715 settings.workspace.close_panel_on_toggle = Some(true);
11716 });
11717 });
11718
11719 // Panel starts closed. Toggling should open and focus it.
11720 workspace.update_in(cx, |workspace, window, cx| {
11721 assert!(!workspace.right_dock().read(cx).is_open());
11722 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11723 });
11724
11725 workspace.update_in(cx, |workspace, window, cx| {
11726 assert!(
11727 workspace.right_dock().read(cx).is_open(),
11728 "Dock should be open after toggling from center"
11729 );
11730 assert!(
11731 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11732 "Panel should be focused after toggling from center"
11733 );
11734 });
11735
11736 // Panel is open and focused. Toggling should close the panel and
11737 // return focus to the center.
11738 workspace.update_in(cx, |workspace, window, cx| {
11739 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11740 });
11741
11742 workspace.update_in(cx, |workspace, window, cx| {
11743 assert!(
11744 !workspace.right_dock().read(cx).is_open(),
11745 "Dock should be closed after toggling from focused panel"
11746 );
11747 assert!(
11748 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11749 "Panel should not be focused after toggling from focused panel"
11750 );
11751 });
11752
11753 // Open the dock and focus something else so the panel is open but not
11754 // focused. Toggling should focus the panel (not close it).
11755 workspace.update_in(cx, |workspace, window, cx| {
11756 workspace
11757 .right_dock()
11758 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11759 window.focus(&pane.read(cx).focus_handle(cx), cx);
11760 });
11761
11762 workspace.update_in(cx, |workspace, window, cx| {
11763 assert!(workspace.right_dock().read(cx).is_open());
11764 assert!(!panel.read(cx).focus_handle(cx).contains_focused(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 toggling focuses an open-but-unfocused panel"
11772 );
11773 assert!(
11774 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11775 "Panel should be focused after toggling an open-but-unfocused panel"
11776 );
11777 });
11778
11779 // Now disable the setting and verify the original behavior: toggling
11780 // from a focused panel moves focus to center but leaves the dock open.
11781 cx.update_global(|store: &mut SettingsStore, cx| {
11782 store.update_user_settings(cx, |settings| {
11783 settings.workspace.close_panel_on_toggle = Some(false);
11784 });
11785 });
11786
11787 workspace.update_in(cx, |workspace, window, cx| {
11788 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11789 });
11790
11791 workspace.update_in(cx, |workspace, window, cx| {
11792 assert!(
11793 workspace.right_dock().read(cx).is_open(),
11794 "Dock should remain open when setting is disabled"
11795 );
11796 assert!(
11797 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11798 "Panel should not be focused after toggling with setting disabled"
11799 );
11800 });
11801 }
11802
11803 #[gpui::test]
11804 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11805 init_test(cx);
11806 let fs = FakeFs::new(cx.executor());
11807
11808 let project = Project::test(fs, [], cx).await;
11809 let (workspace, cx) =
11810 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11811
11812 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11813 workspace.active_pane().clone()
11814 });
11815
11816 // Add an item to the pane so it can be zoomed
11817 workspace.update_in(cx, |workspace, window, cx| {
11818 let item = cx.new(TestItem::new);
11819 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11820 });
11821
11822 // Initially not zoomed
11823 workspace.update_in(cx, |workspace, _window, cx| {
11824 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11825 assert!(
11826 workspace.zoomed.is_none(),
11827 "Workspace should track no zoomed pane"
11828 );
11829 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11830 });
11831
11832 // Zoom In
11833 pane.update_in(cx, |pane, window, cx| {
11834 pane.zoom_in(&crate::ZoomIn, window, cx);
11835 });
11836
11837 workspace.update_in(cx, |workspace, window, cx| {
11838 assert!(
11839 pane.read(cx).is_zoomed(),
11840 "Pane should be zoomed after ZoomIn"
11841 );
11842 assert!(
11843 workspace.zoomed.is_some(),
11844 "Workspace should track the zoomed pane"
11845 );
11846 assert!(
11847 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11848 "ZoomIn should focus the pane"
11849 );
11850 });
11851
11852 // Zoom In again is a no-op
11853 pane.update_in(cx, |pane, window, cx| {
11854 pane.zoom_in(&crate::ZoomIn, window, cx);
11855 });
11856
11857 workspace.update_in(cx, |workspace, window, cx| {
11858 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11859 assert!(
11860 workspace.zoomed.is_some(),
11861 "Workspace still tracks zoomed pane"
11862 );
11863 assert!(
11864 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11865 "Pane remains focused after repeated ZoomIn"
11866 );
11867 });
11868
11869 // Zoom Out
11870 pane.update_in(cx, |pane, window, cx| {
11871 pane.zoom_out(&crate::ZoomOut, window, cx);
11872 });
11873
11874 workspace.update_in(cx, |workspace, _window, cx| {
11875 assert!(
11876 !pane.read(cx).is_zoomed(),
11877 "Pane should unzoom after ZoomOut"
11878 );
11879 assert!(
11880 workspace.zoomed.is_none(),
11881 "Workspace clears zoom tracking after ZoomOut"
11882 );
11883 });
11884
11885 // Zoom Out again is a no-op
11886 pane.update_in(cx, |pane, window, cx| {
11887 pane.zoom_out(&crate::ZoomOut, window, cx);
11888 });
11889
11890 workspace.update_in(cx, |workspace, _window, cx| {
11891 assert!(
11892 !pane.read(cx).is_zoomed(),
11893 "Second ZoomOut keeps pane unzoomed"
11894 );
11895 assert!(
11896 workspace.zoomed.is_none(),
11897 "Workspace remains without zoomed pane"
11898 );
11899 });
11900 }
11901
11902 #[gpui::test]
11903 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11904 init_test(cx);
11905 let fs = FakeFs::new(cx.executor());
11906
11907 let project = Project::test(fs, [], cx).await;
11908 let (workspace, cx) =
11909 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11910 workspace.update_in(cx, |workspace, window, cx| {
11911 // Open two docks
11912 let left_dock = workspace.dock_at_position(DockPosition::Left);
11913 let right_dock = workspace.dock_at_position(DockPosition::Right);
11914
11915 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11916 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11917
11918 assert!(left_dock.read(cx).is_open());
11919 assert!(right_dock.read(cx).is_open());
11920 });
11921
11922 workspace.update_in(cx, |workspace, window, cx| {
11923 // Toggle all docks - should close both
11924 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11925
11926 let left_dock = workspace.dock_at_position(DockPosition::Left);
11927 let right_dock = workspace.dock_at_position(DockPosition::Right);
11928 assert!(!left_dock.read(cx).is_open());
11929 assert!(!right_dock.read(cx).is_open());
11930 });
11931
11932 workspace.update_in(cx, |workspace, window, cx| {
11933 // Toggle again - should reopen both
11934 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11935
11936 let left_dock = workspace.dock_at_position(DockPosition::Left);
11937 let right_dock = workspace.dock_at_position(DockPosition::Right);
11938 assert!(left_dock.read(cx).is_open());
11939 assert!(right_dock.read(cx).is_open());
11940 });
11941 }
11942
11943 #[gpui::test]
11944 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11945 init_test(cx);
11946 let fs = FakeFs::new(cx.executor());
11947
11948 let project = Project::test(fs, [], cx).await;
11949 let (workspace, cx) =
11950 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11951 workspace.update_in(cx, |workspace, window, cx| {
11952 // Open two docks
11953 let left_dock = workspace.dock_at_position(DockPosition::Left);
11954 let right_dock = workspace.dock_at_position(DockPosition::Right);
11955
11956 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11957 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11958
11959 assert!(left_dock.read(cx).is_open());
11960 assert!(right_dock.read(cx).is_open());
11961 });
11962
11963 workspace.update_in(cx, |workspace, window, cx| {
11964 // Close them manually
11965 workspace.toggle_dock(DockPosition::Left, window, cx);
11966 workspace.toggle_dock(DockPosition::Right, window, cx);
11967
11968 let left_dock = workspace.dock_at_position(DockPosition::Left);
11969 let right_dock = workspace.dock_at_position(DockPosition::Right);
11970 assert!(!left_dock.read(cx).is_open());
11971 assert!(!right_dock.read(cx).is_open());
11972 });
11973
11974 workspace.update_in(cx, |workspace, window, cx| {
11975 // Toggle all docks - only last closed (right dock) should reopen
11976 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11977
11978 let left_dock = workspace.dock_at_position(DockPosition::Left);
11979 let right_dock = workspace.dock_at_position(DockPosition::Right);
11980 assert!(!left_dock.read(cx).is_open());
11981 assert!(right_dock.read(cx).is_open());
11982 });
11983 }
11984
11985 #[gpui::test]
11986 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11987 init_test(cx);
11988 let fs = FakeFs::new(cx.executor());
11989 let project = Project::test(fs, [], cx).await;
11990 let (multi_workspace, cx) =
11991 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11992 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11993
11994 // Open two docks (left and right) with one panel each
11995 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11996 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11997 workspace.add_panel(left_panel.clone(), window, cx);
11998
11999 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12000 workspace.add_panel(right_panel.clone(), window, cx);
12001
12002 workspace.toggle_dock(DockPosition::Left, window, cx);
12003 workspace.toggle_dock(DockPosition::Right, window, cx);
12004
12005 // Verify initial state
12006 assert!(
12007 workspace.left_dock().read(cx).is_open(),
12008 "Left dock should be open"
12009 );
12010 assert_eq!(
12011 workspace
12012 .left_dock()
12013 .read(cx)
12014 .visible_panel()
12015 .unwrap()
12016 .panel_id(),
12017 left_panel.panel_id(),
12018 "Left panel should be visible in left dock"
12019 );
12020 assert!(
12021 workspace.right_dock().read(cx).is_open(),
12022 "Right dock should be open"
12023 );
12024 assert_eq!(
12025 workspace
12026 .right_dock()
12027 .read(cx)
12028 .visible_panel()
12029 .unwrap()
12030 .panel_id(),
12031 right_panel.panel_id(),
12032 "Right panel should be visible in right dock"
12033 );
12034 assert!(
12035 !workspace.bottom_dock().read(cx).is_open(),
12036 "Bottom dock should be closed"
12037 );
12038
12039 (left_panel, right_panel)
12040 });
12041
12042 // Focus the left panel and move it to the next position (bottom dock)
12043 workspace.update_in(cx, |workspace, window, cx| {
12044 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12045 assert!(
12046 left_panel.read(cx).focus_handle(cx).is_focused(window),
12047 "Left panel should be focused"
12048 );
12049 });
12050
12051 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12052
12053 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12054 workspace.update(cx, |workspace, cx| {
12055 assert!(
12056 !workspace.left_dock().read(cx).is_open(),
12057 "Left dock should be closed"
12058 );
12059 assert!(
12060 workspace.bottom_dock().read(cx).is_open(),
12061 "Bottom dock should now be open"
12062 );
12063 assert_eq!(
12064 left_panel.read(cx).position,
12065 DockPosition::Bottom,
12066 "Left panel should now be in the bottom dock"
12067 );
12068 assert_eq!(
12069 workspace
12070 .bottom_dock()
12071 .read(cx)
12072 .visible_panel()
12073 .unwrap()
12074 .panel_id(),
12075 left_panel.panel_id(),
12076 "Left panel should be the visible panel in the bottom dock"
12077 );
12078 });
12079
12080 // Toggle all docks off
12081 workspace.update_in(cx, |workspace, window, cx| {
12082 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12083 assert!(
12084 !workspace.left_dock().read(cx).is_open(),
12085 "Left dock should be closed"
12086 );
12087 assert!(
12088 !workspace.right_dock().read(cx).is_open(),
12089 "Right dock should be closed"
12090 );
12091 assert!(
12092 !workspace.bottom_dock().read(cx).is_open(),
12093 "Bottom dock should be closed"
12094 );
12095 });
12096
12097 // Toggle all docks back on and verify positions are restored
12098 workspace.update_in(cx, |workspace, window, cx| {
12099 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12100 assert!(
12101 !workspace.left_dock().read(cx).is_open(),
12102 "Left dock should remain closed"
12103 );
12104 assert!(
12105 workspace.right_dock().read(cx).is_open(),
12106 "Right dock should remain open"
12107 );
12108 assert!(
12109 workspace.bottom_dock().read(cx).is_open(),
12110 "Bottom dock should remain open"
12111 );
12112 assert_eq!(
12113 left_panel.read(cx).position,
12114 DockPosition::Bottom,
12115 "Left panel should remain in the bottom dock"
12116 );
12117 assert_eq!(
12118 right_panel.read(cx).position,
12119 DockPosition::Right,
12120 "Right panel should remain in the right dock"
12121 );
12122 assert_eq!(
12123 workspace
12124 .bottom_dock()
12125 .read(cx)
12126 .visible_panel()
12127 .unwrap()
12128 .panel_id(),
12129 left_panel.panel_id(),
12130 "Left panel should be the visible panel in the right dock"
12131 );
12132 });
12133 }
12134
12135 #[gpui::test]
12136 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12137 init_test(cx);
12138
12139 let fs = FakeFs::new(cx.executor());
12140
12141 let project = Project::test(fs, None, cx).await;
12142 let (workspace, cx) =
12143 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12144
12145 // Let's arrange the panes like this:
12146 //
12147 // +-----------------------+
12148 // | top |
12149 // +------+--------+-------+
12150 // | left | center | right |
12151 // +------+--------+-------+
12152 // | bottom |
12153 // +-----------------------+
12154
12155 let top_item = cx.new(|cx| {
12156 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12157 });
12158 let bottom_item = cx.new(|cx| {
12159 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12160 });
12161 let left_item = cx.new(|cx| {
12162 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12163 });
12164 let right_item = cx.new(|cx| {
12165 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12166 });
12167 let center_item = cx.new(|cx| {
12168 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12169 });
12170
12171 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12172 let top_pane_id = workspace.active_pane().entity_id();
12173 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12174 workspace.split_pane(
12175 workspace.active_pane().clone(),
12176 SplitDirection::Down,
12177 window,
12178 cx,
12179 );
12180 top_pane_id
12181 });
12182 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12183 let bottom_pane_id = workspace.active_pane().entity_id();
12184 workspace.add_item_to_active_pane(
12185 Box::new(bottom_item.clone()),
12186 None,
12187 false,
12188 window,
12189 cx,
12190 );
12191 workspace.split_pane(
12192 workspace.active_pane().clone(),
12193 SplitDirection::Up,
12194 window,
12195 cx,
12196 );
12197 bottom_pane_id
12198 });
12199 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12200 let left_pane_id = workspace.active_pane().entity_id();
12201 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12202 workspace.split_pane(
12203 workspace.active_pane().clone(),
12204 SplitDirection::Right,
12205 window,
12206 cx,
12207 );
12208 left_pane_id
12209 });
12210 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12211 let right_pane_id = workspace.active_pane().entity_id();
12212 workspace.add_item_to_active_pane(
12213 Box::new(right_item.clone()),
12214 None,
12215 false,
12216 window,
12217 cx,
12218 );
12219 workspace.split_pane(
12220 workspace.active_pane().clone(),
12221 SplitDirection::Left,
12222 window,
12223 cx,
12224 );
12225 right_pane_id
12226 });
12227 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12228 let center_pane_id = workspace.active_pane().entity_id();
12229 workspace.add_item_to_active_pane(
12230 Box::new(center_item.clone()),
12231 None,
12232 false,
12233 window,
12234 cx,
12235 );
12236 center_pane_id
12237 });
12238 cx.executor().run_until_parked();
12239
12240 workspace.update_in(cx, |workspace, window, cx| {
12241 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12242
12243 // Join into next from center pane into right
12244 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12245 });
12246
12247 workspace.update_in(cx, |workspace, window, cx| {
12248 let active_pane = workspace.active_pane();
12249 assert_eq!(right_pane_id, active_pane.entity_id());
12250 assert_eq!(2, active_pane.read(cx).items_len());
12251 let item_ids_in_pane =
12252 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12253 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12254 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12255
12256 // Join into next from right pane into bottom
12257 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12258 });
12259
12260 workspace.update_in(cx, |workspace, window, cx| {
12261 let active_pane = workspace.active_pane();
12262 assert_eq!(bottom_pane_id, active_pane.entity_id());
12263 assert_eq!(3, active_pane.read(cx).items_len());
12264 let item_ids_in_pane =
12265 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12266 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12267 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12268 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12269
12270 // Join into next from bottom pane into left
12271 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12272 });
12273
12274 workspace.update_in(cx, |workspace, window, cx| {
12275 let active_pane = workspace.active_pane();
12276 assert_eq!(left_pane_id, active_pane.entity_id());
12277 assert_eq!(4, active_pane.read(cx).items_len());
12278 let item_ids_in_pane =
12279 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12280 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12281 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12282 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12283 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12284
12285 // Join into next from left pane into top
12286 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12287 });
12288
12289 workspace.update_in(cx, |workspace, window, cx| {
12290 let active_pane = workspace.active_pane();
12291 assert_eq!(top_pane_id, active_pane.entity_id());
12292 assert_eq!(5, active_pane.read(cx).items_len());
12293 let item_ids_in_pane =
12294 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12295 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12296 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12297 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12298 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12299 assert!(item_ids_in_pane.contains(&top_item.item_id()));
12300
12301 // Single pane left: no-op
12302 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12303 });
12304
12305 workspace.update(cx, |workspace, _cx| {
12306 let active_pane = workspace.active_pane();
12307 assert_eq!(top_pane_id, active_pane.entity_id());
12308 });
12309 }
12310
12311 fn add_an_item_to_active_pane(
12312 cx: &mut VisualTestContext,
12313 workspace: &Entity<Workspace>,
12314 item_id: u64,
12315 ) -> Entity<TestItem> {
12316 let item = cx.new(|cx| {
12317 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12318 item_id,
12319 "item{item_id}.txt",
12320 cx,
12321 )])
12322 });
12323 workspace.update_in(cx, |workspace, window, cx| {
12324 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12325 });
12326 item
12327 }
12328
12329 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12330 workspace.update_in(cx, |workspace, window, cx| {
12331 workspace.split_pane(
12332 workspace.active_pane().clone(),
12333 SplitDirection::Right,
12334 window,
12335 cx,
12336 )
12337 })
12338 }
12339
12340 #[gpui::test]
12341 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12342 init_test(cx);
12343 let fs = FakeFs::new(cx.executor());
12344 let project = Project::test(fs, None, cx).await;
12345 let (workspace, cx) =
12346 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12347
12348 add_an_item_to_active_pane(cx, &workspace, 1);
12349 split_pane(cx, &workspace);
12350 add_an_item_to_active_pane(cx, &workspace, 2);
12351 split_pane(cx, &workspace); // empty pane
12352 split_pane(cx, &workspace);
12353 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12354
12355 cx.executor().run_until_parked();
12356
12357 workspace.update(cx, |workspace, cx| {
12358 let num_panes = workspace.panes().len();
12359 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12360 let active_item = workspace
12361 .active_pane()
12362 .read(cx)
12363 .active_item()
12364 .expect("item is in focus");
12365
12366 assert_eq!(num_panes, 4);
12367 assert_eq!(num_items_in_current_pane, 1);
12368 assert_eq!(active_item.item_id(), last_item.item_id());
12369 });
12370
12371 workspace.update_in(cx, |workspace, window, cx| {
12372 workspace.join_all_panes(window, cx);
12373 });
12374
12375 workspace.update(cx, |workspace, cx| {
12376 let num_panes = workspace.panes().len();
12377 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12378 let active_item = workspace
12379 .active_pane()
12380 .read(cx)
12381 .active_item()
12382 .expect("item is in focus");
12383
12384 assert_eq!(num_panes, 1);
12385 assert_eq!(num_items_in_current_pane, 3);
12386 assert_eq!(active_item.item_id(), last_item.item_id());
12387 });
12388 }
12389
12390 #[gpui::test]
12391 async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12392 init_test(cx);
12393 let fs = FakeFs::new(cx.executor());
12394
12395 let project = Project::test(fs, [], cx).await;
12396 let (multi_workspace, cx) =
12397 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12398 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12399
12400 workspace.update(cx, |workspace, _cx| {
12401 workspace.bounds.size.width = px(800.);
12402 });
12403
12404 workspace.update_in(cx, |workspace, window, cx| {
12405 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12406 workspace.add_panel(panel, window, cx);
12407 workspace.toggle_dock(DockPosition::Right, window, cx);
12408 });
12409
12410 let (panel, resized_width, ratio_basis_width) =
12411 workspace.update_in(cx, |workspace, window, cx| {
12412 let item = cx.new(|cx| {
12413 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12414 });
12415 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12416
12417 let dock = workspace.right_dock().read(cx);
12418 let workspace_width = workspace.bounds.size.width;
12419 let initial_width = workspace
12420 .dock_size(&dock, window, cx)
12421 .expect("flexible dock should have an initial width");
12422
12423 assert_eq!(initial_width, workspace_width / 2.);
12424
12425 workspace.resize_right_dock(px(300.), window, cx);
12426
12427 let dock = workspace.right_dock().read(cx);
12428 let resized_width = workspace
12429 .dock_size(&dock, window, cx)
12430 .expect("flexible dock should keep its resized width");
12431
12432 assert_eq!(resized_width, px(300.));
12433
12434 let panel = workspace
12435 .right_dock()
12436 .read(cx)
12437 .visible_panel()
12438 .expect("flexible dock should have a visible panel")
12439 .panel_id();
12440
12441 (panel, resized_width, workspace_width)
12442 });
12443
12444 workspace.update_in(cx, |workspace, window, cx| {
12445 workspace.toggle_dock(DockPosition::Right, window, cx);
12446 workspace.toggle_dock(DockPosition::Right, window, cx);
12447
12448 let dock = workspace.right_dock().read(cx);
12449 let reopened_width = workspace
12450 .dock_size(&dock, window, cx)
12451 .expect("flexible dock should restore when reopened");
12452
12453 assert_eq!(reopened_width, resized_width);
12454
12455 let right_dock = workspace.right_dock().read(cx);
12456 let flexible_panel = right_dock
12457 .visible_panel()
12458 .expect("flexible dock should still have a visible panel");
12459 assert_eq!(flexible_panel.panel_id(), panel);
12460 assert_eq!(
12461 right_dock
12462 .stored_panel_size_state(flexible_panel.as_ref())
12463 .and_then(|size_state| size_state.flex),
12464 Some(
12465 resized_width.to_f64() as f32
12466 / (workspace.bounds.size.width - resized_width).to_f64() as f32
12467 )
12468 );
12469 });
12470
12471 workspace.update_in(cx, |workspace, window, cx| {
12472 workspace.split_pane(
12473 workspace.active_pane().clone(),
12474 SplitDirection::Right,
12475 window,
12476 cx,
12477 );
12478
12479 let dock = workspace.right_dock().read(cx);
12480 let split_width = workspace
12481 .dock_size(&dock, window, cx)
12482 .expect("flexible dock should keep its user-resized proportion");
12483
12484 assert_eq!(split_width, px(300.));
12485
12486 workspace.bounds.size.width = px(1600.);
12487
12488 let dock = workspace.right_dock().read(cx);
12489 let resized_window_width = workspace
12490 .dock_size(&dock, window, cx)
12491 .expect("flexible dock should preserve proportional size on window resize");
12492
12493 assert_eq!(
12494 resized_window_width,
12495 workspace.bounds.size.width
12496 * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12497 );
12498 });
12499 }
12500
12501 #[gpui::test]
12502 async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12503 init_test(cx);
12504 let fs = FakeFs::new(cx.executor());
12505
12506 // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12507 {
12508 let project = Project::test(fs.clone(), [], cx).await;
12509 let (multi_workspace, cx) =
12510 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12511 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12512
12513 workspace.update(cx, |workspace, _cx| {
12514 workspace.set_random_database_id();
12515 workspace.bounds.size.width = px(800.);
12516 });
12517
12518 let panel = workspace.update_in(cx, |workspace, window, cx| {
12519 let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12520 workspace.add_panel(panel.clone(), window, cx);
12521 workspace.toggle_dock(DockPosition::Left, window, cx);
12522 panel
12523 });
12524
12525 workspace.update_in(cx, |workspace, window, cx| {
12526 workspace.resize_left_dock(px(350.), window, cx);
12527 });
12528
12529 cx.run_until_parked();
12530
12531 let persisted = workspace.read_with(cx, |workspace, cx| {
12532 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12533 });
12534 assert_eq!(
12535 persisted.and_then(|s| s.size),
12536 Some(px(350.)),
12537 "fixed-width panel size should be persisted to KVP"
12538 );
12539
12540 // Remove the panel and re-add a fresh instance with the same key.
12541 // The new instance should have its size state restored from KVP.
12542 workspace.update_in(cx, |workspace, window, cx| {
12543 workspace.remove_panel(&panel, window, cx);
12544 });
12545
12546 workspace.update_in(cx, |workspace, window, cx| {
12547 let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12548 workspace.add_panel(new_panel, window, cx);
12549
12550 let left_dock = workspace.left_dock().read(cx);
12551 let size_state = left_dock
12552 .panel::<TestPanel>()
12553 .and_then(|p| left_dock.stored_panel_size_state(&p));
12554 assert_eq!(
12555 size_state.and_then(|s| s.size),
12556 Some(px(350.)),
12557 "re-added fixed-width panel should restore persisted size from KVP"
12558 );
12559 });
12560 }
12561
12562 // Flexible panel: both pixel size and ratio are persisted and restored.
12563 {
12564 let project = Project::test(fs.clone(), [], cx).await;
12565 let (multi_workspace, cx) =
12566 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12567 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12568
12569 workspace.update(cx, |workspace, _cx| {
12570 workspace.set_random_database_id();
12571 workspace.bounds.size.width = px(800.);
12572 });
12573
12574 let panel = workspace.update_in(cx, |workspace, window, cx| {
12575 let item = cx.new(|cx| {
12576 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12577 });
12578 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12579
12580 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12581 workspace.add_panel(panel.clone(), window, cx);
12582 workspace.toggle_dock(DockPosition::Right, window, cx);
12583 panel
12584 });
12585
12586 workspace.update_in(cx, |workspace, window, cx| {
12587 workspace.resize_right_dock(px(300.), window, cx);
12588 });
12589
12590 cx.run_until_parked();
12591
12592 let persisted = workspace
12593 .read_with(cx, |workspace, cx| {
12594 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12595 })
12596 .expect("flexible panel state should be persisted to KVP");
12597 assert_eq!(
12598 persisted.size, None,
12599 "flexible panel should not persist a redundant pixel size"
12600 );
12601 let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12602
12603 // Remove the panel and re-add: both size and ratio should be restored.
12604 workspace.update_in(cx, |workspace, window, cx| {
12605 workspace.remove_panel(&panel, window, cx);
12606 });
12607
12608 workspace.update_in(cx, |workspace, window, cx| {
12609 let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12610 workspace.add_panel(new_panel, window, cx);
12611
12612 let right_dock = workspace.right_dock().read(cx);
12613 let size_state = right_dock
12614 .panel::<TestPanel>()
12615 .and_then(|p| right_dock.stored_panel_size_state(&p))
12616 .expect("re-added flexible panel should have restored size state from KVP");
12617 assert_eq!(
12618 size_state.size, None,
12619 "re-added flexible panel should not have a persisted pixel size"
12620 );
12621 assert_eq!(
12622 size_state.flex,
12623 Some(original_ratio),
12624 "re-added flexible panel should restore persisted flex"
12625 );
12626 });
12627 }
12628 }
12629
12630 #[gpui::test]
12631 async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12632 init_test(cx);
12633 let fs = FakeFs::new(cx.executor());
12634
12635 let project = Project::test(fs, [], cx).await;
12636 let (multi_workspace, cx) =
12637 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12638 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12639
12640 workspace.update(cx, |workspace, _cx| {
12641 workspace.bounds.size.width = px(900.);
12642 });
12643
12644 // Step 1: Add a tab to the center pane then open a flexible panel in the left
12645 // dock. With one full-width center pane the default ratio is 0.5, so the panel
12646 // and the center pane each take half the workspace width.
12647 workspace.update_in(cx, |workspace, window, cx| {
12648 let item = cx.new(|cx| {
12649 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12650 });
12651 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12652
12653 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12654 workspace.add_panel(panel, window, cx);
12655 workspace.toggle_dock(DockPosition::Left, window, cx);
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 have an active panel");
12661
12662 assert_eq!(
12663 left_width,
12664 workspace.bounds.size.width / 2.,
12665 "flexible left panel should split evenly with the center pane"
12666 );
12667 });
12668
12669 // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12670 // change horizontal width fractions, so the flexible panel stays at the same
12671 // width as each half of the split.
12672 workspace.update_in(cx, |workspace, window, cx| {
12673 workspace.split_pane(
12674 workspace.active_pane().clone(),
12675 SplitDirection::Down,
12676 window,
12677 cx,
12678 );
12679
12680 let left_dock = workspace.left_dock().read(cx);
12681 let left_width = workspace
12682 .dock_size(&left_dock, window, cx)
12683 .expect("left dock should still have an active panel after vertical split");
12684
12685 assert_eq!(
12686 left_width,
12687 workspace.bounds.size.width / 2.,
12688 "flexible left panel width should match each vertically-split pane"
12689 );
12690 });
12691
12692 // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12693 // size reduces the available width, so the flexible left panel and the center
12694 // panes all shrink proportionally to accommodate it.
12695 workspace.update_in(cx, |workspace, window, cx| {
12696 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12697 workspace.add_panel(panel, window, cx);
12698 workspace.toggle_dock(DockPosition::Right, window, cx);
12699
12700 let right_dock = workspace.right_dock().read(cx);
12701 let right_width = workspace
12702 .dock_size(&right_dock, window, cx)
12703 .expect("right dock should have an active panel");
12704
12705 let left_dock = workspace.left_dock().read(cx);
12706 let left_width = workspace
12707 .dock_size(&left_dock, window, cx)
12708 .expect("left dock should still have an active panel");
12709
12710 let available_width = workspace.bounds.size.width - right_width;
12711 assert_eq!(
12712 left_width,
12713 available_width / 2.,
12714 "flexible left panel should shrink proportionally as the right dock takes space"
12715 );
12716 });
12717
12718 // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12719 // flex sizing and the workspace width is divided among left-flex, center
12720 // (implicit flex 1.0), and right-flex.
12721 workspace.update_in(cx, |workspace, window, cx| {
12722 let right_dock = workspace.right_dock().clone();
12723 let right_panel = right_dock
12724 .read(cx)
12725 .visible_panel()
12726 .expect("right dock should have a visible panel")
12727 .clone();
12728 workspace.toggle_dock_panel_flexible_size(
12729 &right_dock,
12730 right_panel.as_ref(),
12731 window,
12732 cx,
12733 );
12734
12735 let right_dock = right_dock.read(cx);
12736 let right_panel = right_dock
12737 .visible_panel()
12738 .expect("right dock should still have a visible panel");
12739 assert!(
12740 right_panel.has_flexible_size(window, cx),
12741 "right panel should now be flexible"
12742 );
12743
12744 let right_size_state = right_dock
12745 .stored_panel_size_state(right_panel.as_ref())
12746 .expect("right panel should have a stored size state after toggling");
12747 let right_flex = right_size_state
12748 .flex
12749 .expect("right panel should have a flex value after toggling");
12750
12751 let left_dock = workspace.left_dock().read(cx);
12752 let left_width = workspace
12753 .dock_size(&left_dock, window, cx)
12754 .expect("left dock should still have an active panel");
12755 let right_width = workspace
12756 .dock_size(&right_dock, window, cx)
12757 .expect("right dock should still have an active panel");
12758
12759 let left_flex = workspace
12760 .default_dock_flex(DockPosition::Left)
12761 .expect("left dock should have a default flex");
12762
12763 let total_flex = left_flex + 1.0 + right_flex;
12764 let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12765 let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12766 assert_eq!(
12767 left_width, expected_left,
12768 "flexible left panel should share workspace width via flex ratios"
12769 );
12770 assert_eq!(
12771 right_width, expected_right,
12772 "flexible right panel should share workspace width via flex ratios"
12773 );
12774 });
12775 }
12776
12777 struct TestModal(FocusHandle);
12778
12779 impl TestModal {
12780 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12781 Self(cx.focus_handle())
12782 }
12783 }
12784
12785 impl EventEmitter<DismissEvent> for TestModal {}
12786
12787 impl Focusable for TestModal {
12788 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12789 self.0.clone()
12790 }
12791 }
12792
12793 impl ModalView for TestModal {}
12794
12795 impl Render for TestModal {
12796 fn render(
12797 &mut self,
12798 _window: &mut Window,
12799 _cx: &mut Context<TestModal>,
12800 ) -> impl IntoElement {
12801 div().track_focus(&self.0)
12802 }
12803 }
12804
12805 #[gpui::test]
12806 async fn test_panels(cx: &mut gpui::TestAppContext) {
12807 init_test(cx);
12808 let fs = FakeFs::new(cx.executor());
12809
12810 let project = Project::test(fs, [], cx).await;
12811 let (multi_workspace, cx) =
12812 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12813 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12814
12815 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12816 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12817 workspace.add_panel(panel_1.clone(), window, cx);
12818 workspace.toggle_dock(DockPosition::Left, window, cx);
12819 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12820 workspace.add_panel(panel_2.clone(), window, cx);
12821 workspace.toggle_dock(DockPosition::Right, window, cx);
12822
12823 let left_dock = workspace.left_dock();
12824 assert_eq!(
12825 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12826 panel_1.panel_id()
12827 );
12828 assert_eq!(
12829 workspace.dock_size(&left_dock.read(cx), window, cx),
12830 Some(px(300.))
12831 );
12832
12833 workspace.resize_left_dock(px(1337.), window, cx);
12834 assert_eq!(
12835 workspace
12836 .right_dock()
12837 .read(cx)
12838 .visible_panel()
12839 .unwrap()
12840 .panel_id(),
12841 panel_2.panel_id(),
12842 );
12843
12844 (panel_1, panel_2)
12845 });
12846
12847 // Move panel_1 to the right
12848 panel_1.update_in(cx, |panel_1, window, cx| {
12849 panel_1.set_position(DockPosition::Right, window, cx)
12850 });
12851
12852 workspace.update_in(cx, |workspace, window, cx| {
12853 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12854 // Since it was the only panel on the left, the left dock should now be closed.
12855 assert!(!workspace.left_dock().read(cx).is_open());
12856 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12857 let right_dock = workspace.right_dock();
12858 assert_eq!(
12859 right_dock.read(cx).visible_panel().unwrap().panel_id(),
12860 panel_1.panel_id()
12861 );
12862 assert_eq!(
12863 right_dock
12864 .read(cx)
12865 .active_panel_size()
12866 .unwrap()
12867 .size
12868 .unwrap(),
12869 px(1337.)
12870 );
12871
12872 // Now we move panel_2 to the left
12873 panel_2.set_position(DockPosition::Left, window, cx);
12874 });
12875
12876 workspace.update(cx, |workspace, cx| {
12877 // Since panel_2 was not visible on the right, we don't open the left dock.
12878 assert!(!workspace.left_dock().read(cx).is_open());
12879 // And the right dock is unaffected in its displaying of panel_1
12880 assert!(workspace.right_dock().read(cx).is_open());
12881 assert_eq!(
12882 workspace
12883 .right_dock()
12884 .read(cx)
12885 .visible_panel()
12886 .unwrap()
12887 .panel_id(),
12888 panel_1.panel_id(),
12889 );
12890 });
12891
12892 // Move panel_1 back to the left
12893 panel_1.update_in(cx, |panel_1, window, cx| {
12894 panel_1.set_position(DockPosition::Left, window, cx)
12895 });
12896
12897 workspace.update_in(cx, |workspace, window, cx| {
12898 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12899 let left_dock = workspace.left_dock();
12900 assert!(left_dock.read(cx).is_open());
12901 assert_eq!(
12902 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12903 panel_1.panel_id()
12904 );
12905 assert_eq!(
12906 workspace.dock_size(&left_dock.read(cx), window, cx),
12907 Some(px(1337.))
12908 );
12909 // And the right dock should be closed as it no longer has any panels.
12910 assert!(!workspace.right_dock().read(cx).is_open());
12911
12912 // Now we move panel_1 to the bottom
12913 panel_1.set_position(DockPosition::Bottom, window, cx);
12914 });
12915
12916 workspace.update_in(cx, |workspace, window, cx| {
12917 // Since panel_1 was visible on the left, we close the left dock.
12918 assert!(!workspace.left_dock().read(cx).is_open());
12919 // The bottom dock is sized based on the panel's default size,
12920 // since the panel orientation changed from vertical to horizontal.
12921 let bottom_dock = workspace.bottom_dock();
12922 assert_eq!(
12923 workspace.dock_size(&bottom_dock.read(cx), window, cx),
12924 Some(px(300.))
12925 );
12926 // Close bottom dock and move panel_1 back to the left.
12927 bottom_dock.update(cx, |bottom_dock, cx| {
12928 bottom_dock.set_open(false, window, cx)
12929 });
12930 panel_1.set_position(DockPosition::Left, window, cx);
12931 });
12932
12933 // Emit activated event on panel 1
12934 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12935
12936 // Now the left dock is open and panel_1 is active and focused.
12937 workspace.update_in(cx, |workspace, window, cx| {
12938 let left_dock = workspace.left_dock();
12939 assert!(left_dock.read(cx).is_open());
12940 assert_eq!(
12941 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12942 panel_1.panel_id(),
12943 );
12944 assert!(panel_1.focus_handle(cx).is_focused(window));
12945 });
12946
12947 // Emit closed event on panel 2, which is not active
12948 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12949
12950 // Wo don't close the left dock, because panel_2 wasn't the active panel
12951 workspace.update(cx, |workspace, cx| {
12952 let left_dock = workspace.left_dock();
12953 assert!(left_dock.read(cx).is_open());
12954 assert_eq!(
12955 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12956 panel_1.panel_id(),
12957 );
12958 });
12959
12960 // Emitting a ZoomIn event shows the panel as zoomed.
12961 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12962 workspace.read_with(cx, |workspace, _| {
12963 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12964 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12965 });
12966
12967 // Move panel to another dock while it is zoomed
12968 panel_1.update_in(cx, |panel, window, cx| {
12969 panel.set_position(DockPosition::Right, window, cx)
12970 });
12971 workspace.read_with(cx, |workspace, _| {
12972 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12973
12974 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12975 });
12976
12977 // This is a helper for getting a:
12978 // - valid focus on an element,
12979 // - that isn't a part of the panes and panels system of the Workspace,
12980 // - and doesn't trigger the 'on_focus_lost' API.
12981 let focus_other_view = {
12982 let workspace = workspace.clone();
12983 move |cx: &mut VisualTestContext| {
12984 workspace.update_in(cx, |workspace, window, cx| {
12985 if workspace.active_modal::<TestModal>(cx).is_some() {
12986 workspace.toggle_modal(window, cx, TestModal::new);
12987 workspace.toggle_modal(window, cx, TestModal::new);
12988 } else {
12989 workspace.toggle_modal(window, cx, TestModal::new);
12990 }
12991 })
12992 }
12993 };
12994
12995 // If focus is transferred to another view that's not a panel or another pane, we still show
12996 // the panel as zoomed.
12997 focus_other_view(cx);
12998 workspace.read_with(cx, |workspace, _| {
12999 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13000 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13001 });
13002
13003 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13004 workspace.update_in(cx, |_workspace, window, cx| {
13005 cx.focus_self(window);
13006 });
13007 workspace.read_with(cx, |workspace, _| {
13008 assert_eq!(workspace.zoomed, None);
13009 assert_eq!(workspace.zoomed_position, None);
13010 });
13011
13012 // If focus is transferred again to another view that's not a panel or a pane, we won't
13013 // show the panel as zoomed because it wasn't zoomed before.
13014 focus_other_view(cx);
13015 workspace.read_with(cx, |workspace, _| {
13016 assert_eq!(workspace.zoomed, None);
13017 assert_eq!(workspace.zoomed_position, None);
13018 });
13019
13020 // When the panel is activated, it is zoomed again.
13021 cx.dispatch_action(ToggleRightDock);
13022 workspace.read_with(cx, |workspace, _| {
13023 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13024 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13025 });
13026
13027 // Emitting a ZoomOut event unzooms the panel.
13028 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13029 workspace.read_with(cx, |workspace, _| {
13030 assert_eq!(workspace.zoomed, None);
13031 assert_eq!(workspace.zoomed_position, None);
13032 });
13033
13034 // Emit closed event on panel 1, which is active
13035 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13036
13037 // Now the left dock is closed, because panel_1 was the active panel
13038 workspace.update(cx, |workspace, cx| {
13039 let right_dock = workspace.right_dock();
13040 assert!(!right_dock.read(cx).is_open());
13041 });
13042 }
13043
13044 #[gpui::test]
13045 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13046 init_test(cx);
13047
13048 let fs = FakeFs::new(cx.background_executor.clone());
13049 let project = Project::test(fs, [], cx).await;
13050 let (workspace, cx) =
13051 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13052 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13053
13054 let dirty_regular_buffer = cx.new(|cx| {
13055 TestItem::new(cx)
13056 .with_dirty(true)
13057 .with_label("1.txt")
13058 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13059 });
13060 let dirty_regular_buffer_2 = cx.new(|cx| {
13061 TestItem::new(cx)
13062 .with_dirty(true)
13063 .with_label("2.txt")
13064 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13065 });
13066 let dirty_multi_buffer_with_both = cx.new(|cx| {
13067 TestItem::new(cx)
13068 .with_dirty(true)
13069 .with_buffer_kind(ItemBufferKind::Multibuffer)
13070 .with_label("Fake Project Search")
13071 .with_project_items(&[
13072 dirty_regular_buffer.read(cx).project_items[0].clone(),
13073 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13074 ])
13075 });
13076 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13077 workspace.update_in(cx, |workspace, window, cx| {
13078 workspace.add_item(
13079 pane.clone(),
13080 Box::new(dirty_regular_buffer.clone()),
13081 None,
13082 false,
13083 false,
13084 window,
13085 cx,
13086 );
13087 workspace.add_item(
13088 pane.clone(),
13089 Box::new(dirty_regular_buffer_2.clone()),
13090 None,
13091 false,
13092 false,
13093 window,
13094 cx,
13095 );
13096 workspace.add_item(
13097 pane.clone(),
13098 Box::new(dirty_multi_buffer_with_both.clone()),
13099 None,
13100 false,
13101 false,
13102 window,
13103 cx,
13104 );
13105 });
13106
13107 pane.update_in(cx, |pane, window, cx| {
13108 pane.activate_item(2, true, true, window, cx);
13109 assert_eq!(
13110 pane.active_item().unwrap().item_id(),
13111 multi_buffer_with_both_files_id,
13112 "Should select the multi buffer in the pane"
13113 );
13114 });
13115 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13116 pane.close_other_items(
13117 &CloseOtherItems {
13118 save_intent: Some(SaveIntent::Save),
13119 close_pinned: true,
13120 },
13121 None,
13122 window,
13123 cx,
13124 )
13125 });
13126 cx.background_executor.run_until_parked();
13127 assert!(!cx.has_pending_prompt());
13128 close_all_but_multi_buffer_task
13129 .await
13130 .expect("Closing all buffers but the multi buffer failed");
13131 pane.update(cx, |pane, cx| {
13132 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13133 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13134 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13135 assert_eq!(pane.items_len(), 1);
13136 assert_eq!(
13137 pane.active_item().unwrap().item_id(),
13138 multi_buffer_with_both_files_id,
13139 "Should have only the multi buffer left in the pane"
13140 );
13141 assert!(
13142 dirty_multi_buffer_with_both.read(cx).is_dirty,
13143 "The multi buffer containing the unsaved buffer should still be dirty"
13144 );
13145 });
13146
13147 dirty_regular_buffer.update(cx, |buffer, cx| {
13148 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13149 });
13150
13151 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13152 pane.close_active_item(
13153 &CloseActiveItem {
13154 save_intent: Some(SaveIntent::Close),
13155 close_pinned: false,
13156 },
13157 window,
13158 cx,
13159 )
13160 });
13161 cx.background_executor.run_until_parked();
13162 assert!(
13163 cx.has_pending_prompt(),
13164 "Dirty multi buffer should prompt a save dialog"
13165 );
13166 cx.simulate_prompt_answer("Save");
13167 cx.background_executor.run_until_parked();
13168 close_multi_buffer_task
13169 .await
13170 .expect("Closing the multi buffer failed");
13171 pane.update(cx, |pane, cx| {
13172 assert_eq!(
13173 dirty_multi_buffer_with_both.read(cx).save_count,
13174 1,
13175 "Multi buffer item should get be saved"
13176 );
13177 // Test impl does not save inner items, so we do not assert them
13178 assert_eq!(
13179 pane.items_len(),
13180 0,
13181 "No more items should be left in the pane"
13182 );
13183 assert!(pane.active_item().is_none());
13184 });
13185 }
13186
13187 #[gpui::test]
13188 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13189 cx: &mut TestAppContext,
13190 ) {
13191 init_test(cx);
13192
13193 let fs = FakeFs::new(cx.background_executor.clone());
13194 let project = Project::test(fs, [], cx).await;
13195 let (workspace, cx) =
13196 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13197 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13198
13199 let dirty_regular_buffer = cx.new(|cx| {
13200 TestItem::new(cx)
13201 .with_dirty(true)
13202 .with_label("1.txt")
13203 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13204 });
13205 let dirty_regular_buffer_2 = cx.new(|cx| {
13206 TestItem::new(cx)
13207 .with_dirty(true)
13208 .with_label("2.txt")
13209 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13210 });
13211 let clear_regular_buffer = cx.new(|cx| {
13212 TestItem::new(cx)
13213 .with_label("3.txt")
13214 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13215 });
13216
13217 let dirty_multi_buffer_with_both = cx.new(|cx| {
13218 TestItem::new(cx)
13219 .with_dirty(true)
13220 .with_buffer_kind(ItemBufferKind::Multibuffer)
13221 .with_label("Fake Project Search")
13222 .with_project_items(&[
13223 dirty_regular_buffer.read(cx).project_items[0].clone(),
13224 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13225 clear_regular_buffer.read(cx).project_items[0].clone(),
13226 ])
13227 });
13228 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13229 workspace.update_in(cx, |workspace, window, cx| {
13230 workspace.add_item(
13231 pane.clone(),
13232 Box::new(dirty_regular_buffer.clone()),
13233 None,
13234 false,
13235 false,
13236 window,
13237 cx,
13238 );
13239 workspace.add_item(
13240 pane.clone(),
13241 Box::new(dirty_multi_buffer_with_both.clone()),
13242 None,
13243 false,
13244 false,
13245 window,
13246 cx,
13247 );
13248 });
13249
13250 pane.update_in(cx, |pane, window, cx| {
13251 pane.activate_item(1, true, true, window, cx);
13252 assert_eq!(
13253 pane.active_item().unwrap().item_id(),
13254 multi_buffer_with_both_files_id,
13255 "Should select the multi buffer in the pane"
13256 );
13257 });
13258 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13259 pane.close_active_item(
13260 &CloseActiveItem {
13261 save_intent: None,
13262 close_pinned: false,
13263 },
13264 window,
13265 cx,
13266 )
13267 });
13268 cx.background_executor.run_until_parked();
13269 assert!(
13270 cx.has_pending_prompt(),
13271 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13272 );
13273 }
13274
13275 /// Tests that when `close_on_file_delete` is enabled, files are automatically
13276 /// closed when they are deleted from disk.
13277 #[gpui::test]
13278 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13279 init_test(cx);
13280
13281 // Enable the close_on_disk_deletion setting
13282 cx.update_global(|store: &mut SettingsStore, cx| {
13283 store.update_user_settings(cx, |settings| {
13284 settings.workspace.close_on_file_delete = Some(true);
13285 });
13286 });
13287
13288 let fs = FakeFs::new(cx.background_executor.clone());
13289 let project = Project::test(fs, [], cx).await;
13290 let (workspace, cx) =
13291 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13292 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13293
13294 // Create a test item that simulates a file
13295 let item = cx.new(|cx| {
13296 TestItem::new(cx)
13297 .with_label("test.txt")
13298 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13299 });
13300
13301 // Add item to workspace
13302 workspace.update_in(cx, |workspace, window, cx| {
13303 workspace.add_item(
13304 pane.clone(),
13305 Box::new(item.clone()),
13306 None,
13307 false,
13308 false,
13309 window,
13310 cx,
13311 );
13312 });
13313
13314 // Verify the item is in the pane
13315 pane.read_with(cx, |pane, _| {
13316 assert_eq!(pane.items().count(), 1);
13317 });
13318
13319 // Simulate file deletion by setting the item's deleted state
13320 item.update(cx, |item, _| {
13321 item.set_has_deleted_file(true);
13322 });
13323
13324 // Emit UpdateTab event to trigger the close behavior
13325 cx.run_until_parked();
13326 item.update(cx, |_, cx| {
13327 cx.emit(ItemEvent::UpdateTab);
13328 });
13329
13330 // Allow the close operation to complete
13331 cx.run_until_parked();
13332
13333 // Verify the item was automatically closed
13334 pane.read_with(cx, |pane, _| {
13335 assert_eq!(
13336 pane.items().count(),
13337 0,
13338 "Item should be automatically closed when file is deleted"
13339 );
13340 });
13341 }
13342
13343 /// Tests that when `close_on_file_delete` is disabled (default), files remain
13344 /// open with a strikethrough when they are deleted from disk.
13345 #[gpui::test]
13346 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13347 init_test(cx);
13348
13349 // Ensure close_on_disk_deletion is disabled (default)
13350 cx.update_global(|store: &mut SettingsStore, cx| {
13351 store.update_user_settings(cx, |settings| {
13352 settings.workspace.close_on_file_delete = Some(false);
13353 });
13354 });
13355
13356 let fs = FakeFs::new(cx.background_executor.clone());
13357 let project = Project::test(fs, [], cx).await;
13358 let (workspace, cx) =
13359 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13360 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13361
13362 // Create a test item that simulates a file
13363 let item = cx.new(|cx| {
13364 TestItem::new(cx)
13365 .with_label("test.txt")
13366 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13367 });
13368
13369 // Add item to workspace
13370 workspace.update_in(cx, |workspace, window, cx| {
13371 workspace.add_item(
13372 pane.clone(),
13373 Box::new(item.clone()),
13374 None,
13375 false,
13376 false,
13377 window,
13378 cx,
13379 );
13380 });
13381
13382 // Verify the item is in the pane
13383 pane.read_with(cx, |pane, _| {
13384 assert_eq!(pane.items().count(), 1);
13385 });
13386
13387 // Simulate file deletion
13388 item.update(cx, |item, _| {
13389 item.set_has_deleted_file(true);
13390 });
13391
13392 // Emit UpdateTab event
13393 cx.run_until_parked();
13394 item.update(cx, |_, cx| {
13395 cx.emit(ItemEvent::UpdateTab);
13396 });
13397
13398 // Allow any potential close operation to complete
13399 cx.run_until_parked();
13400
13401 // Verify the item remains open (with strikethrough)
13402 pane.read_with(cx, |pane, _| {
13403 assert_eq!(
13404 pane.items().count(),
13405 1,
13406 "Item should remain open when close_on_disk_deletion is disabled"
13407 );
13408 });
13409
13410 // Verify the item shows as deleted
13411 item.read_with(cx, |item, _| {
13412 assert!(
13413 item.has_deleted_file,
13414 "Item should be marked as having deleted file"
13415 );
13416 });
13417 }
13418
13419 /// Tests that dirty files are not automatically closed when deleted from disk,
13420 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13421 /// unsaved changes without being prompted.
13422 #[gpui::test]
13423 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13424 init_test(cx);
13425
13426 // Enable the close_on_file_delete setting
13427 cx.update_global(|store: &mut SettingsStore, cx| {
13428 store.update_user_settings(cx, |settings| {
13429 settings.workspace.close_on_file_delete = Some(true);
13430 });
13431 });
13432
13433 let fs = FakeFs::new(cx.background_executor.clone());
13434 let project = Project::test(fs, [], cx).await;
13435 let (workspace, cx) =
13436 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13437 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13438
13439 // Create a dirty test item
13440 let item = cx.new(|cx| {
13441 TestItem::new(cx)
13442 .with_dirty(true)
13443 .with_label("test.txt")
13444 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13445 });
13446
13447 // Add item to workspace
13448 workspace.update_in(cx, |workspace, window, cx| {
13449 workspace.add_item(
13450 pane.clone(),
13451 Box::new(item.clone()),
13452 None,
13453 false,
13454 false,
13455 window,
13456 cx,
13457 );
13458 });
13459
13460 // Simulate file deletion
13461 item.update(cx, |item, _| {
13462 item.set_has_deleted_file(true);
13463 });
13464
13465 // Emit UpdateTab event to trigger the close behavior
13466 cx.run_until_parked();
13467 item.update(cx, |_, cx| {
13468 cx.emit(ItemEvent::UpdateTab);
13469 });
13470
13471 // Allow any potential close operation to complete
13472 cx.run_until_parked();
13473
13474 // Verify the item remains open (dirty files are not auto-closed)
13475 pane.read_with(cx, |pane, _| {
13476 assert_eq!(
13477 pane.items().count(),
13478 1,
13479 "Dirty items should not be automatically closed even when file is deleted"
13480 );
13481 });
13482
13483 // Verify the item is marked as deleted and still dirty
13484 item.read_with(cx, |item, _| {
13485 assert!(
13486 item.has_deleted_file,
13487 "Item should be marked as having deleted file"
13488 );
13489 assert!(item.is_dirty, "Item should still be dirty");
13490 });
13491 }
13492
13493 /// Tests that navigation history is cleaned up when files are auto-closed
13494 /// due to deletion from disk.
13495 #[gpui::test]
13496 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13497 init_test(cx);
13498
13499 // Enable the close_on_file_delete setting
13500 cx.update_global(|store: &mut SettingsStore, cx| {
13501 store.update_user_settings(cx, |settings| {
13502 settings.workspace.close_on_file_delete = Some(true);
13503 });
13504 });
13505
13506 let fs = FakeFs::new(cx.background_executor.clone());
13507 let project = Project::test(fs, [], cx).await;
13508 let (workspace, cx) =
13509 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13510 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13511
13512 // Create test items
13513 let item1 = cx.new(|cx| {
13514 TestItem::new(cx)
13515 .with_label("test1.txt")
13516 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13517 });
13518 let item1_id = item1.item_id();
13519
13520 let item2 = cx.new(|cx| {
13521 TestItem::new(cx)
13522 .with_label("test2.txt")
13523 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13524 });
13525
13526 // Add items to workspace
13527 workspace.update_in(cx, |workspace, window, cx| {
13528 workspace.add_item(
13529 pane.clone(),
13530 Box::new(item1.clone()),
13531 None,
13532 false,
13533 false,
13534 window,
13535 cx,
13536 );
13537 workspace.add_item(
13538 pane.clone(),
13539 Box::new(item2.clone()),
13540 None,
13541 false,
13542 false,
13543 window,
13544 cx,
13545 );
13546 });
13547
13548 // Activate item1 to ensure it gets navigation entries
13549 pane.update_in(cx, |pane, window, cx| {
13550 pane.activate_item(0, true, true, window, cx);
13551 });
13552
13553 // Switch to item2 and back to create navigation history
13554 pane.update_in(cx, |pane, window, cx| {
13555 pane.activate_item(1, true, true, window, cx);
13556 });
13557 cx.run_until_parked();
13558
13559 pane.update_in(cx, |pane, window, cx| {
13560 pane.activate_item(0, true, true, window, cx);
13561 });
13562 cx.run_until_parked();
13563
13564 // Simulate file deletion for item1
13565 item1.update(cx, |item, _| {
13566 item.set_has_deleted_file(true);
13567 });
13568
13569 // Emit UpdateTab event to trigger the close behavior
13570 item1.update(cx, |_, cx| {
13571 cx.emit(ItemEvent::UpdateTab);
13572 });
13573 cx.run_until_parked();
13574
13575 // Verify item1 was closed
13576 pane.read_with(cx, |pane, _| {
13577 assert_eq!(
13578 pane.items().count(),
13579 1,
13580 "Should have 1 item remaining after auto-close"
13581 );
13582 });
13583
13584 // Check navigation history after close
13585 let has_item = pane.read_with(cx, |pane, cx| {
13586 let mut has_item = false;
13587 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13588 if entry.item.id() == item1_id {
13589 has_item = true;
13590 }
13591 });
13592 has_item
13593 });
13594
13595 assert!(
13596 !has_item,
13597 "Navigation history should not contain closed item entries"
13598 );
13599 }
13600
13601 #[gpui::test]
13602 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13603 cx: &mut TestAppContext,
13604 ) {
13605 init_test(cx);
13606
13607 let fs = FakeFs::new(cx.background_executor.clone());
13608 let project = Project::test(fs, [], cx).await;
13609 let (workspace, cx) =
13610 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13611 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13612
13613 let dirty_regular_buffer = cx.new(|cx| {
13614 TestItem::new(cx)
13615 .with_dirty(true)
13616 .with_label("1.txt")
13617 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13618 });
13619 let dirty_regular_buffer_2 = cx.new(|cx| {
13620 TestItem::new(cx)
13621 .with_dirty(true)
13622 .with_label("2.txt")
13623 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13624 });
13625 let clear_regular_buffer = cx.new(|cx| {
13626 TestItem::new(cx)
13627 .with_label("3.txt")
13628 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13629 });
13630
13631 let dirty_multi_buffer = cx.new(|cx| {
13632 TestItem::new(cx)
13633 .with_dirty(true)
13634 .with_buffer_kind(ItemBufferKind::Multibuffer)
13635 .with_label("Fake Project Search")
13636 .with_project_items(&[
13637 dirty_regular_buffer.read(cx).project_items[0].clone(),
13638 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13639 clear_regular_buffer.read(cx).project_items[0].clone(),
13640 ])
13641 });
13642 workspace.update_in(cx, |workspace, window, cx| {
13643 workspace.add_item(
13644 pane.clone(),
13645 Box::new(dirty_regular_buffer.clone()),
13646 None,
13647 false,
13648 false,
13649 window,
13650 cx,
13651 );
13652 workspace.add_item(
13653 pane.clone(),
13654 Box::new(dirty_regular_buffer_2.clone()),
13655 None,
13656 false,
13657 false,
13658 window,
13659 cx,
13660 );
13661 workspace.add_item(
13662 pane.clone(),
13663 Box::new(dirty_multi_buffer.clone()),
13664 None,
13665 false,
13666 false,
13667 window,
13668 cx,
13669 );
13670 });
13671
13672 pane.update_in(cx, |pane, window, cx| {
13673 pane.activate_item(2, true, true, window, cx);
13674 assert_eq!(
13675 pane.active_item().unwrap().item_id(),
13676 dirty_multi_buffer.item_id(),
13677 "Should select the multi buffer in the pane"
13678 );
13679 });
13680 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13681 pane.close_active_item(
13682 &CloseActiveItem {
13683 save_intent: None,
13684 close_pinned: false,
13685 },
13686 window,
13687 cx,
13688 )
13689 });
13690 cx.background_executor.run_until_parked();
13691 assert!(
13692 !cx.has_pending_prompt(),
13693 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13694 );
13695 close_multi_buffer_task
13696 .await
13697 .expect("Closing multi buffer failed");
13698 pane.update(cx, |pane, cx| {
13699 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13700 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13701 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13702 assert_eq!(
13703 pane.items()
13704 .map(|item| item.item_id())
13705 .sorted()
13706 .collect::<Vec<_>>(),
13707 vec![
13708 dirty_regular_buffer.item_id(),
13709 dirty_regular_buffer_2.item_id(),
13710 ],
13711 "Should have no multi buffer left in the pane"
13712 );
13713 assert!(dirty_regular_buffer.read(cx).is_dirty);
13714 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13715 });
13716 }
13717
13718 #[gpui::test]
13719 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13720 init_test(cx);
13721 let fs = FakeFs::new(cx.executor());
13722 let project = Project::test(fs, [], cx).await;
13723 let (multi_workspace, cx) =
13724 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13725 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13726
13727 // Add a new panel to the right dock, opening the dock and setting the
13728 // focus to the new panel.
13729 let panel = workspace.update_in(cx, |workspace, window, cx| {
13730 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13731 workspace.add_panel(panel.clone(), window, cx);
13732
13733 workspace
13734 .right_dock()
13735 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13736
13737 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13738
13739 panel
13740 });
13741
13742 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13743 // panel to the next valid position which, in this case, is the left
13744 // dock.
13745 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13746 workspace.update(cx, |workspace, cx| {
13747 assert!(workspace.left_dock().read(cx).is_open());
13748 assert_eq!(panel.read(cx).position, DockPosition::Left);
13749 });
13750
13751 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13752 // panel to the next valid position which, in this case, is the bottom
13753 // dock.
13754 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13755 workspace.update(cx, |workspace, cx| {
13756 assert!(workspace.bottom_dock().read(cx).is_open());
13757 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13758 });
13759
13760 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13761 // around moving the panel to its initial position, the right dock.
13762 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13763 workspace.update(cx, |workspace, cx| {
13764 assert!(workspace.right_dock().read(cx).is_open());
13765 assert_eq!(panel.read(cx).position, DockPosition::Right);
13766 });
13767
13768 // Remove focus from the panel, ensuring that, if the panel is not
13769 // focused, the `MoveFocusedPanelToNextPosition` action does not update
13770 // the panel's position, so the panel is still in the right dock.
13771 workspace.update_in(cx, |workspace, window, cx| {
13772 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13773 });
13774
13775 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13776 workspace.update(cx, |workspace, cx| {
13777 assert!(workspace.right_dock().read(cx).is_open());
13778 assert_eq!(panel.read(cx).position, DockPosition::Right);
13779 });
13780 }
13781
13782 #[gpui::test]
13783 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13784 init_test(cx);
13785
13786 let fs = FakeFs::new(cx.executor());
13787 let project = Project::test(fs, [], cx).await;
13788 let (workspace, cx) =
13789 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13790
13791 let item_1 = cx.new(|cx| {
13792 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13793 });
13794 workspace.update_in(cx, |workspace, window, cx| {
13795 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13796 workspace.move_item_to_pane_in_direction(
13797 &MoveItemToPaneInDirection {
13798 direction: SplitDirection::Right,
13799 focus: true,
13800 clone: false,
13801 },
13802 window,
13803 cx,
13804 );
13805 workspace.move_item_to_pane_at_index(
13806 &MoveItemToPane {
13807 destination: 3,
13808 focus: true,
13809 clone: false,
13810 },
13811 window,
13812 cx,
13813 );
13814
13815 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13816 assert_eq!(
13817 pane_items_paths(&workspace.active_pane, cx),
13818 vec!["first.txt".to_string()],
13819 "Single item was not moved anywhere"
13820 );
13821 });
13822
13823 let item_2 = cx.new(|cx| {
13824 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13825 });
13826 workspace.update_in(cx, |workspace, window, cx| {
13827 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13828 assert_eq!(
13829 pane_items_paths(&workspace.panes[0], cx),
13830 vec!["first.txt".to_string(), "second.txt".to_string()],
13831 );
13832 workspace.move_item_to_pane_in_direction(
13833 &MoveItemToPaneInDirection {
13834 direction: SplitDirection::Right,
13835 focus: true,
13836 clone: false,
13837 },
13838 window,
13839 cx,
13840 );
13841
13842 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13843 assert_eq!(
13844 pane_items_paths(&workspace.panes[0], cx),
13845 vec!["first.txt".to_string()],
13846 "After moving, one item should be left in the original pane"
13847 );
13848 assert_eq!(
13849 pane_items_paths(&workspace.panes[1], cx),
13850 vec!["second.txt".to_string()],
13851 "New item should have been moved to the new pane"
13852 );
13853 });
13854
13855 let item_3 = cx.new(|cx| {
13856 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13857 });
13858 workspace.update_in(cx, |workspace, window, cx| {
13859 let original_pane = workspace.panes[0].clone();
13860 workspace.set_active_pane(&original_pane, window, cx);
13861 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13862 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13863 assert_eq!(
13864 pane_items_paths(&workspace.active_pane, cx),
13865 vec!["first.txt".to_string(), "third.txt".to_string()],
13866 "New pane should be ready to move one item out"
13867 );
13868
13869 workspace.move_item_to_pane_at_index(
13870 &MoveItemToPane {
13871 destination: 3,
13872 focus: true,
13873 clone: false,
13874 },
13875 window,
13876 cx,
13877 );
13878 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13879 assert_eq!(
13880 pane_items_paths(&workspace.active_pane, cx),
13881 vec!["first.txt".to_string()],
13882 "After moving, one item should be left in the original pane"
13883 );
13884 assert_eq!(
13885 pane_items_paths(&workspace.panes[1], cx),
13886 vec!["second.txt".to_string()],
13887 "Previously created pane should be unchanged"
13888 );
13889 assert_eq!(
13890 pane_items_paths(&workspace.panes[2], cx),
13891 vec!["third.txt".to_string()],
13892 "New item should have been moved to the new pane"
13893 );
13894 });
13895 }
13896
13897 #[gpui::test]
13898 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13899 init_test(cx);
13900
13901 let fs = FakeFs::new(cx.executor());
13902 let project = Project::test(fs, [], cx).await;
13903 let (workspace, cx) =
13904 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13905
13906 let item_1 = cx.new(|cx| {
13907 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13908 });
13909 workspace.update_in(cx, |workspace, window, cx| {
13910 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13911 workspace.move_item_to_pane_in_direction(
13912 &MoveItemToPaneInDirection {
13913 direction: SplitDirection::Right,
13914 focus: true,
13915 clone: true,
13916 },
13917 window,
13918 cx,
13919 );
13920 });
13921 cx.run_until_parked();
13922 workspace.update_in(cx, |workspace, window, cx| {
13923 workspace.move_item_to_pane_at_index(
13924 &MoveItemToPane {
13925 destination: 3,
13926 focus: true,
13927 clone: true,
13928 },
13929 window,
13930 cx,
13931 );
13932 });
13933 cx.run_until_parked();
13934
13935 workspace.update(cx, |workspace, cx| {
13936 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13937 for pane in workspace.panes() {
13938 assert_eq!(
13939 pane_items_paths(pane, cx),
13940 vec!["first.txt".to_string()],
13941 "Single item exists in all panes"
13942 );
13943 }
13944 });
13945
13946 // verify that the active pane has been updated after waiting for the
13947 // pane focus event to fire and resolve
13948 workspace.read_with(cx, |workspace, _app| {
13949 assert_eq!(
13950 workspace.active_pane(),
13951 &workspace.panes[2],
13952 "The third pane should be the active one: {:?}",
13953 workspace.panes
13954 );
13955 })
13956 }
13957
13958 #[gpui::test]
13959 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13960 init_test(cx);
13961
13962 let fs = FakeFs::new(cx.executor());
13963 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13964
13965 let project = Project::test(fs, ["root".as_ref()], cx).await;
13966 let (workspace, cx) =
13967 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13968
13969 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13970 // Add item to pane A with project path
13971 let item_a = cx.new(|cx| {
13972 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13973 });
13974 workspace.update_in(cx, |workspace, window, cx| {
13975 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13976 });
13977
13978 // Split to create pane B
13979 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13980 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13981 });
13982
13983 // Add item with SAME project path to pane B, and pin it
13984 let item_b = cx.new(|cx| {
13985 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13986 });
13987 pane_b.update_in(cx, |pane, window, cx| {
13988 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13989 pane.set_pinned_count(1);
13990 });
13991
13992 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13993 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13994
13995 // close_pinned: false should only close the unpinned copy
13996 workspace.update_in(cx, |workspace, window, cx| {
13997 workspace.close_item_in_all_panes(
13998 &CloseItemInAllPanes {
13999 save_intent: Some(SaveIntent::Close),
14000 close_pinned: false,
14001 },
14002 window,
14003 cx,
14004 )
14005 });
14006 cx.executor().run_until_parked();
14007
14008 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14009 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14010 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14011 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14012
14013 // Split again, seeing as closing the previous item also closed its
14014 // pane, so only pane remains, which does not allow us to properly test
14015 // that both items close when `close_pinned: true`.
14016 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14017 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14018 });
14019
14020 // Add an item with the same project path to pane C so that
14021 // close_item_in_all_panes can determine what to close across all panes
14022 // (it reads the active item from the active pane, and split_pane
14023 // creates an empty pane).
14024 let item_c = cx.new(|cx| {
14025 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14026 });
14027 pane_c.update_in(cx, |pane, window, cx| {
14028 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14029 });
14030
14031 // close_pinned: true should close the pinned copy too
14032 workspace.update_in(cx, |workspace, window, cx| {
14033 let panes_count = workspace.panes().len();
14034 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14035
14036 workspace.close_item_in_all_panes(
14037 &CloseItemInAllPanes {
14038 save_intent: Some(SaveIntent::Close),
14039 close_pinned: true,
14040 },
14041 window,
14042 cx,
14043 )
14044 });
14045 cx.executor().run_until_parked();
14046
14047 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14048 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14049 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14050 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14051 }
14052
14053 mod register_project_item_tests {
14054
14055 use super::*;
14056
14057 // View
14058 struct TestPngItemView {
14059 focus_handle: FocusHandle,
14060 }
14061 // Model
14062 struct TestPngItem {}
14063
14064 impl project::ProjectItem for TestPngItem {
14065 fn try_open(
14066 _project: &Entity<Project>,
14067 path: &ProjectPath,
14068 cx: &mut App,
14069 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14070 if path.path.extension().unwrap() == "png" {
14071 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14072 } else {
14073 None
14074 }
14075 }
14076
14077 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14078 None
14079 }
14080
14081 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14082 None
14083 }
14084
14085 fn is_dirty(&self) -> bool {
14086 false
14087 }
14088 }
14089
14090 impl Item for TestPngItemView {
14091 type Event = ();
14092 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14093 "".into()
14094 }
14095 }
14096 impl EventEmitter<()> for TestPngItemView {}
14097 impl Focusable for TestPngItemView {
14098 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14099 self.focus_handle.clone()
14100 }
14101 }
14102
14103 impl Render for TestPngItemView {
14104 fn render(
14105 &mut self,
14106 _window: &mut Window,
14107 _cx: &mut Context<Self>,
14108 ) -> impl IntoElement {
14109 Empty
14110 }
14111 }
14112
14113 impl ProjectItem for TestPngItemView {
14114 type Item = TestPngItem;
14115
14116 fn for_project_item(
14117 _project: Entity<Project>,
14118 _pane: Option<&Pane>,
14119 _item: Entity<Self::Item>,
14120 _: &mut Window,
14121 cx: &mut Context<Self>,
14122 ) -> Self
14123 where
14124 Self: Sized,
14125 {
14126 Self {
14127 focus_handle: cx.focus_handle(),
14128 }
14129 }
14130 }
14131
14132 // View
14133 struct TestIpynbItemView {
14134 focus_handle: FocusHandle,
14135 }
14136 // Model
14137 struct TestIpynbItem {}
14138
14139 impl project::ProjectItem for TestIpynbItem {
14140 fn try_open(
14141 _project: &Entity<Project>,
14142 path: &ProjectPath,
14143 cx: &mut App,
14144 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14145 if path.path.extension().unwrap() == "ipynb" {
14146 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14147 } else {
14148 None
14149 }
14150 }
14151
14152 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14153 None
14154 }
14155
14156 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14157 None
14158 }
14159
14160 fn is_dirty(&self) -> bool {
14161 false
14162 }
14163 }
14164
14165 impl Item for TestIpynbItemView {
14166 type Event = ();
14167 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14168 "".into()
14169 }
14170 }
14171 impl EventEmitter<()> for TestIpynbItemView {}
14172 impl Focusable for TestIpynbItemView {
14173 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14174 self.focus_handle.clone()
14175 }
14176 }
14177
14178 impl Render for TestIpynbItemView {
14179 fn render(
14180 &mut self,
14181 _window: &mut Window,
14182 _cx: &mut Context<Self>,
14183 ) -> impl IntoElement {
14184 Empty
14185 }
14186 }
14187
14188 impl ProjectItem for TestIpynbItemView {
14189 type Item = TestIpynbItem;
14190
14191 fn for_project_item(
14192 _project: Entity<Project>,
14193 _pane: Option<&Pane>,
14194 _item: Entity<Self::Item>,
14195 _: &mut Window,
14196 cx: &mut Context<Self>,
14197 ) -> Self
14198 where
14199 Self: Sized,
14200 {
14201 Self {
14202 focus_handle: cx.focus_handle(),
14203 }
14204 }
14205 }
14206
14207 struct TestAlternatePngItemView {
14208 focus_handle: FocusHandle,
14209 }
14210
14211 impl Item for TestAlternatePngItemView {
14212 type Event = ();
14213 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14214 "".into()
14215 }
14216 }
14217
14218 impl EventEmitter<()> for TestAlternatePngItemView {}
14219 impl Focusable for TestAlternatePngItemView {
14220 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14221 self.focus_handle.clone()
14222 }
14223 }
14224
14225 impl Render for TestAlternatePngItemView {
14226 fn render(
14227 &mut self,
14228 _window: &mut Window,
14229 _cx: &mut Context<Self>,
14230 ) -> impl IntoElement {
14231 Empty
14232 }
14233 }
14234
14235 impl ProjectItem for TestAlternatePngItemView {
14236 type Item = TestPngItem;
14237
14238 fn for_project_item(
14239 _project: Entity<Project>,
14240 _pane: Option<&Pane>,
14241 _item: Entity<Self::Item>,
14242 _: &mut Window,
14243 cx: &mut Context<Self>,
14244 ) -> Self
14245 where
14246 Self: Sized,
14247 {
14248 Self {
14249 focus_handle: cx.focus_handle(),
14250 }
14251 }
14252 }
14253
14254 #[gpui::test]
14255 async fn test_register_project_item(cx: &mut TestAppContext) {
14256 init_test(cx);
14257
14258 cx.update(|cx| {
14259 register_project_item::<TestPngItemView>(cx);
14260 register_project_item::<TestIpynbItemView>(cx);
14261 });
14262
14263 let fs = FakeFs::new(cx.executor());
14264 fs.insert_tree(
14265 "/root1",
14266 json!({
14267 "one.png": "BINARYDATAHERE",
14268 "two.ipynb": "{ totally a notebook }",
14269 "three.txt": "editing text, sure why not?"
14270 }),
14271 )
14272 .await;
14273
14274 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14275 let (workspace, cx) =
14276 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14277
14278 let worktree_id = project.update(cx, |project, cx| {
14279 project.worktrees(cx).next().unwrap().read(cx).id()
14280 });
14281
14282 let handle = workspace
14283 .update_in(cx, |workspace, window, cx| {
14284 let project_path = (worktree_id, rel_path("one.png"));
14285 workspace.open_path(project_path, None, true, window, cx)
14286 })
14287 .await
14288 .unwrap();
14289
14290 // Now we can check if the handle we got back errored or not
14291 assert_eq!(
14292 handle.to_any_view().entity_type(),
14293 TypeId::of::<TestPngItemView>()
14294 );
14295
14296 let handle = workspace
14297 .update_in(cx, |workspace, window, cx| {
14298 let project_path = (worktree_id, rel_path("two.ipynb"));
14299 workspace.open_path(project_path, None, true, window, cx)
14300 })
14301 .await
14302 .unwrap();
14303
14304 assert_eq!(
14305 handle.to_any_view().entity_type(),
14306 TypeId::of::<TestIpynbItemView>()
14307 );
14308
14309 let handle = workspace
14310 .update_in(cx, |workspace, window, cx| {
14311 let project_path = (worktree_id, rel_path("three.txt"));
14312 workspace.open_path(project_path, None, true, window, cx)
14313 })
14314 .await;
14315 assert!(handle.is_err());
14316 }
14317
14318 #[gpui::test]
14319 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14320 init_test(cx);
14321
14322 cx.update(|cx| {
14323 register_project_item::<TestPngItemView>(cx);
14324 register_project_item::<TestAlternatePngItemView>(cx);
14325 });
14326
14327 let fs = FakeFs::new(cx.executor());
14328 fs.insert_tree(
14329 "/root1",
14330 json!({
14331 "one.png": "BINARYDATAHERE",
14332 "two.ipynb": "{ totally a notebook }",
14333 "three.txt": "editing text, sure why not?"
14334 }),
14335 )
14336 .await;
14337 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14338 let (workspace, cx) =
14339 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14340 let worktree_id = project.update(cx, |project, cx| {
14341 project.worktrees(cx).next().unwrap().read(cx).id()
14342 });
14343
14344 let handle = workspace
14345 .update_in(cx, |workspace, window, cx| {
14346 let project_path = (worktree_id, rel_path("one.png"));
14347 workspace.open_path(project_path, None, true, window, cx)
14348 })
14349 .await
14350 .unwrap();
14351
14352 // This _must_ be the second item registered
14353 assert_eq!(
14354 handle.to_any_view().entity_type(),
14355 TypeId::of::<TestAlternatePngItemView>()
14356 );
14357
14358 let handle = workspace
14359 .update_in(cx, |workspace, window, cx| {
14360 let project_path = (worktree_id, rel_path("three.txt"));
14361 workspace.open_path(project_path, None, true, window, cx)
14362 })
14363 .await;
14364 assert!(handle.is_err());
14365 }
14366 }
14367
14368 #[gpui::test]
14369 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14370 init_test(cx);
14371
14372 let fs = FakeFs::new(cx.executor());
14373 let project = Project::test(fs, [], cx).await;
14374 let (workspace, _cx) =
14375 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14376
14377 // Test with status bar shown (default)
14378 workspace.read_with(cx, |workspace, cx| {
14379 let visible = workspace.status_bar_visible(cx);
14380 assert!(visible, "Status bar should be visible by default");
14381 });
14382
14383 // Test with status bar hidden
14384 cx.update_global(|store: &mut SettingsStore, cx| {
14385 store.update_user_settings(cx, |settings| {
14386 settings.status_bar.get_or_insert_default().show = Some(false);
14387 });
14388 });
14389
14390 workspace.read_with(cx, |workspace, cx| {
14391 let visible = workspace.status_bar_visible(cx);
14392 assert!(!visible, "Status bar should be hidden when show is false");
14393 });
14394
14395 // Test with status bar shown explicitly
14396 cx.update_global(|store: &mut SettingsStore, cx| {
14397 store.update_user_settings(cx, |settings| {
14398 settings.status_bar.get_or_insert_default().show = Some(true);
14399 });
14400 });
14401
14402 workspace.read_with(cx, |workspace, cx| {
14403 let visible = workspace.status_bar_visible(cx);
14404 assert!(visible, "Status bar should be visible when show is true");
14405 });
14406 }
14407
14408 #[gpui::test]
14409 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14410 init_test(cx);
14411
14412 let fs = FakeFs::new(cx.executor());
14413 let project = Project::test(fs, [], cx).await;
14414 let (multi_workspace, cx) =
14415 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14416 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14417 let panel = workspace.update_in(cx, |workspace, window, cx| {
14418 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14419 workspace.add_panel(panel.clone(), window, cx);
14420
14421 workspace
14422 .right_dock()
14423 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14424
14425 panel
14426 });
14427
14428 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14429 let item_a = cx.new(TestItem::new);
14430 let item_b = cx.new(TestItem::new);
14431 let item_a_id = item_a.entity_id();
14432 let item_b_id = item_b.entity_id();
14433
14434 pane.update_in(cx, |pane, window, cx| {
14435 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14436 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14437 });
14438
14439 pane.read_with(cx, |pane, _| {
14440 assert_eq!(pane.items_len(), 2);
14441 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14442 });
14443
14444 workspace.update_in(cx, |workspace, window, cx| {
14445 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14446 });
14447
14448 workspace.update_in(cx, |_, window, cx| {
14449 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14450 });
14451
14452 // Assert that the `pane::CloseActiveItem` action is handled at the
14453 // workspace level when one of the dock panels is focused and, in that
14454 // case, the center pane's active item is closed but the focus is not
14455 // moved.
14456 cx.dispatch_action(pane::CloseActiveItem::default());
14457 cx.run_until_parked();
14458
14459 pane.read_with(cx, |pane, _| {
14460 assert_eq!(pane.items_len(), 1);
14461 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14462 });
14463
14464 workspace.update_in(cx, |workspace, window, cx| {
14465 assert!(workspace.right_dock().read(cx).is_open());
14466 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14467 });
14468 }
14469
14470 #[gpui::test]
14471 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14472 init_test(cx);
14473 let fs = FakeFs::new(cx.executor());
14474
14475 let project_a = Project::test(fs.clone(), [], cx).await;
14476 let project_b = Project::test(fs, [], cx).await;
14477
14478 let multi_workspace_handle =
14479 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14480 cx.run_until_parked();
14481
14482 let workspace_a = multi_workspace_handle
14483 .read_with(cx, |mw, _| mw.workspace().clone())
14484 .unwrap();
14485
14486 let _workspace_b = multi_workspace_handle
14487 .update(cx, |mw, window, cx| {
14488 mw.test_add_workspace(project_b, window, cx)
14489 })
14490 .unwrap();
14491
14492 // Switch to workspace A
14493 multi_workspace_handle
14494 .update(cx, |mw, window, cx| {
14495 let workspace = mw.workspaces()[0].clone();
14496 mw.activate(workspace, window, cx);
14497 })
14498 .unwrap();
14499
14500 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14501
14502 // Add a panel to workspace A's right dock and open the dock
14503 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14504 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14505 workspace.add_panel(panel.clone(), window, cx);
14506 workspace
14507 .right_dock()
14508 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14509 panel
14510 });
14511
14512 // Focus the panel through the workspace (matching existing test pattern)
14513 workspace_a.update_in(cx, |workspace, window, cx| {
14514 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14515 });
14516
14517 // Zoom the panel
14518 panel.update_in(cx, |panel, window, cx| {
14519 panel.set_zoomed(true, window, cx);
14520 });
14521
14522 // Verify the panel is zoomed and the dock is open
14523 workspace_a.update_in(cx, |workspace, window, cx| {
14524 assert!(
14525 workspace.right_dock().read(cx).is_open(),
14526 "dock should be open before switch"
14527 );
14528 assert!(
14529 panel.is_zoomed(window, cx),
14530 "panel should be zoomed before switch"
14531 );
14532 assert!(
14533 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14534 "panel should be focused before switch"
14535 );
14536 });
14537
14538 // Switch to workspace B
14539 multi_workspace_handle
14540 .update(cx, |mw, window, cx| {
14541 let workspace = mw.workspaces()[1].clone();
14542 mw.activate(workspace, window, cx);
14543 })
14544 .unwrap();
14545 cx.run_until_parked();
14546
14547 // Switch back to workspace A
14548 multi_workspace_handle
14549 .update(cx, |mw, window, cx| {
14550 let workspace = mw.workspaces()[0].clone();
14551 mw.activate(workspace, window, cx);
14552 })
14553 .unwrap();
14554 cx.run_until_parked();
14555
14556 // Verify the panel is still zoomed and the dock is still open
14557 workspace_a.update_in(cx, |workspace, window, cx| {
14558 assert!(
14559 workspace.right_dock().read(cx).is_open(),
14560 "dock should still be open after switching back"
14561 );
14562 assert!(
14563 panel.is_zoomed(window, cx),
14564 "panel should still be zoomed after switching back"
14565 );
14566 });
14567 }
14568
14569 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14570 pane.read(cx)
14571 .items()
14572 .flat_map(|item| {
14573 item.project_paths(cx)
14574 .into_iter()
14575 .map(|path| path.path.display(PathStyle::local()).into_owned())
14576 })
14577 .collect()
14578 }
14579
14580 pub fn init_test(cx: &mut TestAppContext) {
14581 cx.update(|cx| {
14582 let settings_store = SettingsStore::test(cx);
14583 cx.set_global(settings_store);
14584 cx.set_global(db::AppDatabase::test_new());
14585 theme_settings::init(theme::LoadThemes::JustBase, cx);
14586 });
14587 }
14588
14589 #[gpui::test]
14590 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14591 use settings::{ThemeName, ThemeSelection};
14592 use theme::SystemAppearance;
14593 use zed_actions::theme::ToggleMode;
14594
14595 init_test(cx);
14596
14597 let fs = FakeFs::new(cx.executor());
14598 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14599
14600 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14601 .await;
14602
14603 // Build a test project and workspace view so the test can invoke
14604 // the workspace action handler the same way the UI would.
14605 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14606 let (workspace, cx) =
14607 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14608
14609 // Seed the settings file with a plain static light theme so the
14610 // first toggle always starts from a known persisted state.
14611 workspace.update_in(cx, |_workspace, _window, cx| {
14612 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14613 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14614 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14615 });
14616 });
14617 cx.executor().advance_clock(Duration::from_millis(200));
14618 cx.run_until_parked();
14619
14620 // Confirm the initial persisted settings contain the static theme
14621 // we just wrote before any toggling happens.
14622 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14623 assert!(settings_text.contains(r#""theme": "One Light""#));
14624
14625 // Toggle once. This should migrate the persisted theme settings
14626 // into light/dark slots and enable system mode.
14627 workspace.update_in(cx, |workspace, window, cx| {
14628 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14629 });
14630 cx.executor().advance_clock(Duration::from_millis(200));
14631 cx.run_until_parked();
14632
14633 // 1. Static -> Dynamic
14634 // this assertion checks theme changed from static to dynamic.
14635 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14636 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14637 assert_eq!(
14638 parsed["theme"],
14639 serde_json::json!({
14640 "mode": "system",
14641 "light": "One Light",
14642 "dark": "One Dark"
14643 })
14644 );
14645
14646 // 2. Toggle again, suppose it will change the mode to light
14647 workspace.update_in(cx, |workspace, window, cx| {
14648 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14649 });
14650 cx.executor().advance_clock(Duration::from_millis(200));
14651 cx.run_until_parked();
14652
14653 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14654 assert!(settings_text.contains(r#""mode": "light""#));
14655 }
14656
14657 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14658 let item = TestProjectItem::new(id, path, cx);
14659 item.update(cx, |item, _| {
14660 item.is_dirty = true;
14661 });
14662 item
14663 }
14664
14665 #[gpui::test]
14666 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14667 cx: &mut gpui::TestAppContext,
14668 ) {
14669 init_test(cx);
14670 let fs = FakeFs::new(cx.executor());
14671
14672 let project = Project::test(fs, [], cx).await;
14673 let (workspace, cx) =
14674 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14675
14676 let panel = workspace.update_in(cx, |workspace, window, cx| {
14677 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14678 workspace.add_panel(panel.clone(), window, cx);
14679 workspace
14680 .right_dock()
14681 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14682 panel
14683 });
14684
14685 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14686 pane.update_in(cx, |pane, window, cx| {
14687 let item = cx.new(TestItem::new);
14688 pane.add_item(Box::new(item), true, true, None, window, cx);
14689 });
14690
14691 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14692 // mirrors the real-world flow and avoids side effects from directly
14693 // focusing the panel while the center pane is active.
14694 workspace.update_in(cx, |workspace, window, cx| {
14695 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14696 });
14697
14698 panel.update_in(cx, |panel, window, cx| {
14699 panel.set_zoomed(true, window, cx);
14700 });
14701
14702 workspace.update_in(cx, |workspace, window, cx| {
14703 assert!(workspace.right_dock().read(cx).is_open());
14704 assert!(panel.is_zoomed(window, cx));
14705 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14706 });
14707
14708 // Simulate a spurious pane::Event::Focus on the center pane while the
14709 // panel still has focus. This mirrors what happens during macOS window
14710 // activation: the center pane fires a focus event even though actual
14711 // focus remains on the dock panel.
14712 pane.update_in(cx, |_, _, cx| {
14713 cx.emit(pane::Event::Focus);
14714 });
14715
14716 // The dock must remain open because the panel had focus at the time the
14717 // event was processed. Before the fix, dock_to_preserve was None for
14718 // panels that don't implement pane(), causing the dock to close.
14719 workspace.update_in(cx, |workspace, window, cx| {
14720 assert!(
14721 workspace.right_dock().read(cx).is_open(),
14722 "Dock should stay open when its zoomed panel (without pane()) still has focus"
14723 );
14724 assert!(panel.is_zoomed(window, cx));
14725 });
14726 }
14727
14728 #[gpui::test]
14729 async fn test_panels_stay_open_after_position_change_and_settings_update(
14730 cx: &mut gpui::TestAppContext,
14731 ) {
14732 init_test(cx);
14733 let fs = FakeFs::new(cx.executor());
14734 let project = Project::test(fs, [], cx).await;
14735 let (workspace, cx) =
14736 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14737
14738 // Add two panels to the left dock and open it.
14739 let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14740 let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14741 let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14742 workspace.add_panel(panel_a.clone(), window, cx);
14743 workspace.add_panel(panel_b.clone(), window, cx);
14744 workspace.left_dock().update(cx, |dock, cx| {
14745 dock.set_open(true, window, cx);
14746 dock.activate_panel(0, window, cx);
14747 });
14748 (panel_a, panel_b)
14749 });
14750
14751 workspace.update_in(cx, |workspace, _, cx| {
14752 assert!(workspace.left_dock().read(cx).is_open());
14753 });
14754
14755 // Simulate a feature flag changing default dock positions: both panels
14756 // move from Left to Right.
14757 workspace.update_in(cx, |_workspace, _window, cx| {
14758 panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14759 panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14760 cx.update_global::<SettingsStore, _>(|_, _| {});
14761 });
14762
14763 // Both panels should now be in the right dock.
14764 workspace.update_in(cx, |workspace, _, cx| {
14765 let right_dock = workspace.right_dock().read(cx);
14766 assert_eq!(right_dock.panels_len(), 2);
14767 });
14768
14769 // Open the right dock and activate panel_b (simulating the user
14770 // opening the panel after it moved).
14771 workspace.update_in(cx, |workspace, window, cx| {
14772 workspace.right_dock().update(cx, |dock, cx| {
14773 dock.set_open(true, window, cx);
14774 dock.activate_panel(1, window, cx);
14775 });
14776 });
14777
14778 // Now trigger another SettingsStore change
14779 workspace.update_in(cx, |_workspace, _window, cx| {
14780 cx.update_global::<SettingsStore, _>(|_, _| {});
14781 });
14782
14783 workspace.update_in(cx, |workspace, _, cx| {
14784 assert!(
14785 workspace.right_dock().read(cx).is_open(),
14786 "Right dock should still be open after a settings change"
14787 );
14788 assert_eq!(
14789 workspace.right_dock().read(cx).panels_len(),
14790 2,
14791 "Both panels should still be in the right dock"
14792 );
14793 });
14794 }
14795}