1pub mod active_file_name;
2pub mod dock;
3pub mod history_manager;
4pub mod invalid_item_view;
5pub mod item;
6mod modal_layer;
7mod multi_workspace;
8pub mod notifications;
9pub mod pane;
10pub mod pane_group;
11pub mod path_list {
12 pub use util::path_list::{PathList, SerializedPathList};
13}
14mod persistence;
15pub mod searchable;
16mod security_modal;
17pub mod shared_screen;
18use db::smol::future::yield_now;
19pub use shared_screen::SharedScreen;
20mod status_bar;
21pub mod tasks;
22mod theme_preview;
23mod toast_layer;
24mod toolbar;
25pub mod welcome;
26mod workspace_settings;
27
28pub use crate::notifications::NotificationFrame;
29pub use dock::Panel;
30pub use multi_workspace::{
31 CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
32 MultiWorkspaceEvent, NextWorkspace, PreviousWorkspace, Sidebar, SidebarHandle,
33 SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar, sidebar_side_context_menu,
34};
35pub use path_list::{PathList, SerializedPathList};
36pub use toast_layer::{ToastAction, ToastLayer, ToastView};
37
38use anyhow::{Context as _, Result, anyhow};
39use client::{
40 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
41 proto::{self, ErrorCode, PanelId, PeerId},
42};
43use collections::{HashMap, HashSet, hash_map};
44use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
45use fs::Fs;
46use futures::{
47 Future, FutureExt, StreamExt,
48 channel::{
49 mpsc::{self, UnboundedReceiver, UnboundedSender},
50 oneshot,
51 },
52 future::{Shared, try_join_all},
53};
54use gpui::{
55 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
56 Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
57 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
58 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
59 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
60 WindowOptions, actions, canvas, point, relative, size, transparent_black,
61};
62pub use history_manager::*;
63pub use item::{
64 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
65 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
66};
67use itertools::Itertools;
68use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
69pub use modal_layer::*;
70use node_runtime::NodeRuntime;
71use notifications::{
72 DetachAndPromptErr, Notifications, dismiss_app_notification,
73 simple_message_notification::MessageNotification,
74};
75pub use pane::*;
76pub use pane_group::{
77 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
78 SplitDirection,
79};
80use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
81pub use persistence::{
82 WorkspaceDb, delete_unloaded_items,
83 model::{
84 DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
85 SessionWorkspace,
86 },
87 read_serialized_multi_workspaces, resolve_worktree_workspaces,
88};
89use postage::stream::Stream;
90use project::{
91 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
92 WorktreeSettings,
93 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
94 project_settings::ProjectSettings,
95 toolchain_store::ToolchainStoreEvent,
96 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
97};
98use remote::{
99 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
100 remote_client::ConnectionIdentifier,
101};
102use schemars::JsonSchema;
103use serde::Deserialize;
104use session::AppSession;
105use settings::{
106 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
107};
108
109use sqlez::{
110 bindable::{Bind, Column, StaticColumnCount},
111 statement::Statement,
112};
113use status_bar::StatusBar;
114pub use status_bar::StatusItemView;
115use std::{
116 any::TypeId,
117 borrow::Cow,
118 cell::RefCell,
119 cmp,
120 collections::VecDeque,
121 env,
122 hash::Hash,
123 path::{Path, PathBuf},
124 process::ExitStatus,
125 rc::Rc,
126 sync::{
127 Arc, LazyLock, Weak,
128 atomic::{AtomicBool, AtomicUsize},
129 },
130 time::Duration,
131};
132use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
133use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
134pub use toolbar::{
135 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
136};
137pub use ui;
138use ui::{Window, prelude::*};
139use util::{
140 ResultExt, TryFutureExt,
141 paths::{PathStyle, SanitizedPath},
142 rel_path::RelPath,
143 serde::default_true,
144};
145use uuid::Uuid;
146pub use workspace_settings::{
147 AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
148 WorkspaceSettings,
149};
150use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
151
152use crate::{item::ItemBufferKind, notifications::NotificationId};
153use crate::{
154 persistence::{
155 SerializedAxis,
156 model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
157 },
158 security_modal::SecurityModal,
159};
160
161pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
162
163static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
164 env::var("ZED_WINDOW_SIZE")
165 .ok()
166 .as_deref()
167 .and_then(parse_pixel_size_env_var)
168});
169
170static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
171 env::var("ZED_WINDOW_POSITION")
172 .ok()
173 .as_deref()
174 .and_then(parse_pixel_position_env_var)
175});
176
177pub trait TerminalProvider {
178 fn spawn(
179 &self,
180 task: SpawnInTerminal,
181 window: &mut Window,
182 cx: &mut App,
183 ) -> Task<Option<Result<ExitStatus>>>;
184}
185
186pub trait DebuggerProvider {
187 // `active_buffer` is used to resolve build task's name against language-specific tasks.
188 fn start_session(
189 &self,
190 definition: DebugScenario,
191 task_context: SharedTaskContext,
192 active_buffer: Option<Entity<Buffer>>,
193 worktree_id: Option<WorktreeId>,
194 window: &mut Window,
195 cx: &mut App,
196 );
197
198 fn spawn_task_or_modal(
199 &self,
200 workspace: &mut Workspace,
201 action: &Spawn,
202 window: &mut Window,
203 cx: &mut Context<Workspace>,
204 );
205
206 fn task_scheduled(&self, cx: &mut App);
207 fn debug_scenario_scheduled(&self, cx: &mut App);
208 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
209
210 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
211}
212
213/// Opens a file or directory.
214#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
215#[action(namespace = workspace)]
216pub struct Open {
217 /// When true, opens in a new window. When false, adds to the current
218 /// window as a new workspace (multi-workspace).
219 #[serde(default = "Open::default_create_new_window")]
220 pub create_new_window: bool,
221}
222
223impl Open {
224 pub const DEFAULT: Self = Self {
225 create_new_window: true,
226 };
227
228 /// Used by `#[serde(default)]` on the `create_new_window` field so that
229 /// the serde default and `Open::DEFAULT` stay in sync.
230 fn default_create_new_window() -> bool {
231 Self::DEFAULT.create_new_window
232 }
233}
234
235impl Default for Open {
236 fn default() -> Self {
237 Self::DEFAULT
238 }
239}
240
241actions!(
242 workspace,
243 [
244 /// Activates the next pane in the workspace.
245 ActivateNextPane,
246 /// Activates the previous pane in the workspace.
247 ActivatePreviousPane,
248 /// Activates the last pane in the workspace.
249 ActivateLastPane,
250 /// Switches to the next window.
251 ActivateNextWindow,
252 /// Switches to the previous window.
253 ActivatePreviousWindow,
254 /// Adds a folder to the current project.
255 AddFolderToProject,
256 /// Clears all notifications.
257 ClearAllNotifications,
258 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
259 ClearNavigationHistory,
260 /// Closes the active dock.
261 CloseActiveDock,
262 /// Closes all docks.
263 CloseAllDocks,
264 /// Toggles all docks.
265 ToggleAllDocks,
266 /// Closes the current window.
267 CloseWindow,
268 /// Closes the current project.
269 CloseProject,
270 /// Opens the feedback dialog.
271 Feedback,
272 /// Follows the next collaborator in the session.
273 FollowNextCollaborator,
274 /// Moves the focused panel to the next position.
275 MoveFocusedPanelToNextPosition,
276 /// Creates a new file.
277 NewFile,
278 /// Creates a new file in a vertical split.
279 NewFileSplitVertical,
280 /// Creates a new file in a horizontal split.
281 NewFileSplitHorizontal,
282 /// Opens a new search.
283 NewSearch,
284 /// Opens a new window.
285 NewWindow,
286 /// Opens multiple files.
287 OpenFiles,
288 /// Opens the current location in terminal.
289 OpenInTerminal,
290 /// Opens the component preview.
291 OpenComponentPreview,
292 /// Reloads the active item.
293 ReloadActiveItem,
294 /// Resets the active dock to its default size.
295 ResetActiveDockSize,
296 /// Resets all open docks to their default sizes.
297 ResetOpenDocksSize,
298 /// Reloads the application
299 Reload,
300 /// Saves the current file with a new name.
301 SaveAs,
302 /// Saves without formatting.
303 SaveWithoutFormat,
304 /// Shuts down all debug adapters.
305 ShutdownDebugAdapters,
306 /// Suppresses the current notification.
307 SuppressNotification,
308 /// Toggles the bottom dock.
309 ToggleBottomDock,
310 /// Toggles centered layout mode.
311 ToggleCenteredLayout,
312 /// Toggles edit prediction feature globally for all files.
313 ToggleEditPrediction,
314 /// Toggles the left dock.
315 ToggleLeftDock,
316 /// Toggles the right dock.
317 ToggleRightDock,
318 /// Toggles zoom on the active pane.
319 ToggleZoom,
320 /// Toggles read-only mode for the active item (if supported by that item).
321 ToggleReadOnlyFile,
322 /// Zooms in on the active pane.
323 ZoomIn,
324 /// Zooms out of the active pane.
325 ZoomOut,
326 /// If any worktrees are in restricted mode, shows a modal with possible actions.
327 /// If the modal is shown already, closes it without trusting any worktree.
328 ToggleWorktreeSecurity,
329 /// Clears all trusted worktrees, placing them in restricted mode on next open.
330 /// Requires restart to take effect on already opened projects.
331 ClearTrustedWorktrees,
332 /// Stops following a collaborator.
333 Unfollow,
334 /// Restores the banner.
335 RestoreBanner,
336 /// Toggles expansion of the selected item.
337 ToggleExpandItem,
338 ]
339);
340
341/// Activates a specific pane by its index.
342#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
343#[action(namespace = workspace)]
344pub struct ActivatePane(pub usize);
345
346/// Moves an item to a specific pane by index.
347#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
348#[action(namespace = workspace)]
349#[serde(deny_unknown_fields)]
350pub struct MoveItemToPane {
351 #[serde(default = "default_1")]
352 pub destination: usize,
353 #[serde(default = "default_true")]
354 pub focus: bool,
355 #[serde(default)]
356 pub clone: bool,
357}
358
359fn default_1() -> usize {
360 1
361}
362
363/// Moves an item to a pane in the specified direction.
364#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
365#[action(namespace = workspace)]
366#[serde(deny_unknown_fields)]
367pub struct MoveItemToPaneInDirection {
368 #[serde(default = "default_right")]
369 pub direction: SplitDirection,
370 #[serde(default = "default_true")]
371 pub focus: bool,
372 #[serde(default)]
373 pub clone: bool,
374}
375
376/// Creates a new file in a split of the desired direction.
377#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
378#[action(namespace = workspace)]
379#[serde(deny_unknown_fields)]
380pub struct NewFileSplit(pub SplitDirection);
381
382fn default_right() -> SplitDirection {
383 SplitDirection::Right
384}
385
386/// Saves all open files in the workspace.
387#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
388#[action(namespace = workspace)]
389#[serde(deny_unknown_fields)]
390pub struct SaveAll {
391 #[serde(default)]
392 pub save_intent: Option<SaveIntent>,
393}
394
395/// Saves the current file with the specified options.
396#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
397#[action(namespace = workspace)]
398#[serde(deny_unknown_fields)]
399pub struct Save {
400 #[serde(default)]
401 pub save_intent: Option<SaveIntent>,
402}
403
404/// Moves Focus to the central panes in the workspace.
405#[derive(Clone, Debug, PartialEq, Eq, Action)]
406#[action(namespace = workspace)]
407pub struct FocusCenterPane;
408
409/// Closes all items and panes in the workspace.
410#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
411#[action(namespace = workspace)]
412#[serde(deny_unknown_fields)]
413pub struct CloseAllItemsAndPanes {
414 #[serde(default)]
415 pub save_intent: Option<SaveIntent>,
416}
417
418/// Closes all inactive tabs and panes in the workspace.
419#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
420#[action(namespace = workspace)]
421#[serde(deny_unknown_fields)]
422pub struct CloseInactiveTabsAndPanes {
423 #[serde(default)]
424 pub save_intent: Option<SaveIntent>,
425}
426
427/// Closes the active item across all panes.
428#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
429#[action(namespace = workspace)]
430#[serde(deny_unknown_fields)]
431pub struct CloseItemInAllPanes {
432 #[serde(default)]
433 pub save_intent: Option<SaveIntent>,
434 #[serde(default)]
435 pub close_pinned: bool,
436}
437
438/// Sends a sequence of keystrokes to the active element.
439#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
440#[action(namespace = workspace)]
441pub struct SendKeystrokes(pub String);
442
443actions!(
444 project_symbols,
445 [
446 /// Toggles the project symbols search.
447 #[action(name = "Toggle")]
448 ToggleProjectSymbols
449 ]
450);
451
452/// Toggles the file finder interface.
453#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
454#[action(namespace = file_finder, name = "Toggle")]
455#[serde(deny_unknown_fields)]
456pub struct ToggleFileFinder {
457 #[serde(default)]
458 pub separate_history: bool,
459}
460
461/// Opens a new terminal in the center.
462#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
463#[action(namespace = workspace)]
464#[serde(deny_unknown_fields)]
465pub struct NewCenterTerminal {
466 /// If true, creates a local terminal even in remote projects.
467 #[serde(default)]
468 pub local: bool,
469}
470
471/// Opens a new terminal.
472#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
473#[action(namespace = workspace)]
474#[serde(deny_unknown_fields)]
475pub struct NewTerminal {
476 /// If true, creates a local terminal even in remote projects.
477 #[serde(default)]
478 pub local: bool,
479}
480
481/// Increases size of a currently focused dock by a given amount of pixels.
482#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
483#[action(namespace = workspace)]
484#[serde(deny_unknown_fields)]
485pub struct IncreaseActiveDockSize {
486 /// For 0px parameter, uses UI font size value.
487 #[serde(default)]
488 pub px: u32,
489}
490
491/// Decreases size of a currently focused dock by a given amount of pixels.
492#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
493#[action(namespace = workspace)]
494#[serde(deny_unknown_fields)]
495pub struct DecreaseActiveDockSize {
496 /// For 0px parameter, uses UI font size value.
497 #[serde(default)]
498 pub px: u32,
499}
500
501/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
502#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
503#[action(namespace = workspace)]
504#[serde(deny_unknown_fields)]
505pub struct IncreaseOpenDocksSize {
506 /// For 0px parameter, uses UI font size value.
507 #[serde(default)]
508 pub px: u32,
509}
510
511/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
512#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
513#[action(namespace = workspace)]
514#[serde(deny_unknown_fields)]
515pub struct DecreaseOpenDocksSize {
516 /// For 0px parameter, uses UI font size value.
517 #[serde(default)]
518 pub px: u32,
519}
520
521actions!(
522 workspace,
523 [
524 /// Activates the pane to the left.
525 ActivatePaneLeft,
526 /// Activates the pane to the right.
527 ActivatePaneRight,
528 /// Activates the pane above.
529 ActivatePaneUp,
530 /// Activates the pane below.
531 ActivatePaneDown,
532 /// Swaps the current pane with the one to the left.
533 SwapPaneLeft,
534 /// Swaps the current pane with the one to the right.
535 SwapPaneRight,
536 /// Swaps the current pane with the one above.
537 SwapPaneUp,
538 /// Swaps the current pane with the one below.
539 SwapPaneDown,
540 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
541 SwapPaneAdjacent,
542 /// Move the current pane to be at the far left.
543 MovePaneLeft,
544 /// Move the current pane to be at the far right.
545 MovePaneRight,
546 /// Move the current pane to be at the very top.
547 MovePaneUp,
548 /// Move the current pane to be at the very bottom.
549 MovePaneDown,
550 ]
551);
552
553#[derive(PartialEq, Eq, Debug)]
554pub enum CloseIntent {
555 /// Quit the program entirely.
556 Quit,
557 /// Close a window.
558 CloseWindow,
559 /// Replace the workspace in an existing window.
560 ReplaceWindow,
561}
562
563#[derive(Clone)]
564pub struct Toast {
565 id: NotificationId,
566 msg: Cow<'static, str>,
567 autohide: bool,
568 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
569}
570
571impl Toast {
572 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
573 Toast {
574 id,
575 msg: msg.into(),
576 on_click: None,
577 autohide: false,
578 }
579 }
580
581 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
582 where
583 M: Into<Cow<'static, str>>,
584 F: Fn(&mut Window, &mut App) + 'static,
585 {
586 self.on_click = Some((message.into(), Arc::new(on_click)));
587 self
588 }
589
590 pub fn autohide(mut self) -> Self {
591 self.autohide = true;
592 self
593 }
594}
595
596impl PartialEq for Toast {
597 fn eq(&self, other: &Self) -> bool {
598 self.id == other.id
599 && self.msg == other.msg
600 && self.on_click.is_some() == other.on_click.is_some()
601 }
602}
603
604/// Opens a new terminal with the specified working directory.
605#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
606#[action(namespace = workspace)]
607#[serde(deny_unknown_fields)]
608pub struct OpenTerminal {
609 pub working_directory: PathBuf,
610 /// If true, creates a local terminal even in remote projects.
611 #[serde(default)]
612 pub local: bool,
613}
614
615#[derive(
616 Clone,
617 Copy,
618 Debug,
619 Default,
620 Hash,
621 PartialEq,
622 Eq,
623 PartialOrd,
624 Ord,
625 serde::Serialize,
626 serde::Deserialize,
627)]
628pub struct WorkspaceId(i64);
629
630impl WorkspaceId {
631 pub fn from_i64(value: i64) -> Self {
632 Self(value)
633 }
634}
635
636impl StaticColumnCount for WorkspaceId {}
637impl Bind for WorkspaceId {
638 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
639 self.0.bind(statement, start_index)
640 }
641}
642impl Column for WorkspaceId {
643 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
644 i64::column(statement, start_index)
645 .map(|(i, next_index)| (Self(i), next_index))
646 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
647 }
648}
649impl From<WorkspaceId> for i64 {
650 fn from(val: WorkspaceId) -> Self {
651 val.0
652 }
653}
654
655fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
656 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
657 workspace_window
658 .update(cx, |multi_workspace, window, cx| {
659 let workspace = multi_workspace.workspace().clone();
660 workspace.update(cx, |workspace, cx| {
661 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
662 });
663 })
664 .ok();
665 } else {
666 let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, true, cx);
667 cx.spawn(async move |cx| {
668 let OpenResult { window, .. } = task.await?;
669 window.update(cx, |multi_workspace, window, cx| {
670 window.activate_window();
671 let workspace = multi_workspace.workspace().clone();
672 workspace.update(cx, |workspace, cx| {
673 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
674 });
675 })?;
676 anyhow::Ok(())
677 })
678 .detach_and_log_err(cx);
679 }
680}
681
682pub fn prompt_for_open_path_and_open(
683 workspace: &mut Workspace,
684 app_state: Arc<AppState>,
685 options: PathPromptOptions,
686 create_new_window: bool,
687 window: &mut Window,
688 cx: &mut Context<Workspace>,
689) {
690 let paths = workspace.prompt_for_open_path(
691 options,
692 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
693 window,
694 cx,
695 );
696 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
697 cx.spawn_in(window, async move |this, cx| {
698 let Some(paths) = paths.await.log_err().flatten() else {
699 return;
700 };
701 if !create_new_window {
702 if let Some(handle) = multi_workspace_handle {
703 if let Some(task) = handle
704 .update(cx, |multi_workspace, window, cx| {
705 multi_workspace.open_project(paths, window, cx)
706 })
707 .log_err()
708 {
709 task.await.log_err();
710 }
711 return;
712 }
713 }
714 if let Some(task) = this
715 .update_in(cx, |this, window, cx| {
716 this.open_workspace_for_paths(false, paths, window, cx)
717 })
718 .log_err()
719 {
720 task.await.log_err();
721 }
722 })
723 .detach();
724}
725
726pub fn init(app_state: Arc<AppState>, cx: &mut App) {
727 component::init();
728 theme_preview::init(cx);
729 toast_layer::init(cx);
730 history_manager::init(app_state.fs.clone(), cx);
731
732 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
733 .on_action(|_: &Reload, cx| reload(cx))
734 .on_action({
735 let app_state = Arc::downgrade(&app_state);
736 move |_: &Open, cx: &mut App| {
737 if let Some(app_state) = app_state.upgrade() {
738 prompt_and_open_paths(
739 app_state,
740 PathPromptOptions {
741 files: true,
742 directories: true,
743 multiple: true,
744 prompt: None,
745 },
746 cx,
747 );
748 }
749 }
750 })
751 .on_action({
752 let app_state = Arc::downgrade(&app_state);
753 move |_: &OpenFiles, cx: &mut App| {
754 let directories = cx.can_select_mixed_files_and_dirs();
755 if let Some(app_state) = app_state.upgrade() {
756 prompt_and_open_paths(
757 app_state,
758 PathPromptOptions {
759 files: true,
760 directories,
761 multiple: true,
762 prompt: None,
763 },
764 cx,
765 );
766 }
767 }
768 });
769}
770
771type BuildProjectItemFn =
772 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
773
774type BuildProjectItemForPathFn =
775 fn(
776 &Entity<Project>,
777 &ProjectPath,
778 &mut Window,
779 &mut App,
780 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
781
782#[derive(Clone, Default)]
783struct ProjectItemRegistry {
784 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
785 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
786}
787
788impl ProjectItemRegistry {
789 fn register<T: ProjectItem>(&mut self) {
790 self.build_project_item_fns_by_type.insert(
791 TypeId::of::<T::Item>(),
792 |item, project, pane, window, cx| {
793 let item = item.downcast().unwrap();
794 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
795 as Box<dyn ItemHandle>
796 },
797 );
798 self.build_project_item_for_path_fns
799 .push(|project, project_path, window, cx| {
800 let project_path = project_path.clone();
801 let is_file = project
802 .read(cx)
803 .entry_for_path(&project_path, cx)
804 .is_some_and(|entry| entry.is_file());
805 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
806 let is_local = project.read(cx).is_local();
807 let project_item =
808 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
809 let project = project.clone();
810 Some(window.spawn(cx, async move |cx| {
811 match project_item.await.with_context(|| {
812 format!(
813 "opening project path {:?}",
814 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
815 )
816 }) {
817 Ok(project_item) => {
818 let project_item = project_item;
819 let project_entry_id: Option<ProjectEntryId> =
820 project_item.read_with(cx, project::ProjectItem::entry_id);
821 let build_workspace_item = Box::new(
822 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
823 Box::new(cx.new(|cx| {
824 T::for_project_item(
825 project,
826 Some(pane),
827 project_item,
828 window,
829 cx,
830 )
831 })) as Box<dyn ItemHandle>
832 },
833 ) as Box<_>;
834 Ok((project_entry_id, build_workspace_item))
835 }
836 Err(e) => {
837 log::warn!("Failed to open a project item: {e:#}");
838 if e.error_code() == ErrorCode::Internal {
839 if let Some(abs_path) =
840 entry_abs_path.as_deref().filter(|_| is_file)
841 {
842 if let Some(broken_project_item_view) =
843 cx.update(|window, cx| {
844 T::for_broken_project_item(
845 abs_path, is_local, &e, window, cx,
846 )
847 })?
848 {
849 let build_workspace_item = Box::new(
850 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
851 cx.new(|_| broken_project_item_view).boxed_clone()
852 },
853 )
854 as Box<_>;
855 return Ok((None, build_workspace_item));
856 }
857 }
858 }
859 Err(e)
860 }
861 }
862 }))
863 });
864 }
865
866 fn open_path(
867 &self,
868 project: &Entity<Project>,
869 path: &ProjectPath,
870 window: &mut Window,
871 cx: &mut App,
872 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
873 let Some(open_project_item) = self
874 .build_project_item_for_path_fns
875 .iter()
876 .rev()
877 .find_map(|open_project_item| open_project_item(project, path, window, cx))
878 else {
879 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
880 };
881 open_project_item
882 }
883
884 fn build_item<T: project::ProjectItem>(
885 &self,
886 item: Entity<T>,
887 project: Entity<Project>,
888 pane: Option<&Pane>,
889 window: &mut Window,
890 cx: &mut App,
891 ) -> Option<Box<dyn ItemHandle>> {
892 let build = self
893 .build_project_item_fns_by_type
894 .get(&TypeId::of::<T>())?;
895 Some(build(item.into_any(), project, pane, window, cx))
896 }
897}
898
899type WorkspaceItemBuilder =
900 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
901
902impl Global for ProjectItemRegistry {}
903
904/// Registers a [ProjectItem] for the app. When opening a file, all the registered
905/// items will get a chance to open the file, starting from the project item that
906/// was added last.
907pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
908 cx.default_global::<ProjectItemRegistry>().register::<I>();
909}
910
911#[derive(Default)]
912pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
913
914struct FollowableViewDescriptor {
915 from_state_proto: fn(
916 Entity<Workspace>,
917 ViewId,
918 &mut Option<proto::view::Variant>,
919 &mut Window,
920 &mut App,
921 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
922 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
923}
924
925impl Global for FollowableViewRegistry {}
926
927impl FollowableViewRegistry {
928 pub fn register<I: FollowableItem>(cx: &mut App) {
929 cx.default_global::<Self>().0.insert(
930 TypeId::of::<I>(),
931 FollowableViewDescriptor {
932 from_state_proto: |workspace, id, state, window, cx| {
933 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
934 cx.foreground_executor()
935 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
936 })
937 },
938 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
939 },
940 );
941 }
942
943 pub fn from_state_proto(
944 workspace: Entity<Workspace>,
945 view_id: ViewId,
946 mut state: Option<proto::view::Variant>,
947 window: &mut Window,
948 cx: &mut App,
949 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
950 cx.update_default_global(|this: &mut Self, cx| {
951 this.0.values().find_map(|descriptor| {
952 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
953 })
954 })
955 }
956
957 pub fn to_followable_view(
958 view: impl Into<AnyView>,
959 cx: &App,
960 ) -> Option<Box<dyn FollowableItemHandle>> {
961 let this = cx.try_global::<Self>()?;
962 let view = view.into();
963 let descriptor = this.0.get(&view.entity_type())?;
964 Some((descriptor.to_followable_view)(&view))
965 }
966}
967
968#[derive(Copy, Clone)]
969struct SerializableItemDescriptor {
970 deserialize: fn(
971 Entity<Project>,
972 WeakEntity<Workspace>,
973 WorkspaceId,
974 ItemId,
975 &mut Window,
976 &mut Context<Pane>,
977 ) -> Task<Result<Box<dyn ItemHandle>>>,
978 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
979 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
980}
981
982#[derive(Default)]
983struct SerializableItemRegistry {
984 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
985 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
986}
987
988impl Global for SerializableItemRegistry {}
989
990impl SerializableItemRegistry {
991 fn deserialize(
992 item_kind: &str,
993 project: Entity<Project>,
994 workspace: WeakEntity<Workspace>,
995 workspace_id: WorkspaceId,
996 item_item: ItemId,
997 window: &mut Window,
998 cx: &mut Context<Pane>,
999 ) -> Task<Result<Box<dyn ItemHandle>>> {
1000 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1001 return Task::ready(Err(anyhow!(
1002 "cannot deserialize {}, descriptor not found",
1003 item_kind
1004 )));
1005 };
1006
1007 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1008 }
1009
1010 fn cleanup(
1011 item_kind: &str,
1012 workspace_id: WorkspaceId,
1013 loaded_items: Vec<ItemId>,
1014 window: &mut Window,
1015 cx: &mut App,
1016 ) -> Task<Result<()>> {
1017 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1018 return Task::ready(Err(anyhow!(
1019 "cannot cleanup {}, descriptor not found",
1020 item_kind
1021 )));
1022 };
1023
1024 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1025 }
1026
1027 fn view_to_serializable_item_handle(
1028 view: AnyView,
1029 cx: &App,
1030 ) -> Option<Box<dyn SerializableItemHandle>> {
1031 let this = cx.try_global::<Self>()?;
1032 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1033 Some((descriptor.view_to_serializable_item)(view))
1034 }
1035
1036 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1037 let this = cx.try_global::<Self>()?;
1038 this.descriptors_by_kind.get(item_kind).copied()
1039 }
1040}
1041
1042pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1043 let serialized_item_kind = I::serialized_item_kind();
1044
1045 let registry = cx.default_global::<SerializableItemRegistry>();
1046 let descriptor = SerializableItemDescriptor {
1047 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1048 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1049 cx.foreground_executor()
1050 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1051 },
1052 cleanup: |workspace_id, loaded_items, window, cx| {
1053 I::cleanup(workspace_id, loaded_items, window, cx)
1054 },
1055 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1056 };
1057 registry
1058 .descriptors_by_kind
1059 .insert(Arc::from(serialized_item_kind), descriptor);
1060 registry
1061 .descriptors_by_type
1062 .insert(TypeId::of::<I>(), descriptor);
1063}
1064
1065pub struct AppState {
1066 pub languages: Arc<LanguageRegistry>,
1067 pub client: Arc<Client>,
1068 pub user_store: Entity<UserStore>,
1069 pub workspace_store: Entity<WorkspaceStore>,
1070 pub fs: Arc<dyn fs::Fs>,
1071 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1072 pub node_runtime: NodeRuntime,
1073 pub session: Entity<AppSession>,
1074}
1075
1076struct GlobalAppState(Weak<AppState>);
1077
1078impl Global for GlobalAppState {}
1079
1080pub struct WorkspaceStore {
1081 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1082 client: Arc<Client>,
1083 _subscriptions: Vec<client::Subscription>,
1084}
1085
1086#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1087pub enum CollaboratorId {
1088 PeerId(PeerId),
1089 Agent,
1090}
1091
1092impl From<PeerId> for CollaboratorId {
1093 fn from(peer_id: PeerId) -> Self {
1094 CollaboratorId::PeerId(peer_id)
1095 }
1096}
1097
1098impl From<&PeerId> for CollaboratorId {
1099 fn from(peer_id: &PeerId) -> Self {
1100 CollaboratorId::PeerId(*peer_id)
1101 }
1102}
1103
1104#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1105struct Follower {
1106 project_id: Option<u64>,
1107 peer_id: PeerId,
1108}
1109
1110impl AppState {
1111 #[track_caller]
1112 pub fn global(cx: &App) -> Weak<Self> {
1113 cx.global::<GlobalAppState>().0.clone()
1114 }
1115 pub fn try_global(cx: &App) -> Option<Weak<Self>> {
1116 cx.try_global::<GlobalAppState>()
1117 .map(|state| state.0.clone())
1118 }
1119 pub fn set_global(state: Weak<AppState>, cx: &mut App) {
1120 cx.set_global(GlobalAppState(state));
1121 }
1122
1123 #[cfg(any(test, feature = "test-support"))]
1124 pub fn test(cx: &mut App) -> Arc<Self> {
1125 use fs::Fs;
1126 use node_runtime::NodeRuntime;
1127 use session::Session;
1128 use settings::SettingsStore;
1129
1130 if !cx.has_global::<SettingsStore>() {
1131 let settings_store = SettingsStore::test(cx);
1132 cx.set_global(settings_store);
1133 }
1134
1135 let fs = fs::FakeFs::new(cx.background_executor().clone());
1136 <dyn Fs>::set_global(fs.clone(), cx);
1137 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1138 let clock = Arc::new(clock::FakeSystemClock::new());
1139 let http_client = http_client::FakeHttpClient::with_404_response();
1140 let client = Client::new(clock, http_client, cx);
1141 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1142 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1143 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1144
1145 theme::init(theme::LoadThemes::JustBase, cx);
1146 client::init(&client, cx);
1147
1148 Arc::new(Self {
1149 client,
1150 fs,
1151 languages,
1152 user_store,
1153 workspace_store,
1154 node_runtime: NodeRuntime::unavailable(),
1155 build_window_options: |_, _| Default::default(),
1156 session,
1157 })
1158 }
1159}
1160
1161struct DelayedDebouncedEditAction {
1162 task: Option<Task<()>>,
1163 cancel_channel: Option<oneshot::Sender<()>>,
1164}
1165
1166impl DelayedDebouncedEditAction {
1167 fn new() -> DelayedDebouncedEditAction {
1168 DelayedDebouncedEditAction {
1169 task: None,
1170 cancel_channel: None,
1171 }
1172 }
1173
1174 fn fire_new<F>(
1175 &mut self,
1176 delay: Duration,
1177 window: &mut Window,
1178 cx: &mut Context<Workspace>,
1179 func: F,
1180 ) where
1181 F: 'static
1182 + Send
1183 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1184 {
1185 if let Some(channel) = self.cancel_channel.take() {
1186 _ = channel.send(());
1187 }
1188
1189 let (sender, mut receiver) = oneshot::channel::<()>();
1190 self.cancel_channel = Some(sender);
1191
1192 let previous_task = self.task.take();
1193 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1194 let mut timer = cx.background_executor().timer(delay).fuse();
1195 if let Some(previous_task) = previous_task {
1196 previous_task.await;
1197 }
1198
1199 futures::select_biased! {
1200 _ = receiver => return,
1201 _ = timer => {}
1202 }
1203
1204 if let Some(result) = workspace
1205 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1206 .log_err()
1207 {
1208 result.await.log_err();
1209 }
1210 }));
1211 }
1212}
1213
1214pub enum Event {
1215 PaneAdded(Entity<Pane>),
1216 PaneRemoved,
1217 ItemAdded {
1218 item: Box<dyn ItemHandle>,
1219 },
1220 ActiveItemChanged,
1221 ItemRemoved {
1222 item_id: EntityId,
1223 },
1224 UserSavedItem {
1225 pane: WeakEntity<Pane>,
1226 item: Box<dyn WeakItemHandle>,
1227 save_intent: SaveIntent,
1228 },
1229 ContactRequestedJoin(u64),
1230 WorkspaceCreated(WeakEntity<Workspace>),
1231 OpenBundledFile {
1232 text: Cow<'static, str>,
1233 title: &'static str,
1234 language: &'static str,
1235 },
1236 ZoomChanged,
1237 ModalOpened,
1238 Activate,
1239 PanelAdded(AnyView),
1240}
1241
1242#[derive(Debug, Clone)]
1243pub enum OpenVisible {
1244 All,
1245 None,
1246 OnlyFiles,
1247 OnlyDirectories,
1248}
1249
1250enum WorkspaceLocation {
1251 // Valid local paths or SSH project to serialize
1252 Location(SerializedWorkspaceLocation, PathList),
1253 // No valid location found hence clear session id
1254 DetachFromSession,
1255 // No valid location found to serialize
1256 None,
1257}
1258
1259type PromptForNewPath = Box<
1260 dyn Fn(
1261 &mut Workspace,
1262 DirectoryLister,
1263 Option<String>,
1264 &mut Window,
1265 &mut Context<Workspace>,
1266 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1267>;
1268
1269type PromptForOpenPath = Box<
1270 dyn Fn(
1271 &mut Workspace,
1272 DirectoryLister,
1273 &mut Window,
1274 &mut Context<Workspace>,
1275 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1276>;
1277
1278#[derive(Default)]
1279struct DispatchingKeystrokes {
1280 dispatched: HashSet<Vec<Keystroke>>,
1281 queue: VecDeque<Keystroke>,
1282 task: Option<Shared<Task<()>>>,
1283}
1284
1285/// Collects everything project-related for a certain window opened.
1286/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1287///
1288/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1289/// The `Workspace` owns everybody's state and serves as a default, "global context",
1290/// that can be used to register a global action to be triggered from any place in the window.
1291pub struct Workspace {
1292 weak_self: WeakEntity<Self>,
1293 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1294 zoomed: Option<AnyWeakView>,
1295 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1296 zoomed_position: Option<DockPosition>,
1297 center: PaneGroup,
1298 left_dock: Entity<Dock>,
1299 bottom_dock: Entity<Dock>,
1300 right_dock: Entity<Dock>,
1301 panes: Vec<Entity<Pane>>,
1302 active_worktree_override: Option<WorktreeId>,
1303 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1304 active_pane: Entity<Pane>,
1305 last_active_center_pane: Option<WeakEntity<Pane>>,
1306 last_active_view_id: Option<proto::ViewId>,
1307 status_bar: Entity<StatusBar>,
1308 pub(crate) modal_layer: Entity<ModalLayer>,
1309 toast_layer: Entity<ToastLayer>,
1310 titlebar_item: Option<AnyView>,
1311 notifications: Notifications,
1312 suppressed_notifications: HashSet<NotificationId>,
1313 project: Entity<Project>,
1314 follower_states: HashMap<CollaboratorId, FollowerState>,
1315 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1316 window_edited: bool,
1317 last_window_title: Option<String>,
1318 dirty_items: HashMap<EntityId, Subscription>,
1319 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1320 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1321 database_id: Option<WorkspaceId>,
1322 app_state: Arc<AppState>,
1323 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1324 _subscriptions: Vec<Subscription>,
1325 _apply_leader_updates: Task<Result<()>>,
1326 _observe_current_user: Task<Result<()>>,
1327 _schedule_serialize_workspace: Option<Task<()>>,
1328 _serialize_workspace_task: Option<Task<()>>,
1329 _schedule_serialize_ssh_paths: Option<Task<()>>,
1330 pane_history_timestamp: Arc<AtomicUsize>,
1331 bounds: Bounds<Pixels>,
1332 pub centered_layout: bool,
1333 bounds_save_task_queued: Option<Task<()>>,
1334 on_prompt_for_new_path: Option<PromptForNewPath>,
1335 on_prompt_for_open_path: Option<PromptForOpenPath>,
1336 terminal_provider: Option<Box<dyn TerminalProvider>>,
1337 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1338 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1339 _items_serializer: Task<Result<()>>,
1340 session_id: Option<String>,
1341 scheduled_tasks: Vec<Task<()>>,
1342 last_open_dock_positions: Vec<DockPosition>,
1343 removing: bool,
1344 _panels_task: Option<Task<Result<()>>>,
1345 sidebar_focus_handle: Option<FocusHandle>,
1346 multi_workspace: Option<WeakEntity<MultiWorkspace>>,
1347}
1348
1349impl EventEmitter<Event> for Workspace {}
1350
1351#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1352pub struct ViewId {
1353 pub creator: CollaboratorId,
1354 pub id: u64,
1355}
1356
1357pub struct FollowerState {
1358 center_pane: Entity<Pane>,
1359 dock_pane: Option<Entity<Pane>>,
1360 active_view_id: Option<ViewId>,
1361 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1362}
1363
1364struct FollowerView {
1365 view: Box<dyn FollowableItemHandle>,
1366 location: Option<proto::PanelId>,
1367}
1368
1369impl Workspace {
1370 pub fn new(
1371 workspace_id: Option<WorkspaceId>,
1372 project: Entity<Project>,
1373 app_state: Arc<AppState>,
1374 window: &mut Window,
1375 cx: &mut Context<Self>,
1376 ) -> Self {
1377 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1378 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1379 if let TrustedWorktreesEvent::Trusted(..) = e {
1380 // Do not persist auto trusted worktrees
1381 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1382 worktrees_store.update(cx, |worktrees_store, cx| {
1383 worktrees_store.schedule_serialization(
1384 cx,
1385 |new_trusted_worktrees, cx| {
1386 let timeout =
1387 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1388 let db = WorkspaceDb::global(cx);
1389 cx.background_spawn(async move {
1390 timeout.await;
1391 db.save_trusted_worktrees(new_trusted_worktrees)
1392 .await
1393 .log_err();
1394 })
1395 },
1396 )
1397 });
1398 }
1399 }
1400 })
1401 .detach();
1402
1403 cx.observe_global::<SettingsStore>(|_, cx| {
1404 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1405 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1406 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1407 trusted_worktrees.auto_trust_all(cx);
1408 })
1409 }
1410 }
1411 })
1412 .detach();
1413 }
1414
1415 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1416 match event {
1417 project::Event::RemoteIdChanged(_) => {
1418 this.update_window_title(window, cx);
1419 }
1420
1421 project::Event::CollaboratorLeft(peer_id) => {
1422 this.collaborator_left(*peer_id, window, cx);
1423 }
1424
1425 &project::Event::WorktreeRemoved(_) => {
1426 this.update_window_title(window, cx);
1427 this.serialize_workspace(window, cx);
1428 this.update_history(cx);
1429 }
1430
1431 &project::Event::WorktreeAdded(id) => {
1432 this.update_window_title(window, cx);
1433 if this
1434 .project()
1435 .read(cx)
1436 .worktree_for_id(id, cx)
1437 .is_some_and(|wt| wt.read(cx).is_visible())
1438 {
1439 this.serialize_workspace(window, cx);
1440 this.update_history(cx);
1441 }
1442 }
1443 project::Event::WorktreeUpdatedEntries(..) => {
1444 this.update_window_title(window, cx);
1445 this.serialize_workspace(window, cx);
1446 }
1447
1448 project::Event::DisconnectedFromHost => {
1449 this.update_window_edited(window, cx);
1450 let leaders_to_unfollow =
1451 this.follower_states.keys().copied().collect::<Vec<_>>();
1452 for leader_id in leaders_to_unfollow {
1453 this.unfollow(leader_id, window, cx);
1454 }
1455 }
1456
1457 project::Event::DisconnectedFromRemote {
1458 server_not_running: _,
1459 } => {
1460 this.update_window_edited(window, cx);
1461 }
1462
1463 project::Event::Closed => {
1464 window.remove_window();
1465 }
1466
1467 project::Event::DeletedEntry(_, entry_id) => {
1468 for pane in this.panes.iter() {
1469 pane.update(cx, |pane, cx| {
1470 pane.handle_deleted_project_item(*entry_id, window, cx)
1471 });
1472 }
1473 }
1474
1475 project::Event::Toast {
1476 notification_id,
1477 message,
1478 link,
1479 } => this.show_notification(
1480 NotificationId::named(notification_id.clone()),
1481 cx,
1482 |cx| {
1483 let mut notification = MessageNotification::new(message.clone(), cx);
1484 if let Some(link) = link {
1485 notification = notification
1486 .more_info_message(link.label)
1487 .more_info_url(link.url);
1488 }
1489
1490 cx.new(|_| notification)
1491 },
1492 ),
1493
1494 project::Event::HideToast { notification_id } => {
1495 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1496 }
1497
1498 project::Event::LanguageServerPrompt(request) => {
1499 struct LanguageServerPrompt;
1500
1501 this.show_notification(
1502 NotificationId::composite::<LanguageServerPrompt>(request.id),
1503 cx,
1504 |cx| {
1505 cx.new(|cx| {
1506 notifications::LanguageServerPrompt::new(request.clone(), cx)
1507 })
1508 },
1509 );
1510 }
1511
1512 project::Event::AgentLocationChanged => {
1513 this.handle_agent_location_changed(window, cx)
1514 }
1515
1516 _ => {}
1517 }
1518 cx.notify()
1519 })
1520 .detach();
1521
1522 cx.subscribe_in(
1523 &project.read(cx).breakpoint_store(),
1524 window,
1525 |workspace, _, event, window, cx| match event {
1526 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1527 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1528 workspace.serialize_workspace(window, cx);
1529 }
1530 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1531 },
1532 )
1533 .detach();
1534 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1535 cx.subscribe_in(
1536 &toolchain_store,
1537 window,
1538 |workspace, _, event, window, cx| match event {
1539 ToolchainStoreEvent::CustomToolchainsModified => {
1540 workspace.serialize_workspace(window, cx);
1541 }
1542 _ => {}
1543 },
1544 )
1545 .detach();
1546 }
1547
1548 cx.on_focus_lost(window, |this, window, cx| {
1549 let focus_handle = this.focus_handle(cx);
1550 window.focus(&focus_handle, cx);
1551 })
1552 .detach();
1553
1554 let weak_handle = cx.entity().downgrade();
1555 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1556
1557 let center_pane = cx.new(|cx| {
1558 let mut center_pane = Pane::new(
1559 weak_handle.clone(),
1560 project.clone(),
1561 pane_history_timestamp.clone(),
1562 None,
1563 NewFile.boxed_clone(),
1564 true,
1565 window,
1566 cx,
1567 );
1568 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1569 center_pane.set_should_display_welcome_page(true);
1570 center_pane
1571 });
1572 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1573 .detach();
1574
1575 window.focus(¢er_pane.focus_handle(cx), cx);
1576
1577 cx.emit(Event::PaneAdded(center_pane.clone()));
1578
1579 let any_window_handle = window.window_handle();
1580 app_state.workspace_store.update(cx, |store, _| {
1581 store
1582 .workspaces
1583 .insert((any_window_handle, weak_handle.clone()));
1584 });
1585
1586 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1587 let mut connection_status = app_state.client.status();
1588 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1589 current_user.next().await;
1590 connection_status.next().await;
1591 let mut stream =
1592 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1593
1594 while stream.recv().await.is_some() {
1595 this.update(cx, |_, cx| cx.notify())?;
1596 }
1597 anyhow::Ok(())
1598 });
1599
1600 // All leader updates are enqueued and then processed in a single task, so
1601 // that each asynchronous operation can be run in order.
1602 let (leader_updates_tx, mut leader_updates_rx) =
1603 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1604 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1605 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1606 Self::process_leader_update(&this, leader_id, update, cx)
1607 .await
1608 .log_err();
1609 }
1610
1611 Ok(())
1612 });
1613
1614 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1615 let modal_layer = cx.new(|_| ModalLayer::new());
1616 let toast_layer = cx.new(|_| ToastLayer::new());
1617 cx.subscribe(
1618 &modal_layer,
1619 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1620 cx.emit(Event::ModalOpened);
1621 },
1622 )
1623 .detach();
1624
1625 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1626 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1627 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1628 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1629 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1630 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1631 let multi_workspace = window
1632 .root::<MultiWorkspace>()
1633 .flatten()
1634 .map(|mw| mw.downgrade());
1635 let status_bar = cx.new(|cx| {
1636 let mut status_bar =
1637 StatusBar::new(¢er_pane.clone(), multi_workspace.clone(), window, cx);
1638 status_bar.add_left_item(left_dock_buttons, window, cx);
1639 status_bar.add_right_item(right_dock_buttons, window, cx);
1640 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1641 status_bar
1642 });
1643
1644 let session_id = app_state.session.read(cx).id().to_owned();
1645
1646 let mut active_call = None;
1647 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1648 let subscriptions =
1649 vec![
1650 call.0
1651 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1652 ];
1653 active_call = Some((call, subscriptions));
1654 }
1655
1656 let (serializable_items_tx, serializable_items_rx) =
1657 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1658 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1659 Self::serialize_items(&this, serializable_items_rx, cx).await
1660 });
1661
1662 let subscriptions = vec![
1663 cx.observe_window_activation(window, Self::on_window_activation_changed),
1664 cx.observe_window_bounds(window, move |this, window, cx| {
1665 if this.bounds_save_task_queued.is_some() {
1666 return;
1667 }
1668 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1669 cx.background_executor()
1670 .timer(Duration::from_millis(100))
1671 .await;
1672 this.update_in(cx, |this, window, cx| {
1673 this.save_window_bounds(window, cx).detach();
1674 this.bounds_save_task_queued.take();
1675 })
1676 .ok();
1677 }));
1678 cx.notify();
1679 }),
1680 cx.observe_window_appearance(window, |_, window, cx| {
1681 let window_appearance = window.appearance();
1682
1683 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1684
1685 GlobalTheme::reload_theme(cx);
1686 GlobalTheme::reload_icon_theme(cx);
1687 }),
1688 cx.on_release({
1689 let weak_handle = weak_handle.clone();
1690 move |this, cx| {
1691 this.app_state.workspace_store.update(cx, move |store, _| {
1692 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1693 })
1694 }
1695 }),
1696 ];
1697
1698 cx.defer_in(window, move |this, window, cx| {
1699 this.update_window_title(window, cx);
1700 this.show_initial_notifications(cx);
1701 });
1702
1703 let mut center = PaneGroup::new(center_pane.clone());
1704 center.set_is_center(true);
1705 center.mark_positions(cx);
1706
1707 Workspace {
1708 weak_self: weak_handle.clone(),
1709 zoomed: None,
1710 zoomed_position: None,
1711 previous_dock_drag_coordinates: None,
1712 center,
1713 panes: vec![center_pane.clone()],
1714 panes_by_item: Default::default(),
1715 active_pane: center_pane.clone(),
1716 last_active_center_pane: Some(center_pane.downgrade()),
1717 last_active_view_id: None,
1718 status_bar,
1719 modal_layer,
1720 toast_layer,
1721 titlebar_item: None,
1722 active_worktree_override: None,
1723 notifications: Notifications::default(),
1724 suppressed_notifications: HashSet::default(),
1725 left_dock,
1726 bottom_dock,
1727 right_dock,
1728 _panels_task: None,
1729 project: project.clone(),
1730 follower_states: Default::default(),
1731 last_leaders_by_pane: Default::default(),
1732 dispatching_keystrokes: Default::default(),
1733 window_edited: false,
1734 last_window_title: None,
1735 dirty_items: Default::default(),
1736 active_call,
1737 database_id: workspace_id,
1738 app_state,
1739 _observe_current_user,
1740 _apply_leader_updates,
1741 _schedule_serialize_workspace: None,
1742 _serialize_workspace_task: None,
1743 _schedule_serialize_ssh_paths: None,
1744 leader_updates_tx,
1745 _subscriptions: subscriptions,
1746 pane_history_timestamp,
1747 workspace_actions: Default::default(),
1748 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1749 bounds: Default::default(),
1750 centered_layout: false,
1751 bounds_save_task_queued: None,
1752 on_prompt_for_new_path: None,
1753 on_prompt_for_open_path: None,
1754 terminal_provider: None,
1755 debugger_provider: None,
1756 serializable_items_tx,
1757 _items_serializer,
1758 session_id: Some(session_id),
1759
1760 scheduled_tasks: Vec::new(),
1761 last_open_dock_positions: Vec::new(),
1762 removing: false,
1763 sidebar_focus_handle: None,
1764 multi_workspace,
1765 }
1766 }
1767
1768 pub fn new_local(
1769 abs_paths: Vec<PathBuf>,
1770 app_state: Arc<AppState>,
1771 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1772 env: Option<HashMap<String, String>>,
1773 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1774 activate: bool,
1775 cx: &mut App,
1776 ) -> Task<anyhow::Result<OpenResult>> {
1777 let project_handle = Project::local(
1778 app_state.client.clone(),
1779 app_state.node_runtime.clone(),
1780 app_state.user_store.clone(),
1781 app_state.languages.clone(),
1782 app_state.fs.clone(),
1783 env,
1784 Default::default(),
1785 cx,
1786 );
1787
1788 let db = WorkspaceDb::global(cx);
1789 let kvp = db::kvp::KeyValueStore::global(cx);
1790 cx.spawn(async move |cx| {
1791 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1792 for path in abs_paths.into_iter() {
1793 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1794 paths_to_open.push(canonical)
1795 } else {
1796 paths_to_open.push(path)
1797 }
1798 }
1799
1800 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1801
1802 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1803 paths_to_open = paths.ordered_paths().cloned().collect();
1804 if !paths.is_lexicographically_ordered() {
1805 project_handle.update(cx, |project, cx| {
1806 project.set_worktrees_reordered(true, cx);
1807 });
1808 }
1809 }
1810
1811 // Get project paths for all of the abs_paths
1812 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1813 Vec::with_capacity(paths_to_open.len());
1814
1815 for path in paths_to_open.into_iter() {
1816 if let Some((_, project_entry)) = cx
1817 .update(|cx| {
1818 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1819 })
1820 .await
1821 .log_err()
1822 {
1823 project_paths.push((path, Some(project_entry)));
1824 } else {
1825 project_paths.push((path, None));
1826 }
1827 }
1828
1829 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1830 serialized_workspace.id
1831 } else {
1832 db.next_id().await.unwrap_or_else(|_| Default::default())
1833 };
1834
1835 let toolchains = db.toolchains(workspace_id).await?;
1836
1837 for (toolchain, worktree_path, path) in toolchains {
1838 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1839 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1840 this.find_worktree(&worktree_path, cx)
1841 .and_then(|(worktree, rel_path)| {
1842 if rel_path.is_empty() {
1843 Some(worktree.read(cx).id())
1844 } else {
1845 None
1846 }
1847 })
1848 }) else {
1849 // We did not find a worktree with a given path, but that's whatever.
1850 continue;
1851 };
1852 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1853 continue;
1854 }
1855
1856 project_handle
1857 .update(cx, |this, cx| {
1858 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1859 })
1860 .await;
1861 }
1862 if let Some(workspace) = serialized_workspace.as_ref() {
1863 project_handle.update(cx, |this, cx| {
1864 for (scope, toolchains) in &workspace.user_toolchains {
1865 for toolchain in toolchains {
1866 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1867 }
1868 }
1869 });
1870 }
1871
1872 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1873 if let Some(window) = requesting_window {
1874 let centered_layout = serialized_workspace
1875 .as_ref()
1876 .map(|w| w.centered_layout)
1877 .unwrap_or(false);
1878
1879 let workspace = window.update(cx, |multi_workspace, window, cx| {
1880 let workspace = cx.new(|cx| {
1881 let mut workspace = Workspace::new(
1882 Some(workspace_id),
1883 project_handle.clone(),
1884 app_state.clone(),
1885 window,
1886 cx,
1887 );
1888
1889 workspace.centered_layout = centered_layout;
1890
1891 // Call init callback to add items before window renders
1892 if let Some(init) = init {
1893 init(&mut workspace, window, cx);
1894 }
1895
1896 workspace
1897 });
1898 if activate {
1899 multi_workspace.activate(workspace.clone(), cx);
1900 } else {
1901 multi_workspace.add_workspace(workspace.clone(), cx);
1902 }
1903 workspace
1904 })?;
1905 (window, workspace)
1906 } else {
1907 let window_bounds_override = window_bounds_env_override();
1908
1909 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1910 (Some(WindowBounds::Windowed(bounds)), None)
1911 } else if let Some(workspace) = serialized_workspace.as_ref()
1912 && let Some(display) = workspace.display
1913 && let Some(bounds) = workspace.window_bounds.as_ref()
1914 {
1915 // Reopening an existing workspace - restore its saved bounds
1916 (Some(bounds.0), Some(display))
1917 } else if let Some((display, bounds)) =
1918 persistence::read_default_window_bounds(&kvp)
1919 {
1920 // New or empty workspace - use the last known window bounds
1921 (Some(bounds), Some(display))
1922 } else {
1923 // New window - let GPUI's default_bounds() handle cascading
1924 (None, None)
1925 };
1926
1927 // Use the serialized workspace to construct the new window
1928 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1929 options.window_bounds = window_bounds;
1930 let centered_layout = serialized_workspace
1931 .as_ref()
1932 .map(|w| w.centered_layout)
1933 .unwrap_or(false);
1934 let window = cx.open_window(options, {
1935 let app_state = app_state.clone();
1936 let project_handle = project_handle.clone();
1937 move |window, cx| {
1938 let workspace = cx.new(|cx| {
1939 let mut workspace = Workspace::new(
1940 Some(workspace_id),
1941 project_handle,
1942 app_state,
1943 window,
1944 cx,
1945 );
1946 workspace.centered_layout = centered_layout;
1947
1948 // Call init callback to add items before window renders
1949 if let Some(init) = init {
1950 init(&mut workspace, window, cx);
1951 }
1952
1953 workspace
1954 });
1955 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1956 }
1957 })?;
1958 let workspace =
1959 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1960 multi_workspace.workspace().clone()
1961 })?;
1962 (window, workspace)
1963 };
1964
1965 notify_if_database_failed(window, cx);
1966 // Check if this is an empty workspace (no paths to open)
1967 // An empty workspace is one where project_paths is empty
1968 let is_empty_workspace = project_paths.is_empty();
1969 // Check if serialized workspace has paths before it's moved
1970 let serialized_workspace_has_paths = serialized_workspace
1971 .as_ref()
1972 .map(|ws| !ws.paths.is_empty())
1973 .unwrap_or(false);
1974
1975 let opened_items = window
1976 .update(cx, |_, window, cx| {
1977 workspace.update(cx, |_workspace: &mut Workspace, cx| {
1978 open_items(serialized_workspace, project_paths, window, cx)
1979 })
1980 })?
1981 .await
1982 .unwrap_or_default();
1983
1984 // Restore default dock state for empty workspaces
1985 // Only restore if:
1986 // 1. This is an empty workspace (no paths), AND
1987 // 2. The serialized workspace either doesn't exist or has no paths
1988 if is_empty_workspace && !serialized_workspace_has_paths {
1989 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
1990 window
1991 .update(cx, |_, window, cx| {
1992 workspace.update(cx, |workspace, cx| {
1993 for (dock, serialized_dock) in [
1994 (&workspace.right_dock, &default_docks.right),
1995 (&workspace.left_dock, &default_docks.left),
1996 (&workspace.bottom_dock, &default_docks.bottom),
1997 ] {
1998 dock.update(cx, |dock, cx| {
1999 dock.serialized_dock = Some(serialized_dock.clone());
2000 dock.restore_state(window, cx);
2001 });
2002 }
2003 cx.notify();
2004 });
2005 })
2006 .log_err();
2007 }
2008 }
2009
2010 window
2011 .update(cx, |_, _window, cx| {
2012 workspace.update(cx, |this: &mut Workspace, cx| {
2013 this.update_history(cx);
2014 });
2015 })
2016 .log_err();
2017 Ok(OpenResult {
2018 window,
2019 workspace,
2020 opened_items,
2021 })
2022 })
2023 }
2024
2025 pub fn weak_handle(&self) -> WeakEntity<Self> {
2026 self.weak_self.clone()
2027 }
2028
2029 pub fn left_dock(&self) -> &Entity<Dock> {
2030 &self.left_dock
2031 }
2032
2033 pub fn bottom_dock(&self) -> &Entity<Dock> {
2034 &self.bottom_dock
2035 }
2036
2037 pub fn set_bottom_dock_layout(
2038 &mut self,
2039 layout: BottomDockLayout,
2040 window: &mut Window,
2041 cx: &mut Context<Self>,
2042 ) {
2043 let fs = self.project().read(cx).fs();
2044 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2045 content.workspace.bottom_dock_layout = Some(layout);
2046 });
2047
2048 cx.notify();
2049 self.serialize_workspace(window, cx);
2050 }
2051
2052 pub fn right_dock(&self) -> &Entity<Dock> {
2053 &self.right_dock
2054 }
2055
2056 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2057 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2058 }
2059
2060 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2061 let left_dock = self.left_dock.read(cx);
2062 let left_visible = left_dock.is_open();
2063 let left_active_panel = left_dock
2064 .active_panel()
2065 .map(|panel| panel.persistent_name().to_string());
2066 // `zoomed_position` is kept in sync with individual panel zoom state
2067 // by the dock code in `Dock::new` and `Dock::add_panel`.
2068 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2069
2070 let right_dock = self.right_dock.read(cx);
2071 let right_visible = right_dock.is_open();
2072 let right_active_panel = right_dock
2073 .active_panel()
2074 .map(|panel| panel.persistent_name().to_string());
2075 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2076
2077 let bottom_dock = self.bottom_dock.read(cx);
2078 let bottom_visible = bottom_dock.is_open();
2079 let bottom_active_panel = bottom_dock
2080 .active_panel()
2081 .map(|panel| panel.persistent_name().to_string());
2082 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2083
2084 DockStructure {
2085 left: DockData {
2086 visible: left_visible,
2087 active_panel: left_active_panel,
2088 zoom: left_dock_zoom,
2089 },
2090 right: DockData {
2091 visible: right_visible,
2092 active_panel: right_active_panel,
2093 zoom: right_dock_zoom,
2094 },
2095 bottom: DockData {
2096 visible: bottom_visible,
2097 active_panel: bottom_active_panel,
2098 zoom: bottom_dock_zoom,
2099 },
2100 }
2101 }
2102
2103 pub fn set_dock_structure(
2104 &self,
2105 docks: DockStructure,
2106 window: &mut Window,
2107 cx: &mut Context<Self>,
2108 ) {
2109 for (dock, data) in [
2110 (&self.left_dock, docks.left),
2111 (&self.bottom_dock, docks.bottom),
2112 (&self.right_dock, docks.right),
2113 ] {
2114 dock.update(cx, |dock, cx| {
2115 dock.serialized_dock = Some(data);
2116 dock.restore_state(window, cx);
2117 });
2118 }
2119 }
2120
2121 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2122 self.items(cx)
2123 .filter_map(|item| {
2124 let project_path = item.project_path(cx)?;
2125 self.project.read(cx).absolute_path(&project_path, cx)
2126 })
2127 .collect()
2128 }
2129
2130 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2131 match position {
2132 DockPosition::Left => &self.left_dock,
2133 DockPosition::Bottom => &self.bottom_dock,
2134 DockPosition::Right => &self.right_dock,
2135 }
2136 }
2137
2138 pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
2139 self.all_docks().into_iter().find_map(|dock| {
2140 let dock = dock.read(cx);
2141 dock.has_agent_panel(cx).then_some(dock.position())
2142 })
2143 }
2144
2145 pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
2146 self.all_docks().into_iter().find_map(|dock| {
2147 let dock = dock.read(cx);
2148 let panel = dock.panel::<T>()?;
2149 dock.stored_panel_size_state(&panel)
2150 })
2151 }
2152
2153 pub fn persisted_panel_size_state(
2154 &self,
2155 panel_key: &'static str,
2156 cx: &App,
2157 ) -> Option<dock::PanelSizeState> {
2158 dock::Dock::load_persisted_size_state(self, panel_key, cx)
2159 }
2160
2161 pub fn persist_panel_size_state(
2162 &self,
2163 panel_key: &str,
2164 size_state: dock::PanelSizeState,
2165 cx: &mut App,
2166 ) {
2167 let Some(workspace_id) = self
2168 .database_id()
2169 .map(|id| i64::from(id).to_string())
2170 .or(self.session_id())
2171 else {
2172 return;
2173 };
2174
2175 let kvp = db::kvp::KeyValueStore::global(cx);
2176 let panel_key = panel_key.to_string();
2177 cx.background_spawn(async move {
2178 let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
2179 scope
2180 .write(
2181 format!("{workspace_id}:{panel_key}"),
2182 serde_json::to_string(&size_state)?,
2183 )
2184 .await
2185 })
2186 .detach_and_log_err(cx);
2187 }
2188
2189 pub fn set_panel_size_state<T: Panel>(
2190 &mut self,
2191 size_state: dock::PanelSizeState,
2192 window: &mut Window,
2193 cx: &mut Context<Self>,
2194 ) -> bool {
2195 let Some(panel) = self.panel::<T>(cx) else {
2196 return false;
2197 };
2198
2199 let dock = self.dock_at_position(panel.position(window, cx));
2200 let did_set = dock.update(cx, |dock, cx| {
2201 dock.set_panel_size_state(&panel, size_state, cx)
2202 });
2203
2204 if did_set {
2205 self.persist_panel_size_state(T::panel_key(), size_state, cx);
2206 }
2207
2208 did_set
2209 }
2210
2211 fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
2212 let panel = dock.active_panel()?;
2213 let size_state = dock
2214 .stored_panel_size_state(panel.as_ref())
2215 .unwrap_or_default();
2216 let position = dock.position();
2217
2218 if position.axis() == Axis::Horizontal
2219 && panel.supports_flexible_size(window, cx)
2220 && let Some(ratio) = size_state
2221 .flexible_size_ratio
2222 .or_else(|| self.default_flexible_dock_ratio(position))
2223 && let Some(available_width) =
2224 self.available_width_for_horizontal_dock(position, window, cx)
2225 {
2226 return Some((available_width * ratio.clamp(0.0, 1.0)).max(RESIZE_HANDLE_SIZE));
2227 }
2228
2229 Some(
2230 size_state
2231 .size
2232 .unwrap_or_else(|| panel.default_size(window, cx)),
2233 )
2234 }
2235
2236 pub fn flexible_dock_ratio_for_size(
2237 &self,
2238 position: DockPosition,
2239 size: Pixels,
2240 window: &Window,
2241 cx: &App,
2242 ) -> Option<f32> {
2243 if position.axis() != Axis::Horizontal {
2244 return None;
2245 }
2246
2247 let available_width = self.available_width_for_horizontal_dock(position, window, cx)?;
2248 let available_width = available_width.max(RESIZE_HANDLE_SIZE);
2249 Some((size / available_width).clamp(0.0, 1.0))
2250 }
2251
2252 fn available_width_for_horizontal_dock(
2253 &self,
2254 position: DockPosition,
2255 window: &Window,
2256 cx: &App,
2257 ) -> Option<Pixels> {
2258 let workspace_width = self.bounds.size.width;
2259 if workspace_width <= Pixels::ZERO {
2260 return None;
2261 }
2262
2263 let opposite_position = match position {
2264 DockPosition::Left => DockPosition::Right,
2265 DockPosition::Right => DockPosition::Left,
2266 DockPosition::Bottom => return None,
2267 };
2268
2269 let opposite_width = self
2270 .dock_at_position(opposite_position)
2271 .read(cx)
2272 .stored_active_panel_size(window, cx)
2273 .unwrap_or(Pixels::ZERO);
2274
2275 Some((workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE))
2276 }
2277
2278 pub fn default_flexible_dock_ratio(&self, position: DockPosition) -> Option<f32> {
2279 if position.axis() != Axis::Horizontal {
2280 return None;
2281 }
2282
2283 let pane = self.last_active_center_pane.clone()?.upgrade()?;
2284 let pane_fraction = self.center.width_fraction_for_pane(&pane).unwrap_or(1.0);
2285 Some((pane_fraction / (1.0 + pane_fraction)).clamp(0.0, 1.0))
2286 }
2287
2288 pub fn is_edited(&self) -> bool {
2289 self.window_edited
2290 }
2291
2292 pub fn add_panel<T: Panel>(
2293 &mut self,
2294 panel: Entity<T>,
2295 window: &mut Window,
2296 cx: &mut Context<Self>,
2297 ) {
2298 let focus_handle = panel.panel_focus_handle(cx);
2299 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2300 .detach();
2301
2302 let dock_position = panel.position(window, cx);
2303 let dock = self.dock_at_position(dock_position);
2304 let any_panel = panel.to_any();
2305 let persisted_size_state =
2306 self.persisted_panel_size_state(T::panel_key(), cx)
2307 .or_else(|| {
2308 load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
2309 let state = dock::PanelSizeState {
2310 size: Some(size),
2311 flexible_size_ratio: None,
2312 };
2313 self.persist_panel_size_state(T::panel_key(), state, cx);
2314 state
2315 })
2316 });
2317
2318 dock.update(cx, |dock, cx| {
2319 let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
2320 if let Some(size_state) = persisted_size_state {
2321 dock.set_panel_size_state(&panel, size_state, cx);
2322 }
2323 index
2324 });
2325
2326 cx.emit(Event::PanelAdded(any_panel));
2327 }
2328
2329 pub fn remove_panel<T: Panel>(
2330 &mut self,
2331 panel: &Entity<T>,
2332 window: &mut Window,
2333 cx: &mut Context<Self>,
2334 ) {
2335 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2336 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2337 }
2338 }
2339
2340 pub fn status_bar(&self) -> &Entity<StatusBar> {
2341 &self.status_bar
2342 }
2343
2344 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2345 self.sidebar_focus_handle = handle;
2346 }
2347
2348 pub fn status_bar_visible(&self, cx: &App) -> bool {
2349 StatusBarSettings::get_global(cx).show
2350 }
2351
2352 pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
2353 self.multi_workspace.as_ref()
2354 }
2355
2356 pub fn set_multi_workspace(
2357 &mut self,
2358 multi_workspace: WeakEntity<MultiWorkspace>,
2359 cx: &mut App,
2360 ) {
2361 self.status_bar.update(cx, |status_bar, cx| {
2362 status_bar.set_multi_workspace(multi_workspace.clone(), cx);
2363 });
2364 self.multi_workspace = Some(multi_workspace);
2365 }
2366
2367 pub fn app_state(&self) -> &Arc<AppState> {
2368 &self.app_state
2369 }
2370
2371 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2372 self._panels_task = Some(task);
2373 }
2374
2375 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2376 self._panels_task.take()
2377 }
2378
2379 pub fn user_store(&self) -> &Entity<UserStore> {
2380 &self.app_state.user_store
2381 }
2382
2383 pub fn project(&self) -> &Entity<Project> {
2384 &self.project
2385 }
2386
2387 pub fn path_style(&self, cx: &App) -> PathStyle {
2388 self.project.read(cx).path_style(cx)
2389 }
2390
2391 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2392 let mut history: HashMap<EntityId, usize> = HashMap::default();
2393
2394 for pane_handle in &self.panes {
2395 let pane = pane_handle.read(cx);
2396
2397 for entry in pane.activation_history() {
2398 history.insert(
2399 entry.entity_id,
2400 history
2401 .get(&entry.entity_id)
2402 .cloned()
2403 .unwrap_or(0)
2404 .max(entry.timestamp),
2405 );
2406 }
2407 }
2408
2409 history
2410 }
2411
2412 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2413 let mut recent_item: Option<Entity<T>> = None;
2414 let mut recent_timestamp = 0;
2415 for pane_handle in &self.panes {
2416 let pane = pane_handle.read(cx);
2417 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2418 pane.items().map(|item| (item.item_id(), item)).collect();
2419 for entry in pane.activation_history() {
2420 if entry.timestamp > recent_timestamp
2421 && let Some(&item) = item_map.get(&entry.entity_id)
2422 && let Some(typed_item) = item.act_as::<T>(cx)
2423 {
2424 recent_timestamp = entry.timestamp;
2425 recent_item = Some(typed_item);
2426 }
2427 }
2428 }
2429 recent_item
2430 }
2431
2432 pub fn recent_navigation_history_iter(
2433 &self,
2434 cx: &App,
2435 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2436 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2437 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2438
2439 for pane in &self.panes {
2440 let pane = pane.read(cx);
2441
2442 pane.nav_history()
2443 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2444 if let Some(fs_path) = &fs_path {
2445 abs_paths_opened
2446 .entry(fs_path.clone())
2447 .or_default()
2448 .insert(project_path.clone());
2449 }
2450 let timestamp = entry.timestamp;
2451 match history.entry(project_path) {
2452 hash_map::Entry::Occupied(mut entry) => {
2453 let (_, old_timestamp) = entry.get();
2454 if ×tamp > old_timestamp {
2455 entry.insert((fs_path, timestamp));
2456 }
2457 }
2458 hash_map::Entry::Vacant(entry) => {
2459 entry.insert((fs_path, timestamp));
2460 }
2461 }
2462 });
2463
2464 if let Some(item) = pane.active_item()
2465 && let Some(project_path) = item.project_path(cx)
2466 {
2467 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2468
2469 if let Some(fs_path) = &fs_path {
2470 abs_paths_opened
2471 .entry(fs_path.clone())
2472 .or_default()
2473 .insert(project_path.clone());
2474 }
2475
2476 history.insert(project_path, (fs_path, std::usize::MAX));
2477 }
2478 }
2479
2480 history
2481 .into_iter()
2482 .sorted_by_key(|(_, (_, order))| *order)
2483 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2484 .rev()
2485 .filter(move |(history_path, abs_path)| {
2486 let latest_project_path_opened = abs_path
2487 .as_ref()
2488 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2489 .and_then(|project_paths| {
2490 project_paths
2491 .iter()
2492 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2493 });
2494
2495 latest_project_path_opened.is_none_or(|path| path == history_path)
2496 })
2497 }
2498
2499 pub fn recent_navigation_history(
2500 &self,
2501 limit: Option<usize>,
2502 cx: &App,
2503 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2504 self.recent_navigation_history_iter(cx)
2505 .take(limit.unwrap_or(usize::MAX))
2506 .collect()
2507 }
2508
2509 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2510 for pane in &self.panes {
2511 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2512 }
2513 }
2514
2515 fn navigate_history(
2516 &mut self,
2517 pane: WeakEntity<Pane>,
2518 mode: NavigationMode,
2519 window: &mut Window,
2520 cx: &mut Context<Workspace>,
2521 ) -> Task<Result<()>> {
2522 self.navigate_history_impl(
2523 pane,
2524 mode,
2525 window,
2526 &mut |history, cx| history.pop(mode, cx),
2527 cx,
2528 )
2529 }
2530
2531 fn navigate_tag_history(
2532 &mut self,
2533 pane: WeakEntity<Pane>,
2534 mode: TagNavigationMode,
2535 window: &mut Window,
2536 cx: &mut Context<Workspace>,
2537 ) -> Task<Result<()>> {
2538 self.navigate_history_impl(
2539 pane,
2540 NavigationMode::Normal,
2541 window,
2542 &mut |history, _cx| history.pop_tag(mode),
2543 cx,
2544 )
2545 }
2546
2547 fn navigate_history_impl(
2548 &mut self,
2549 pane: WeakEntity<Pane>,
2550 mode: NavigationMode,
2551 window: &mut Window,
2552 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2553 cx: &mut Context<Workspace>,
2554 ) -> Task<Result<()>> {
2555 let to_load = if let Some(pane) = pane.upgrade() {
2556 pane.update(cx, |pane, cx| {
2557 window.focus(&pane.focus_handle(cx), cx);
2558 loop {
2559 // Retrieve the weak item handle from the history.
2560 let entry = cb(pane.nav_history_mut(), cx)?;
2561
2562 // If the item is still present in this pane, then activate it.
2563 if let Some(index) = entry
2564 .item
2565 .upgrade()
2566 .and_then(|v| pane.index_for_item(v.as_ref()))
2567 {
2568 let prev_active_item_index = pane.active_item_index();
2569 pane.nav_history_mut().set_mode(mode);
2570 pane.activate_item(index, true, true, window, cx);
2571 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2572
2573 let mut navigated = prev_active_item_index != pane.active_item_index();
2574 if let Some(data) = entry.data {
2575 navigated |= pane.active_item()?.navigate(data, window, cx);
2576 }
2577
2578 if navigated {
2579 break None;
2580 }
2581 } else {
2582 // If the item is no longer present in this pane, then retrieve its
2583 // path info in order to reopen it.
2584 break pane
2585 .nav_history()
2586 .path_for_item(entry.item.id())
2587 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2588 }
2589 }
2590 })
2591 } else {
2592 None
2593 };
2594
2595 if let Some((project_path, abs_path, entry)) = to_load {
2596 // If the item was no longer present, then load it again from its previous path, first try the local path
2597 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2598
2599 cx.spawn_in(window, async move |workspace, cx| {
2600 let open_by_project_path = open_by_project_path.await;
2601 let mut navigated = false;
2602 match open_by_project_path
2603 .with_context(|| format!("Navigating to {project_path:?}"))
2604 {
2605 Ok((project_entry_id, build_item)) => {
2606 let prev_active_item_id = pane.update(cx, |pane, _| {
2607 pane.nav_history_mut().set_mode(mode);
2608 pane.active_item().map(|p| p.item_id())
2609 })?;
2610
2611 pane.update_in(cx, |pane, window, cx| {
2612 let item = pane.open_item(
2613 project_entry_id,
2614 project_path,
2615 true,
2616 entry.is_preview,
2617 true,
2618 None,
2619 window, cx,
2620 build_item,
2621 );
2622 navigated |= Some(item.item_id()) != prev_active_item_id;
2623 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2624 if let Some(data) = entry.data {
2625 navigated |= item.navigate(data, window, cx);
2626 }
2627 })?;
2628 }
2629 Err(open_by_project_path_e) => {
2630 // Fall back to opening by abs path, in case an external file was opened and closed,
2631 // and its worktree is now dropped
2632 if let Some(abs_path) = abs_path {
2633 let prev_active_item_id = pane.update(cx, |pane, _| {
2634 pane.nav_history_mut().set_mode(mode);
2635 pane.active_item().map(|p| p.item_id())
2636 })?;
2637 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2638 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2639 })?;
2640 match open_by_abs_path
2641 .await
2642 .with_context(|| format!("Navigating to {abs_path:?}"))
2643 {
2644 Ok(item) => {
2645 pane.update_in(cx, |pane, window, cx| {
2646 navigated |= Some(item.item_id()) != prev_active_item_id;
2647 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2648 if let Some(data) = entry.data {
2649 navigated |= item.navigate(data, window, cx);
2650 }
2651 })?;
2652 }
2653 Err(open_by_abs_path_e) => {
2654 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2655 }
2656 }
2657 }
2658 }
2659 }
2660
2661 if !navigated {
2662 workspace
2663 .update_in(cx, |workspace, window, cx| {
2664 Self::navigate_history(workspace, pane, mode, window, cx)
2665 })?
2666 .await?;
2667 }
2668
2669 Ok(())
2670 })
2671 } else {
2672 Task::ready(Ok(()))
2673 }
2674 }
2675
2676 pub fn go_back(
2677 &mut self,
2678 pane: WeakEntity<Pane>,
2679 window: &mut Window,
2680 cx: &mut Context<Workspace>,
2681 ) -> Task<Result<()>> {
2682 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2683 }
2684
2685 pub fn go_forward(
2686 &mut self,
2687 pane: WeakEntity<Pane>,
2688 window: &mut Window,
2689 cx: &mut Context<Workspace>,
2690 ) -> Task<Result<()>> {
2691 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2692 }
2693
2694 pub fn reopen_closed_item(
2695 &mut self,
2696 window: &mut Window,
2697 cx: &mut Context<Workspace>,
2698 ) -> Task<Result<()>> {
2699 self.navigate_history(
2700 self.active_pane().downgrade(),
2701 NavigationMode::ReopeningClosedItem,
2702 window,
2703 cx,
2704 )
2705 }
2706
2707 pub fn client(&self) -> &Arc<Client> {
2708 &self.app_state.client
2709 }
2710
2711 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2712 self.titlebar_item = Some(item);
2713 cx.notify();
2714 }
2715
2716 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2717 self.on_prompt_for_new_path = Some(prompt)
2718 }
2719
2720 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2721 self.on_prompt_for_open_path = Some(prompt)
2722 }
2723
2724 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2725 self.terminal_provider = Some(Box::new(provider));
2726 }
2727
2728 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2729 self.debugger_provider = Some(Arc::new(provider));
2730 }
2731
2732 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2733 self.debugger_provider.clone()
2734 }
2735
2736 pub fn prompt_for_open_path(
2737 &mut self,
2738 path_prompt_options: PathPromptOptions,
2739 lister: DirectoryLister,
2740 window: &mut Window,
2741 cx: &mut Context<Self>,
2742 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2743 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2744 let prompt = self.on_prompt_for_open_path.take().unwrap();
2745 let rx = prompt(self, lister, window, cx);
2746 self.on_prompt_for_open_path = Some(prompt);
2747 rx
2748 } else {
2749 let (tx, rx) = oneshot::channel();
2750 let abs_path = cx.prompt_for_paths(path_prompt_options);
2751
2752 cx.spawn_in(window, async move |workspace, cx| {
2753 let Ok(result) = abs_path.await else {
2754 return Ok(());
2755 };
2756
2757 match result {
2758 Ok(result) => {
2759 tx.send(result).ok();
2760 }
2761 Err(err) => {
2762 let rx = workspace.update_in(cx, |workspace, window, cx| {
2763 workspace.show_portal_error(err.to_string(), cx);
2764 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2765 let rx = prompt(workspace, lister, window, cx);
2766 workspace.on_prompt_for_open_path = Some(prompt);
2767 rx
2768 })?;
2769 if let Ok(path) = rx.await {
2770 tx.send(path).ok();
2771 }
2772 }
2773 };
2774 anyhow::Ok(())
2775 })
2776 .detach();
2777
2778 rx
2779 }
2780 }
2781
2782 pub fn prompt_for_new_path(
2783 &mut self,
2784 lister: DirectoryLister,
2785 suggested_name: Option<String>,
2786 window: &mut Window,
2787 cx: &mut Context<Self>,
2788 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2789 if self.project.read(cx).is_via_collab()
2790 || self.project.read(cx).is_via_remote_server()
2791 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2792 {
2793 let prompt = self.on_prompt_for_new_path.take().unwrap();
2794 let rx = prompt(self, lister, suggested_name, window, cx);
2795 self.on_prompt_for_new_path = Some(prompt);
2796 return rx;
2797 }
2798
2799 let (tx, rx) = oneshot::channel();
2800 cx.spawn_in(window, async move |workspace, cx| {
2801 let abs_path = workspace.update(cx, |workspace, cx| {
2802 let relative_to = workspace
2803 .most_recent_active_path(cx)
2804 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2805 .or_else(|| {
2806 let project = workspace.project.read(cx);
2807 project.visible_worktrees(cx).find_map(|worktree| {
2808 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2809 })
2810 })
2811 .or_else(std::env::home_dir)
2812 .unwrap_or_else(|| PathBuf::from(""));
2813 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2814 })?;
2815 let abs_path = match abs_path.await? {
2816 Ok(path) => path,
2817 Err(err) => {
2818 let rx = workspace.update_in(cx, |workspace, window, cx| {
2819 workspace.show_portal_error(err.to_string(), cx);
2820
2821 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2822 let rx = prompt(workspace, lister, suggested_name, window, cx);
2823 workspace.on_prompt_for_new_path = Some(prompt);
2824 rx
2825 })?;
2826 if let Ok(path) = rx.await {
2827 tx.send(path).ok();
2828 }
2829 return anyhow::Ok(());
2830 }
2831 };
2832
2833 tx.send(abs_path.map(|path| vec![path])).ok();
2834 anyhow::Ok(())
2835 })
2836 .detach();
2837
2838 rx
2839 }
2840
2841 pub fn titlebar_item(&self) -> Option<AnyView> {
2842 self.titlebar_item.clone()
2843 }
2844
2845 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2846 /// When set, git-related operations should use this worktree instead of deriving
2847 /// the active worktree from the focused file.
2848 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2849 self.active_worktree_override
2850 }
2851
2852 pub fn set_active_worktree_override(
2853 &mut self,
2854 worktree_id: Option<WorktreeId>,
2855 cx: &mut Context<Self>,
2856 ) {
2857 self.active_worktree_override = worktree_id;
2858 cx.notify();
2859 }
2860
2861 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2862 self.active_worktree_override = None;
2863 cx.notify();
2864 }
2865
2866 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2867 ///
2868 /// If the given workspace has a local project, then it will be passed
2869 /// to the callback. Otherwise, a new empty window will be created.
2870 pub fn with_local_workspace<T, F>(
2871 &mut self,
2872 window: &mut Window,
2873 cx: &mut Context<Self>,
2874 callback: F,
2875 ) -> Task<Result<T>>
2876 where
2877 T: 'static,
2878 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2879 {
2880 if self.project.read(cx).is_local() {
2881 Task::ready(Ok(callback(self, window, cx)))
2882 } else {
2883 let env = self.project.read(cx).cli_environment(cx);
2884 let task = Self::new_local(
2885 Vec::new(),
2886 self.app_state.clone(),
2887 None,
2888 env,
2889 None,
2890 true,
2891 cx,
2892 );
2893 cx.spawn_in(window, async move |_vh, cx| {
2894 let OpenResult {
2895 window: multi_workspace_window,
2896 ..
2897 } = task.await?;
2898 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2899 let workspace = multi_workspace.workspace().clone();
2900 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2901 })
2902 })
2903 }
2904 }
2905
2906 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2907 ///
2908 /// If the given workspace has a local project, then it will be passed
2909 /// to the callback. Otherwise, a new empty window will be created.
2910 pub fn with_local_or_wsl_workspace<T, F>(
2911 &mut self,
2912 window: &mut Window,
2913 cx: &mut Context<Self>,
2914 callback: F,
2915 ) -> Task<Result<T>>
2916 where
2917 T: 'static,
2918 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2919 {
2920 let project = self.project.read(cx);
2921 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2922 Task::ready(Ok(callback(self, window, cx)))
2923 } else {
2924 let env = self.project.read(cx).cli_environment(cx);
2925 let task = Self::new_local(
2926 Vec::new(),
2927 self.app_state.clone(),
2928 None,
2929 env,
2930 None,
2931 true,
2932 cx,
2933 );
2934 cx.spawn_in(window, async move |_vh, cx| {
2935 let OpenResult {
2936 window: multi_workspace_window,
2937 ..
2938 } = task.await?;
2939 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2940 let workspace = multi_workspace.workspace().clone();
2941 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2942 })
2943 })
2944 }
2945 }
2946
2947 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2948 self.project.read(cx).worktrees(cx)
2949 }
2950
2951 pub fn visible_worktrees<'a>(
2952 &self,
2953 cx: &'a App,
2954 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2955 self.project.read(cx).visible_worktrees(cx)
2956 }
2957
2958 #[cfg(any(test, feature = "test-support"))]
2959 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2960 let futures = self
2961 .worktrees(cx)
2962 .filter_map(|worktree| worktree.read(cx).as_local())
2963 .map(|worktree| worktree.scan_complete())
2964 .collect::<Vec<_>>();
2965 async move {
2966 for future in futures {
2967 future.await;
2968 }
2969 }
2970 }
2971
2972 pub fn close_global(cx: &mut App) {
2973 cx.defer(|cx| {
2974 cx.windows().iter().find(|window| {
2975 window
2976 .update(cx, |_, window, _| {
2977 if window.is_window_active() {
2978 //This can only get called when the window's project connection has been lost
2979 //so we don't need to prompt the user for anything and instead just close the window
2980 window.remove_window();
2981 true
2982 } else {
2983 false
2984 }
2985 })
2986 .unwrap_or(false)
2987 });
2988 });
2989 }
2990
2991 pub fn move_focused_panel_to_next_position(
2992 &mut self,
2993 _: &MoveFocusedPanelToNextPosition,
2994 window: &mut Window,
2995 cx: &mut Context<Self>,
2996 ) {
2997 let docks = self.all_docks();
2998 let active_dock = docks
2999 .into_iter()
3000 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
3001
3002 if let Some(dock) = active_dock {
3003 dock.update(cx, |dock, cx| {
3004 let active_panel = dock
3005 .active_panel()
3006 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
3007
3008 if let Some(panel) = active_panel {
3009 panel.move_to_next_position(window, cx);
3010 }
3011 })
3012 }
3013 }
3014
3015 pub fn prepare_to_close(
3016 &mut self,
3017 close_intent: CloseIntent,
3018 window: &mut Window,
3019 cx: &mut Context<Self>,
3020 ) -> Task<Result<bool>> {
3021 let active_call = self.active_global_call();
3022
3023 cx.spawn_in(window, async move |this, cx| {
3024 this.update(cx, |this, _| {
3025 if close_intent == CloseIntent::CloseWindow {
3026 this.removing = true;
3027 }
3028 })?;
3029
3030 let workspace_count = cx.update(|_window, cx| {
3031 cx.windows()
3032 .iter()
3033 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
3034 .count()
3035 })?;
3036
3037 #[cfg(target_os = "macos")]
3038 let save_last_workspace = false;
3039
3040 // On Linux and Windows, closing the last window should restore the last workspace.
3041 #[cfg(not(target_os = "macos"))]
3042 let save_last_workspace = {
3043 let remaining_workspaces = cx.update(|_window, cx| {
3044 cx.windows()
3045 .iter()
3046 .filter_map(|window| window.downcast::<MultiWorkspace>())
3047 .filter_map(|multi_workspace| {
3048 multi_workspace
3049 .update(cx, |multi_workspace, _, cx| {
3050 multi_workspace.workspace().read(cx).removing
3051 })
3052 .ok()
3053 })
3054 .filter(|removing| !removing)
3055 .count()
3056 })?;
3057
3058 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
3059 };
3060
3061 if let Some(active_call) = active_call
3062 && workspace_count == 1
3063 && cx
3064 .update(|_window, cx| active_call.0.is_in_room(cx))
3065 .unwrap_or(false)
3066 {
3067 if close_intent == CloseIntent::CloseWindow {
3068 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
3069 let answer = cx.update(|window, cx| {
3070 window.prompt(
3071 PromptLevel::Warning,
3072 "Do you want to leave the current call?",
3073 None,
3074 &["Close window and hang up", "Cancel"],
3075 cx,
3076 )
3077 })?;
3078
3079 if answer.await.log_err() == Some(1) {
3080 return anyhow::Ok(false);
3081 } else {
3082 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
3083 task.await.log_err();
3084 }
3085 }
3086 }
3087 if close_intent == CloseIntent::ReplaceWindow {
3088 _ = cx.update(|_window, cx| {
3089 let multi_workspace = cx
3090 .windows()
3091 .iter()
3092 .filter_map(|window| window.downcast::<MultiWorkspace>())
3093 .next()
3094 .unwrap();
3095 let project = multi_workspace
3096 .read(cx)?
3097 .workspace()
3098 .read(cx)
3099 .project
3100 .clone();
3101 if project.read(cx).is_shared() {
3102 active_call.0.unshare_project(project, cx)?;
3103 }
3104 Ok::<_, anyhow::Error>(())
3105 });
3106 }
3107 }
3108
3109 let save_result = this
3110 .update_in(cx, |this, window, cx| {
3111 this.save_all_internal(SaveIntent::Close, window, cx)
3112 })?
3113 .await;
3114
3115 // If we're not quitting, but closing, we remove the workspace from
3116 // the current session.
3117 if close_intent != CloseIntent::Quit
3118 && !save_last_workspace
3119 && save_result.as_ref().is_ok_and(|&res| res)
3120 {
3121 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
3122 .await;
3123 }
3124
3125 save_result
3126 })
3127 }
3128
3129 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
3130 self.save_all_internal(
3131 action.save_intent.unwrap_or(SaveIntent::SaveAll),
3132 window,
3133 cx,
3134 )
3135 .detach_and_log_err(cx);
3136 }
3137
3138 fn send_keystrokes(
3139 &mut self,
3140 action: &SendKeystrokes,
3141 window: &mut Window,
3142 cx: &mut Context<Self>,
3143 ) {
3144 let keystrokes: Vec<Keystroke> = action
3145 .0
3146 .split(' ')
3147 .flat_map(|k| Keystroke::parse(k).log_err())
3148 .map(|k| {
3149 cx.keyboard_mapper()
3150 .map_key_equivalent(k, false)
3151 .inner()
3152 .clone()
3153 })
3154 .collect();
3155 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
3156 }
3157
3158 pub fn send_keystrokes_impl(
3159 &mut self,
3160 keystrokes: Vec<Keystroke>,
3161 window: &mut Window,
3162 cx: &mut Context<Self>,
3163 ) -> Shared<Task<()>> {
3164 let mut state = self.dispatching_keystrokes.borrow_mut();
3165 if !state.dispatched.insert(keystrokes.clone()) {
3166 cx.propagate();
3167 return state.task.clone().unwrap();
3168 }
3169
3170 state.queue.extend(keystrokes);
3171
3172 let keystrokes = self.dispatching_keystrokes.clone();
3173 if state.task.is_none() {
3174 state.task = Some(
3175 window
3176 .spawn(cx, async move |cx| {
3177 // limit to 100 keystrokes to avoid infinite recursion.
3178 for _ in 0..100 {
3179 let keystroke = {
3180 let mut state = keystrokes.borrow_mut();
3181 let Some(keystroke) = state.queue.pop_front() else {
3182 state.dispatched.clear();
3183 state.task.take();
3184 return;
3185 };
3186 keystroke
3187 };
3188 cx.update(|window, cx| {
3189 let focused = window.focused(cx);
3190 window.dispatch_keystroke(keystroke.clone(), cx);
3191 if window.focused(cx) != focused {
3192 // dispatch_keystroke may cause the focus to change.
3193 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3194 // And we need that to happen before the next keystroke to keep vim mode happy...
3195 // (Note that the tests always do this implicitly, so you must manually test with something like:
3196 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3197 // )
3198 window.draw(cx).clear();
3199 }
3200 })
3201 .ok();
3202
3203 // Yield between synthetic keystrokes so deferred focus and
3204 // other effects can settle before dispatching the next key.
3205 yield_now().await;
3206 }
3207
3208 *keystrokes.borrow_mut() = Default::default();
3209 log::error!("over 100 keystrokes passed to send_keystrokes");
3210 })
3211 .shared(),
3212 );
3213 }
3214 state.task.clone().unwrap()
3215 }
3216
3217 fn save_all_internal(
3218 &mut self,
3219 mut save_intent: SaveIntent,
3220 window: &mut Window,
3221 cx: &mut Context<Self>,
3222 ) -> Task<Result<bool>> {
3223 if self.project.read(cx).is_disconnected(cx) {
3224 return Task::ready(Ok(true));
3225 }
3226 let dirty_items = self
3227 .panes
3228 .iter()
3229 .flat_map(|pane| {
3230 pane.read(cx).items().filter_map(|item| {
3231 if item.is_dirty(cx) {
3232 item.tab_content_text(0, cx);
3233 Some((pane.downgrade(), item.boxed_clone()))
3234 } else {
3235 None
3236 }
3237 })
3238 })
3239 .collect::<Vec<_>>();
3240
3241 let project = self.project.clone();
3242 cx.spawn_in(window, async move |workspace, cx| {
3243 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3244 let (serialize_tasks, remaining_dirty_items) =
3245 workspace.update_in(cx, |workspace, window, cx| {
3246 let mut remaining_dirty_items = Vec::new();
3247 let mut serialize_tasks = Vec::new();
3248 for (pane, item) in dirty_items {
3249 if let Some(task) = item
3250 .to_serializable_item_handle(cx)
3251 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3252 {
3253 serialize_tasks.push(task);
3254 } else {
3255 remaining_dirty_items.push((pane, item));
3256 }
3257 }
3258 (serialize_tasks, remaining_dirty_items)
3259 })?;
3260
3261 futures::future::try_join_all(serialize_tasks).await?;
3262
3263 if !remaining_dirty_items.is_empty() {
3264 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3265 }
3266
3267 if remaining_dirty_items.len() > 1 {
3268 let answer = workspace.update_in(cx, |_, window, cx| {
3269 let detail = Pane::file_names_for_prompt(
3270 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3271 cx,
3272 );
3273 window.prompt(
3274 PromptLevel::Warning,
3275 "Do you want to save all changes in the following files?",
3276 Some(&detail),
3277 &["Save all", "Discard all", "Cancel"],
3278 cx,
3279 )
3280 })?;
3281 match answer.await.log_err() {
3282 Some(0) => save_intent = SaveIntent::SaveAll,
3283 Some(1) => save_intent = SaveIntent::Skip,
3284 Some(2) => return Ok(false),
3285 _ => {}
3286 }
3287 }
3288
3289 remaining_dirty_items
3290 } else {
3291 dirty_items
3292 };
3293
3294 for (pane, item) in dirty_items {
3295 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3296 (
3297 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3298 item.project_entry_ids(cx),
3299 )
3300 })?;
3301 if (singleton || !project_entry_ids.is_empty())
3302 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3303 {
3304 return Ok(false);
3305 }
3306 }
3307 Ok(true)
3308 })
3309 }
3310
3311 pub fn open_workspace_for_paths(
3312 &mut self,
3313 replace_current_window: bool,
3314 paths: Vec<PathBuf>,
3315 window: &mut Window,
3316 cx: &mut Context<Self>,
3317 ) -> Task<Result<Entity<Workspace>>> {
3318 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
3319 let is_remote = self.project.read(cx).is_via_collab();
3320 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3321 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3322
3323 let window_to_replace = if replace_current_window {
3324 window_handle
3325 } else if is_remote || has_worktree || has_dirty_items {
3326 None
3327 } else {
3328 window_handle
3329 };
3330 let app_state = self.app_state.clone();
3331
3332 cx.spawn(async move |_, cx| {
3333 let OpenResult { workspace, .. } = cx
3334 .update(|cx| {
3335 open_paths(
3336 &paths,
3337 app_state,
3338 OpenOptions {
3339 replace_window: window_to_replace,
3340 ..Default::default()
3341 },
3342 cx,
3343 )
3344 })
3345 .await?;
3346 Ok(workspace)
3347 })
3348 }
3349
3350 #[allow(clippy::type_complexity)]
3351 pub fn open_paths(
3352 &mut self,
3353 mut abs_paths: Vec<PathBuf>,
3354 options: OpenOptions,
3355 pane: Option<WeakEntity<Pane>>,
3356 window: &mut Window,
3357 cx: &mut Context<Self>,
3358 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3359 let fs = self.app_state.fs.clone();
3360
3361 let caller_ordered_abs_paths = abs_paths.clone();
3362
3363 // Sort the paths to ensure we add worktrees for parents before their children.
3364 abs_paths.sort_unstable();
3365 cx.spawn_in(window, async move |this, cx| {
3366 let mut tasks = Vec::with_capacity(abs_paths.len());
3367
3368 for abs_path in &abs_paths {
3369 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3370 OpenVisible::All => Some(true),
3371 OpenVisible::None => Some(false),
3372 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3373 Some(Some(metadata)) => Some(!metadata.is_dir),
3374 Some(None) => Some(true),
3375 None => None,
3376 },
3377 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3378 Some(Some(metadata)) => Some(metadata.is_dir),
3379 Some(None) => Some(false),
3380 None => None,
3381 },
3382 };
3383 let project_path = match visible {
3384 Some(visible) => match this
3385 .update(cx, |this, cx| {
3386 Workspace::project_path_for_path(
3387 this.project.clone(),
3388 abs_path,
3389 visible,
3390 cx,
3391 )
3392 })
3393 .log_err()
3394 {
3395 Some(project_path) => project_path.await.log_err(),
3396 None => None,
3397 },
3398 None => None,
3399 };
3400
3401 let this = this.clone();
3402 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3403 let fs = fs.clone();
3404 let pane = pane.clone();
3405 let task = cx.spawn(async move |cx| {
3406 let (_worktree, project_path) = project_path?;
3407 if fs.is_dir(&abs_path).await {
3408 // Opening a directory should not race to update the active entry.
3409 // We'll select/reveal a deterministic final entry after all paths finish opening.
3410 None
3411 } else {
3412 Some(
3413 this.update_in(cx, |this, window, cx| {
3414 this.open_path(
3415 project_path,
3416 pane,
3417 options.focus.unwrap_or(true),
3418 window,
3419 cx,
3420 )
3421 })
3422 .ok()?
3423 .await,
3424 )
3425 }
3426 });
3427 tasks.push(task);
3428 }
3429
3430 let results = futures::future::join_all(tasks).await;
3431
3432 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3433 let mut winner: Option<(PathBuf, bool)> = None;
3434 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3435 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3436 if !metadata.is_dir {
3437 winner = Some((abs_path, false));
3438 break;
3439 }
3440 if winner.is_none() {
3441 winner = Some((abs_path, true));
3442 }
3443 } else if winner.is_none() {
3444 winner = Some((abs_path, false));
3445 }
3446 }
3447
3448 // Compute the winner entry id on the foreground thread and emit once, after all
3449 // paths finish opening. This avoids races between concurrently-opening paths
3450 // (directories in particular) and makes the resulting project panel selection
3451 // deterministic.
3452 if let Some((winner_abs_path, winner_is_dir)) = winner {
3453 'emit_winner: {
3454 let winner_abs_path: Arc<Path> =
3455 SanitizedPath::new(&winner_abs_path).as_path().into();
3456
3457 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3458 OpenVisible::All => true,
3459 OpenVisible::None => false,
3460 OpenVisible::OnlyFiles => !winner_is_dir,
3461 OpenVisible::OnlyDirectories => winner_is_dir,
3462 };
3463
3464 let Some(worktree_task) = this
3465 .update(cx, |workspace, cx| {
3466 workspace.project.update(cx, |project, cx| {
3467 project.find_or_create_worktree(
3468 winner_abs_path.as_ref(),
3469 visible,
3470 cx,
3471 )
3472 })
3473 })
3474 .ok()
3475 else {
3476 break 'emit_winner;
3477 };
3478
3479 let Ok((worktree, _)) = worktree_task.await else {
3480 break 'emit_winner;
3481 };
3482
3483 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3484 let worktree = worktree.read(cx);
3485 let worktree_abs_path = worktree.abs_path();
3486 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3487 worktree.root_entry()
3488 } else {
3489 winner_abs_path
3490 .strip_prefix(worktree_abs_path.as_ref())
3491 .ok()
3492 .and_then(|relative_path| {
3493 let relative_path =
3494 RelPath::new(relative_path, PathStyle::local())
3495 .log_err()?;
3496 worktree.entry_for_path(&relative_path)
3497 })
3498 }?;
3499 Some(entry.id)
3500 }) else {
3501 break 'emit_winner;
3502 };
3503
3504 this.update(cx, |workspace, cx| {
3505 workspace.project.update(cx, |_, cx| {
3506 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3507 });
3508 })
3509 .ok();
3510 }
3511 }
3512
3513 results
3514 })
3515 }
3516
3517 pub fn open_resolved_path(
3518 &mut self,
3519 path: ResolvedPath,
3520 window: &mut Window,
3521 cx: &mut Context<Self>,
3522 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3523 match path {
3524 ResolvedPath::ProjectPath { project_path, .. } => {
3525 self.open_path(project_path, None, true, window, cx)
3526 }
3527 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3528 PathBuf::from(path),
3529 OpenOptions {
3530 visible: Some(OpenVisible::None),
3531 ..Default::default()
3532 },
3533 window,
3534 cx,
3535 ),
3536 }
3537 }
3538
3539 pub fn absolute_path_of_worktree(
3540 &self,
3541 worktree_id: WorktreeId,
3542 cx: &mut Context<Self>,
3543 ) -> Option<PathBuf> {
3544 self.project
3545 .read(cx)
3546 .worktree_for_id(worktree_id, cx)
3547 // TODO: use `abs_path` or `root_dir`
3548 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3549 }
3550
3551 pub fn add_folder_to_project(
3552 &mut self,
3553 _: &AddFolderToProject,
3554 window: &mut Window,
3555 cx: &mut Context<Self>,
3556 ) {
3557 let project = self.project.read(cx);
3558 if project.is_via_collab() {
3559 self.show_error(
3560 &anyhow!("You cannot add folders to someone else's project"),
3561 cx,
3562 );
3563 return;
3564 }
3565 let paths = self.prompt_for_open_path(
3566 PathPromptOptions {
3567 files: false,
3568 directories: true,
3569 multiple: true,
3570 prompt: None,
3571 },
3572 DirectoryLister::Project(self.project.clone()),
3573 window,
3574 cx,
3575 );
3576 cx.spawn_in(window, async move |this, cx| {
3577 if let Some(paths) = paths.await.log_err().flatten() {
3578 let results = this
3579 .update_in(cx, |this, window, cx| {
3580 this.open_paths(
3581 paths,
3582 OpenOptions {
3583 visible: Some(OpenVisible::All),
3584 ..Default::default()
3585 },
3586 None,
3587 window,
3588 cx,
3589 )
3590 })?
3591 .await;
3592 for result in results.into_iter().flatten() {
3593 result.log_err();
3594 }
3595 }
3596 anyhow::Ok(())
3597 })
3598 .detach_and_log_err(cx);
3599 }
3600
3601 pub fn project_path_for_path(
3602 project: Entity<Project>,
3603 abs_path: &Path,
3604 visible: bool,
3605 cx: &mut App,
3606 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3607 let entry = project.update(cx, |project, cx| {
3608 project.find_or_create_worktree(abs_path, visible, cx)
3609 });
3610 cx.spawn(async move |cx| {
3611 let (worktree, path) = entry.await?;
3612 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3613 Ok((worktree, ProjectPath { worktree_id, path }))
3614 })
3615 }
3616
3617 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3618 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3619 }
3620
3621 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3622 self.items_of_type(cx).max_by_key(|item| item.item_id())
3623 }
3624
3625 pub fn items_of_type<'a, T: Item>(
3626 &'a self,
3627 cx: &'a App,
3628 ) -> impl 'a + Iterator<Item = Entity<T>> {
3629 self.panes
3630 .iter()
3631 .flat_map(|pane| pane.read(cx).items_of_type())
3632 }
3633
3634 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3635 self.active_pane().read(cx).active_item()
3636 }
3637
3638 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3639 let item = self.active_item(cx)?;
3640 item.to_any_view().downcast::<I>().ok()
3641 }
3642
3643 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3644 self.active_item(cx).and_then(|item| item.project_path(cx))
3645 }
3646
3647 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3648 self.recent_navigation_history_iter(cx)
3649 .filter_map(|(path, abs_path)| {
3650 let worktree = self
3651 .project
3652 .read(cx)
3653 .worktree_for_id(path.worktree_id, cx)?;
3654 if worktree.read(cx).is_visible() {
3655 abs_path
3656 } else {
3657 None
3658 }
3659 })
3660 .next()
3661 }
3662
3663 pub fn save_active_item(
3664 &mut self,
3665 save_intent: SaveIntent,
3666 window: &mut Window,
3667 cx: &mut App,
3668 ) -> Task<Result<()>> {
3669 let project = self.project.clone();
3670 let pane = self.active_pane();
3671 let item = pane.read(cx).active_item();
3672 let pane = pane.downgrade();
3673
3674 window.spawn(cx, async move |cx| {
3675 if let Some(item) = item {
3676 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3677 .await
3678 .map(|_| ())
3679 } else {
3680 Ok(())
3681 }
3682 })
3683 }
3684
3685 pub fn close_inactive_items_and_panes(
3686 &mut self,
3687 action: &CloseInactiveTabsAndPanes,
3688 window: &mut Window,
3689 cx: &mut Context<Self>,
3690 ) {
3691 if let Some(task) = self.close_all_internal(
3692 true,
3693 action.save_intent.unwrap_or(SaveIntent::Close),
3694 window,
3695 cx,
3696 ) {
3697 task.detach_and_log_err(cx)
3698 }
3699 }
3700
3701 pub fn close_all_items_and_panes(
3702 &mut self,
3703 action: &CloseAllItemsAndPanes,
3704 window: &mut Window,
3705 cx: &mut Context<Self>,
3706 ) {
3707 if let Some(task) = self.close_all_internal(
3708 false,
3709 action.save_intent.unwrap_or(SaveIntent::Close),
3710 window,
3711 cx,
3712 ) {
3713 task.detach_and_log_err(cx)
3714 }
3715 }
3716
3717 /// Closes the active item across all panes.
3718 pub fn close_item_in_all_panes(
3719 &mut self,
3720 action: &CloseItemInAllPanes,
3721 window: &mut Window,
3722 cx: &mut Context<Self>,
3723 ) {
3724 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3725 return;
3726 };
3727
3728 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3729 let close_pinned = action.close_pinned;
3730
3731 if let Some(project_path) = active_item.project_path(cx) {
3732 self.close_items_with_project_path(
3733 &project_path,
3734 save_intent,
3735 close_pinned,
3736 window,
3737 cx,
3738 );
3739 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3740 let item_id = active_item.item_id();
3741 self.active_pane().update(cx, |pane, cx| {
3742 pane.close_item_by_id(item_id, save_intent, window, cx)
3743 .detach_and_log_err(cx);
3744 });
3745 }
3746 }
3747
3748 /// Closes all items with the given project path across all panes.
3749 pub fn close_items_with_project_path(
3750 &mut self,
3751 project_path: &ProjectPath,
3752 save_intent: SaveIntent,
3753 close_pinned: bool,
3754 window: &mut Window,
3755 cx: &mut Context<Self>,
3756 ) {
3757 let panes = self.panes().to_vec();
3758 for pane in panes {
3759 pane.update(cx, |pane, cx| {
3760 pane.close_items_for_project_path(
3761 project_path,
3762 save_intent,
3763 close_pinned,
3764 window,
3765 cx,
3766 )
3767 .detach_and_log_err(cx);
3768 });
3769 }
3770 }
3771
3772 fn close_all_internal(
3773 &mut self,
3774 retain_active_pane: bool,
3775 save_intent: SaveIntent,
3776 window: &mut Window,
3777 cx: &mut Context<Self>,
3778 ) -> Option<Task<Result<()>>> {
3779 let current_pane = self.active_pane();
3780
3781 let mut tasks = Vec::new();
3782
3783 if retain_active_pane {
3784 let current_pane_close = current_pane.update(cx, |pane, cx| {
3785 pane.close_other_items(
3786 &CloseOtherItems {
3787 save_intent: None,
3788 close_pinned: false,
3789 },
3790 None,
3791 window,
3792 cx,
3793 )
3794 });
3795
3796 tasks.push(current_pane_close);
3797 }
3798
3799 for pane in self.panes() {
3800 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3801 continue;
3802 }
3803
3804 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3805 pane.close_all_items(
3806 &CloseAllItems {
3807 save_intent: Some(save_intent),
3808 close_pinned: false,
3809 },
3810 window,
3811 cx,
3812 )
3813 });
3814
3815 tasks.push(close_pane_items)
3816 }
3817
3818 if tasks.is_empty() {
3819 None
3820 } else {
3821 Some(cx.spawn_in(window, async move |_, _| {
3822 for task in tasks {
3823 task.await?
3824 }
3825 Ok(())
3826 }))
3827 }
3828 }
3829
3830 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3831 self.dock_at_position(position).read(cx).is_open()
3832 }
3833
3834 pub fn toggle_dock(
3835 &mut self,
3836 dock_side: DockPosition,
3837 window: &mut Window,
3838 cx: &mut Context<Self>,
3839 ) {
3840 let mut focus_center = false;
3841 let mut reveal_dock = false;
3842
3843 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3844 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3845
3846 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3847 telemetry::event!(
3848 "Panel Button Clicked",
3849 name = panel.persistent_name(),
3850 toggle_state = !was_visible
3851 );
3852 }
3853 if was_visible {
3854 self.save_open_dock_positions(cx);
3855 }
3856
3857 let dock = self.dock_at_position(dock_side);
3858 dock.update(cx, |dock, cx| {
3859 dock.set_open(!was_visible, window, cx);
3860
3861 if dock.active_panel().is_none() {
3862 let Some(panel_ix) = dock
3863 .first_enabled_panel_idx(cx)
3864 .log_with_level(log::Level::Info)
3865 else {
3866 return;
3867 };
3868 dock.activate_panel(panel_ix, window, cx);
3869 }
3870
3871 if let Some(active_panel) = dock.active_panel() {
3872 if was_visible {
3873 if active_panel
3874 .panel_focus_handle(cx)
3875 .contains_focused(window, cx)
3876 {
3877 focus_center = true;
3878 }
3879 } else {
3880 let focus_handle = &active_panel.panel_focus_handle(cx);
3881 window.focus(focus_handle, cx);
3882 reveal_dock = true;
3883 }
3884 }
3885 });
3886
3887 if reveal_dock {
3888 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3889 }
3890
3891 if focus_center {
3892 self.active_pane
3893 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3894 }
3895
3896 cx.notify();
3897 self.serialize_workspace(window, cx);
3898 }
3899
3900 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3901 self.all_docks().into_iter().find(|&dock| {
3902 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3903 })
3904 }
3905
3906 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3907 if let Some(dock) = self.active_dock(window, cx).cloned() {
3908 self.save_open_dock_positions(cx);
3909 dock.update(cx, |dock, cx| {
3910 dock.set_open(false, window, cx);
3911 });
3912 return true;
3913 }
3914 false
3915 }
3916
3917 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3918 self.save_open_dock_positions(cx);
3919 for dock in self.all_docks() {
3920 dock.update(cx, |dock, cx| {
3921 dock.set_open(false, window, cx);
3922 });
3923 }
3924
3925 cx.focus_self(window);
3926 cx.notify();
3927 self.serialize_workspace(window, cx);
3928 }
3929
3930 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3931 self.all_docks()
3932 .into_iter()
3933 .filter_map(|dock| {
3934 let dock_ref = dock.read(cx);
3935 if dock_ref.is_open() {
3936 Some(dock_ref.position())
3937 } else {
3938 None
3939 }
3940 })
3941 .collect()
3942 }
3943
3944 /// Saves the positions of currently open docks.
3945 ///
3946 /// Updates `last_open_dock_positions` with positions of all currently open
3947 /// docks, to later be restored by the 'Toggle All Docks' action.
3948 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3949 let open_dock_positions = self.get_open_dock_positions(cx);
3950 if !open_dock_positions.is_empty() {
3951 self.last_open_dock_positions = open_dock_positions;
3952 }
3953 }
3954
3955 /// Toggles all docks between open and closed states.
3956 ///
3957 /// If any docks are open, closes all and remembers their positions. If all
3958 /// docks are closed, restores the last remembered dock configuration.
3959 fn toggle_all_docks(
3960 &mut self,
3961 _: &ToggleAllDocks,
3962 window: &mut Window,
3963 cx: &mut Context<Self>,
3964 ) {
3965 let open_dock_positions = self.get_open_dock_positions(cx);
3966
3967 if !open_dock_positions.is_empty() {
3968 self.close_all_docks(window, cx);
3969 } else if !self.last_open_dock_positions.is_empty() {
3970 self.restore_last_open_docks(window, cx);
3971 }
3972 }
3973
3974 /// Reopens docks from the most recently remembered configuration.
3975 ///
3976 /// Opens all docks whose positions are stored in `last_open_dock_positions`
3977 /// and clears the stored positions.
3978 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3979 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
3980
3981 for position in positions_to_open {
3982 let dock = self.dock_at_position(position);
3983 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
3984 }
3985
3986 cx.focus_self(window);
3987 cx.notify();
3988 self.serialize_workspace(window, cx);
3989 }
3990
3991 /// Transfer focus to the panel of the given type.
3992 pub fn focus_panel<T: Panel>(
3993 &mut self,
3994 window: &mut Window,
3995 cx: &mut Context<Self>,
3996 ) -> Option<Entity<T>> {
3997 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
3998 panel.to_any().downcast().ok()
3999 }
4000
4001 /// Focus the panel of the given type if it isn't already focused. If it is
4002 /// already focused, then transfer focus back to the workspace center.
4003 /// When the `close_panel_on_toggle` setting is enabled, also closes the
4004 /// panel when transferring focus back to the center.
4005 pub fn toggle_panel_focus<T: Panel>(
4006 &mut self,
4007 window: &mut Window,
4008 cx: &mut Context<Self>,
4009 ) -> bool {
4010 let mut did_focus_panel = false;
4011 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
4012 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
4013 did_focus_panel
4014 });
4015
4016 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
4017 self.close_panel::<T>(window, cx);
4018 }
4019
4020 telemetry::event!(
4021 "Panel Button Clicked",
4022 name = T::persistent_name(),
4023 toggle_state = did_focus_panel
4024 );
4025
4026 did_focus_panel
4027 }
4028
4029 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4030 if let Some(item) = self.active_item(cx) {
4031 item.item_focus_handle(cx).focus(window, cx);
4032 } else {
4033 log::error!("Could not find a focus target when switching focus to the center panes",);
4034 }
4035 }
4036
4037 pub fn activate_panel_for_proto_id(
4038 &mut self,
4039 panel_id: PanelId,
4040 window: &mut Window,
4041 cx: &mut Context<Self>,
4042 ) -> Option<Arc<dyn PanelHandle>> {
4043 let mut panel = None;
4044 for dock in self.all_docks() {
4045 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
4046 panel = dock.update(cx, |dock, cx| {
4047 dock.activate_panel(panel_index, window, cx);
4048 dock.set_open(true, window, cx);
4049 dock.active_panel().cloned()
4050 });
4051 break;
4052 }
4053 }
4054
4055 if panel.is_some() {
4056 cx.notify();
4057 self.serialize_workspace(window, cx);
4058 }
4059
4060 panel
4061 }
4062
4063 /// Focus or unfocus the given panel type, depending on the given callback.
4064 fn focus_or_unfocus_panel<T: Panel>(
4065 &mut self,
4066 window: &mut Window,
4067 cx: &mut Context<Self>,
4068 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
4069 ) -> Option<Arc<dyn PanelHandle>> {
4070 let mut result_panel = None;
4071 let mut serialize = false;
4072 for dock in self.all_docks() {
4073 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4074 let mut focus_center = false;
4075 let panel = dock.update(cx, |dock, cx| {
4076 dock.activate_panel(panel_index, window, cx);
4077
4078 let panel = dock.active_panel().cloned();
4079 if let Some(panel) = panel.as_ref() {
4080 if should_focus(&**panel, window, cx) {
4081 dock.set_open(true, window, cx);
4082 panel.panel_focus_handle(cx).focus(window, cx);
4083 } else {
4084 focus_center = true;
4085 }
4086 }
4087 panel
4088 });
4089
4090 if focus_center {
4091 self.active_pane
4092 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4093 }
4094
4095 result_panel = panel;
4096 serialize = true;
4097 break;
4098 }
4099 }
4100
4101 if serialize {
4102 self.serialize_workspace(window, cx);
4103 }
4104
4105 cx.notify();
4106 result_panel
4107 }
4108
4109 /// Open the panel of the given type
4110 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4111 for dock in self.all_docks() {
4112 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4113 dock.update(cx, |dock, cx| {
4114 dock.activate_panel(panel_index, window, cx);
4115 dock.set_open(true, window, cx);
4116 });
4117 }
4118 }
4119 }
4120
4121 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
4122 for dock in self.all_docks().iter() {
4123 dock.update(cx, |dock, cx| {
4124 if dock.panel::<T>().is_some() {
4125 dock.set_open(false, window, cx)
4126 }
4127 })
4128 }
4129 }
4130
4131 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
4132 self.all_docks()
4133 .iter()
4134 .find_map(|dock| dock.read(cx).panel::<T>())
4135 }
4136
4137 fn dismiss_zoomed_items_to_reveal(
4138 &mut self,
4139 dock_to_reveal: Option<DockPosition>,
4140 window: &mut Window,
4141 cx: &mut Context<Self>,
4142 ) {
4143 // If a center pane is zoomed, unzoom it.
4144 for pane in &self.panes {
4145 if pane != &self.active_pane || dock_to_reveal.is_some() {
4146 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4147 }
4148 }
4149
4150 // If another dock is zoomed, hide it.
4151 let mut focus_center = false;
4152 for dock in self.all_docks() {
4153 dock.update(cx, |dock, cx| {
4154 if Some(dock.position()) != dock_to_reveal
4155 && let Some(panel) = dock.active_panel()
4156 && panel.is_zoomed(window, cx)
4157 {
4158 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
4159 dock.set_open(false, window, cx);
4160 }
4161 });
4162 }
4163
4164 if focus_center {
4165 self.active_pane
4166 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4167 }
4168
4169 if self.zoomed_position != dock_to_reveal {
4170 self.zoomed = None;
4171 self.zoomed_position = None;
4172 cx.emit(Event::ZoomChanged);
4173 }
4174
4175 cx.notify();
4176 }
4177
4178 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4179 let pane = cx.new(|cx| {
4180 let mut pane = Pane::new(
4181 self.weak_handle(),
4182 self.project.clone(),
4183 self.pane_history_timestamp.clone(),
4184 None,
4185 NewFile.boxed_clone(),
4186 true,
4187 window,
4188 cx,
4189 );
4190 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4191 pane
4192 });
4193 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4194 .detach();
4195 self.panes.push(pane.clone());
4196
4197 window.focus(&pane.focus_handle(cx), cx);
4198
4199 cx.emit(Event::PaneAdded(pane.clone()));
4200 pane
4201 }
4202
4203 pub fn add_item_to_center(
4204 &mut self,
4205 item: Box<dyn ItemHandle>,
4206 window: &mut Window,
4207 cx: &mut Context<Self>,
4208 ) -> bool {
4209 if let Some(center_pane) = self.last_active_center_pane.clone() {
4210 if let Some(center_pane) = center_pane.upgrade() {
4211 center_pane.update(cx, |pane, cx| {
4212 pane.add_item(item, true, true, None, window, cx)
4213 });
4214 true
4215 } else {
4216 false
4217 }
4218 } else {
4219 false
4220 }
4221 }
4222
4223 pub fn add_item_to_active_pane(
4224 &mut self,
4225 item: Box<dyn ItemHandle>,
4226 destination_index: Option<usize>,
4227 focus_item: bool,
4228 window: &mut Window,
4229 cx: &mut App,
4230 ) {
4231 self.add_item(
4232 self.active_pane.clone(),
4233 item,
4234 destination_index,
4235 false,
4236 focus_item,
4237 window,
4238 cx,
4239 )
4240 }
4241
4242 pub fn add_item(
4243 &mut self,
4244 pane: Entity<Pane>,
4245 item: Box<dyn ItemHandle>,
4246 destination_index: Option<usize>,
4247 activate_pane: bool,
4248 focus_item: bool,
4249 window: &mut Window,
4250 cx: &mut App,
4251 ) {
4252 pane.update(cx, |pane, cx| {
4253 pane.add_item(
4254 item,
4255 activate_pane,
4256 focus_item,
4257 destination_index,
4258 window,
4259 cx,
4260 )
4261 });
4262 }
4263
4264 pub fn split_item(
4265 &mut self,
4266 split_direction: SplitDirection,
4267 item: Box<dyn ItemHandle>,
4268 window: &mut Window,
4269 cx: &mut Context<Self>,
4270 ) {
4271 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4272 self.add_item(new_pane, item, None, true, true, window, cx);
4273 }
4274
4275 pub fn open_abs_path(
4276 &mut self,
4277 abs_path: PathBuf,
4278 options: OpenOptions,
4279 window: &mut Window,
4280 cx: &mut Context<Self>,
4281 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4282 cx.spawn_in(window, async move |workspace, cx| {
4283 let open_paths_task_result = workspace
4284 .update_in(cx, |workspace, window, cx| {
4285 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4286 })
4287 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4288 .await;
4289 anyhow::ensure!(
4290 open_paths_task_result.len() == 1,
4291 "open abs path {abs_path:?} task returned incorrect number of results"
4292 );
4293 match open_paths_task_result
4294 .into_iter()
4295 .next()
4296 .expect("ensured single task result")
4297 {
4298 Some(open_result) => {
4299 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4300 }
4301 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4302 }
4303 })
4304 }
4305
4306 pub fn split_abs_path(
4307 &mut self,
4308 abs_path: PathBuf,
4309 visible: bool,
4310 window: &mut Window,
4311 cx: &mut Context<Self>,
4312 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4313 let project_path_task =
4314 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4315 cx.spawn_in(window, async move |this, cx| {
4316 let (_, path) = project_path_task.await?;
4317 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4318 .await
4319 })
4320 }
4321
4322 pub fn open_path(
4323 &mut self,
4324 path: impl Into<ProjectPath>,
4325 pane: Option<WeakEntity<Pane>>,
4326 focus_item: bool,
4327 window: &mut Window,
4328 cx: &mut App,
4329 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4330 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4331 }
4332
4333 pub fn open_path_preview(
4334 &mut self,
4335 path: impl Into<ProjectPath>,
4336 pane: Option<WeakEntity<Pane>>,
4337 focus_item: bool,
4338 allow_preview: bool,
4339 activate: bool,
4340 window: &mut Window,
4341 cx: &mut App,
4342 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4343 let pane = pane.unwrap_or_else(|| {
4344 self.last_active_center_pane.clone().unwrap_or_else(|| {
4345 self.panes
4346 .first()
4347 .expect("There must be an active pane")
4348 .downgrade()
4349 })
4350 });
4351
4352 let project_path = path.into();
4353 let task = self.load_path(project_path.clone(), window, cx);
4354 window.spawn(cx, async move |cx| {
4355 let (project_entry_id, build_item) = task.await?;
4356
4357 pane.update_in(cx, |pane, window, cx| {
4358 pane.open_item(
4359 project_entry_id,
4360 project_path,
4361 focus_item,
4362 allow_preview,
4363 activate,
4364 None,
4365 window,
4366 cx,
4367 build_item,
4368 )
4369 })
4370 })
4371 }
4372
4373 pub fn split_path(
4374 &mut self,
4375 path: impl Into<ProjectPath>,
4376 window: &mut Window,
4377 cx: &mut Context<Self>,
4378 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4379 self.split_path_preview(path, false, None, window, cx)
4380 }
4381
4382 pub fn split_path_preview(
4383 &mut self,
4384 path: impl Into<ProjectPath>,
4385 allow_preview: bool,
4386 split_direction: Option<SplitDirection>,
4387 window: &mut Window,
4388 cx: &mut Context<Self>,
4389 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4390 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4391 self.panes
4392 .first()
4393 .expect("There must be an active pane")
4394 .downgrade()
4395 });
4396
4397 if let Member::Pane(center_pane) = &self.center.root
4398 && center_pane.read(cx).items_len() == 0
4399 {
4400 return self.open_path(path, Some(pane), true, window, cx);
4401 }
4402
4403 let project_path = path.into();
4404 let task = self.load_path(project_path.clone(), window, cx);
4405 cx.spawn_in(window, async move |this, cx| {
4406 let (project_entry_id, build_item) = task.await?;
4407 this.update_in(cx, move |this, window, cx| -> Option<_> {
4408 let pane = pane.upgrade()?;
4409 let new_pane = this.split_pane(
4410 pane,
4411 split_direction.unwrap_or(SplitDirection::Right),
4412 window,
4413 cx,
4414 );
4415 new_pane.update(cx, |new_pane, cx| {
4416 Some(new_pane.open_item(
4417 project_entry_id,
4418 project_path,
4419 true,
4420 allow_preview,
4421 true,
4422 None,
4423 window,
4424 cx,
4425 build_item,
4426 ))
4427 })
4428 })
4429 .map(|option| option.context("pane was dropped"))?
4430 })
4431 }
4432
4433 fn load_path(
4434 &mut self,
4435 path: ProjectPath,
4436 window: &mut Window,
4437 cx: &mut App,
4438 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4439 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4440 registry.open_path(self.project(), &path, window, cx)
4441 }
4442
4443 pub fn find_project_item<T>(
4444 &self,
4445 pane: &Entity<Pane>,
4446 project_item: &Entity<T::Item>,
4447 cx: &App,
4448 ) -> Option<Entity<T>>
4449 where
4450 T: ProjectItem,
4451 {
4452 use project::ProjectItem as _;
4453 let project_item = project_item.read(cx);
4454 let entry_id = project_item.entry_id(cx);
4455 let project_path = project_item.project_path(cx);
4456
4457 let mut item = None;
4458 if let Some(entry_id) = entry_id {
4459 item = pane.read(cx).item_for_entry(entry_id, cx);
4460 }
4461 if item.is_none()
4462 && let Some(project_path) = project_path
4463 {
4464 item = pane.read(cx).item_for_path(project_path, cx);
4465 }
4466
4467 item.and_then(|item| item.downcast::<T>())
4468 }
4469
4470 pub fn is_project_item_open<T>(
4471 &self,
4472 pane: &Entity<Pane>,
4473 project_item: &Entity<T::Item>,
4474 cx: &App,
4475 ) -> bool
4476 where
4477 T: ProjectItem,
4478 {
4479 self.find_project_item::<T>(pane, project_item, cx)
4480 .is_some()
4481 }
4482
4483 pub fn open_project_item<T>(
4484 &mut self,
4485 pane: Entity<Pane>,
4486 project_item: Entity<T::Item>,
4487 activate_pane: bool,
4488 focus_item: bool,
4489 keep_old_preview: bool,
4490 allow_new_preview: bool,
4491 window: &mut Window,
4492 cx: &mut Context<Self>,
4493 ) -> Entity<T>
4494 where
4495 T: ProjectItem,
4496 {
4497 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4498
4499 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4500 if !keep_old_preview
4501 && let Some(old_id) = old_item_id
4502 && old_id != item.item_id()
4503 {
4504 // switching to a different item, so unpreview old active item
4505 pane.update(cx, |pane, _| {
4506 pane.unpreview_item_if_preview(old_id);
4507 });
4508 }
4509
4510 self.activate_item(&item, activate_pane, focus_item, window, cx);
4511 if !allow_new_preview {
4512 pane.update(cx, |pane, _| {
4513 pane.unpreview_item_if_preview(item.item_id());
4514 });
4515 }
4516 return item;
4517 }
4518
4519 let item = pane.update(cx, |pane, cx| {
4520 cx.new(|cx| {
4521 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4522 })
4523 });
4524 let mut destination_index = None;
4525 pane.update(cx, |pane, cx| {
4526 if !keep_old_preview && let Some(old_id) = old_item_id {
4527 pane.unpreview_item_if_preview(old_id);
4528 }
4529 if allow_new_preview {
4530 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4531 }
4532 });
4533
4534 self.add_item(
4535 pane,
4536 Box::new(item.clone()),
4537 destination_index,
4538 activate_pane,
4539 focus_item,
4540 window,
4541 cx,
4542 );
4543 item
4544 }
4545
4546 pub fn open_shared_screen(
4547 &mut self,
4548 peer_id: PeerId,
4549 window: &mut Window,
4550 cx: &mut Context<Self>,
4551 ) {
4552 if let Some(shared_screen) =
4553 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4554 {
4555 self.active_pane.update(cx, |pane, cx| {
4556 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4557 });
4558 }
4559 }
4560
4561 pub fn activate_item(
4562 &mut self,
4563 item: &dyn ItemHandle,
4564 activate_pane: bool,
4565 focus_item: bool,
4566 window: &mut Window,
4567 cx: &mut App,
4568 ) -> bool {
4569 let result = self.panes.iter().find_map(|pane| {
4570 pane.read(cx)
4571 .index_for_item(item)
4572 .map(|ix| (pane.clone(), ix))
4573 });
4574 if let Some((pane, ix)) = result {
4575 pane.update(cx, |pane, cx| {
4576 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4577 });
4578 true
4579 } else {
4580 false
4581 }
4582 }
4583
4584 fn activate_pane_at_index(
4585 &mut self,
4586 action: &ActivatePane,
4587 window: &mut Window,
4588 cx: &mut Context<Self>,
4589 ) {
4590 let panes = self.center.panes();
4591 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4592 window.focus(&pane.focus_handle(cx), cx);
4593 } else {
4594 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4595 .detach();
4596 }
4597 }
4598
4599 fn move_item_to_pane_at_index(
4600 &mut self,
4601 action: &MoveItemToPane,
4602 window: &mut Window,
4603 cx: &mut Context<Self>,
4604 ) {
4605 let panes = self.center.panes();
4606 let destination = match panes.get(action.destination) {
4607 Some(&destination) => destination.clone(),
4608 None => {
4609 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4610 return;
4611 }
4612 let direction = SplitDirection::Right;
4613 let split_off_pane = self
4614 .find_pane_in_direction(direction, cx)
4615 .unwrap_or_else(|| self.active_pane.clone());
4616 let new_pane = self.add_pane(window, cx);
4617 self.center.split(&split_off_pane, &new_pane, direction, cx);
4618 new_pane
4619 }
4620 };
4621
4622 if action.clone {
4623 if self
4624 .active_pane
4625 .read(cx)
4626 .active_item()
4627 .is_some_and(|item| item.can_split(cx))
4628 {
4629 clone_active_item(
4630 self.database_id(),
4631 &self.active_pane,
4632 &destination,
4633 action.focus,
4634 window,
4635 cx,
4636 );
4637 return;
4638 }
4639 }
4640 move_active_item(
4641 &self.active_pane,
4642 &destination,
4643 action.focus,
4644 true,
4645 window,
4646 cx,
4647 )
4648 }
4649
4650 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4651 let panes = self.center.panes();
4652 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4653 let next_ix = (ix + 1) % panes.len();
4654 let next_pane = panes[next_ix].clone();
4655 window.focus(&next_pane.focus_handle(cx), cx);
4656 }
4657 }
4658
4659 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4660 let panes = self.center.panes();
4661 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4662 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4663 let prev_pane = panes[prev_ix].clone();
4664 window.focus(&prev_pane.focus_handle(cx), cx);
4665 }
4666 }
4667
4668 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4669 let last_pane = self.center.last_pane();
4670 window.focus(&last_pane.focus_handle(cx), cx);
4671 }
4672
4673 pub fn activate_pane_in_direction(
4674 &mut self,
4675 direction: SplitDirection,
4676 window: &mut Window,
4677 cx: &mut App,
4678 ) {
4679 use ActivateInDirectionTarget as Target;
4680 enum Origin {
4681 Sidebar,
4682 LeftDock,
4683 RightDock,
4684 BottomDock,
4685 Center,
4686 }
4687
4688 let origin: Origin = if self
4689 .sidebar_focus_handle
4690 .as_ref()
4691 .is_some_and(|h| h.contains_focused(window, cx))
4692 {
4693 Origin::Sidebar
4694 } else {
4695 [
4696 (&self.left_dock, Origin::LeftDock),
4697 (&self.right_dock, Origin::RightDock),
4698 (&self.bottom_dock, Origin::BottomDock),
4699 ]
4700 .into_iter()
4701 .find_map(|(dock, origin)| {
4702 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4703 Some(origin)
4704 } else {
4705 None
4706 }
4707 })
4708 .unwrap_or(Origin::Center)
4709 };
4710
4711 let get_last_active_pane = || {
4712 let pane = self
4713 .last_active_center_pane
4714 .clone()
4715 .unwrap_or_else(|| {
4716 self.panes
4717 .first()
4718 .expect("There must be an active pane")
4719 .downgrade()
4720 })
4721 .upgrade()?;
4722 (pane.read(cx).items_len() != 0).then_some(pane)
4723 };
4724
4725 let try_dock =
4726 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4727
4728 let sidebar_target = self
4729 .sidebar_focus_handle
4730 .as_ref()
4731 .map(|h| Target::Sidebar(h.clone()));
4732
4733 let target = match (origin, direction) {
4734 // From the sidebar, only Right navigates into the workspace.
4735 (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
4736 .or_else(|| get_last_active_pane().map(Target::Pane))
4737 .or_else(|| try_dock(&self.bottom_dock))
4738 .or_else(|| try_dock(&self.right_dock)),
4739
4740 (Origin::Sidebar, _) => None,
4741
4742 // We're in the center, so we first try to go to a different pane,
4743 // otherwise try to go to a dock.
4744 (Origin::Center, direction) => {
4745 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4746 Some(Target::Pane(pane))
4747 } else {
4748 match direction {
4749 SplitDirection::Up => None,
4750 SplitDirection::Down => try_dock(&self.bottom_dock),
4751 SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
4752 SplitDirection::Right => try_dock(&self.right_dock),
4753 }
4754 }
4755 }
4756
4757 (Origin::LeftDock, SplitDirection::Right) => {
4758 if let Some(last_active_pane) = get_last_active_pane() {
4759 Some(Target::Pane(last_active_pane))
4760 } else {
4761 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4762 }
4763 }
4764
4765 (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
4766
4767 (Origin::LeftDock, SplitDirection::Down)
4768 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4769
4770 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4771 (Origin::BottomDock, SplitDirection::Left) => {
4772 try_dock(&self.left_dock).or(sidebar_target)
4773 }
4774 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4775
4776 (Origin::RightDock, SplitDirection::Left) => {
4777 if let Some(last_active_pane) = get_last_active_pane() {
4778 Some(Target::Pane(last_active_pane))
4779 } else {
4780 try_dock(&self.bottom_dock)
4781 .or_else(|| try_dock(&self.left_dock))
4782 .or(sidebar_target)
4783 }
4784 }
4785
4786 _ => None,
4787 };
4788
4789 match target {
4790 Some(ActivateInDirectionTarget::Pane(pane)) => {
4791 let pane = pane.read(cx);
4792 if let Some(item) = pane.active_item() {
4793 item.item_focus_handle(cx).focus(window, cx);
4794 } else {
4795 log::error!(
4796 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4797 );
4798 }
4799 }
4800 Some(ActivateInDirectionTarget::Dock(dock)) => {
4801 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4802 window.defer(cx, move |window, cx| {
4803 let dock = dock.read(cx);
4804 if let Some(panel) = dock.active_panel() {
4805 panel.panel_focus_handle(cx).focus(window, cx);
4806 } else {
4807 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4808 }
4809 })
4810 }
4811 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4812 focus_handle.focus(window, cx);
4813 }
4814 None => {}
4815 }
4816 }
4817
4818 pub fn move_item_to_pane_in_direction(
4819 &mut self,
4820 action: &MoveItemToPaneInDirection,
4821 window: &mut Window,
4822 cx: &mut Context<Self>,
4823 ) {
4824 let destination = match self.find_pane_in_direction(action.direction, cx) {
4825 Some(destination) => destination,
4826 None => {
4827 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4828 return;
4829 }
4830 let new_pane = self.add_pane(window, cx);
4831 self.center
4832 .split(&self.active_pane, &new_pane, action.direction, cx);
4833 new_pane
4834 }
4835 };
4836
4837 if action.clone {
4838 if self
4839 .active_pane
4840 .read(cx)
4841 .active_item()
4842 .is_some_and(|item| item.can_split(cx))
4843 {
4844 clone_active_item(
4845 self.database_id(),
4846 &self.active_pane,
4847 &destination,
4848 action.focus,
4849 window,
4850 cx,
4851 );
4852 return;
4853 }
4854 }
4855 move_active_item(
4856 &self.active_pane,
4857 &destination,
4858 action.focus,
4859 true,
4860 window,
4861 cx,
4862 );
4863 }
4864
4865 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4866 self.center.bounding_box_for_pane(pane)
4867 }
4868
4869 pub fn find_pane_in_direction(
4870 &mut self,
4871 direction: SplitDirection,
4872 cx: &App,
4873 ) -> Option<Entity<Pane>> {
4874 self.center
4875 .find_pane_in_direction(&self.active_pane, direction, cx)
4876 .cloned()
4877 }
4878
4879 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4880 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4881 self.center.swap(&self.active_pane, &to, cx);
4882 cx.notify();
4883 }
4884 }
4885
4886 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4887 if self
4888 .center
4889 .move_to_border(&self.active_pane, direction, cx)
4890 .unwrap()
4891 {
4892 cx.notify();
4893 }
4894 }
4895
4896 pub fn resize_pane(
4897 &mut self,
4898 axis: gpui::Axis,
4899 amount: Pixels,
4900 window: &mut Window,
4901 cx: &mut Context<Self>,
4902 ) {
4903 let docks = self.all_docks();
4904 let active_dock = docks
4905 .into_iter()
4906 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4907
4908 if let Some(dock_entity) = active_dock {
4909 let dock = dock_entity.read(cx);
4910 let Some(panel_size) = self.dock_size(&dock, window, cx) else {
4911 return;
4912 };
4913 match dock.position() {
4914 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4915 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4916 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4917 }
4918 } else {
4919 self.center
4920 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4921 }
4922 cx.notify();
4923 }
4924
4925 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4926 self.center.reset_pane_sizes(cx);
4927 cx.notify();
4928 }
4929
4930 fn handle_pane_focused(
4931 &mut self,
4932 pane: Entity<Pane>,
4933 window: &mut Window,
4934 cx: &mut Context<Self>,
4935 ) {
4936 // This is explicitly hoisted out of the following check for pane identity as
4937 // terminal panel panes are not registered as a center panes.
4938 self.status_bar.update(cx, |status_bar, cx| {
4939 status_bar.set_active_pane(&pane, window, cx);
4940 });
4941 if self.active_pane != pane {
4942 self.set_active_pane(&pane, window, cx);
4943 }
4944
4945 if self.last_active_center_pane.is_none() {
4946 self.last_active_center_pane = Some(pane.downgrade());
4947 }
4948
4949 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
4950 // This prevents the dock from closing when focus events fire during window activation.
4951 // We also preserve any dock whose active panel itself has focus — this covers
4952 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
4953 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
4954 let dock_read = dock.read(cx);
4955 if let Some(panel) = dock_read.active_panel() {
4956 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
4957 || panel.panel_focus_handle(cx).contains_focused(window, cx)
4958 {
4959 return Some(dock_read.position());
4960 }
4961 }
4962 None
4963 });
4964
4965 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
4966 if pane.read(cx).is_zoomed() {
4967 self.zoomed = Some(pane.downgrade().into());
4968 } else {
4969 self.zoomed = None;
4970 }
4971 self.zoomed_position = None;
4972 cx.emit(Event::ZoomChanged);
4973 self.update_active_view_for_followers(window, cx);
4974 pane.update(cx, |pane, _| {
4975 pane.track_alternate_file_items();
4976 });
4977
4978 cx.notify();
4979 }
4980
4981 fn set_active_pane(
4982 &mut self,
4983 pane: &Entity<Pane>,
4984 window: &mut Window,
4985 cx: &mut Context<Self>,
4986 ) {
4987 self.active_pane = pane.clone();
4988 self.active_item_path_changed(true, window, cx);
4989 self.last_active_center_pane = Some(pane.downgrade());
4990 }
4991
4992 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4993 self.update_active_view_for_followers(window, cx);
4994 }
4995
4996 fn handle_pane_event(
4997 &mut self,
4998 pane: &Entity<Pane>,
4999 event: &pane::Event,
5000 window: &mut Window,
5001 cx: &mut Context<Self>,
5002 ) {
5003 let mut serialize_workspace = true;
5004 match event {
5005 pane::Event::AddItem { item } => {
5006 item.added_to_pane(self, pane.clone(), window, cx);
5007 cx.emit(Event::ItemAdded {
5008 item: item.boxed_clone(),
5009 });
5010 }
5011 pane::Event::Split { direction, mode } => {
5012 match mode {
5013 SplitMode::ClonePane => {
5014 self.split_and_clone(pane.clone(), *direction, window, cx)
5015 .detach();
5016 }
5017 SplitMode::EmptyPane => {
5018 self.split_pane(pane.clone(), *direction, window, cx);
5019 }
5020 SplitMode::MovePane => {
5021 self.split_and_move(pane.clone(), *direction, window, cx);
5022 }
5023 };
5024 }
5025 pane::Event::JoinIntoNext => {
5026 self.join_pane_into_next(pane.clone(), window, cx);
5027 }
5028 pane::Event::JoinAll => {
5029 self.join_all_panes(window, cx);
5030 }
5031 pane::Event::Remove { focus_on_pane } => {
5032 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
5033 }
5034 pane::Event::ActivateItem {
5035 local,
5036 focus_changed,
5037 } => {
5038 window.invalidate_character_coordinates();
5039
5040 pane.update(cx, |pane, _| {
5041 pane.track_alternate_file_items();
5042 });
5043 if *local {
5044 self.unfollow_in_pane(pane, window, cx);
5045 }
5046 serialize_workspace = *focus_changed || pane != self.active_pane();
5047 if pane == self.active_pane() {
5048 self.active_item_path_changed(*focus_changed, window, cx);
5049 self.update_active_view_for_followers(window, cx);
5050 } else if *local {
5051 self.set_active_pane(pane, window, cx);
5052 }
5053 }
5054 pane::Event::UserSavedItem { item, save_intent } => {
5055 cx.emit(Event::UserSavedItem {
5056 pane: pane.downgrade(),
5057 item: item.boxed_clone(),
5058 save_intent: *save_intent,
5059 });
5060 serialize_workspace = false;
5061 }
5062 pane::Event::ChangeItemTitle => {
5063 if *pane == self.active_pane {
5064 self.active_item_path_changed(false, window, cx);
5065 }
5066 serialize_workspace = false;
5067 }
5068 pane::Event::RemovedItem { item } => {
5069 cx.emit(Event::ActiveItemChanged);
5070 self.update_window_edited(window, cx);
5071 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
5072 && entry.get().entity_id() == pane.entity_id()
5073 {
5074 entry.remove();
5075 }
5076 cx.emit(Event::ItemRemoved {
5077 item_id: item.item_id(),
5078 });
5079 }
5080 pane::Event::Focus => {
5081 window.invalidate_character_coordinates();
5082 self.handle_pane_focused(pane.clone(), window, cx);
5083 }
5084 pane::Event::ZoomIn => {
5085 if *pane == self.active_pane {
5086 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
5087 if pane.read(cx).has_focus(window, cx) {
5088 self.zoomed = Some(pane.downgrade().into());
5089 self.zoomed_position = None;
5090 cx.emit(Event::ZoomChanged);
5091 }
5092 cx.notify();
5093 }
5094 }
5095 pane::Event::ZoomOut => {
5096 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
5097 if self.zoomed_position.is_none() {
5098 self.zoomed = None;
5099 cx.emit(Event::ZoomChanged);
5100 }
5101 cx.notify();
5102 }
5103 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
5104 }
5105
5106 if serialize_workspace {
5107 self.serialize_workspace(window, cx);
5108 }
5109 }
5110
5111 pub fn unfollow_in_pane(
5112 &mut self,
5113 pane: &Entity<Pane>,
5114 window: &mut Window,
5115 cx: &mut Context<Workspace>,
5116 ) -> Option<CollaboratorId> {
5117 let leader_id = self.leader_for_pane(pane)?;
5118 self.unfollow(leader_id, window, cx);
5119 Some(leader_id)
5120 }
5121
5122 pub fn split_pane(
5123 &mut self,
5124 pane_to_split: Entity<Pane>,
5125 split_direction: SplitDirection,
5126 window: &mut Window,
5127 cx: &mut Context<Self>,
5128 ) -> Entity<Pane> {
5129 let new_pane = self.add_pane(window, cx);
5130 self.center
5131 .split(&pane_to_split, &new_pane, split_direction, cx);
5132 cx.notify();
5133 new_pane
5134 }
5135
5136 pub fn split_and_move(
5137 &mut self,
5138 pane: Entity<Pane>,
5139 direction: SplitDirection,
5140 window: &mut Window,
5141 cx: &mut Context<Self>,
5142 ) {
5143 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
5144 return;
5145 };
5146 let new_pane = self.add_pane(window, cx);
5147 new_pane.update(cx, |pane, cx| {
5148 pane.add_item(item, true, true, None, window, cx)
5149 });
5150 self.center.split(&pane, &new_pane, direction, cx);
5151 cx.notify();
5152 }
5153
5154 pub fn split_and_clone(
5155 &mut self,
5156 pane: Entity<Pane>,
5157 direction: SplitDirection,
5158 window: &mut Window,
5159 cx: &mut Context<Self>,
5160 ) -> Task<Option<Entity<Pane>>> {
5161 let Some(item) = pane.read(cx).active_item() else {
5162 return Task::ready(None);
5163 };
5164 if !item.can_split(cx) {
5165 return Task::ready(None);
5166 }
5167 let task = item.clone_on_split(self.database_id(), window, cx);
5168 cx.spawn_in(window, async move |this, cx| {
5169 if let Some(clone) = task.await {
5170 this.update_in(cx, |this, window, cx| {
5171 let new_pane = this.add_pane(window, cx);
5172 let nav_history = pane.read(cx).fork_nav_history();
5173 new_pane.update(cx, |pane, cx| {
5174 pane.set_nav_history(nav_history, cx);
5175 pane.add_item(clone, true, true, None, window, cx)
5176 });
5177 this.center.split(&pane, &new_pane, direction, cx);
5178 cx.notify();
5179 new_pane
5180 })
5181 .ok()
5182 } else {
5183 None
5184 }
5185 })
5186 }
5187
5188 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5189 let active_item = self.active_pane.read(cx).active_item();
5190 for pane in &self.panes {
5191 join_pane_into_active(&self.active_pane, pane, window, cx);
5192 }
5193 if let Some(active_item) = active_item {
5194 self.activate_item(active_item.as_ref(), true, true, window, cx);
5195 }
5196 cx.notify();
5197 }
5198
5199 pub fn join_pane_into_next(
5200 &mut self,
5201 pane: Entity<Pane>,
5202 window: &mut Window,
5203 cx: &mut Context<Self>,
5204 ) {
5205 let next_pane = self
5206 .find_pane_in_direction(SplitDirection::Right, cx)
5207 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5208 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5209 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5210 let Some(next_pane) = next_pane else {
5211 return;
5212 };
5213 move_all_items(&pane, &next_pane, window, cx);
5214 cx.notify();
5215 }
5216
5217 fn remove_pane(
5218 &mut self,
5219 pane: Entity<Pane>,
5220 focus_on: Option<Entity<Pane>>,
5221 window: &mut Window,
5222 cx: &mut Context<Self>,
5223 ) {
5224 if self.center.remove(&pane, cx).unwrap() {
5225 self.force_remove_pane(&pane, &focus_on, window, cx);
5226 self.unfollow_in_pane(&pane, window, cx);
5227 self.last_leaders_by_pane.remove(&pane.downgrade());
5228 for removed_item in pane.read(cx).items() {
5229 self.panes_by_item.remove(&removed_item.item_id());
5230 }
5231
5232 cx.notify();
5233 } else {
5234 self.active_item_path_changed(true, window, cx);
5235 }
5236 cx.emit(Event::PaneRemoved);
5237 }
5238
5239 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5240 &mut self.panes
5241 }
5242
5243 pub fn panes(&self) -> &[Entity<Pane>] {
5244 &self.panes
5245 }
5246
5247 pub fn active_pane(&self) -> &Entity<Pane> {
5248 &self.active_pane
5249 }
5250
5251 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5252 for dock in self.all_docks() {
5253 if dock.focus_handle(cx).contains_focused(window, cx)
5254 && let Some(pane) = dock
5255 .read(cx)
5256 .active_panel()
5257 .and_then(|panel| panel.pane(cx))
5258 {
5259 return pane;
5260 }
5261 }
5262 self.active_pane().clone()
5263 }
5264
5265 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5266 self.find_pane_in_direction(SplitDirection::Right, cx)
5267 .unwrap_or_else(|| {
5268 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5269 })
5270 }
5271
5272 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5273 self.pane_for_item_id(handle.item_id())
5274 }
5275
5276 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5277 let weak_pane = self.panes_by_item.get(&item_id)?;
5278 weak_pane.upgrade()
5279 }
5280
5281 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5282 self.panes
5283 .iter()
5284 .find(|pane| pane.entity_id() == entity_id)
5285 .cloned()
5286 }
5287
5288 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5289 self.follower_states.retain(|leader_id, state| {
5290 if *leader_id == CollaboratorId::PeerId(peer_id) {
5291 for item in state.items_by_leader_view_id.values() {
5292 item.view.set_leader_id(None, window, cx);
5293 }
5294 false
5295 } else {
5296 true
5297 }
5298 });
5299 cx.notify();
5300 }
5301
5302 pub fn start_following(
5303 &mut self,
5304 leader_id: impl Into<CollaboratorId>,
5305 window: &mut Window,
5306 cx: &mut Context<Self>,
5307 ) -> Option<Task<Result<()>>> {
5308 let leader_id = leader_id.into();
5309 let pane = self.active_pane().clone();
5310
5311 self.last_leaders_by_pane
5312 .insert(pane.downgrade(), leader_id);
5313 self.unfollow(leader_id, window, cx);
5314 self.unfollow_in_pane(&pane, window, cx);
5315 self.follower_states.insert(
5316 leader_id,
5317 FollowerState {
5318 center_pane: pane.clone(),
5319 dock_pane: None,
5320 active_view_id: None,
5321 items_by_leader_view_id: Default::default(),
5322 },
5323 );
5324 cx.notify();
5325
5326 match leader_id {
5327 CollaboratorId::PeerId(leader_peer_id) => {
5328 let room_id = self.active_call()?.room_id(cx)?;
5329 let project_id = self.project.read(cx).remote_id();
5330 let request = self.app_state.client.request(proto::Follow {
5331 room_id,
5332 project_id,
5333 leader_id: Some(leader_peer_id),
5334 });
5335
5336 Some(cx.spawn_in(window, async move |this, cx| {
5337 let response = request.await?;
5338 this.update(cx, |this, _| {
5339 let state = this
5340 .follower_states
5341 .get_mut(&leader_id)
5342 .context("following interrupted")?;
5343 state.active_view_id = response
5344 .active_view
5345 .as_ref()
5346 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5347 anyhow::Ok(())
5348 })??;
5349 if let Some(view) = response.active_view {
5350 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5351 }
5352 this.update_in(cx, |this, window, cx| {
5353 this.leader_updated(leader_id, window, cx)
5354 })?;
5355 Ok(())
5356 }))
5357 }
5358 CollaboratorId::Agent => {
5359 self.leader_updated(leader_id, window, cx)?;
5360 Some(Task::ready(Ok(())))
5361 }
5362 }
5363 }
5364
5365 pub fn follow_next_collaborator(
5366 &mut self,
5367 _: &FollowNextCollaborator,
5368 window: &mut Window,
5369 cx: &mut Context<Self>,
5370 ) {
5371 let collaborators = self.project.read(cx).collaborators();
5372 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5373 let mut collaborators = collaborators.keys().copied();
5374 for peer_id in collaborators.by_ref() {
5375 if CollaboratorId::PeerId(peer_id) == leader_id {
5376 break;
5377 }
5378 }
5379 collaborators.next().map(CollaboratorId::PeerId)
5380 } else if let Some(last_leader_id) =
5381 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5382 {
5383 match last_leader_id {
5384 CollaboratorId::PeerId(peer_id) => {
5385 if collaborators.contains_key(peer_id) {
5386 Some(*last_leader_id)
5387 } else {
5388 None
5389 }
5390 }
5391 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5392 }
5393 } else {
5394 None
5395 };
5396
5397 let pane = self.active_pane.clone();
5398 let Some(leader_id) = next_leader_id.or_else(|| {
5399 Some(CollaboratorId::PeerId(
5400 collaborators.keys().copied().next()?,
5401 ))
5402 }) else {
5403 return;
5404 };
5405 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5406 return;
5407 }
5408 if let Some(task) = self.start_following(leader_id, window, cx) {
5409 task.detach_and_log_err(cx)
5410 }
5411 }
5412
5413 pub fn follow(
5414 &mut self,
5415 leader_id: impl Into<CollaboratorId>,
5416 window: &mut Window,
5417 cx: &mut Context<Self>,
5418 ) {
5419 let leader_id = leader_id.into();
5420
5421 if let CollaboratorId::PeerId(peer_id) = leader_id {
5422 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5423 return;
5424 };
5425 let Some(remote_participant) =
5426 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5427 else {
5428 return;
5429 };
5430
5431 let project = self.project.read(cx);
5432
5433 let other_project_id = match remote_participant.location {
5434 ParticipantLocation::External => None,
5435 ParticipantLocation::UnsharedProject => None,
5436 ParticipantLocation::SharedProject { project_id } => {
5437 if Some(project_id) == project.remote_id() {
5438 None
5439 } else {
5440 Some(project_id)
5441 }
5442 }
5443 };
5444
5445 // if they are active in another project, follow there.
5446 if let Some(project_id) = other_project_id {
5447 let app_state = self.app_state.clone();
5448 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5449 .detach_and_log_err(cx);
5450 }
5451 }
5452
5453 // if you're already following, find the right pane and focus it.
5454 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5455 window.focus(&follower_state.pane().focus_handle(cx), cx);
5456
5457 return;
5458 }
5459
5460 // Otherwise, follow.
5461 if let Some(task) = self.start_following(leader_id, window, cx) {
5462 task.detach_and_log_err(cx)
5463 }
5464 }
5465
5466 pub fn unfollow(
5467 &mut self,
5468 leader_id: impl Into<CollaboratorId>,
5469 window: &mut Window,
5470 cx: &mut Context<Self>,
5471 ) -> Option<()> {
5472 cx.notify();
5473
5474 let leader_id = leader_id.into();
5475 let state = self.follower_states.remove(&leader_id)?;
5476 for (_, item) in state.items_by_leader_view_id {
5477 item.view.set_leader_id(None, window, cx);
5478 }
5479
5480 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5481 let project_id = self.project.read(cx).remote_id();
5482 let room_id = self.active_call()?.room_id(cx)?;
5483 self.app_state
5484 .client
5485 .send(proto::Unfollow {
5486 room_id,
5487 project_id,
5488 leader_id: Some(leader_peer_id),
5489 })
5490 .log_err();
5491 }
5492
5493 Some(())
5494 }
5495
5496 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5497 self.follower_states.contains_key(&id.into())
5498 }
5499
5500 fn active_item_path_changed(
5501 &mut self,
5502 focus_changed: bool,
5503 window: &mut Window,
5504 cx: &mut Context<Self>,
5505 ) {
5506 cx.emit(Event::ActiveItemChanged);
5507 let active_entry = self.active_project_path(cx);
5508 self.project.update(cx, |project, cx| {
5509 project.set_active_path(active_entry.clone(), cx)
5510 });
5511
5512 if focus_changed && let Some(project_path) = &active_entry {
5513 let git_store_entity = self.project.read(cx).git_store().clone();
5514 git_store_entity.update(cx, |git_store, cx| {
5515 git_store.set_active_repo_for_path(project_path, cx);
5516 });
5517 }
5518
5519 self.update_window_title(window, cx);
5520 }
5521
5522 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5523 let project = self.project().read(cx);
5524 let mut title = String::new();
5525
5526 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5527 let name = {
5528 let settings_location = SettingsLocation {
5529 worktree_id: worktree.read(cx).id(),
5530 path: RelPath::empty(),
5531 };
5532
5533 let settings = WorktreeSettings::get(Some(settings_location), cx);
5534 match &settings.project_name {
5535 Some(name) => name.as_str(),
5536 None => worktree.read(cx).root_name_str(),
5537 }
5538 };
5539 if i > 0 {
5540 title.push_str(", ");
5541 }
5542 title.push_str(name);
5543 }
5544
5545 if title.is_empty() {
5546 title = "empty project".to_string();
5547 }
5548
5549 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5550 let filename = path.path.file_name().or_else(|| {
5551 Some(
5552 project
5553 .worktree_for_id(path.worktree_id, cx)?
5554 .read(cx)
5555 .root_name_str(),
5556 )
5557 });
5558
5559 if let Some(filename) = filename {
5560 title.push_str(" — ");
5561 title.push_str(filename.as_ref());
5562 }
5563 }
5564
5565 if project.is_via_collab() {
5566 title.push_str(" ↙");
5567 } else if project.is_shared() {
5568 title.push_str(" ↗");
5569 }
5570
5571 if let Some(last_title) = self.last_window_title.as_ref()
5572 && &title == last_title
5573 {
5574 return;
5575 }
5576 window.set_window_title(&title);
5577 SystemWindowTabController::update_tab_title(
5578 cx,
5579 window.window_handle().window_id(),
5580 SharedString::from(&title),
5581 );
5582 self.last_window_title = Some(title);
5583 }
5584
5585 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5586 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5587 if is_edited != self.window_edited {
5588 self.window_edited = is_edited;
5589 window.set_window_edited(self.window_edited)
5590 }
5591 }
5592
5593 fn update_item_dirty_state(
5594 &mut self,
5595 item: &dyn ItemHandle,
5596 window: &mut Window,
5597 cx: &mut App,
5598 ) {
5599 let is_dirty = item.is_dirty(cx);
5600 let item_id = item.item_id();
5601 let was_dirty = self.dirty_items.contains_key(&item_id);
5602 if is_dirty == was_dirty {
5603 return;
5604 }
5605 if was_dirty {
5606 self.dirty_items.remove(&item_id);
5607 self.update_window_edited(window, cx);
5608 return;
5609 }
5610
5611 let workspace = self.weak_handle();
5612 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5613 return;
5614 };
5615 let on_release_callback = Box::new(move |cx: &mut App| {
5616 window_handle
5617 .update(cx, |_, window, cx| {
5618 workspace
5619 .update(cx, |workspace, cx| {
5620 workspace.dirty_items.remove(&item_id);
5621 workspace.update_window_edited(window, cx)
5622 })
5623 .ok();
5624 })
5625 .ok();
5626 });
5627
5628 let s = item.on_release(cx, on_release_callback);
5629 self.dirty_items.insert(item_id, s);
5630 self.update_window_edited(window, cx);
5631 }
5632
5633 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5634 if self.notifications.is_empty() {
5635 None
5636 } else {
5637 Some(
5638 div()
5639 .absolute()
5640 .right_3()
5641 .bottom_3()
5642 .w_112()
5643 .h_full()
5644 .flex()
5645 .flex_col()
5646 .justify_end()
5647 .gap_2()
5648 .children(
5649 self.notifications
5650 .iter()
5651 .map(|(_, notification)| notification.clone().into_any()),
5652 ),
5653 )
5654 }
5655 }
5656
5657 // RPC handlers
5658
5659 fn active_view_for_follower(
5660 &self,
5661 follower_project_id: Option<u64>,
5662 window: &mut Window,
5663 cx: &mut Context<Self>,
5664 ) -> Option<proto::View> {
5665 let (item, panel_id) = self.active_item_for_followers(window, cx);
5666 let item = item?;
5667 let leader_id = self
5668 .pane_for(&*item)
5669 .and_then(|pane| self.leader_for_pane(&pane));
5670 let leader_peer_id = match leader_id {
5671 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5672 Some(CollaboratorId::Agent) | None => None,
5673 };
5674
5675 let item_handle = item.to_followable_item_handle(cx)?;
5676 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5677 let variant = item_handle.to_state_proto(window, cx)?;
5678
5679 if item_handle.is_project_item(window, cx)
5680 && (follower_project_id.is_none()
5681 || follower_project_id != self.project.read(cx).remote_id())
5682 {
5683 return None;
5684 }
5685
5686 Some(proto::View {
5687 id: id.to_proto(),
5688 leader_id: leader_peer_id,
5689 variant: Some(variant),
5690 panel_id: panel_id.map(|id| id as i32),
5691 })
5692 }
5693
5694 fn handle_follow(
5695 &mut self,
5696 follower_project_id: Option<u64>,
5697 window: &mut Window,
5698 cx: &mut Context<Self>,
5699 ) -> proto::FollowResponse {
5700 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5701
5702 cx.notify();
5703 proto::FollowResponse {
5704 views: active_view.iter().cloned().collect(),
5705 active_view,
5706 }
5707 }
5708
5709 fn handle_update_followers(
5710 &mut self,
5711 leader_id: PeerId,
5712 message: proto::UpdateFollowers,
5713 _window: &mut Window,
5714 _cx: &mut Context<Self>,
5715 ) {
5716 self.leader_updates_tx
5717 .unbounded_send((leader_id, message))
5718 .ok();
5719 }
5720
5721 async fn process_leader_update(
5722 this: &WeakEntity<Self>,
5723 leader_id: PeerId,
5724 update: proto::UpdateFollowers,
5725 cx: &mut AsyncWindowContext,
5726 ) -> Result<()> {
5727 match update.variant.context("invalid update")? {
5728 proto::update_followers::Variant::CreateView(view) => {
5729 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5730 let should_add_view = this.update(cx, |this, _| {
5731 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5732 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5733 } else {
5734 anyhow::Ok(false)
5735 }
5736 })??;
5737
5738 if should_add_view {
5739 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5740 }
5741 }
5742 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5743 let should_add_view = this.update(cx, |this, _| {
5744 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5745 state.active_view_id = update_active_view
5746 .view
5747 .as_ref()
5748 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5749
5750 if state.active_view_id.is_some_and(|view_id| {
5751 !state.items_by_leader_view_id.contains_key(&view_id)
5752 }) {
5753 anyhow::Ok(true)
5754 } else {
5755 anyhow::Ok(false)
5756 }
5757 } else {
5758 anyhow::Ok(false)
5759 }
5760 })??;
5761
5762 if should_add_view && let Some(view) = update_active_view.view {
5763 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5764 }
5765 }
5766 proto::update_followers::Variant::UpdateView(update_view) => {
5767 let variant = update_view.variant.context("missing update view variant")?;
5768 let id = update_view.id.context("missing update view id")?;
5769 let mut tasks = Vec::new();
5770 this.update_in(cx, |this, window, cx| {
5771 let project = this.project.clone();
5772 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5773 let view_id = ViewId::from_proto(id.clone())?;
5774 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5775 tasks.push(item.view.apply_update_proto(
5776 &project,
5777 variant.clone(),
5778 window,
5779 cx,
5780 ));
5781 }
5782 }
5783 anyhow::Ok(())
5784 })??;
5785 try_join_all(tasks).await.log_err();
5786 }
5787 }
5788 this.update_in(cx, |this, window, cx| {
5789 this.leader_updated(leader_id, window, cx)
5790 })?;
5791 Ok(())
5792 }
5793
5794 async fn add_view_from_leader(
5795 this: WeakEntity<Self>,
5796 leader_id: PeerId,
5797 view: &proto::View,
5798 cx: &mut AsyncWindowContext,
5799 ) -> Result<()> {
5800 let this = this.upgrade().context("workspace dropped")?;
5801
5802 let Some(id) = view.id.clone() else {
5803 anyhow::bail!("no id for view");
5804 };
5805 let id = ViewId::from_proto(id)?;
5806 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5807
5808 let pane = this.update(cx, |this, _cx| {
5809 let state = this
5810 .follower_states
5811 .get(&leader_id.into())
5812 .context("stopped following")?;
5813 anyhow::Ok(state.pane().clone())
5814 })?;
5815 let existing_item = pane.update_in(cx, |pane, window, cx| {
5816 let client = this.read(cx).client().clone();
5817 pane.items().find_map(|item| {
5818 let item = item.to_followable_item_handle(cx)?;
5819 if item.remote_id(&client, window, cx) == Some(id) {
5820 Some(item)
5821 } else {
5822 None
5823 }
5824 })
5825 })?;
5826 let item = if let Some(existing_item) = existing_item {
5827 existing_item
5828 } else {
5829 let variant = view.variant.clone();
5830 anyhow::ensure!(variant.is_some(), "missing view variant");
5831
5832 let task = cx.update(|window, cx| {
5833 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5834 })?;
5835
5836 let Some(task) = task else {
5837 anyhow::bail!(
5838 "failed to construct view from leader (maybe from a different version of zed?)"
5839 );
5840 };
5841
5842 let mut new_item = task.await?;
5843 pane.update_in(cx, |pane, window, cx| {
5844 let mut item_to_remove = None;
5845 for (ix, item) in pane.items().enumerate() {
5846 if let Some(item) = item.to_followable_item_handle(cx) {
5847 match new_item.dedup(item.as_ref(), window, cx) {
5848 Some(item::Dedup::KeepExisting) => {
5849 new_item =
5850 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5851 break;
5852 }
5853 Some(item::Dedup::ReplaceExisting) => {
5854 item_to_remove = Some((ix, item.item_id()));
5855 break;
5856 }
5857 None => {}
5858 }
5859 }
5860 }
5861
5862 if let Some((ix, id)) = item_to_remove {
5863 pane.remove_item(id, false, false, window, cx);
5864 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5865 }
5866 })?;
5867
5868 new_item
5869 };
5870
5871 this.update_in(cx, |this, window, cx| {
5872 let state = this.follower_states.get_mut(&leader_id.into())?;
5873 item.set_leader_id(Some(leader_id.into()), window, cx);
5874 state.items_by_leader_view_id.insert(
5875 id,
5876 FollowerView {
5877 view: item,
5878 location: panel_id,
5879 },
5880 );
5881
5882 Some(())
5883 })
5884 .context("no follower state")?;
5885
5886 Ok(())
5887 }
5888
5889 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5890 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5891 return;
5892 };
5893
5894 if let Some(agent_location) = self.project.read(cx).agent_location() {
5895 let buffer_entity_id = agent_location.buffer.entity_id();
5896 let view_id = ViewId {
5897 creator: CollaboratorId::Agent,
5898 id: buffer_entity_id.as_u64(),
5899 };
5900 follower_state.active_view_id = Some(view_id);
5901
5902 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5903 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5904 hash_map::Entry::Vacant(entry) => {
5905 let existing_view =
5906 follower_state
5907 .center_pane
5908 .read(cx)
5909 .items()
5910 .find_map(|item| {
5911 let item = item.to_followable_item_handle(cx)?;
5912 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5913 && item.project_item_model_ids(cx).as_slice()
5914 == [buffer_entity_id]
5915 {
5916 Some(item)
5917 } else {
5918 None
5919 }
5920 });
5921 let view = existing_view.or_else(|| {
5922 agent_location.buffer.upgrade().and_then(|buffer| {
5923 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5924 registry.build_item(buffer, self.project.clone(), None, window, cx)
5925 })?
5926 .to_followable_item_handle(cx)
5927 })
5928 });
5929
5930 view.map(|view| {
5931 entry.insert(FollowerView {
5932 view,
5933 location: None,
5934 })
5935 })
5936 }
5937 };
5938
5939 if let Some(item) = item {
5940 item.view
5941 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5942 item.view
5943 .update_agent_location(agent_location.position, window, cx);
5944 }
5945 } else {
5946 follower_state.active_view_id = None;
5947 }
5948
5949 self.leader_updated(CollaboratorId::Agent, window, cx);
5950 }
5951
5952 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5953 let mut is_project_item = true;
5954 let mut update = proto::UpdateActiveView::default();
5955 if window.is_window_active() {
5956 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5957
5958 if let Some(item) = active_item
5959 && item.item_focus_handle(cx).contains_focused(window, cx)
5960 {
5961 let leader_id = self
5962 .pane_for(&*item)
5963 .and_then(|pane| self.leader_for_pane(&pane));
5964 let leader_peer_id = match leader_id {
5965 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5966 Some(CollaboratorId::Agent) | None => None,
5967 };
5968
5969 if let Some(item) = item.to_followable_item_handle(cx) {
5970 let id = item
5971 .remote_id(&self.app_state.client, window, cx)
5972 .map(|id| id.to_proto());
5973
5974 if let Some(id) = id
5975 && let Some(variant) = item.to_state_proto(window, cx)
5976 {
5977 let view = Some(proto::View {
5978 id,
5979 leader_id: leader_peer_id,
5980 variant: Some(variant),
5981 panel_id: panel_id.map(|id| id as i32),
5982 });
5983
5984 is_project_item = item.is_project_item(window, cx);
5985 update = proto::UpdateActiveView { view };
5986 };
5987 }
5988 }
5989 }
5990
5991 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5992 if active_view_id != self.last_active_view_id.as_ref() {
5993 self.last_active_view_id = active_view_id.cloned();
5994 self.update_followers(
5995 is_project_item,
5996 proto::update_followers::Variant::UpdateActiveView(update),
5997 window,
5998 cx,
5999 );
6000 }
6001 }
6002
6003 fn active_item_for_followers(
6004 &self,
6005 window: &mut Window,
6006 cx: &mut App,
6007 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
6008 let mut active_item = None;
6009 let mut panel_id = None;
6010 for dock in self.all_docks() {
6011 if dock.focus_handle(cx).contains_focused(window, cx)
6012 && let Some(panel) = dock.read(cx).active_panel()
6013 && let Some(pane) = panel.pane(cx)
6014 && let Some(item) = pane.read(cx).active_item()
6015 {
6016 active_item = Some(item);
6017 panel_id = panel.remote_id();
6018 break;
6019 }
6020 }
6021
6022 if active_item.is_none() {
6023 active_item = self.active_pane().read(cx).active_item();
6024 }
6025 (active_item, panel_id)
6026 }
6027
6028 fn update_followers(
6029 &self,
6030 project_only: bool,
6031 update: proto::update_followers::Variant,
6032 _: &mut Window,
6033 cx: &mut App,
6034 ) -> Option<()> {
6035 // If this update only applies to for followers in the current project,
6036 // then skip it unless this project is shared. If it applies to all
6037 // followers, regardless of project, then set `project_id` to none,
6038 // indicating that it goes to all followers.
6039 let project_id = if project_only {
6040 Some(self.project.read(cx).remote_id()?)
6041 } else {
6042 None
6043 };
6044 self.app_state().workspace_store.update(cx, |store, cx| {
6045 store.update_followers(project_id, update, cx)
6046 })
6047 }
6048
6049 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
6050 self.follower_states.iter().find_map(|(leader_id, state)| {
6051 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
6052 Some(*leader_id)
6053 } else {
6054 None
6055 }
6056 })
6057 }
6058
6059 fn leader_updated(
6060 &mut self,
6061 leader_id: impl Into<CollaboratorId>,
6062 window: &mut Window,
6063 cx: &mut Context<Self>,
6064 ) -> Option<Box<dyn ItemHandle>> {
6065 cx.notify();
6066
6067 let leader_id = leader_id.into();
6068 let (panel_id, item) = match leader_id {
6069 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
6070 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
6071 };
6072
6073 let state = self.follower_states.get(&leader_id)?;
6074 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
6075 let pane;
6076 if let Some(panel_id) = panel_id {
6077 pane = self
6078 .activate_panel_for_proto_id(panel_id, window, cx)?
6079 .pane(cx)?;
6080 let state = self.follower_states.get_mut(&leader_id)?;
6081 state.dock_pane = Some(pane.clone());
6082 } else {
6083 pane = state.center_pane.clone();
6084 let state = self.follower_states.get_mut(&leader_id)?;
6085 if let Some(dock_pane) = state.dock_pane.take() {
6086 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
6087 }
6088 }
6089
6090 pane.update(cx, |pane, cx| {
6091 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
6092 if let Some(index) = pane.index_for_item(item.as_ref()) {
6093 pane.activate_item(index, false, false, window, cx);
6094 } else {
6095 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
6096 }
6097
6098 if focus_active_item {
6099 pane.focus_active_item(window, cx)
6100 }
6101 });
6102
6103 Some(item)
6104 }
6105
6106 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
6107 let state = self.follower_states.get(&CollaboratorId::Agent)?;
6108 let active_view_id = state.active_view_id?;
6109 Some(
6110 state
6111 .items_by_leader_view_id
6112 .get(&active_view_id)?
6113 .view
6114 .boxed_clone(),
6115 )
6116 }
6117
6118 fn active_item_for_peer(
6119 &self,
6120 peer_id: PeerId,
6121 window: &mut Window,
6122 cx: &mut Context<Self>,
6123 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
6124 let call = self.active_call()?;
6125 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
6126 let leader_in_this_app;
6127 let leader_in_this_project;
6128 match participant.location {
6129 ParticipantLocation::SharedProject { project_id } => {
6130 leader_in_this_app = true;
6131 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
6132 }
6133 ParticipantLocation::UnsharedProject => {
6134 leader_in_this_app = true;
6135 leader_in_this_project = false;
6136 }
6137 ParticipantLocation::External => {
6138 leader_in_this_app = false;
6139 leader_in_this_project = false;
6140 }
6141 };
6142 let state = self.follower_states.get(&peer_id.into())?;
6143 let mut item_to_activate = None;
6144 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
6145 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
6146 && (leader_in_this_project || !item.view.is_project_item(window, cx))
6147 {
6148 item_to_activate = Some((item.location, item.view.boxed_clone()));
6149 }
6150 } else if let Some(shared_screen) =
6151 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
6152 {
6153 item_to_activate = Some((None, Box::new(shared_screen)));
6154 }
6155 item_to_activate
6156 }
6157
6158 fn shared_screen_for_peer(
6159 &self,
6160 peer_id: PeerId,
6161 pane: &Entity<Pane>,
6162 window: &mut Window,
6163 cx: &mut App,
6164 ) -> Option<Entity<SharedScreen>> {
6165 self.active_call()?
6166 .create_shared_screen(peer_id, pane, window, cx)
6167 }
6168
6169 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6170 if window.is_window_active() {
6171 self.update_active_view_for_followers(window, cx);
6172
6173 if let Some(database_id) = self.database_id {
6174 let db = WorkspaceDb::global(cx);
6175 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6176 .detach();
6177 }
6178 } else {
6179 for pane in &self.panes {
6180 pane.update(cx, |pane, cx| {
6181 if let Some(item) = pane.active_item() {
6182 item.workspace_deactivated(window, cx);
6183 }
6184 for item in pane.items() {
6185 if matches!(
6186 item.workspace_settings(cx).autosave,
6187 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6188 ) {
6189 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6190 .detach_and_log_err(cx);
6191 }
6192 }
6193 });
6194 }
6195 }
6196 }
6197
6198 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6199 self.active_call.as_ref().map(|(call, _)| &*call.0)
6200 }
6201
6202 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6203 self.active_call.as_ref().map(|(call, _)| call.clone())
6204 }
6205
6206 fn on_active_call_event(
6207 &mut self,
6208 event: &ActiveCallEvent,
6209 window: &mut Window,
6210 cx: &mut Context<Self>,
6211 ) {
6212 match event {
6213 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6214 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6215 self.leader_updated(participant_id, window, cx);
6216 }
6217 }
6218 }
6219
6220 pub fn database_id(&self) -> Option<WorkspaceId> {
6221 self.database_id
6222 }
6223
6224 #[cfg(any(test, feature = "test-support"))]
6225 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6226 self.database_id = Some(id);
6227 }
6228
6229 pub fn session_id(&self) -> Option<String> {
6230 self.session_id.clone()
6231 }
6232
6233 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6234 let Some(display) = window.display(cx) else {
6235 return Task::ready(());
6236 };
6237 let Ok(display_uuid) = display.uuid() else {
6238 return Task::ready(());
6239 };
6240
6241 let window_bounds = window.inner_window_bounds();
6242 let database_id = self.database_id;
6243 let has_paths = !self.root_paths(cx).is_empty();
6244 let db = WorkspaceDb::global(cx);
6245 let kvp = db::kvp::KeyValueStore::global(cx);
6246
6247 cx.background_executor().spawn(async move {
6248 if !has_paths {
6249 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6250 .await
6251 .log_err();
6252 }
6253 if let Some(database_id) = database_id {
6254 db.set_window_open_status(
6255 database_id,
6256 SerializedWindowBounds(window_bounds),
6257 display_uuid,
6258 )
6259 .await
6260 .log_err();
6261 } else {
6262 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6263 .await
6264 .log_err();
6265 }
6266 })
6267 }
6268
6269 /// Bypass the 200ms serialization throttle and write workspace state to
6270 /// the DB immediately. Returns a task the caller can await to ensure the
6271 /// write completes. Used by the quit handler so the most recent state
6272 /// isn't lost to a pending throttle timer when the process exits.
6273 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6274 self._schedule_serialize_workspace.take();
6275 self._serialize_workspace_task.take();
6276 self.bounds_save_task_queued.take();
6277
6278 let bounds_task = self.save_window_bounds(window, cx);
6279 let serialize_task = self.serialize_workspace_internal(window, cx);
6280 cx.spawn(async move |_| {
6281 bounds_task.await;
6282 serialize_task.await;
6283 })
6284 }
6285
6286 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6287 let project = self.project().read(cx);
6288 project
6289 .visible_worktrees(cx)
6290 .map(|worktree| worktree.read(cx).abs_path())
6291 .collect::<Vec<_>>()
6292 }
6293
6294 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6295 match member {
6296 Member::Axis(PaneAxis { members, .. }) => {
6297 for child in members.iter() {
6298 self.remove_panes(child.clone(), window, cx)
6299 }
6300 }
6301 Member::Pane(pane) => {
6302 self.force_remove_pane(&pane, &None, window, cx);
6303 }
6304 }
6305 }
6306
6307 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6308 self.session_id.take();
6309 self.serialize_workspace_internal(window, cx)
6310 }
6311
6312 fn force_remove_pane(
6313 &mut self,
6314 pane: &Entity<Pane>,
6315 focus_on: &Option<Entity<Pane>>,
6316 window: &mut Window,
6317 cx: &mut Context<Workspace>,
6318 ) {
6319 self.panes.retain(|p| p != pane);
6320 if let Some(focus_on) = focus_on {
6321 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6322 } else if self.active_pane() == pane {
6323 self.panes
6324 .last()
6325 .unwrap()
6326 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6327 }
6328 if self.last_active_center_pane == Some(pane.downgrade()) {
6329 self.last_active_center_pane = None;
6330 }
6331 cx.notify();
6332 }
6333
6334 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6335 if self._schedule_serialize_workspace.is_none() {
6336 self._schedule_serialize_workspace =
6337 Some(cx.spawn_in(window, async move |this, cx| {
6338 cx.background_executor()
6339 .timer(SERIALIZATION_THROTTLE_TIME)
6340 .await;
6341 this.update_in(cx, |this, window, cx| {
6342 this._serialize_workspace_task =
6343 Some(this.serialize_workspace_internal(window, cx));
6344 this._schedule_serialize_workspace.take();
6345 })
6346 .log_err();
6347 }));
6348 }
6349 }
6350
6351 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6352 let Some(database_id) = self.database_id() else {
6353 return Task::ready(());
6354 };
6355
6356 fn serialize_pane_handle(
6357 pane_handle: &Entity<Pane>,
6358 window: &mut Window,
6359 cx: &mut App,
6360 ) -> SerializedPane {
6361 let (items, active, pinned_count) = {
6362 let pane = pane_handle.read(cx);
6363 let active_item_id = pane.active_item().map(|item| item.item_id());
6364 (
6365 pane.items()
6366 .filter_map(|handle| {
6367 let handle = handle.to_serializable_item_handle(cx)?;
6368
6369 Some(SerializedItem {
6370 kind: Arc::from(handle.serialized_item_kind()),
6371 item_id: handle.item_id().as_u64(),
6372 active: Some(handle.item_id()) == active_item_id,
6373 preview: pane.is_active_preview_item(handle.item_id()),
6374 })
6375 })
6376 .collect::<Vec<_>>(),
6377 pane.has_focus(window, cx),
6378 pane.pinned_count(),
6379 )
6380 };
6381
6382 SerializedPane::new(items, active, pinned_count)
6383 }
6384
6385 fn build_serialized_pane_group(
6386 pane_group: &Member,
6387 window: &mut Window,
6388 cx: &mut App,
6389 ) -> SerializedPaneGroup {
6390 match pane_group {
6391 Member::Axis(PaneAxis {
6392 axis,
6393 members,
6394 flexes,
6395 bounding_boxes: _,
6396 }) => SerializedPaneGroup::Group {
6397 axis: SerializedAxis(*axis),
6398 children: members
6399 .iter()
6400 .map(|member| build_serialized_pane_group(member, window, cx))
6401 .collect::<Vec<_>>(),
6402 flexes: Some(flexes.lock().clone()),
6403 },
6404 Member::Pane(pane_handle) => {
6405 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6406 }
6407 }
6408 }
6409
6410 fn build_serialized_docks(
6411 this: &Workspace,
6412 window: &mut Window,
6413 cx: &mut App,
6414 ) -> DockStructure {
6415 this.capture_dock_state(window, cx)
6416 }
6417
6418 match self.workspace_location(cx) {
6419 WorkspaceLocation::Location(location, paths) => {
6420 let breakpoints = self.project.update(cx, |project, cx| {
6421 project
6422 .breakpoint_store()
6423 .read(cx)
6424 .all_source_breakpoints(cx)
6425 });
6426 let user_toolchains = self
6427 .project
6428 .read(cx)
6429 .user_toolchains(cx)
6430 .unwrap_or_default();
6431
6432 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6433 let docks = build_serialized_docks(self, window, cx);
6434 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6435
6436 let serialized_workspace = SerializedWorkspace {
6437 id: database_id,
6438 location,
6439 paths,
6440 center_group,
6441 window_bounds,
6442 display: Default::default(),
6443 docks,
6444 centered_layout: self.centered_layout,
6445 session_id: self.session_id.clone(),
6446 breakpoints,
6447 window_id: Some(window.window_handle().window_id().as_u64()),
6448 user_toolchains,
6449 };
6450
6451 let db = WorkspaceDb::global(cx);
6452 window.spawn(cx, async move |_| {
6453 db.save_workspace(serialized_workspace).await;
6454 })
6455 }
6456 WorkspaceLocation::DetachFromSession => {
6457 let window_bounds = SerializedWindowBounds(window.window_bounds());
6458 let display = window.display(cx).and_then(|d| d.uuid().ok());
6459 // Save dock state for empty local workspaces
6460 let docks = build_serialized_docks(self, window, cx);
6461 let db = WorkspaceDb::global(cx);
6462 let kvp = db::kvp::KeyValueStore::global(cx);
6463 window.spawn(cx, async move |_| {
6464 db.set_window_open_status(
6465 database_id,
6466 window_bounds,
6467 display.unwrap_or_default(),
6468 )
6469 .await
6470 .log_err();
6471 db.set_session_id(database_id, None).await.log_err();
6472 persistence::write_default_dock_state(&kvp, docks)
6473 .await
6474 .log_err();
6475 })
6476 }
6477 WorkspaceLocation::None => {
6478 // Save dock state for empty non-local workspaces
6479 let docks = build_serialized_docks(self, window, cx);
6480 let kvp = db::kvp::KeyValueStore::global(cx);
6481 window.spawn(cx, async move |_| {
6482 persistence::write_default_dock_state(&kvp, docks)
6483 .await
6484 .log_err();
6485 })
6486 }
6487 }
6488 }
6489
6490 fn has_any_items_open(&self, cx: &App) -> bool {
6491 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6492 }
6493
6494 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6495 let paths = PathList::new(&self.root_paths(cx));
6496 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6497 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6498 } else if self.project.read(cx).is_local() {
6499 if !paths.is_empty() || self.has_any_items_open(cx) {
6500 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6501 } else {
6502 WorkspaceLocation::DetachFromSession
6503 }
6504 } else {
6505 WorkspaceLocation::None
6506 }
6507 }
6508
6509 fn update_history(&self, cx: &mut App) {
6510 let Some(id) = self.database_id() else {
6511 return;
6512 };
6513 if !self.project.read(cx).is_local() {
6514 return;
6515 }
6516 if let Some(manager) = HistoryManager::global(cx) {
6517 let paths = PathList::new(&self.root_paths(cx));
6518 manager.update(cx, |this, cx| {
6519 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6520 });
6521 }
6522 }
6523
6524 async fn serialize_items(
6525 this: &WeakEntity<Self>,
6526 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6527 cx: &mut AsyncWindowContext,
6528 ) -> Result<()> {
6529 const CHUNK_SIZE: usize = 200;
6530
6531 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6532
6533 while let Some(items_received) = serializable_items.next().await {
6534 let unique_items =
6535 items_received
6536 .into_iter()
6537 .fold(HashMap::default(), |mut acc, item| {
6538 acc.entry(item.item_id()).or_insert(item);
6539 acc
6540 });
6541
6542 // We use into_iter() here so that the references to the items are moved into
6543 // the tasks and not kept alive while we're sleeping.
6544 for (_, item) in unique_items.into_iter() {
6545 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6546 item.serialize(workspace, false, window, cx)
6547 }) {
6548 cx.background_spawn(async move { task.await.log_err() })
6549 .detach();
6550 }
6551 }
6552
6553 cx.background_executor()
6554 .timer(SERIALIZATION_THROTTLE_TIME)
6555 .await;
6556 }
6557
6558 Ok(())
6559 }
6560
6561 pub(crate) fn enqueue_item_serialization(
6562 &mut self,
6563 item: Box<dyn SerializableItemHandle>,
6564 ) -> Result<()> {
6565 self.serializable_items_tx
6566 .unbounded_send(item)
6567 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6568 }
6569
6570 pub(crate) fn load_workspace(
6571 serialized_workspace: SerializedWorkspace,
6572 paths_to_open: Vec<Option<ProjectPath>>,
6573 window: &mut Window,
6574 cx: &mut Context<Workspace>,
6575 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6576 cx.spawn_in(window, async move |workspace, cx| {
6577 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6578
6579 let mut center_group = None;
6580 let mut center_items = None;
6581
6582 // Traverse the splits tree and add to things
6583 if let Some((group, active_pane, items)) = serialized_workspace
6584 .center_group
6585 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6586 .await
6587 {
6588 center_items = Some(items);
6589 center_group = Some((group, active_pane))
6590 }
6591
6592 let mut items_by_project_path = HashMap::default();
6593 let mut item_ids_by_kind = HashMap::default();
6594 let mut all_deserialized_items = Vec::default();
6595 cx.update(|_, cx| {
6596 for item in center_items.unwrap_or_default().into_iter().flatten() {
6597 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6598 item_ids_by_kind
6599 .entry(serializable_item_handle.serialized_item_kind())
6600 .or_insert(Vec::new())
6601 .push(item.item_id().as_u64() as ItemId);
6602 }
6603
6604 if let Some(project_path) = item.project_path(cx) {
6605 items_by_project_path.insert(project_path, item.clone());
6606 }
6607 all_deserialized_items.push(item);
6608 }
6609 })?;
6610
6611 let opened_items = paths_to_open
6612 .into_iter()
6613 .map(|path_to_open| {
6614 path_to_open
6615 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6616 })
6617 .collect::<Vec<_>>();
6618
6619 // Remove old panes from workspace panes list
6620 workspace.update_in(cx, |workspace, window, cx| {
6621 if let Some((center_group, active_pane)) = center_group {
6622 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6623
6624 // Swap workspace center group
6625 workspace.center = PaneGroup::with_root(center_group);
6626 workspace.center.set_is_center(true);
6627 workspace.center.mark_positions(cx);
6628
6629 if let Some(active_pane) = active_pane {
6630 workspace.set_active_pane(&active_pane, window, cx);
6631 cx.focus_self(window);
6632 } else {
6633 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6634 }
6635 }
6636
6637 let docks = serialized_workspace.docks;
6638
6639 for (dock, serialized_dock) in [
6640 (&mut workspace.right_dock, docks.right),
6641 (&mut workspace.left_dock, docks.left),
6642 (&mut workspace.bottom_dock, docks.bottom),
6643 ]
6644 .iter_mut()
6645 {
6646 dock.update(cx, |dock, cx| {
6647 dock.serialized_dock = Some(serialized_dock.clone());
6648 dock.restore_state(window, cx);
6649 });
6650 }
6651
6652 cx.notify();
6653 })?;
6654
6655 let _ = project
6656 .update(cx, |project, cx| {
6657 project
6658 .breakpoint_store()
6659 .update(cx, |breakpoint_store, cx| {
6660 breakpoint_store
6661 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6662 })
6663 })
6664 .await;
6665
6666 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6667 // after loading the items, we might have different items and in order to avoid
6668 // the database filling up, we delete items that haven't been loaded now.
6669 //
6670 // The items that have been loaded, have been saved after they've been added to the workspace.
6671 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6672 item_ids_by_kind
6673 .into_iter()
6674 .map(|(item_kind, loaded_items)| {
6675 SerializableItemRegistry::cleanup(
6676 item_kind,
6677 serialized_workspace.id,
6678 loaded_items,
6679 window,
6680 cx,
6681 )
6682 .log_err()
6683 })
6684 .collect::<Vec<_>>()
6685 })?;
6686
6687 futures::future::join_all(clean_up_tasks).await;
6688
6689 workspace
6690 .update_in(cx, |workspace, window, cx| {
6691 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6692 workspace.serialize_workspace_internal(window, cx).detach();
6693
6694 // Ensure that we mark the window as edited if we did load dirty items
6695 workspace.update_window_edited(window, cx);
6696 })
6697 .ok();
6698
6699 Ok(opened_items)
6700 })
6701 }
6702
6703 pub fn key_context(&self, cx: &App) -> KeyContext {
6704 let mut context = KeyContext::new_with_defaults();
6705 context.add("Workspace");
6706 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6707 if let Some(status) = self
6708 .debugger_provider
6709 .as_ref()
6710 .and_then(|provider| provider.active_thread_state(cx))
6711 {
6712 match status {
6713 ThreadStatus::Running | ThreadStatus::Stepping => {
6714 context.add("debugger_running");
6715 }
6716 ThreadStatus::Stopped => context.add("debugger_stopped"),
6717 ThreadStatus::Exited | ThreadStatus::Ended => {}
6718 }
6719 }
6720
6721 if self.left_dock.read(cx).is_open() {
6722 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6723 context.set("left_dock", active_panel.panel_key());
6724 }
6725 }
6726
6727 if self.right_dock.read(cx).is_open() {
6728 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6729 context.set("right_dock", active_panel.panel_key());
6730 }
6731 }
6732
6733 if self.bottom_dock.read(cx).is_open() {
6734 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6735 context.set("bottom_dock", active_panel.panel_key());
6736 }
6737 }
6738
6739 context
6740 }
6741
6742 /// Multiworkspace uses this to add workspace action handling to itself
6743 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6744 self.add_workspace_actions_listeners(div, window, cx)
6745 .on_action(cx.listener(
6746 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6747 for action in &action_sequence.0 {
6748 window.dispatch_action(action.boxed_clone(), cx);
6749 }
6750 },
6751 ))
6752 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6753 .on_action(cx.listener(Self::close_all_items_and_panes))
6754 .on_action(cx.listener(Self::close_item_in_all_panes))
6755 .on_action(cx.listener(Self::save_all))
6756 .on_action(cx.listener(Self::send_keystrokes))
6757 .on_action(cx.listener(Self::add_folder_to_project))
6758 .on_action(cx.listener(Self::follow_next_collaborator))
6759 .on_action(cx.listener(Self::activate_pane_at_index))
6760 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6761 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6762 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6763 .on_action(cx.listener(Self::toggle_theme_mode))
6764 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6765 let pane = workspace.active_pane().clone();
6766 workspace.unfollow_in_pane(&pane, window, cx);
6767 }))
6768 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6769 workspace
6770 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6771 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6772 }))
6773 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6774 workspace
6775 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6776 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6777 }))
6778 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6779 workspace
6780 .save_active_item(SaveIntent::SaveAs, window, cx)
6781 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6782 }))
6783 .on_action(
6784 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6785 workspace.activate_previous_pane(window, cx)
6786 }),
6787 )
6788 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6789 workspace.activate_next_pane(window, cx)
6790 }))
6791 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6792 workspace.activate_last_pane(window, cx)
6793 }))
6794 .on_action(
6795 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6796 workspace.activate_next_window(cx)
6797 }),
6798 )
6799 .on_action(
6800 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6801 workspace.activate_previous_window(cx)
6802 }),
6803 )
6804 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6805 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6806 }))
6807 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6808 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6809 }))
6810 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6811 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6812 }))
6813 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6814 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6815 }))
6816 .on_action(cx.listener(
6817 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6818 workspace.move_item_to_pane_in_direction(action, window, cx)
6819 },
6820 ))
6821 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6822 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6823 }))
6824 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6825 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6826 }))
6827 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6828 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6829 }))
6830 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6831 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6832 }))
6833 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6834 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6835 SplitDirection::Down,
6836 SplitDirection::Up,
6837 SplitDirection::Right,
6838 SplitDirection::Left,
6839 ];
6840 for dir in DIRECTION_PRIORITY {
6841 if workspace.find_pane_in_direction(dir, cx).is_some() {
6842 workspace.swap_pane_in_direction(dir, cx);
6843 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6844 break;
6845 }
6846 }
6847 }))
6848 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6849 workspace.move_pane_to_border(SplitDirection::Left, cx)
6850 }))
6851 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6852 workspace.move_pane_to_border(SplitDirection::Right, cx)
6853 }))
6854 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6855 workspace.move_pane_to_border(SplitDirection::Up, cx)
6856 }))
6857 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6858 workspace.move_pane_to_border(SplitDirection::Down, cx)
6859 }))
6860 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6861 this.toggle_dock(DockPosition::Left, window, cx);
6862 }))
6863 .on_action(cx.listener(
6864 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6865 workspace.toggle_dock(DockPosition::Right, window, cx);
6866 },
6867 ))
6868 .on_action(cx.listener(
6869 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6870 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6871 },
6872 ))
6873 .on_action(cx.listener(
6874 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6875 if !workspace.close_active_dock(window, cx) {
6876 cx.propagate();
6877 }
6878 },
6879 ))
6880 .on_action(
6881 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6882 workspace.close_all_docks(window, cx);
6883 }),
6884 )
6885 .on_action(cx.listener(Self::toggle_all_docks))
6886 .on_action(cx.listener(
6887 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6888 workspace.clear_all_notifications(cx);
6889 },
6890 ))
6891 .on_action(cx.listener(
6892 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6893 workspace.clear_navigation_history(window, cx);
6894 },
6895 ))
6896 .on_action(cx.listener(
6897 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6898 if let Some((notification_id, _)) = workspace.notifications.pop() {
6899 workspace.suppress_notification(¬ification_id, cx);
6900 }
6901 },
6902 ))
6903 .on_action(cx.listener(
6904 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6905 workspace.show_worktree_trust_security_modal(true, window, cx);
6906 },
6907 ))
6908 .on_action(
6909 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6910 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6911 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6912 trusted_worktrees.clear_trusted_paths()
6913 });
6914 let db = WorkspaceDb::global(cx);
6915 cx.spawn(async move |_, cx| {
6916 if db.clear_trusted_worktrees().await.log_err().is_some() {
6917 cx.update(|cx| reload(cx));
6918 }
6919 })
6920 .detach();
6921 }
6922 }),
6923 )
6924 .on_action(cx.listener(
6925 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6926 workspace.reopen_closed_item(window, cx).detach();
6927 },
6928 ))
6929 .on_action(cx.listener(
6930 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6931 for dock in workspace.all_docks() {
6932 if dock.focus_handle(cx).contains_focused(window, cx) {
6933 let panel = dock.read(cx).active_panel().cloned();
6934 if let Some(panel) = panel {
6935 dock.update(cx, |dock, cx| {
6936 dock.set_panel_size_state(
6937 panel.as_ref(),
6938 dock::PanelSizeState::default(),
6939 cx,
6940 );
6941 });
6942 }
6943 return;
6944 }
6945 }
6946 },
6947 ))
6948 .on_action(cx.listener(
6949 |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
6950 for dock in workspace.all_docks() {
6951 let panel = dock.read(cx).visible_panel().cloned();
6952 if let Some(panel) = panel {
6953 dock.update(cx, |dock, cx| {
6954 dock.set_panel_size_state(
6955 panel.as_ref(),
6956 dock::PanelSizeState::default(),
6957 cx,
6958 );
6959 });
6960 }
6961 }
6962 },
6963 ))
6964 .on_action(cx.listener(
6965 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6966 adjust_active_dock_size_by_px(
6967 px_with_ui_font_fallback(act.px, cx),
6968 workspace,
6969 window,
6970 cx,
6971 );
6972 },
6973 ))
6974 .on_action(cx.listener(
6975 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
6976 adjust_active_dock_size_by_px(
6977 px_with_ui_font_fallback(act.px, cx) * -1.,
6978 workspace,
6979 window,
6980 cx,
6981 );
6982 },
6983 ))
6984 .on_action(cx.listener(
6985 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
6986 adjust_open_docks_size_by_px(
6987 px_with_ui_font_fallback(act.px, cx),
6988 workspace,
6989 window,
6990 cx,
6991 );
6992 },
6993 ))
6994 .on_action(cx.listener(
6995 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
6996 adjust_open_docks_size_by_px(
6997 px_with_ui_font_fallback(act.px, cx) * -1.,
6998 workspace,
6999 window,
7000 cx,
7001 );
7002 },
7003 ))
7004 .on_action(cx.listener(Workspace::toggle_centered_layout))
7005 .on_action(cx.listener(
7006 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
7007 if let Some(active_dock) = workspace.active_dock(window, cx) {
7008 let dock = active_dock.read(cx);
7009 if let Some(active_panel) = dock.active_panel() {
7010 if active_panel.pane(cx).is_none() {
7011 let mut recent_pane: Option<Entity<Pane>> = None;
7012 let mut recent_timestamp = 0;
7013 for pane_handle in workspace.panes() {
7014 let pane = pane_handle.read(cx);
7015 for entry in pane.activation_history() {
7016 if entry.timestamp > recent_timestamp {
7017 recent_timestamp = entry.timestamp;
7018 recent_pane = Some(pane_handle.clone());
7019 }
7020 }
7021 }
7022
7023 if let Some(pane) = recent_pane {
7024 pane.update(cx, |pane, cx| {
7025 let current_index = pane.active_item_index();
7026 let items_len = pane.items_len();
7027 if items_len > 0 {
7028 let next_index = if current_index + 1 < items_len {
7029 current_index + 1
7030 } else {
7031 0
7032 };
7033 pane.activate_item(
7034 next_index, false, false, window, cx,
7035 );
7036 }
7037 });
7038 return;
7039 }
7040 }
7041 }
7042 }
7043 cx.propagate();
7044 },
7045 ))
7046 .on_action(cx.listener(
7047 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
7048 if let Some(active_dock) = workspace.active_dock(window, cx) {
7049 let dock = active_dock.read(cx);
7050 if let Some(active_panel) = dock.active_panel() {
7051 if active_panel.pane(cx).is_none() {
7052 let mut recent_pane: Option<Entity<Pane>> = None;
7053 let mut recent_timestamp = 0;
7054 for pane_handle in workspace.panes() {
7055 let pane = pane_handle.read(cx);
7056 for entry in pane.activation_history() {
7057 if entry.timestamp > recent_timestamp {
7058 recent_timestamp = entry.timestamp;
7059 recent_pane = Some(pane_handle.clone());
7060 }
7061 }
7062 }
7063
7064 if let Some(pane) = recent_pane {
7065 pane.update(cx, |pane, cx| {
7066 let current_index = pane.active_item_index();
7067 let items_len = pane.items_len();
7068 if items_len > 0 {
7069 let prev_index = if current_index > 0 {
7070 current_index - 1
7071 } else {
7072 items_len.saturating_sub(1)
7073 };
7074 pane.activate_item(
7075 prev_index, false, false, window, cx,
7076 );
7077 }
7078 });
7079 return;
7080 }
7081 }
7082 }
7083 }
7084 cx.propagate();
7085 },
7086 ))
7087 .on_action(cx.listener(
7088 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
7089 if let Some(active_dock) = workspace.active_dock(window, cx) {
7090 let dock = active_dock.read(cx);
7091 if let Some(active_panel) = dock.active_panel() {
7092 if active_panel.pane(cx).is_none() {
7093 let active_pane = workspace.active_pane().clone();
7094 active_pane.update(cx, |pane, cx| {
7095 pane.close_active_item(action, window, cx)
7096 .detach_and_log_err(cx);
7097 });
7098 return;
7099 }
7100 }
7101 }
7102 cx.propagate();
7103 },
7104 ))
7105 .on_action(
7106 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
7107 let pane = workspace.active_pane().clone();
7108 if let Some(item) = pane.read(cx).active_item() {
7109 item.toggle_read_only(window, cx);
7110 }
7111 }),
7112 )
7113 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
7114 workspace.focus_center_pane(window, cx);
7115 }))
7116 .on_action(cx.listener(Workspace::cancel))
7117 }
7118
7119 #[cfg(any(test, feature = "test-support"))]
7120 pub fn set_random_database_id(&mut self) {
7121 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
7122 }
7123
7124 #[cfg(any(test, feature = "test-support"))]
7125 pub(crate) fn test_new(
7126 project: Entity<Project>,
7127 window: &mut Window,
7128 cx: &mut Context<Self>,
7129 ) -> Self {
7130 use node_runtime::NodeRuntime;
7131 use session::Session;
7132
7133 let client = project.read(cx).client();
7134 let user_store = project.read(cx).user_store();
7135 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
7136 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
7137 window.activate_window();
7138 let app_state = Arc::new(AppState {
7139 languages: project.read(cx).languages().clone(),
7140 workspace_store,
7141 client,
7142 user_store,
7143 fs: project.read(cx).fs().clone(),
7144 build_window_options: |_, _| Default::default(),
7145 node_runtime: NodeRuntime::unavailable(),
7146 session,
7147 });
7148 let workspace = Self::new(Default::default(), project, app_state, window, cx);
7149 workspace
7150 .active_pane
7151 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
7152 workspace
7153 }
7154
7155 pub fn register_action<A: Action>(
7156 &mut self,
7157 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
7158 ) -> &mut Self {
7159 let callback = Arc::new(callback);
7160
7161 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
7162 let callback = callback.clone();
7163 div.on_action(cx.listener(move |workspace, event, window, cx| {
7164 (callback)(workspace, event, window, cx)
7165 }))
7166 }));
7167 self
7168 }
7169 pub fn register_action_renderer(
7170 &mut self,
7171 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
7172 ) -> &mut Self {
7173 self.workspace_actions.push(Box::new(callback));
7174 self
7175 }
7176
7177 fn add_workspace_actions_listeners(
7178 &self,
7179 mut div: Div,
7180 window: &mut Window,
7181 cx: &mut Context<Self>,
7182 ) -> Div {
7183 for action in self.workspace_actions.iter() {
7184 div = (action)(div, self, window, cx)
7185 }
7186 div
7187 }
7188
7189 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7190 self.modal_layer.read(cx).has_active_modal()
7191 }
7192
7193 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7194 self.modal_layer
7195 .read(cx)
7196 .is_active_modal_command_palette(cx)
7197 }
7198
7199 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7200 self.modal_layer.read(cx).active_modal()
7201 }
7202
7203 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7204 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7205 /// If no modal is active, the new modal will be shown.
7206 ///
7207 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7208 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7209 /// will not be shown.
7210 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7211 where
7212 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7213 {
7214 self.modal_layer.update(cx, |modal_layer, cx| {
7215 modal_layer.toggle_modal(window, cx, build)
7216 })
7217 }
7218
7219 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7220 self.modal_layer
7221 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7222 }
7223
7224 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7225 self.toast_layer
7226 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7227 }
7228
7229 pub fn toggle_centered_layout(
7230 &mut self,
7231 _: &ToggleCenteredLayout,
7232 _: &mut Window,
7233 cx: &mut Context<Self>,
7234 ) {
7235 self.centered_layout = !self.centered_layout;
7236 if let Some(database_id) = self.database_id() {
7237 let db = WorkspaceDb::global(cx);
7238 let centered_layout = self.centered_layout;
7239 cx.background_spawn(async move {
7240 db.set_centered_layout(database_id, centered_layout).await
7241 })
7242 .detach_and_log_err(cx);
7243 }
7244 cx.notify();
7245 }
7246
7247 fn adjust_padding(padding: Option<f32>) -> f32 {
7248 padding
7249 .unwrap_or(CenteredPaddingSettings::default().0)
7250 .clamp(
7251 CenteredPaddingSettings::MIN_PADDING,
7252 CenteredPaddingSettings::MAX_PADDING,
7253 )
7254 }
7255
7256 fn render_dock(
7257 &self,
7258 position: DockPosition,
7259 dock: &Entity<Dock>,
7260 window: &mut Window,
7261 cx: &mut App,
7262 ) -> Option<Div> {
7263 if self.zoomed_position == Some(position) {
7264 return None;
7265 }
7266
7267 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7268 let pane = panel.pane(cx)?;
7269 let follower_states = &self.follower_states;
7270 leader_border_for_pane(follower_states, &pane, window, cx)
7271 });
7272
7273 let mut container = div()
7274 .flex()
7275 .overflow_hidden()
7276 .flex_none()
7277 .child(dock.clone())
7278 .children(leader_border);
7279
7280 // Apply sizing only when the dock is open. When closed the dock is still
7281 // included in the element tree so its focus handle remains mounted — without
7282 // this, toggle_panel_focus cannot focus the panel when the dock is closed.
7283 let dock = dock.read(cx);
7284 if let Some(panel) = dock.visible_panel() {
7285 let size_state = dock.stored_panel_size_state(panel.as_ref());
7286 if position.axis() == Axis::Horizontal {
7287 if let Some(ratio) = size_state
7288 .and_then(|state| state.flexible_size_ratio)
7289 .or_else(|| self.default_flexible_dock_ratio(position))
7290 && panel.supports_flexible_size(window, cx)
7291 {
7292 let ratio = ratio.clamp(0.001, 0.999);
7293 let grow = ratio / (1.0 - ratio);
7294 let style = container.style();
7295 style.flex_grow = Some(grow);
7296 style.flex_shrink = Some(1.0);
7297 style.flex_basis = Some(relative(0.).into());
7298 } else {
7299 let size = size_state
7300 .and_then(|state| state.size)
7301 .unwrap_or_else(|| panel.default_size(window, cx));
7302 container = container.w(size);
7303 }
7304 } else {
7305 let size = size_state
7306 .and_then(|state| state.size)
7307 .unwrap_or_else(|| panel.default_size(window, cx));
7308 container = container.h(size);
7309 }
7310 }
7311
7312 Some(container)
7313 }
7314
7315 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7316 window
7317 .root::<MultiWorkspace>()
7318 .flatten()
7319 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7320 }
7321
7322 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7323 self.zoomed.as_ref()
7324 }
7325
7326 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7327 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7328 return;
7329 };
7330 let windows = cx.windows();
7331 let next_window =
7332 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7333 || {
7334 windows
7335 .iter()
7336 .cycle()
7337 .skip_while(|window| window.window_id() != current_window_id)
7338 .nth(1)
7339 },
7340 );
7341
7342 if let Some(window) = next_window {
7343 window
7344 .update(cx, |_, window, _| window.activate_window())
7345 .ok();
7346 }
7347 }
7348
7349 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7350 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7351 return;
7352 };
7353 let windows = cx.windows();
7354 let prev_window =
7355 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7356 || {
7357 windows
7358 .iter()
7359 .rev()
7360 .cycle()
7361 .skip_while(|window| window.window_id() != current_window_id)
7362 .nth(1)
7363 },
7364 );
7365
7366 if let Some(window) = prev_window {
7367 window
7368 .update(cx, |_, window, _| window.activate_window())
7369 .ok();
7370 }
7371 }
7372
7373 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7374 if cx.stop_active_drag(window) {
7375 } else if let Some((notification_id, _)) = self.notifications.pop() {
7376 dismiss_app_notification(¬ification_id, cx);
7377 } else {
7378 cx.propagate();
7379 }
7380 }
7381
7382 fn resize_dock(
7383 &mut self,
7384 dock_pos: DockPosition,
7385 new_size: Pixels,
7386 window: &mut Window,
7387 cx: &mut Context<Self>,
7388 ) {
7389 match dock_pos {
7390 DockPosition::Left => self.resize_left_dock(new_size, window, cx),
7391 DockPosition::Right => self.resize_right_dock(new_size, window, cx),
7392 DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
7393 }
7394 }
7395
7396 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7397 let workspace_width = self.bounds.size.width;
7398 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7399
7400 self.right_dock.read_with(cx, |right_dock, cx| {
7401 let right_dock_size = right_dock
7402 .stored_active_panel_size(window, cx)
7403 .unwrap_or(Pixels::ZERO);
7404 if right_dock_size + size > workspace_width {
7405 size = workspace_width - right_dock_size
7406 }
7407 });
7408
7409 let ratio = self.flexible_dock_ratio_for_size(DockPosition::Left, size, window, cx);
7410 self.left_dock.update(cx, |left_dock, cx| {
7411 if WorkspaceSettings::get_global(cx)
7412 .resize_all_panels_in_dock
7413 .contains(&DockPosition::Left)
7414 {
7415 left_dock.resize_all_panels(Some(size), ratio, window, cx);
7416 } else {
7417 left_dock.resize_active_panel(Some(size), ratio, window, cx);
7418 }
7419 });
7420 }
7421
7422 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7423 let workspace_width = self.bounds.size.width;
7424 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7425 self.left_dock.read_with(cx, |left_dock, cx| {
7426 let left_dock_size = left_dock
7427 .stored_active_panel_size(window, cx)
7428 .unwrap_or(Pixels::ZERO);
7429 if left_dock_size + size > workspace_width {
7430 size = workspace_width - left_dock_size
7431 }
7432 });
7433 let ratio = self.flexible_dock_ratio_for_size(DockPosition::Right, size, window, cx);
7434 self.right_dock.update(cx, |right_dock, cx| {
7435 if WorkspaceSettings::get_global(cx)
7436 .resize_all_panels_in_dock
7437 .contains(&DockPosition::Right)
7438 {
7439 right_dock.resize_all_panels(Some(size), ratio, window, cx);
7440 } else {
7441 right_dock.resize_active_panel(Some(size), ratio, window, cx);
7442 }
7443 });
7444 }
7445
7446 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7447 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7448 self.bottom_dock.update(cx, |bottom_dock, cx| {
7449 if WorkspaceSettings::get_global(cx)
7450 .resize_all_panels_in_dock
7451 .contains(&DockPosition::Bottom)
7452 {
7453 bottom_dock.resize_all_panels(Some(size), None, window, cx);
7454 } else {
7455 bottom_dock.resize_active_panel(Some(size), None, window, cx);
7456 }
7457 });
7458 }
7459
7460 fn toggle_edit_predictions_all_files(
7461 &mut self,
7462 _: &ToggleEditPrediction,
7463 _window: &mut Window,
7464 cx: &mut Context<Self>,
7465 ) {
7466 let fs = self.project().read(cx).fs().clone();
7467 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7468 update_settings_file(fs, cx, move |file, _| {
7469 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7470 });
7471 }
7472
7473 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7474 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7475 let next_mode = match current_mode {
7476 Some(theme::ThemeAppearanceMode::Light) => theme::ThemeAppearanceMode::Dark,
7477 Some(theme::ThemeAppearanceMode::Dark) => theme::ThemeAppearanceMode::Light,
7478 Some(theme::ThemeAppearanceMode::System) | None => match cx.theme().appearance() {
7479 theme::Appearance::Light => theme::ThemeAppearanceMode::Dark,
7480 theme::Appearance::Dark => theme::ThemeAppearanceMode::Light,
7481 },
7482 };
7483
7484 let fs = self.project().read(cx).fs().clone();
7485 settings::update_settings_file(fs, cx, move |settings, _cx| {
7486 theme::set_mode(settings, next_mode);
7487 });
7488 }
7489
7490 pub fn show_worktree_trust_security_modal(
7491 &mut self,
7492 toggle: bool,
7493 window: &mut Window,
7494 cx: &mut Context<Self>,
7495 ) {
7496 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7497 if toggle {
7498 security_modal.update(cx, |security_modal, cx| {
7499 security_modal.dismiss(cx);
7500 })
7501 } else {
7502 security_modal.update(cx, |security_modal, cx| {
7503 security_modal.refresh_restricted_paths(cx);
7504 });
7505 }
7506 } else {
7507 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7508 .map(|trusted_worktrees| {
7509 trusted_worktrees
7510 .read(cx)
7511 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7512 })
7513 .unwrap_or(false);
7514 if has_restricted_worktrees {
7515 let project = self.project().read(cx);
7516 let remote_host = project
7517 .remote_connection_options(cx)
7518 .map(RemoteHostLocation::from);
7519 let worktree_store = project.worktree_store().downgrade();
7520 self.toggle_modal(window, cx, |_, cx| {
7521 SecurityModal::new(worktree_store, remote_host, cx)
7522 });
7523 }
7524 }
7525 }
7526}
7527
7528pub trait AnyActiveCall {
7529 fn entity(&self) -> AnyEntity;
7530 fn is_in_room(&self, _: &App) -> bool;
7531 fn room_id(&self, _: &App) -> Option<u64>;
7532 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7533 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7534 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7535 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7536 fn is_sharing_project(&self, _: &App) -> bool;
7537 fn has_remote_participants(&self, _: &App) -> bool;
7538 fn local_participant_is_guest(&self, _: &App) -> bool;
7539 fn client(&self, _: &App) -> Arc<Client>;
7540 fn share_on_join(&self, _: &App) -> bool;
7541 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7542 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7543 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7544 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7545 fn join_project(
7546 &self,
7547 _: u64,
7548 _: Arc<LanguageRegistry>,
7549 _: Arc<dyn Fs>,
7550 _: &mut App,
7551 ) -> Task<Result<Entity<Project>>>;
7552 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7553 fn subscribe(
7554 &self,
7555 _: &mut Window,
7556 _: &mut Context<Workspace>,
7557 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7558 ) -> Subscription;
7559 fn create_shared_screen(
7560 &self,
7561 _: PeerId,
7562 _: &Entity<Pane>,
7563 _: &mut Window,
7564 _: &mut App,
7565 ) -> Option<Entity<SharedScreen>>;
7566}
7567
7568#[derive(Clone)]
7569pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7570impl Global for GlobalAnyActiveCall {}
7571
7572impl GlobalAnyActiveCall {
7573 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7574 cx.try_global()
7575 }
7576
7577 pub(crate) fn global(cx: &App) -> &Self {
7578 cx.global()
7579 }
7580}
7581
7582pub fn merge_conflict_notification_id() -> NotificationId {
7583 struct MergeConflictNotification;
7584 NotificationId::unique::<MergeConflictNotification>()
7585}
7586
7587/// Workspace-local view of a remote participant's location.
7588#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7589pub enum ParticipantLocation {
7590 SharedProject { project_id: u64 },
7591 UnsharedProject,
7592 External,
7593}
7594
7595impl ParticipantLocation {
7596 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7597 match location
7598 .and_then(|l| l.variant)
7599 .context("participant location was not provided")?
7600 {
7601 proto::participant_location::Variant::SharedProject(project) => {
7602 Ok(Self::SharedProject {
7603 project_id: project.id,
7604 })
7605 }
7606 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7607 proto::participant_location::Variant::External(_) => Ok(Self::External),
7608 }
7609 }
7610}
7611/// Workspace-local view of a remote collaborator's state.
7612/// This is the subset of `call::RemoteParticipant` that workspace needs.
7613#[derive(Clone)]
7614pub struct RemoteCollaborator {
7615 pub user: Arc<User>,
7616 pub peer_id: PeerId,
7617 pub location: ParticipantLocation,
7618 pub participant_index: ParticipantIndex,
7619}
7620
7621pub enum ActiveCallEvent {
7622 ParticipantLocationChanged { participant_id: PeerId },
7623 RemoteVideoTracksChanged { participant_id: PeerId },
7624}
7625
7626fn leader_border_for_pane(
7627 follower_states: &HashMap<CollaboratorId, FollowerState>,
7628 pane: &Entity<Pane>,
7629 _: &Window,
7630 cx: &App,
7631) -> Option<Div> {
7632 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7633 if state.pane() == pane {
7634 Some((*leader_id, state))
7635 } else {
7636 None
7637 }
7638 })?;
7639
7640 let mut leader_color = match leader_id {
7641 CollaboratorId::PeerId(leader_peer_id) => {
7642 let leader = GlobalAnyActiveCall::try_global(cx)?
7643 .0
7644 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7645
7646 cx.theme()
7647 .players()
7648 .color_for_participant(leader.participant_index.0)
7649 .cursor
7650 }
7651 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7652 };
7653 leader_color.fade_out(0.3);
7654 Some(
7655 div()
7656 .absolute()
7657 .size_full()
7658 .left_0()
7659 .top_0()
7660 .border_2()
7661 .border_color(leader_color),
7662 )
7663}
7664
7665fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7666 ZED_WINDOW_POSITION
7667 .zip(*ZED_WINDOW_SIZE)
7668 .map(|(position, size)| Bounds {
7669 origin: position,
7670 size,
7671 })
7672}
7673
7674fn open_items(
7675 serialized_workspace: Option<SerializedWorkspace>,
7676 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7677 window: &mut Window,
7678 cx: &mut Context<Workspace>,
7679) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7680 let restored_items = serialized_workspace.map(|serialized_workspace| {
7681 Workspace::load_workspace(
7682 serialized_workspace,
7683 project_paths_to_open
7684 .iter()
7685 .map(|(_, project_path)| project_path)
7686 .cloned()
7687 .collect(),
7688 window,
7689 cx,
7690 )
7691 });
7692
7693 cx.spawn_in(window, async move |workspace, cx| {
7694 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7695
7696 if let Some(restored_items) = restored_items {
7697 let restored_items = restored_items.await?;
7698
7699 let restored_project_paths = restored_items
7700 .iter()
7701 .filter_map(|item| {
7702 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7703 .ok()
7704 .flatten()
7705 })
7706 .collect::<HashSet<_>>();
7707
7708 for restored_item in restored_items {
7709 opened_items.push(restored_item.map(Ok));
7710 }
7711
7712 project_paths_to_open
7713 .iter_mut()
7714 .for_each(|(_, project_path)| {
7715 if let Some(project_path_to_open) = project_path
7716 && restored_project_paths.contains(project_path_to_open)
7717 {
7718 *project_path = None;
7719 }
7720 });
7721 } else {
7722 for _ in 0..project_paths_to_open.len() {
7723 opened_items.push(None);
7724 }
7725 }
7726 assert!(opened_items.len() == project_paths_to_open.len());
7727
7728 let tasks =
7729 project_paths_to_open
7730 .into_iter()
7731 .enumerate()
7732 .map(|(ix, (abs_path, project_path))| {
7733 let workspace = workspace.clone();
7734 cx.spawn(async move |cx| {
7735 let file_project_path = project_path?;
7736 let abs_path_task = workspace.update(cx, |workspace, cx| {
7737 workspace.project().update(cx, |project, cx| {
7738 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7739 })
7740 });
7741
7742 // We only want to open file paths here. If one of the items
7743 // here is a directory, it was already opened further above
7744 // with a `find_or_create_worktree`.
7745 if let Ok(task) = abs_path_task
7746 && task.await.is_none_or(|p| p.is_file())
7747 {
7748 return Some((
7749 ix,
7750 workspace
7751 .update_in(cx, |workspace, window, cx| {
7752 workspace.open_path(
7753 file_project_path,
7754 None,
7755 true,
7756 window,
7757 cx,
7758 )
7759 })
7760 .log_err()?
7761 .await,
7762 ));
7763 }
7764 None
7765 })
7766 });
7767
7768 let tasks = tasks.collect::<Vec<_>>();
7769
7770 let tasks = futures::future::join_all(tasks);
7771 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7772 opened_items[ix] = Some(path_open_result);
7773 }
7774
7775 Ok(opened_items)
7776 })
7777}
7778
7779#[derive(Clone)]
7780enum ActivateInDirectionTarget {
7781 Pane(Entity<Pane>),
7782 Dock(Entity<Dock>),
7783 Sidebar(FocusHandle),
7784}
7785
7786fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7787 window
7788 .update(cx, |multi_workspace, _, cx| {
7789 let workspace = multi_workspace.workspace().clone();
7790 workspace.update(cx, |workspace, cx| {
7791 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7792 struct DatabaseFailedNotification;
7793
7794 workspace.show_notification(
7795 NotificationId::unique::<DatabaseFailedNotification>(),
7796 cx,
7797 |cx| {
7798 cx.new(|cx| {
7799 MessageNotification::new("Failed to load the database file.", cx)
7800 .primary_message("File an Issue")
7801 .primary_icon(IconName::Plus)
7802 .primary_on_click(|window, cx| {
7803 window.dispatch_action(Box::new(FileBugReport), cx)
7804 })
7805 })
7806 },
7807 );
7808 }
7809 });
7810 })
7811 .log_err();
7812}
7813
7814fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7815 if val == 0 {
7816 ThemeSettings::get_global(cx).ui_font_size(cx)
7817 } else {
7818 px(val as f32)
7819 }
7820}
7821
7822fn adjust_active_dock_size_by_px(
7823 px: Pixels,
7824 workspace: &mut Workspace,
7825 window: &mut Window,
7826 cx: &mut Context<Workspace>,
7827) {
7828 let Some(active_dock) = workspace
7829 .all_docks()
7830 .into_iter()
7831 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7832 else {
7833 return;
7834 };
7835 let dock = active_dock.read(cx);
7836 let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
7837 return;
7838 };
7839 workspace.resize_dock(dock.position(), panel_size + px, window, cx);
7840}
7841
7842fn adjust_open_docks_size_by_px(
7843 px: Pixels,
7844 workspace: &mut Workspace,
7845 window: &mut Window,
7846 cx: &mut Context<Workspace>,
7847) {
7848 let docks = workspace
7849 .all_docks()
7850 .into_iter()
7851 .filter_map(|dock_entity| {
7852 let dock = dock_entity.read(cx);
7853 if dock.is_open() {
7854 let dock_pos = dock.position();
7855 let panel_size = workspace.dock_size(&dock, window, cx)?;
7856 Some((dock_pos, panel_size + px))
7857 } else {
7858 None
7859 }
7860 })
7861 .collect::<Vec<_>>();
7862
7863 for (position, new_size) in docks {
7864 workspace.resize_dock(position, new_size, window, cx);
7865 }
7866}
7867
7868impl Focusable for Workspace {
7869 fn focus_handle(&self, cx: &App) -> FocusHandle {
7870 self.active_pane.focus_handle(cx)
7871 }
7872}
7873
7874#[derive(Clone)]
7875struct DraggedDock(DockPosition);
7876
7877impl Render for DraggedDock {
7878 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7879 gpui::Empty
7880 }
7881}
7882
7883impl Render for Workspace {
7884 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7885 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7886 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7887 log::info!("Rendered first frame");
7888 }
7889
7890 let centered_layout = self.centered_layout
7891 && self.center.panes().len() == 1
7892 && self.active_item(cx).is_some();
7893 let render_padding = |size| {
7894 (size > 0.0).then(|| {
7895 div()
7896 .h_full()
7897 .w(relative(size))
7898 .bg(cx.theme().colors().editor_background)
7899 .border_color(cx.theme().colors().pane_group_border)
7900 })
7901 };
7902 let paddings = if centered_layout {
7903 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7904 (
7905 render_padding(Self::adjust_padding(
7906 settings.left_padding.map(|padding| padding.0),
7907 )),
7908 render_padding(Self::adjust_padding(
7909 settings.right_padding.map(|padding| padding.0),
7910 )),
7911 )
7912 } else {
7913 (None, None)
7914 };
7915 let ui_font = theme::setup_ui_font(window, cx);
7916
7917 let theme = cx.theme().clone();
7918 let colors = theme.colors();
7919 let notification_entities = self
7920 .notifications
7921 .iter()
7922 .map(|(_, notification)| notification.entity_id())
7923 .collect::<Vec<_>>();
7924 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
7925
7926 div()
7927 .relative()
7928 .size_full()
7929 .flex()
7930 .flex_col()
7931 .font(ui_font)
7932 .gap_0()
7933 .justify_start()
7934 .items_start()
7935 .text_color(colors.text)
7936 .overflow_hidden()
7937 .children(self.titlebar_item.clone())
7938 .on_modifiers_changed(move |_, _, cx| {
7939 for &id in ¬ification_entities {
7940 cx.notify(id);
7941 }
7942 })
7943 .child(
7944 div()
7945 .size_full()
7946 .relative()
7947 .flex_1()
7948 .flex()
7949 .flex_col()
7950 .child(
7951 div()
7952 .id("workspace")
7953 .bg(colors.background)
7954 .relative()
7955 .flex_1()
7956 .w_full()
7957 .flex()
7958 .flex_col()
7959 .overflow_hidden()
7960 .border_t_1()
7961 .border_b_1()
7962 .border_color(colors.border)
7963 .child({
7964 let this = cx.entity();
7965 canvas(
7966 move |bounds, window, cx| {
7967 this.update(cx, |this, cx| {
7968 let bounds_changed = this.bounds != bounds;
7969 this.bounds = bounds;
7970
7971 if bounds_changed {
7972 this.left_dock.update(cx, |dock, cx| {
7973 dock.clamp_panel_size(
7974 bounds.size.width,
7975 window,
7976 cx,
7977 )
7978 });
7979
7980 this.right_dock.update(cx, |dock, cx| {
7981 dock.clamp_panel_size(
7982 bounds.size.width,
7983 window,
7984 cx,
7985 )
7986 });
7987
7988 this.bottom_dock.update(cx, |dock, cx| {
7989 dock.clamp_panel_size(
7990 bounds.size.height,
7991 window,
7992 cx,
7993 )
7994 });
7995 }
7996 })
7997 },
7998 |_, _, _, _| {},
7999 )
8000 .absolute()
8001 .size_full()
8002 })
8003 .when(self.zoomed.is_none(), |this| {
8004 this.on_drag_move(cx.listener(
8005 move |workspace,
8006 e: &DragMoveEvent<DraggedDock>,
8007 window,
8008 cx| {
8009 if workspace.previous_dock_drag_coordinates
8010 != Some(e.event.position)
8011 {
8012 workspace.previous_dock_drag_coordinates =
8013 Some(e.event.position);
8014
8015 match e.drag(cx).0 {
8016 DockPosition::Left => {
8017 workspace.resize_left_dock(
8018 e.event.position.x
8019 - workspace.bounds.left(),
8020 window,
8021 cx,
8022 );
8023 }
8024 DockPosition::Right => {
8025 workspace.resize_right_dock(
8026 workspace.bounds.right()
8027 - e.event.position.x,
8028 window,
8029 cx,
8030 );
8031 }
8032 DockPosition::Bottom => {
8033 workspace.resize_bottom_dock(
8034 workspace.bounds.bottom()
8035 - e.event.position.y,
8036 window,
8037 cx,
8038 );
8039 }
8040 };
8041 workspace.serialize_workspace(window, cx);
8042 }
8043 },
8044 ))
8045
8046 })
8047 .child({
8048 match bottom_dock_layout {
8049 BottomDockLayout::Full => div()
8050 .flex()
8051 .flex_col()
8052 .h_full()
8053 .child(
8054 div()
8055 .flex()
8056 .flex_row()
8057 .flex_1()
8058 .overflow_hidden()
8059 .children(self.render_dock(
8060 DockPosition::Left,
8061 &self.left_dock,
8062 window,
8063 cx,
8064 ))
8065
8066 .child(
8067 div()
8068 .flex()
8069 .flex_col()
8070 .flex_1()
8071 .overflow_hidden()
8072 .child(
8073 h_flex()
8074 .flex_1()
8075 .when_some(
8076 paddings.0,
8077 |this, p| {
8078 this.child(
8079 p.border_r_1(),
8080 )
8081 },
8082 )
8083 .child(self.center.render(
8084 self.zoomed.as_ref(),
8085 &PaneRenderContext {
8086 follower_states:
8087 &self.follower_states,
8088 active_call: self.active_call(),
8089 active_pane: &self.active_pane,
8090 app_state: &self.app_state,
8091 project: &self.project,
8092 workspace: &self.weak_self,
8093 },
8094 window,
8095 cx,
8096 ))
8097 .when_some(
8098 paddings.1,
8099 |this, p| {
8100 this.child(
8101 p.border_l_1(),
8102 )
8103 },
8104 ),
8105 ),
8106 )
8107
8108 .children(self.render_dock(
8109 DockPosition::Right,
8110 &self.right_dock,
8111 window,
8112 cx,
8113 )),
8114 )
8115 .child(div().w_full().children(self.render_dock(
8116 DockPosition::Bottom,
8117 &self.bottom_dock,
8118 window,
8119 cx
8120 ))),
8121
8122 BottomDockLayout::LeftAligned => div()
8123 .flex()
8124 .flex_row()
8125 .h_full()
8126 .child(
8127 div()
8128 .flex()
8129 .flex_col()
8130 .flex_1()
8131 .h_full()
8132 .child(
8133 div()
8134 .flex()
8135 .flex_row()
8136 .flex_1()
8137 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
8138
8139 .child(
8140 div()
8141 .flex()
8142 .flex_col()
8143 .flex_1()
8144 .overflow_hidden()
8145 .child(
8146 h_flex()
8147 .flex_1()
8148 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8149 .child(self.center.render(
8150 self.zoomed.as_ref(),
8151 &PaneRenderContext {
8152 follower_states:
8153 &self.follower_states,
8154 active_call: self.active_call(),
8155 active_pane: &self.active_pane,
8156 app_state: &self.app_state,
8157 project: &self.project,
8158 workspace: &self.weak_self,
8159 },
8160 window,
8161 cx,
8162 ))
8163 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8164 )
8165 )
8166
8167 )
8168 .child(
8169 div()
8170 .w_full()
8171 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8172 ),
8173 )
8174 .children(self.render_dock(
8175 DockPosition::Right,
8176 &self.right_dock,
8177 window,
8178 cx,
8179 )),
8180 BottomDockLayout::RightAligned => div()
8181 .flex()
8182 .flex_row()
8183 .h_full()
8184 .children(self.render_dock(
8185 DockPosition::Left,
8186 &self.left_dock,
8187 window,
8188 cx,
8189 ))
8190
8191 .child(
8192 div()
8193 .flex()
8194 .flex_col()
8195 .flex_1()
8196 .h_full()
8197 .child(
8198 div()
8199 .flex()
8200 .flex_row()
8201 .flex_1()
8202 .child(
8203 div()
8204 .flex()
8205 .flex_col()
8206 .flex_1()
8207 .overflow_hidden()
8208 .child(
8209 h_flex()
8210 .flex_1()
8211 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8212 .child(self.center.render(
8213 self.zoomed.as_ref(),
8214 &PaneRenderContext {
8215 follower_states:
8216 &self.follower_states,
8217 active_call: self.active_call(),
8218 active_pane: &self.active_pane,
8219 app_state: &self.app_state,
8220 project: &self.project,
8221 workspace: &self.weak_self,
8222 },
8223 window,
8224 cx,
8225 ))
8226 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8227 )
8228 )
8229
8230 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8231 )
8232 .child(
8233 div()
8234 .w_full()
8235 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8236 ),
8237 ),
8238 BottomDockLayout::Contained => div()
8239 .flex()
8240 .flex_row()
8241 .h_full()
8242 .children(self.render_dock(
8243 DockPosition::Left,
8244 &self.left_dock,
8245 window,
8246 cx,
8247 ))
8248
8249 .child(
8250 div()
8251 .flex()
8252 .flex_col()
8253 .flex_1()
8254 .overflow_hidden()
8255 .child(
8256 h_flex()
8257 .flex_1()
8258 .when_some(paddings.0, |this, p| {
8259 this.child(p.border_r_1())
8260 })
8261 .child(self.center.render(
8262 self.zoomed.as_ref(),
8263 &PaneRenderContext {
8264 follower_states:
8265 &self.follower_states,
8266 active_call: self.active_call(),
8267 active_pane: &self.active_pane,
8268 app_state: &self.app_state,
8269 project: &self.project,
8270 workspace: &self.weak_self,
8271 },
8272 window,
8273 cx,
8274 ))
8275 .when_some(paddings.1, |this, p| {
8276 this.child(p.border_l_1())
8277 }),
8278 )
8279 .children(self.render_dock(
8280 DockPosition::Bottom,
8281 &self.bottom_dock,
8282 window,
8283 cx,
8284 )),
8285 )
8286
8287 .children(self.render_dock(
8288 DockPosition::Right,
8289 &self.right_dock,
8290 window,
8291 cx,
8292 )),
8293 }
8294 })
8295 .children(self.zoomed.as_ref().and_then(|view| {
8296 let zoomed_view = view.upgrade()?;
8297 let div = div()
8298 .occlude()
8299 .absolute()
8300 .overflow_hidden()
8301 .border_color(colors.border)
8302 .bg(colors.background)
8303 .child(zoomed_view)
8304 .inset_0()
8305 .shadow_lg();
8306
8307 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8308 return Some(div);
8309 }
8310
8311 Some(match self.zoomed_position {
8312 Some(DockPosition::Left) => div.right_2().border_r_1(),
8313 Some(DockPosition::Right) => div.left_2().border_l_1(),
8314 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8315 None => {
8316 div.top_2().bottom_2().left_2().right_2().border_1()
8317 }
8318 })
8319 }))
8320 .children(self.render_notifications(window, cx)),
8321 )
8322 .when(self.status_bar_visible(cx), |parent| {
8323 parent.child(self.status_bar.clone())
8324 })
8325 .child(self.toast_layer.clone()),
8326 )
8327 }
8328}
8329
8330impl WorkspaceStore {
8331 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8332 Self {
8333 workspaces: Default::default(),
8334 _subscriptions: vec![
8335 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8336 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8337 ],
8338 client,
8339 }
8340 }
8341
8342 pub fn update_followers(
8343 &self,
8344 project_id: Option<u64>,
8345 update: proto::update_followers::Variant,
8346 cx: &App,
8347 ) -> Option<()> {
8348 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8349 let room_id = active_call.0.room_id(cx)?;
8350 self.client
8351 .send(proto::UpdateFollowers {
8352 room_id,
8353 project_id,
8354 variant: Some(update),
8355 })
8356 .log_err()
8357 }
8358
8359 pub async fn handle_follow(
8360 this: Entity<Self>,
8361 envelope: TypedEnvelope<proto::Follow>,
8362 mut cx: AsyncApp,
8363 ) -> Result<proto::FollowResponse> {
8364 this.update(&mut cx, |this, cx| {
8365 let follower = Follower {
8366 project_id: envelope.payload.project_id,
8367 peer_id: envelope.original_sender_id()?,
8368 };
8369
8370 let mut response = proto::FollowResponse::default();
8371
8372 this.workspaces.retain(|(window_handle, weak_workspace)| {
8373 let Some(workspace) = weak_workspace.upgrade() else {
8374 return false;
8375 };
8376 window_handle
8377 .update(cx, |_, window, cx| {
8378 workspace.update(cx, |workspace, cx| {
8379 let handler_response =
8380 workspace.handle_follow(follower.project_id, window, cx);
8381 if let Some(active_view) = handler_response.active_view
8382 && workspace.project.read(cx).remote_id() == follower.project_id
8383 {
8384 response.active_view = Some(active_view)
8385 }
8386 });
8387 })
8388 .is_ok()
8389 });
8390
8391 Ok(response)
8392 })
8393 }
8394
8395 async fn handle_update_followers(
8396 this: Entity<Self>,
8397 envelope: TypedEnvelope<proto::UpdateFollowers>,
8398 mut cx: AsyncApp,
8399 ) -> Result<()> {
8400 let leader_id = envelope.original_sender_id()?;
8401 let update = envelope.payload;
8402
8403 this.update(&mut cx, |this, cx| {
8404 this.workspaces.retain(|(window_handle, weak_workspace)| {
8405 let Some(workspace) = weak_workspace.upgrade() else {
8406 return false;
8407 };
8408 window_handle
8409 .update(cx, |_, window, cx| {
8410 workspace.update(cx, |workspace, cx| {
8411 let project_id = workspace.project.read(cx).remote_id();
8412 if update.project_id != project_id && update.project_id.is_some() {
8413 return;
8414 }
8415 workspace.handle_update_followers(
8416 leader_id,
8417 update.clone(),
8418 window,
8419 cx,
8420 );
8421 });
8422 })
8423 .is_ok()
8424 });
8425 Ok(())
8426 })
8427 }
8428
8429 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8430 self.workspaces.iter().map(|(_, weak)| weak)
8431 }
8432
8433 pub fn workspaces_with_windows(
8434 &self,
8435 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8436 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8437 }
8438}
8439
8440impl ViewId {
8441 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8442 Ok(Self {
8443 creator: message
8444 .creator
8445 .map(CollaboratorId::PeerId)
8446 .context("creator is missing")?,
8447 id: message.id,
8448 })
8449 }
8450
8451 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8452 if let CollaboratorId::PeerId(peer_id) = self.creator {
8453 Some(proto::ViewId {
8454 creator: Some(peer_id),
8455 id: self.id,
8456 })
8457 } else {
8458 None
8459 }
8460 }
8461}
8462
8463impl FollowerState {
8464 fn pane(&self) -> &Entity<Pane> {
8465 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8466 }
8467}
8468
8469pub trait WorkspaceHandle {
8470 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8471}
8472
8473impl WorkspaceHandle for Entity<Workspace> {
8474 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8475 self.read(cx)
8476 .worktrees(cx)
8477 .flat_map(|worktree| {
8478 let worktree_id = worktree.read(cx).id();
8479 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8480 worktree_id,
8481 path: f.path.clone(),
8482 })
8483 })
8484 .collect::<Vec<_>>()
8485 }
8486}
8487
8488pub async fn last_opened_workspace_location(
8489 db: &WorkspaceDb,
8490 fs: &dyn fs::Fs,
8491) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8492 db.last_workspace(fs)
8493 .await
8494 .log_err()
8495 .flatten()
8496 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8497}
8498
8499pub async fn last_session_workspace_locations(
8500 db: &WorkspaceDb,
8501 last_session_id: &str,
8502 last_session_window_stack: Option<Vec<WindowId>>,
8503 fs: &dyn fs::Fs,
8504) -> Option<Vec<SessionWorkspace>> {
8505 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8506 .await
8507 .log_err()
8508}
8509
8510pub struct MultiWorkspaceRestoreResult {
8511 pub window_handle: WindowHandle<MultiWorkspace>,
8512 pub errors: Vec<anyhow::Error>,
8513}
8514
8515pub async fn restore_multiworkspace(
8516 multi_workspace: SerializedMultiWorkspace,
8517 app_state: Arc<AppState>,
8518 cx: &mut AsyncApp,
8519) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8520 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
8521 let mut group_iter = workspaces.into_iter();
8522 let first = group_iter
8523 .next()
8524 .context("window group must not be empty")?;
8525
8526 let window_handle = if first.paths.is_empty() {
8527 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8528 .await?
8529 } else {
8530 let OpenResult { window, .. } = cx
8531 .update(|cx| {
8532 Workspace::new_local(
8533 first.paths.paths().to_vec(),
8534 app_state.clone(),
8535 None,
8536 None,
8537 None,
8538 true,
8539 cx,
8540 )
8541 })
8542 .await?;
8543 window
8544 };
8545
8546 let mut errors = Vec::new();
8547
8548 for session_workspace in group_iter {
8549 let error = if session_workspace.paths.is_empty() {
8550 cx.update(|cx| {
8551 open_workspace_by_id(
8552 session_workspace.workspace_id,
8553 app_state.clone(),
8554 Some(window_handle),
8555 cx,
8556 )
8557 })
8558 .await
8559 .err()
8560 } else {
8561 cx.update(|cx| {
8562 Workspace::new_local(
8563 session_workspace.paths.paths().to_vec(),
8564 app_state.clone(),
8565 Some(window_handle),
8566 None,
8567 None,
8568 false,
8569 cx,
8570 )
8571 })
8572 .await
8573 .err()
8574 };
8575
8576 if let Some(error) = error {
8577 errors.push(error);
8578 }
8579 }
8580
8581 if let Some(target_id) = state.active_workspace_id {
8582 window_handle
8583 .update(cx, |multi_workspace, window, cx| {
8584 let target_index = multi_workspace
8585 .workspaces()
8586 .iter()
8587 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8588 if let Some(index) = target_index {
8589 multi_workspace.activate_index(index, window, cx);
8590 } else if !multi_workspace.workspaces().is_empty() {
8591 multi_workspace.activate_index(0, window, cx);
8592 }
8593 })
8594 .ok();
8595 } else {
8596 window_handle
8597 .update(cx, |multi_workspace, window, cx| {
8598 if !multi_workspace.workspaces().is_empty() {
8599 multi_workspace.activate_index(0, window, cx);
8600 }
8601 })
8602 .ok();
8603 }
8604
8605 if state.sidebar_open {
8606 window_handle
8607 .update(cx, |multi_workspace, _, cx| {
8608 multi_workspace.open_sidebar(cx);
8609 })
8610 .ok();
8611 }
8612
8613 window_handle
8614 .update(cx, |_, window, _cx| {
8615 window.activate_window();
8616 })
8617 .ok();
8618
8619 Ok(MultiWorkspaceRestoreResult {
8620 window_handle,
8621 errors,
8622 })
8623}
8624
8625actions!(
8626 collab,
8627 [
8628 /// Opens the channel notes for the current call.
8629 ///
8630 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8631 /// channel in the collab panel.
8632 ///
8633 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8634 /// can be copied via "Copy link to section" in the context menu of the channel notes
8635 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8636 OpenChannelNotes,
8637 /// Mutes your microphone.
8638 Mute,
8639 /// Deafens yourself (mute both microphone and speakers).
8640 Deafen,
8641 /// Leaves the current call.
8642 LeaveCall,
8643 /// Shares the current project with collaborators.
8644 ShareProject,
8645 /// Shares your screen with collaborators.
8646 ScreenShare,
8647 /// Copies the current room name and session id for debugging purposes.
8648 CopyRoomId,
8649 ]
8650);
8651
8652/// Opens the channel notes for a specific channel by its ID.
8653#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8654#[action(namespace = collab)]
8655#[serde(deny_unknown_fields)]
8656pub struct OpenChannelNotesById {
8657 pub channel_id: u64,
8658}
8659
8660actions!(
8661 zed,
8662 [
8663 /// Opens the Zed log file.
8664 OpenLog,
8665 /// Reveals the Zed log file in the system file manager.
8666 RevealLogInFileManager
8667 ]
8668);
8669
8670async fn join_channel_internal(
8671 channel_id: ChannelId,
8672 app_state: &Arc<AppState>,
8673 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8674 requesting_workspace: Option<WeakEntity<Workspace>>,
8675 active_call: &dyn AnyActiveCall,
8676 cx: &mut AsyncApp,
8677) -> Result<bool> {
8678 let (should_prompt, already_in_channel) = cx.update(|cx| {
8679 if !active_call.is_in_room(cx) {
8680 return (false, false);
8681 }
8682
8683 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8684 let should_prompt = active_call.is_sharing_project(cx)
8685 && active_call.has_remote_participants(cx)
8686 && !already_in_channel;
8687 (should_prompt, already_in_channel)
8688 });
8689
8690 if already_in_channel {
8691 let task = cx.update(|cx| {
8692 if let Some((project, host)) = active_call.most_active_project(cx) {
8693 Some(join_in_room_project(project, host, app_state.clone(), cx))
8694 } else {
8695 None
8696 }
8697 });
8698 if let Some(task) = task {
8699 task.await?;
8700 }
8701 return anyhow::Ok(true);
8702 }
8703
8704 if should_prompt {
8705 if let Some(multi_workspace) = requesting_window {
8706 let answer = multi_workspace
8707 .update(cx, |_, window, cx| {
8708 window.prompt(
8709 PromptLevel::Warning,
8710 "Do you want to switch channels?",
8711 Some("Leaving this call will unshare your current project."),
8712 &["Yes, Join Channel", "Cancel"],
8713 cx,
8714 )
8715 })?
8716 .await;
8717
8718 if answer == Ok(1) {
8719 return Ok(false);
8720 }
8721 } else {
8722 return Ok(false);
8723 }
8724 }
8725
8726 let client = cx.update(|cx| active_call.client(cx));
8727
8728 let mut client_status = client.status();
8729
8730 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8731 'outer: loop {
8732 let Some(status) = client_status.recv().await else {
8733 anyhow::bail!("error connecting");
8734 };
8735
8736 match status {
8737 Status::Connecting
8738 | Status::Authenticating
8739 | Status::Authenticated
8740 | Status::Reconnecting
8741 | Status::Reauthenticating
8742 | Status::Reauthenticated => continue,
8743 Status::Connected { .. } => break 'outer,
8744 Status::SignedOut | Status::AuthenticationError => {
8745 return Err(ErrorCode::SignedOut.into());
8746 }
8747 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8748 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8749 return Err(ErrorCode::Disconnected.into());
8750 }
8751 }
8752 }
8753
8754 let joined = cx
8755 .update(|cx| active_call.join_channel(channel_id, cx))
8756 .await?;
8757
8758 if !joined {
8759 return anyhow::Ok(true);
8760 }
8761
8762 cx.update(|cx| active_call.room_update_completed(cx)).await;
8763
8764 let task = cx.update(|cx| {
8765 if let Some((project, host)) = active_call.most_active_project(cx) {
8766 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8767 }
8768
8769 // If you are the first to join a channel, see if you should share your project.
8770 if !active_call.has_remote_participants(cx)
8771 && !active_call.local_participant_is_guest(cx)
8772 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8773 {
8774 let project = workspace.update(cx, |workspace, cx| {
8775 let project = workspace.project.read(cx);
8776
8777 if !active_call.share_on_join(cx) {
8778 return None;
8779 }
8780
8781 if (project.is_local() || project.is_via_remote_server())
8782 && project.visible_worktrees(cx).any(|tree| {
8783 tree.read(cx)
8784 .root_entry()
8785 .is_some_and(|entry| entry.is_dir())
8786 })
8787 {
8788 Some(workspace.project.clone())
8789 } else {
8790 None
8791 }
8792 });
8793 if let Some(project) = project {
8794 let share_task = active_call.share_project(project, cx);
8795 return Some(cx.spawn(async move |_cx| -> Result<()> {
8796 share_task.await?;
8797 Ok(())
8798 }));
8799 }
8800 }
8801
8802 None
8803 });
8804 if let Some(task) = task {
8805 task.await?;
8806 return anyhow::Ok(true);
8807 }
8808 anyhow::Ok(false)
8809}
8810
8811pub fn join_channel(
8812 channel_id: ChannelId,
8813 app_state: Arc<AppState>,
8814 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8815 requesting_workspace: Option<WeakEntity<Workspace>>,
8816 cx: &mut App,
8817) -> Task<Result<()>> {
8818 let active_call = GlobalAnyActiveCall::global(cx).clone();
8819 cx.spawn(async move |cx| {
8820 let result = join_channel_internal(
8821 channel_id,
8822 &app_state,
8823 requesting_window,
8824 requesting_workspace,
8825 &*active_call.0,
8826 cx,
8827 )
8828 .await;
8829
8830 // join channel succeeded, and opened a window
8831 if matches!(result, Ok(true)) {
8832 return anyhow::Ok(());
8833 }
8834
8835 // find an existing workspace to focus and show call controls
8836 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8837 if active_window.is_none() {
8838 // no open workspaces, make one to show the error in (blergh)
8839 let OpenResult {
8840 window: window_handle,
8841 ..
8842 } = cx
8843 .update(|cx| {
8844 Workspace::new_local(
8845 vec![],
8846 app_state.clone(),
8847 requesting_window,
8848 None,
8849 None,
8850 true,
8851 cx,
8852 )
8853 })
8854 .await?;
8855
8856 window_handle
8857 .update(cx, |_, window, _cx| {
8858 window.activate_window();
8859 })
8860 .ok();
8861
8862 if result.is_ok() {
8863 cx.update(|cx| {
8864 cx.dispatch_action(&OpenChannelNotes);
8865 });
8866 }
8867
8868 active_window = Some(window_handle);
8869 }
8870
8871 if let Err(err) = result {
8872 log::error!("failed to join channel: {}", err);
8873 if let Some(active_window) = active_window {
8874 active_window
8875 .update(cx, |_, window, cx| {
8876 let detail: SharedString = match err.error_code() {
8877 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8878 ErrorCode::UpgradeRequired => concat!(
8879 "Your are running an unsupported version of Zed. ",
8880 "Please update to continue."
8881 )
8882 .into(),
8883 ErrorCode::NoSuchChannel => concat!(
8884 "No matching channel was found. ",
8885 "Please check the link and try again."
8886 )
8887 .into(),
8888 ErrorCode::Forbidden => concat!(
8889 "This channel is private, and you do not have access. ",
8890 "Please ask someone to add you and try again."
8891 )
8892 .into(),
8893 ErrorCode::Disconnected => {
8894 "Please check your internet connection and try again.".into()
8895 }
8896 _ => format!("{}\n\nPlease try again.", err).into(),
8897 };
8898 window.prompt(
8899 PromptLevel::Critical,
8900 "Failed to join channel",
8901 Some(&detail),
8902 &["Ok"],
8903 cx,
8904 )
8905 })?
8906 .await
8907 .ok();
8908 }
8909 }
8910
8911 // return ok, we showed the error to the user.
8912 anyhow::Ok(())
8913 })
8914}
8915
8916pub async fn get_any_active_multi_workspace(
8917 app_state: Arc<AppState>,
8918 mut cx: AsyncApp,
8919) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8920 // find an existing workspace to focus and show call controls
8921 let active_window = activate_any_workspace_window(&mut cx);
8922 if active_window.is_none() {
8923 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
8924 .await?;
8925 }
8926 activate_any_workspace_window(&mut cx).context("could not open zed")
8927}
8928
8929fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8930 cx.update(|cx| {
8931 if let Some(workspace_window) = cx
8932 .active_window()
8933 .and_then(|window| window.downcast::<MultiWorkspace>())
8934 {
8935 return Some(workspace_window);
8936 }
8937
8938 for window in cx.windows() {
8939 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8940 workspace_window
8941 .update(cx, |_, window, _| window.activate_window())
8942 .ok();
8943 return Some(workspace_window);
8944 }
8945 }
8946 None
8947 })
8948}
8949
8950pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8951 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
8952}
8953
8954pub fn workspace_windows_for_location(
8955 serialized_location: &SerializedWorkspaceLocation,
8956 cx: &App,
8957) -> Vec<WindowHandle<MultiWorkspace>> {
8958 cx.windows()
8959 .into_iter()
8960 .filter_map(|window| window.downcast::<MultiWorkspace>())
8961 .filter(|multi_workspace| {
8962 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
8963 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
8964 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
8965 }
8966 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
8967 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
8968 a.distro_name == b.distro_name
8969 }
8970 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
8971 a.container_id == b.container_id
8972 }
8973 #[cfg(any(test, feature = "test-support"))]
8974 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
8975 a.id == b.id
8976 }
8977 _ => false,
8978 };
8979
8980 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8981 multi_workspace.workspaces().iter().any(|workspace| {
8982 match workspace.read(cx).workspace_location(cx) {
8983 WorkspaceLocation::Location(location, _) => {
8984 match (&location, serialized_location) {
8985 (
8986 SerializedWorkspaceLocation::Local,
8987 SerializedWorkspaceLocation::Local,
8988 ) => true,
8989 (
8990 SerializedWorkspaceLocation::Remote(a),
8991 SerializedWorkspaceLocation::Remote(b),
8992 ) => same_host(a, b),
8993 _ => false,
8994 }
8995 }
8996 _ => false,
8997 }
8998 })
8999 })
9000 })
9001 .collect()
9002}
9003
9004pub async fn find_existing_workspace(
9005 abs_paths: &[PathBuf],
9006 open_options: &OpenOptions,
9007 location: &SerializedWorkspaceLocation,
9008 cx: &mut AsyncApp,
9009) -> (
9010 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
9011 OpenVisible,
9012) {
9013 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
9014 let mut open_visible = OpenVisible::All;
9015 let mut best_match = None;
9016
9017 if open_options.open_new_workspace != Some(true) {
9018 cx.update(|cx| {
9019 for window in workspace_windows_for_location(location, cx) {
9020 if let Ok(multi_workspace) = window.read(cx) {
9021 for workspace in multi_workspace.workspaces() {
9022 let project = workspace.read(cx).project.read(cx);
9023 let m = project.visibility_for_paths(
9024 abs_paths,
9025 open_options.open_new_workspace == None,
9026 cx,
9027 );
9028 if m > best_match {
9029 existing = Some((window, workspace.clone()));
9030 best_match = m;
9031 } else if best_match.is_none()
9032 && open_options.open_new_workspace == Some(false)
9033 {
9034 existing = Some((window, workspace.clone()))
9035 }
9036 }
9037 }
9038 }
9039 });
9040
9041 let all_paths_are_files = existing
9042 .as_ref()
9043 .and_then(|(_, target_workspace)| {
9044 cx.update(|cx| {
9045 let workspace = target_workspace.read(cx);
9046 let project = workspace.project.read(cx);
9047 let path_style = workspace.path_style(cx);
9048 Some(!abs_paths.iter().any(|path| {
9049 let path = util::paths::SanitizedPath::new(path);
9050 project.worktrees(cx).any(|worktree| {
9051 let worktree = worktree.read(cx);
9052 let abs_path = worktree.abs_path();
9053 path_style
9054 .strip_prefix(path.as_ref(), abs_path.as_ref())
9055 .and_then(|rel| worktree.entry_for_path(&rel))
9056 .is_some_and(|e| e.is_dir())
9057 })
9058 }))
9059 })
9060 })
9061 .unwrap_or(false);
9062
9063 if open_options.open_new_workspace.is_none()
9064 && existing.is_some()
9065 && open_options.wait
9066 && all_paths_are_files
9067 {
9068 cx.update(|cx| {
9069 let windows = workspace_windows_for_location(location, cx);
9070 let window = cx
9071 .active_window()
9072 .and_then(|window| window.downcast::<MultiWorkspace>())
9073 .filter(|window| windows.contains(window))
9074 .or_else(|| windows.into_iter().next());
9075 if let Some(window) = window {
9076 if let Ok(multi_workspace) = window.read(cx) {
9077 let active_workspace = multi_workspace.workspace().clone();
9078 existing = Some((window, active_workspace));
9079 open_visible = OpenVisible::None;
9080 }
9081 }
9082 });
9083 }
9084 }
9085 (existing, open_visible)
9086}
9087
9088#[derive(Default, Clone)]
9089pub struct OpenOptions {
9090 pub visible: Option<OpenVisible>,
9091 pub focus: Option<bool>,
9092 pub open_new_workspace: Option<bool>,
9093 pub wait: bool,
9094 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
9095 pub env: Option<HashMap<String, String>>,
9096}
9097
9098/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
9099/// or [`Workspace::open_workspace_for_paths`].
9100pub struct OpenResult {
9101 pub window: WindowHandle<MultiWorkspace>,
9102 pub workspace: Entity<Workspace>,
9103 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
9104}
9105
9106/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
9107pub fn open_workspace_by_id(
9108 workspace_id: WorkspaceId,
9109 app_state: Arc<AppState>,
9110 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9111 cx: &mut App,
9112) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
9113 let project_handle = Project::local(
9114 app_state.client.clone(),
9115 app_state.node_runtime.clone(),
9116 app_state.user_store.clone(),
9117 app_state.languages.clone(),
9118 app_state.fs.clone(),
9119 None,
9120 project::LocalProjectFlags {
9121 init_worktree_trust: true,
9122 ..project::LocalProjectFlags::default()
9123 },
9124 cx,
9125 );
9126
9127 let db = WorkspaceDb::global(cx);
9128 let kvp = db::kvp::KeyValueStore::global(cx);
9129 cx.spawn(async move |cx| {
9130 let serialized_workspace = db
9131 .workspace_for_id(workspace_id)
9132 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
9133
9134 let centered_layout = serialized_workspace.centered_layout;
9135
9136 let (window, workspace) = if let Some(window) = requesting_window {
9137 let workspace = window.update(cx, |multi_workspace, window, cx| {
9138 let workspace = cx.new(|cx| {
9139 let mut workspace = Workspace::new(
9140 Some(workspace_id),
9141 project_handle.clone(),
9142 app_state.clone(),
9143 window,
9144 cx,
9145 );
9146 workspace.centered_layout = centered_layout;
9147 workspace
9148 });
9149 multi_workspace.add_workspace(workspace.clone(), cx);
9150 workspace
9151 })?;
9152 (window, workspace)
9153 } else {
9154 let window_bounds_override = window_bounds_env_override();
9155
9156 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
9157 (Some(WindowBounds::Windowed(bounds)), None)
9158 } else if let Some(display) = serialized_workspace.display
9159 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
9160 {
9161 (Some(bounds.0), Some(display))
9162 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
9163 (Some(bounds), Some(display))
9164 } else {
9165 (None, None)
9166 };
9167
9168 let options = cx.update(|cx| {
9169 let mut options = (app_state.build_window_options)(display, cx);
9170 options.window_bounds = window_bounds;
9171 options
9172 });
9173
9174 let window = cx.open_window(options, {
9175 let app_state = app_state.clone();
9176 let project_handle = project_handle.clone();
9177 move |window, cx| {
9178 let workspace = cx.new(|cx| {
9179 let mut workspace = Workspace::new(
9180 Some(workspace_id),
9181 project_handle,
9182 app_state,
9183 window,
9184 cx,
9185 );
9186 workspace.centered_layout = centered_layout;
9187 workspace
9188 });
9189 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9190 }
9191 })?;
9192
9193 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9194 multi_workspace.workspace().clone()
9195 })?;
9196
9197 (window, workspace)
9198 };
9199
9200 notify_if_database_failed(window, cx);
9201
9202 // Restore items from the serialized workspace
9203 window
9204 .update(cx, |_, window, cx| {
9205 workspace.update(cx, |_workspace, cx| {
9206 open_items(Some(serialized_workspace), vec![], window, cx)
9207 })
9208 })?
9209 .await?;
9210
9211 window.update(cx, |_, window, cx| {
9212 workspace.update(cx, |workspace, cx| {
9213 workspace.serialize_workspace(window, cx);
9214 });
9215 })?;
9216
9217 Ok(window)
9218 })
9219}
9220
9221#[allow(clippy::type_complexity)]
9222pub fn open_paths(
9223 abs_paths: &[PathBuf],
9224 app_state: Arc<AppState>,
9225 open_options: OpenOptions,
9226 cx: &mut App,
9227) -> Task<anyhow::Result<OpenResult>> {
9228 let abs_paths = abs_paths.to_vec();
9229 #[cfg(target_os = "windows")]
9230 let wsl_path = abs_paths
9231 .iter()
9232 .find_map(|p| util::paths::WslPath::from_path(p));
9233
9234 cx.spawn(async move |cx| {
9235 let (mut existing, mut open_visible) = find_existing_workspace(
9236 &abs_paths,
9237 &open_options,
9238 &SerializedWorkspaceLocation::Local,
9239 cx,
9240 )
9241 .await;
9242
9243 // Fallback: if no workspace contains the paths and all paths are files,
9244 // prefer an existing local workspace window (active window first).
9245 if open_options.open_new_workspace.is_none() && existing.is_none() {
9246 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9247 let all_metadatas = futures::future::join_all(all_paths)
9248 .await
9249 .into_iter()
9250 .filter_map(|result| result.ok().flatten())
9251 .collect::<Vec<_>>();
9252
9253 if all_metadatas.iter().all(|file| !file.is_dir) {
9254 cx.update(|cx| {
9255 let windows = workspace_windows_for_location(
9256 &SerializedWorkspaceLocation::Local,
9257 cx,
9258 );
9259 let window = cx
9260 .active_window()
9261 .and_then(|window| window.downcast::<MultiWorkspace>())
9262 .filter(|window| windows.contains(window))
9263 .or_else(|| windows.into_iter().next());
9264 if let Some(window) = window {
9265 if let Ok(multi_workspace) = window.read(cx) {
9266 let active_workspace = multi_workspace.workspace().clone();
9267 existing = Some((window, active_workspace));
9268 open_visible = OpenVisible::None;
9269 }
9270 }
9271 });
9272 }
9273 }
9274
9275 let result = if let Some((existing, target_workspace)) = existing {
9276 let open_task = existing
9277 .update(cx, |multi_workspace, window, cx| {
9278 window.activate_window();
9279 multi_workspace.activate(target_workspace.clone(), cx);
9280 target_workspace.update(cx, |workspace, cx| {
9281 workspace.open_paths(
9282 abs_paths,
9283 OpenOptions {
9284 visible: Some(open_visible),
9285 ..Default::default()
9286 },
9287 None,
9288 window,
9289 cx,
9290 )
9291 })
9292 })?
9293 .await;
9294
9295 _ = existing.update(cx, |multi_workspace, _, cx| {
9296 let workspace = multi_workspace.workspace().clone();
9297 workspace.update(cx, |workspace, cx| {
9298 for item in open_task.iter().flatten() {
9299 if let Err(e) = item {
9300 workspace.show_error(&e, cx);
9301 }
9302 }
9303 });
9304 });
9305
9306 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9307 } else {
9308 let result = cx
9309 .update(move |cx| {
9310 Workspace::new_local(
9311 abs_paths,
9312 app_state.clone(),
9313 open_options.replace_window,
9314 open_options.env,
9315 None,
9316 true,
9317 cx,
9318 )
9319 })
9320 .await;
9321
9322 if let Ok(ref result) = result {
9323 result.window
9324 .update(cx, |_, window, _cx| {
9325 window.activate_window();
9326 })
9327 .log_err();
9328 }
9329
9330 result
9331 };
9332
9333 #[cfg(target_os = "windows")]
9334 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9335 && let Ok(ref result) = result
9336 {
9337 result.window
9338 .update(cx, move |multi_workspace, _window, cx| {
9339 struct OpenInWsl;
9340 let workspace = multi_workspace.workspace().clone();
9341 workspace.update(cx, |workspace, cx| {
9342 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9343 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9344 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9345 cx.new(move |cx| {
9346 MessageNotification::new(msg, cx)
9347 .primary_message("Open in WSL")
9348 .primary_icon(IconName::FolderOpen)
9349 .primary_on_click(move |window, cx| {
9350 window.dispatch_action(Box::new(remote::OpenWslPath {
9351 distro: remote::WslConnectionOptions {
9352 distro_name: distro.clone(),
9353 user: None,
9354 },
9355 paths: vec![path.clone().into()],
9356 }), cx)
9357 })
9358 })
9359 });
9360 });
9361 })
9362 .unwrap();
9363 };
9364 result
9365 })
9366}
9367
9368pub fn open_new(
9369 open_options: OpenOptions,
9370 app_state: Arc<AppState>,
9371 cx: &mut App,
9372 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9373) -> Task<anyhow::Result<()>> {
9374 let task = Workspace::new_local(
9375 Vec::new(),
9376 app_state,
9377 open_options.replace_window,
9378 open_options.env,
9379 Some(Box::new(init)),
9380 true,
9381 cx,
9382 );
9383 cx.spawn(async move |cx| {
9384 let OpenResult { window, .. } = task.await?;
9385 window
9386 .update(cx, |_, window, _cx| {
9387 window.activate_window();
9388 })
9389 .ok();
9390 Ok(())
9391 })
9392}
9393
9394pub fn create_and_open_local_file(
9395 path: &'static Path,
9396 window: &mut Window,
9397 cx: &mut Context<Workspace>,
9398 default_content: impl 'static + Send + FnOnce() -> Rope,
9399) -> Task<Result<Box<dyn ItemHandle>>> {
9400 cx.spawn_in(window, async move |workspace, cx| {
9401 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9402 if !fs.is_file(path).await {
9403 fs.create_file(path, Default::default()).await?;
9404 fs.save(path, &default_content(), Default::default())
9405 .await?;
9406 }
9407
9408 workspace
9409 .update_in(cx, |workspace, window, cx| {
9410 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9411 let path = workspace
9412 .project
9413 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9414 cx.spawn_in(window, async move |workspace, cx| {
9415 let path = path.await?;
9416
9417 let path = fs.canonicalize(&path).await.unwrap_or(path);
9418
9419 let mut items = workspace
9420 .update_in(cx, |workspace, window, cx| {
9421 workspace.open_paths(
9422 vec![path.to_path_buf()],
9423 OpenOptions {
9424 visible: Some(OpenVisible::None),
9425 ..Default::default()
9426 },
9427 None,
9428 window,
9429 cx,
9430 )
9431 })?
9432 .await;
9433 let item = items.pop().flatten();
9434 item.with_context(|| format!("path {path:?} is not a file"))?
9435 })
9436 })
9437 })?
9438 .await?
9439 .await
9440 })
9441}
9442
9443pub fn open_remote_project_with_new_connection(
9444 window: WindowHandle<MultiWorkspace>,
9445 remote_connection: Arc<dyn RemoteConnection>,
9446 cancel_rx: oneshot::Receiver<()>,
9447 delegate: Arc<dyn RemoteClientDelegate>,
9448 app_state: Arc<AppState>,
9449 paths: Vec<PathBuf>,
9450 cx: &mut App,
9451) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9452 cx.spawn(async move |cx| {
9453 let (workspace_id, serialized_workspace) =
9454 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9455 .await?;
9456
9457 let session = match cx
9458 .update(|cx| {
9459 remote::RemoteClient::new(
9460 ConnectionIdentifier::Workspace(workspace_id.0),
9461 remote_connection,
9462 cancel_rx,
9463 delegate,
9464 cx,
9465 )
9466 })
9467 .await?
9468 {
9469 Some(result) => result,
9470 None => return Ok(Vec::new()),
9471 };
9472
9473 let project = cx.update(|cx| {
9474 project::Project::remote(
9475 session,
9476 app_state.client.clone(),
9477 app_state.node_runtime.clone(),
9478 app_state.user_store.clone(),
9479 app_state.languages.clone(),
9480 app_state.fs.clone(),
9481 true,
9482 cx,
9483 )
9484 });
9485
9486 open_remote_project_inner(
9487 project,
9488 paths,
9489 workspace_id,
9490 serialized_workspace,
9491 app_state,
9492 window,
9493 cx,
9494 )
9495 .await
9496 })
9497}
9498
9499pub fn open_remote_project_with_existing_connection(
9500 connection_options: RemoteConnectionOptions,
9501 project: Entity<Project>,
9502 paths: Vec<PathBuf>,
9503 app_state: Arc<AppState>,
9504 window: WindowHandle<MultiWorkspace>,
9505 cx: &mut AsyncApp,
9506) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9507 cx.spawn(async move |cx| {
9508 let (workspace_id, serialized_workspace) =
9509 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9510
9511 open_remote_project_inner(
9512 project,
9513 paths,
9514 workspace_id,
9515 serialized_workspace,
9516 app_state,
9517 window,
9518 cx,
9519 )
9520 .await
9521 })
9522}
9523
9524async fn open_remote_project_inner(
9525 project: Entity<Project>,
9526 paths: Vec<PathBuf>,
9527 workspace_id: WorkspaceId,
9528 serialized_workspace: Option<SerializedWorkspace>,
9529 app_state: Arc<AppState>,
9530 window: WindowHandle<MultiWorkspace>,
9531 cx: &mut AsyncApp,
9532) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9533 let db = cx.update(|cx| WorkspaceDb::global(cx));
9534 let toolchains = db.toolchains(workspace_id).await?;
9535 for (toolchain, worktree_path, path) in toolchains {
9536 project
9537 .update(cx, |this, cx| {
9538 let Some(worktree_id) =
9539 this.find_worktree(&worktree_path, cx)
9540 .and_then(|(worktree, rel_path)| {
9541 if rel_path.is_empty() {
9542 Some(worktree.read(cx).id())
9543 } else {
9544 None
9545 }
9546 })
9547 else {
9548 return Task::ready(None);
9549 };
9550
9551 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9552 })
9553 .await;
9554 }
9555 let mut project_paths_to_open = vec![];
9556 let mut project_path_errors = vec![];
9557
9558 for path in paths {
9559 let result = cx
9560 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9561 .await;
9562 match result {
9563 Ok((_, project_path)) => {
9564 project_paths_to_open.push((path.clone(), Some(project_path)));
9565 }
9566 Err(error) => {
9567 project_path_errors.push(error);
9568 }
9569 };
9570 }
9571
9572 if project_paths_to_open.is_empty() {
9573 return Err(project_path_errors.pop().context("no paths given")?);
9574 }
9575
9576 let workspace = window.update(cx, |multi_workspace, window, cx| {
9577 telemetry::event!("SSH Project Opened");
9578
9579 let new_workspace = cx.new(|cx| {
9580 let mut workspace =
9581 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9582 workspace.update_history(cx);
9583
9584 if let Some(ref serialized) = serialized_workspace {
9585 workspace.centered_layout = serialized.centered_layout;
9586 }
9587
9588 workspace
9589 });
9590
9591 multi_workspace.activate(new_workspace.clone(), cx);
9592 new_workspace
9593 })?;
9594
9595 let items = window
9596 .update(cx, |_, window, cx| {
9597 window.activate_window();
9598 workspace.update(cx, |_workspace, cx| {
9599 open_items(serialized_workspace, project_paths_to_open, window, cx)
9600 })
9601 })?
9602 .await?;
9603
9604 workspace.update(cx, |workspace, cx| {
9605 for error in project_path_errors {
9606 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9607 if let Some(path) = error.error_tag("path") {
9608 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9609 }
9610 } else {
9611 workspace.show_error(&error, cx)
9612 }
9613 }
9614 });
9615
9616 Ok(items.into_iter().map(|item| item?.ok()).collect())
9617}
9618
9619fn deserialize_remote_project(
9620 connection_options: RemoteConnectionOptions,
9621 paths: Vec<PathBuf>,
9622 cx: &AsyncApp,
9623) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9624 let db = cx.update(|cx| WorkspaceDb::global(cx));
9625 cx.background_spawn(async move {
9626 let remote_connection_id = db
9627 .get_or_create_remote_connection(connection_options)
9628 .await?;
9629
9630 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9631
9632 let workspace_id = if let Some(workspace_id) =
9633 serialized_workspace.as_ref().map(|workspace| workspace.id)
9634 {
9635 workspace_id
9636 } else {
9637 db.next_id().await?
9638 };
9639
9640 Ok((workspace_id, serialized_workspace))
9641 })
9642}
9643
9644pub fn join_in_room_project(
9645 project_id: u64,
9646 follow_user_id: u64,
9647 app_state: Arc<AppState>,
9648 cx: &mut App,
9649) -> Task<Result<()>> {
9650 let windows = cx.windows();
9651 cx.spawn(async move |cx| {
9652 let existing_window_and_workspace: Option<(
9653 WindowHandle<MultiWorkspace>,
9654 Entity<Workspace>,
9655 )> = windows.into_iter().find_map(|window_handle| {
9656 window_handle
9657 .downcast::<MultiWorkspace>()
9658 .and_then(|window_handle| {
9659 window_handle
9660 .update(cx, |multi_workspace, _window, cx| {
9661 for workspace in multi_workspace.workspaces() {
9662 if workspace.read(cx).project().read(cx).remote_id()
9663 == Some(project_id)
9664 {
9665 return Some((window_handle, workspace.clone()));
9666 }
9667 }
9668 None
9669 })
9670 .unwrap_or(None)
9671 })
9672 });
9673
9674 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9675 existing_window_and_workspace
9676 {
9677 existing_window
9678 .update(cx, |multi_workspace, _, cx| {
9679 multi_workspace.activate(target_workspace, cx);
9680 })
9681 .ok();
9682 existing_window
9683 } else {
9684 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9685 let project = cx
9686 .update(|cx| {
9687 active_call.0.join_project(
9688 project_id,
9689 app_state.languages.clone(),
9690 app_state.fs.clone(),
9691 cx,
9692 )
9693 })
9694 .await?;
9695
9696 let window_bounds_override = window_bounds_env_override();
9697 cx.update(|cx| {
9698 let mut options = (app_state.build_window_options)(None, cx);
9699 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9700 cx.open_window(options, |window, cx| {
9701 let workspace = cx.new(|cx| {
9702 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9703 });
9704 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9705 })
9706 })?
9707 };
9708
9709 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9710 cx.activate(true);
9711 window.activate_window();
9712
9713 // We set the active workspace above, so this is the correct workspace.
9714 let workspace = multi_workspace.workspace().clone();
9715 workspace.update(cx, |workspace, cx| {
9716 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9717 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9718 .or_else(|| {
9719 // If we couldn't follow the given user, follow the host instead.
9720 let collaborator = workspace
9721 .project()
9722 .read(cx)
9723 .collaborators()
9724 .values()
9725 .find(|collaborator| collaborator.is_host)?;
9726 Some(collaborator.peer_id)
9727 });
9728
9729 if let Some(follow_peer_id) = follow_peer_id {
9730 workspace.follow(follow_peer_id, window, cx);
9731 }
9732 });
9733 })?;
9734
9735 anyhow::Ok(())
9736 })
9737}
9738
9739pub fn reload(cx: &mut App) {
9740 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9741 let mut workspace_windows = cx
9742 .windows()
9743 .into_iter()
9744 .filter_map(|window| window.downcast::<MultiWorkspace>())
9745 .collect::<Vec<_>>();
9746
9747 // If multiple windows have unsaved changes, and need a save prompt,
9748 // prompt in the active window before switching to a different window.
9749 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9750
9751 let mut prompt = None;
9752 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9753 prompt = window
9754 .update(cx, |_, window, cx| {
9755 window.prompt(
9756 PromptLevel::Info,
9757 "Are you sure you want to restart?",
9758 None,
9759 &["Restart", "Cancel"],
9760 cx,
9761 )
9762 })
9763 .ok();
9764 }
9765
9766 cx.spawn(async move |cx| {
9767 if let Some(prompt) = prompt {
9768 let answer = prompt.await?;
9769 if answer != 0 {
9770 return anyhow::Ok(());
9771 }
9772 }
9773
9774 // If the user cancels any save prompt, then keep the app open.
9775 for window in workspace_windows {
9776 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9777 let workspace = multi_workspace.workspace().clone();
9778 workspace.update(cx, |workspace, cx| {
9779 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9780 })
9781 }) && !should_close.await?
9782 {
9783 return anyhow::Ok(());
9784 }
9785 }
9786 cx.update(|cx| cx.restart());
9787 anyhow::Ok(())
9788 })
9789 .detach_and_log_err(cx);
9790}
9791
9792fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9793 let mut parts = value.split(',');
9794 let x: usize = parts.next()?.parse().ok()?;
9795 let y: usize = parts.next()?.parse().ok()?;
9796 Some(point(px(x as f32), px(y as f32)))
9797}
9798
9799fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9800 let mut parts = value.split(',');
9801 let width: usize = parts.next()?.parse().ok()?;
9802 let height: usize = parts.next()?.parse().ok()?;
9803 Some(size(px(width as f32), px(height as f32)))
9804}
9805
9806/// Add client-side decorations (rounded corners, shadows, resize handling) when
9807/// appropriate.
9808///
9809/// The `border_radius_tiling` parameter allows overriding which corners get
9810/// rounded, independently of the actual window tiling state. This is used
9811/// specifically for the workspace switcher sidebar: when the sidebar is open,
9812/// we want square corners on the left (so the sidebar appears flush with the
9813/// window edge) but we still need the shadow padding for proper visual
9814/// appearance. Unlike actual window tiling, this only affects border radius -
9815/// not padding or shadows.
9816pub fn client_side_decorations(
9817 element: impl IntoElement,
9818 window: &mut Window,
9819 cx: &mut App,
9820 border_radius_tiling: Tiling,
9821) -> Stateful<Div> {
9822 const BORDER_SIZE: Pixels = px(1.0);
9823 let decorations = window.window_decorations();
9824 let tiling = match decorations {
9825 Decorations::Server => Tiling::default(),
9826 Decorations::Client { tiling } => tiling,
9827 };
9828
9829 match decorations {
9830 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9831 Decorations::Server => window.set_client_inset(px(0.0)),
9832 }
9833
9834 struct GlobalResizeEdge(ResizeEdge);
9835 impl Global for GlobalResizeEdge {}
9836
9837 div()
9838 .id("window-backdrop")
9839 .bg(transparent_black())
9840 .map(|div| match decorations {
9841 Decorations::Server => div,
9842 Decorations::Client { .. } => div
9843 .when(
9844 !(tiling.top
9845 || tiling.right
9846 || border_radius_tiling.top
9847 || border_radius_tiling.right),
9848 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9849 )
9850 .when(
9851 !(tiling.top
9852 || tiling.left
9853 || border_radius_tiling.top
9854 || border_radius_tiling.left),
9855 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9856 )
9857 .when(
9858 !(tiling.bottom
9859 || tiling.right
9860 || border_radius_tiling.bottom
9861 || border_radius_tiling.right),
9862 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9863 )
9864 .when(
9865 !(tiling.bottom
9866 || tiling.left
9867 || border_radius_tiling.bottom
9868 || border_radius_tiling.left),
9869 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9870 )
9871 .when(!tiling.top, |div| {
9872 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9873 })
9874 .when(!tiling.bottom, |div| {
9875 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9876 })
9877 .when(!tiling.left, |div| {
9878 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9879 })
9880 .when(!tiling.right, |div| {
9881 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9882 })
9883 .on_mouse_move(move |e, window, cx| {
9884 let size = window.window_bounds().get_bounds().size;
9885 let pos = e.position;
9886
9887 let new_edge =
9888 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9889
9890 let edge = cx.try_global::<GlobalResizeEdge>();
9891 if new_edge != edge.map(|edge| edge.0) {
9892 window
9893 .window_handle()
9894 .update(cx, |workspace, _, cx| {
9895 cx.notify(workspace.entity_id());
9896 })
9897 .ok();
9898 }
9899 })
9900 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9901 let size = window.window_bounds().get_bounds().size;
9902 let pos = e.position;
9903
9904 let edge = match resize_edge(
9905 pos,
9906 theme::CLIENT_SIDE_DECORATION_SHADOW,
9907 size,
9908 tiling,
9909 ) {
9910 Some(value) => value,
9911 None => return,
9912 };
9913
9914 window.start_window_resize(edge);
9915 }),
9916 })
9917 .size_full()
9918 .child(
9919 div()
9920 .cursor(CursorStyle::Arrow)
9921 .map(|div| match decorations {
9922 Decorations::Server => div,
9923 Decorations::Client { .. } => div
9924 .border_color(cx.theme().colors().border)
9925 .when(
9926 !(tiling.top
9927 || tiling.right
9928 || border_radius_tiling.top
9929 || border_radius_tiling.right),
9930 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9931 )
9932 .when(
9933 !(tiling.top
9934 || tiling.left
9935 || border_radius_tiling.top
9936 || border_radius_tiling.left),
9937 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9938 )
9939 .when(
9940 !(tiling.bottom
9941 || tiling.right
9942 || border_radius_tiling.bottom
9943 || border_radius_tiling.right),
9944 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9945 )
9946 .when(
9947 !(tiling.bottom
9948 || tiling.left
9949 || border_radius_tiling.bottom
9950 || border_radius_tiling.left),
9951 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9952 )
9953 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9954 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9955 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9956 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9957 .when(!tiling.is_tiled(), |div| {
9958 div.shadow(vec![gpui::BoxShadow {
9959 color: Hsla {
9960 h: 0.,
9961 s: 0.,
9962 l: 0.,
9963 a: 0.4,
9964 },
9965 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9966 spread_radius: px(0.),
9967 offset: point(px(0.0), px(0.0)),
9968 }])
9969 }),
9970 })
9971 .on_mouse_move(|_e, _, cx| {
9972 cx.stop_propagation();
9973 })
9974 .size_full()
9975 .child(element),
9976 )
9977 .map(|div| match decorations {
9978 Decorations::Server => div,
9979 Decorations::Client { tiling, .. } => div.child(
9980 canvas(
9981 |_bounds, window, _| {
9982 window.insert_hitbox(
9983 Bounds::new(
9984 point(px(0.0), px(0.0)),
9985 window.window_bounds().get_bounds().size,
9986 ),
9987 HitboxBehavior::Normal,
9988 )
9989 },
9990 move |_bounds, hitbox, window, cx| {
9991 let mouse = window.mouse_position();
9992 let size = window.window_bounds().get_bounds().size;
9993 let Some(edge) =
9994 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
9995 else {
9996 return;
9997 };
9998 cx.set_global(GlobalResizeEdge(edge));
9999 window.set_cursor_style(
10000 match edge {
10001 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10002 ResizeEdge::Left | ResizeEdge::Right => {
10003 CursorStyle::ResizeLeftRight
10004 }
10005 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10006 CursorStyle::ResizeUpLeftDownRight
10007 }
10008 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10009 CursorStyle::ResizeUpRightDownLeft
10010 }
10011 },
10012 &hitbox,
10013 );
10014 },
10015 )
10016 .size_full()
10017 .absolute(),
10018 ),
10019 })
10020}
10021
10022fn resize_edge(
10023 pos: Point<Pixels>,
10024 shadow_size: Pixels,
10025 window_size: Size<Pixels>,
10026 tiling: Tiling,
10027) -> Option<ResizeEdge> {
10028 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10029 if bounds.contains(&pos) {
10030 return None;
10031 }
10032
10033 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10034 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10035 if !tiling.top && top_left_bounds.contains(&pos) {
10036 return Some(ResizeEdge::TopLeft);
10037 }
10038
10039 let top_right_bounds = Bounds::new(
10040 Point::new(window_size.width - corner_size.width, px(0.)),
10041 corner_size,
10042 );
10043 if !tiling.top && top_right_bounds.contains(&pos) {
10044 return Some(ResizeEdge::TopRight);
10045 }
10046
10047 let bottom_left_bounds = Bounds::new(
10048 Point::new(px(0.), window_size.height - corner_size.height),
10049 corner_size,
10050 );
10051 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10052 return Some(ResizeEdge::BottomLeft);
10053 }
10054
10055 let bottom_right_bounds = Bounds::new(
10056 Point::new(
10057 window_size.width - corner_size.width,
10058 window_size.height - corner_size.height,
10059 ),
10060 corner_size,
10061 );
10062 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10063 return Some(ResizeEdge::BottomRight);
10064 }
10065
10066 if !tiling.top && pos.y < shadow_size {
10067 Some(ResizeEdge::Top)
10068 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10069 Some(ResizeEdge::Bottom)
10070 } else if !tiling.left && pos.x < shadow_size {
10071 Some(ResizeEdge::Left)
10072 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10073 Some(ResizeEdge::Right)
10074 } else {
10075 None
10076 }
10077}
10078
10079fn join_pane_into_active(
10080 active_pane: &Entity<Pane>,
10081 pane: &Entity<Pane>,
10082 window: &mut Window,
10083 cx: &mut App,
10084) {
10085 if pane == active_pane {
10086 } else if pane.read(cx).items_len() == 0 {
10087 pane.update(cx, |_, cx| {
10088 cx.emit(pane::Event::Remove {
10089 focus_on_pane: None,
10090 });
10091 })
10092 } else {
10093 move_all_items(pane, active_pane, window, cx);
10094 }
10095}
10096
10097fn move_all_items(
10098 from_pane: &Entity<Pane>,
10099 to_pane: &Entity<Pane>,
10100 window: &mut Window,
10101 cx: &mut App,
10102) {
10103 let destination_is_different = from_pane != to_pane;
10104 let mut moved_items = 0;
10105 for (item_ix, item_handle) in from_pane
10106 .read(cx)
10107 .items()
10108 .enumerate()
10109 .map(|(ix, item)| (ix, item.clone()))
10110 .collect::<Vec<_>>()
10111 {
10112 let ix = item_ix - moved_items;
10113 if destination_is_different {
10114 // Close item from previous pane
10115 from_pane.update(cx, |source, cx| {
10116 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10117 });
10118 moved_items += 1;
10119 }
10120
10121 // This automatically removes duplicate items in the pane
10122 to_pane.update(cx, |destination, cx| {
10123 destination.add_item(item_handle, true, true, None, window, cx);
10124 window.focus(&destination.focus_handle(cx), cx)
10125 });
10126 }
10127}
10128
10129pub fn move_item(
10130 source: &Entity<Pane>,
10131 destination: &Entity<Pane>,
10132 item_id_to_move: EntityId,
10133 destination_index: usize,
10134 activate: bool,
10135 window: &mut Window,
10136 cx: &mut App,
10137) {
10138 let Some((item_ix, item_handle)) = source
10139 .read(cx)
10140 .items()
10141 .enumerate()
10142 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10143 .map(|(ix, item)| (ix, item.clone()))
10144 else {
10145 // Tab was closed during drag
10146 return;
10147 };
10148
10149 if source != destination {
10150 // Close item from previous pane
10151 source.update(cx, |source, cx| {
10152 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10153 });
10154 }
10155
10156 // This automatically removes duplicate items in the pane
10157 destination.update(cx, |destination, cx| {
10158 destination.add_item_inner(
10159 item_handle,
10160 activate,
10161 activate,
10162 activate,
10163 Some(destination_index),
10164 window,
10165 cx,
10166 );
10167 if activate {
10168 window.focus(&destination.focus_handle(cx), cx)
10169 }
10170 });
10171}
10172
10173pub fn move_active_item(
10174 source: &Entity<Pane>,
10175 destination: &Entity<Pane>,
10176 focus_destination: bool,
10177 close_if_empty: bool,
10178 window: &mut Window,
10179 cx: &mut App,
10180) {
10181 if source == destination {
10182 return;
10183 }
10184 let Some(active_item) = source.read(cx).active_item() else {
10185 return;
10186 };
10187 source.update(cx, |source_pane, cx| {
10188 let item_id = active_item.item_id();
10189 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10190 destination.update(cx, |target_pane, cx| {
10191 target_pane.add_item(
10192 active_item,
10193 focus_destination,
10194 focus_destination,
10195 Some(target_pane.items_len()),
10196 window,
10197 cx,
10198 );
10199 });
10200 });
10201}
10202
10203pub fn clone_active_item(
10204 workspace_id: Option<WorkspaceId>,
10205 source: &Entity<Pane>,
10206 destination: &Entity<Pane>,
10207 focus_destination: bool,
10208 window: &mut Window,
10209 cx: &mut App,
10210) {
10211 if source == destination {
10212 return;
10213 }
10214 let Some(active_item) = source.read(cx).active_item() else {
10215 return;
10216 };
10217 if !active_item.can_split(cx) {
10218 return;
10219 }
10220 let destination = destination.downgrade();
10221 let task = active_item.clone_on_split(workspace_id, window, cx);
10222 window
10223 .spawn(cx, async move |cx| {
10224 let Some(clone) = task.await else {
10225 return;
10226 };
10227 destination
10228 .update_in(cx, |target_pane, window, cx| {
10229 target_pane.add_item(
10230 clone,
10231 focus_destination,
10232 focus_destination,
10233 Some(target_pane.items_len()),
10234 window,
10235 cx,
10236 );
10237 })
10238 .log_err();
10239 })
10240 .detach();
10241}
10242
10243#[derive(Debug)]
10244pub struct WorkspacePosition {
10245 pub window_bounds: Option<WindowBounds>,
10246 pub display: Option<Uuid>,
10247 pub centered_layout: bool,
10248}
10249
10250pub fn remote_workspace_position_from_db(
10251 connection_options: RemoteConnectionOptions,
10252 paths_to_open: &[PathBuf],
10253 cx: &App,
10254) -> Task<Result<WorkspacePosition>> {
10255 let paths = paths_to_open.to_vec();
10256 let db = WorkspaceDb::global(cx);
10257 let kvp = db::kvp::KeyValueStore::global(cx);
10258
10259 cx.background_spawn(async move {
10260 let remote_connection_id = db
10261 .get_or_create_remote_connection(connection_options)
10262 .await
10263 .context("fetching serialized ssh project")?;
10264 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10265
10266 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10267 (Some(WindowBounds::Windowed(bounds)), None)
10268 } else {
10269 let restorable_bounds = serialized_workspace
10270 .as_ref()
10271 .and_then(|workspace| {
10272 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10273 })
10274 .or_else(|| persistence::read_default_window_bounds(&kvp));
10275
10276 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10277 (Some(serialized_bounds), Some(serialized_display))
10278 } else {
10279 (None, None)
10280 }
10281 };
10282
10283 let centered_layout = serialized_workspace
10284 .as_ref()
10285 .map(|w| w.centered_layout)
10286 .unwrap_or(false);
10287
10288 Ok(WorkspacePosition {
10289 window_bounds,
10290 display,
10291 centered_layout,
10292 })
10293 })
10294}
10295
10296pub fn with_active_or_new_workspace(
10297 cx: &mut App,
10298 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10299) {
10300 match cx
10301 .active_window()
10302 .and_then(|w| w.downcast::<MultiWorkspace>())
10303 {
10304 Some(multi_workspace) => {
10305 cx.defer(move |cx| {
10306 multi_workspace
10307 .update(cx, |multi_workspace, window, cx| {
10308 let workspace = multi_workspace.workspace().clone();
10309 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10310 })
10311 .log_err();
10312 });
10313 }
10314 None => {
10315 let app_state = AppState::global(cx);
10316 if let Some(app_state) = app_state.upgrade() {
10317 open_new(
10318 OpenOptions::default(),
10319 app_state,
10320 cx,
10321 move |workspace, window, cx| f(workspace, window, cx),
10322 )
10323 .detach_and_log_err(cx);
10324 }
10325 }
10326 }
10327}
10328
10329/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10330/// key. This migration path only runs once per panel per workspace.
10331fn load_legacy_panel_size(
10332 panel_key: &str,
10333 dock_position: DockPosition,
10334 workspace: &Workspace,
10335 cx: &mut App,
10336) -> Option<Pixels> {
10337 #[derive(Deserialize)]
10338 struct LegacyPanelState {
10339 #[serde(default)]
10340 width: Option<Pixels>,
10341 #[serde(default)]
10342 height: Option<Pixels>,
10343 }
10344
10345 let workspace_id = workspace
10346 .database_id()
10347 .map(|id| i64::from(id).to_string())
10348 .or_else(|| workspace.session_id())?;
10349
10350 let legacy_key = match panel_key {
10351 "ProjectPanel" => {
10352 format!("{}-{:?}", "ProjectPanel", workspace_id)
10353 }
10354 "OutlinePanel" => {
10355 format!("{}-{:?}", "OutlinePanel", workspace_id)
10356 }
10357 "GitPanel" => {
10358 format!("{}-{:?}", "GitPanel", workspace_id)
10359 }
10360 "TerminalPanel" => {
10361 format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10362 }
10363 _ => return None,
10364 };
10365
10366 let kvp = db::kvp::KeyValueStore::global(cx);
10367 let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10368 let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10369 let size = match dock_position {
10370 DockPosition::Bottom => state.height,
10371 DockPosition::Left | DockPosition::Right => state.width,
10372 }?;
10373
10374 cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10375 .detach_and_log_err(cx);
10376
10377 Some(size)
10378}
10379
10380#[cfg(test)]
10381mod tests {
10382 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10383
10384 use super::*;
10385 use crate::{
10386 dock::{PanelEvent, test::TestPanel},
10387 item::{
10388 ItemBufferKind, ItemEvent,
10389 test::{TestItem, TestProjectItem},
10390 },
10391 };
10392 use fs::FakeFs;
10393 use gpui::{
10394 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10395 UpdateGlobal, VisualTestContext, px,
10396 };
10397 use project::{Project, ProjectEntryId};
10398 use serde_json::json;
10399 use settings::SettingsStore;
10400 use util::path;
10401 use util::rel_path::rel_path;
10402
10403 #[gpui::test]
10404 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10405 init_test(cx);
10406
10407 let fs = FakeFs::new(cx.executor());
10408 let project = Project::test(fs, [], cx).await;
10409 let (workspace, cx) =
10410 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10411
10412 // Adding an item with no ambiguity renders the tab without detail.
10413 let item1 = cx.new(|cx| {
10414 let mut item = TestItem::new(cx);
10415 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10416 item
10417 });
10418 workspace.update_in(cx, |workspace, window, cx| {
10419 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10420 });
10421 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10422
10423 // Adding an item that creates ambiguity increases the level of detail on
10424 // both tabs.
10425 let item2 = cx.new_window_entity(|_window, cx| {
10426 let mut item = TestItem::new(cx);
10427 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10428 item
10429 });
10430 workspace.update_in(cx, |workspace, window, cx| {
10431 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10432 });
10433 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10434 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10435
10436 // Adding an item that creates ambiguity increases the level of detail only
10437 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10438 // we stop at the highest detail available.
10439 let item3 = cx.new(|cx| {
10440 let mut item = TestItem::new(cx);
10441 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10442 item
10443 });
10444 workspace.update_in(cx, |workspace, window, cx| {
10445 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10446 });
10447 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10448 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10449 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10450 }
10451
10452 #[gpui::test]
10453 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10454 init_test(cx);
10455
10456 let fs = FakeFs::new(cx.executor());
10457 fs.insert_tree(
10458 "/root1",
10459 json!({
10460 "one.txt": "",
10461 "two.txt": "",
10462 }),
10463 )
10464 .await;
10465 fs.insert_tree(
10466 "/root2",
10467 json!({
10468 "three.txt": "",
10469 }),
10470 )
10471 .await;
10472
10473 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10474 let (workspace, cx) =
10475 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10476 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10477 let worktree_id = project.update(cx, |project, cx| {
10478 project.worktrees(cx).next().unwrap().read(cx).id()
10479 });
10480
10481 let item1 = cx.new(|cx| {
10482 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10483 });
10484 let item2 = cx.new(|cx| {
10485 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10486 });
10487
10488 // Add an item to an empty pane
10489 workspace.update_in(cx, |workspace, window, cx| {
10490 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10491 });
10492 project.update(cx, |project, cx| {
10493 assert_eq!(
10494 project.active_entry(),
10495 project
10496 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10497 .map(|e| e.id)
10498 );
10499 });
10500 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10501
10502 // Add a second item to a non-empty pane
10503 workspace.update_in(cx, |workspace, window, cx| {
10504 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10505 });
10506 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10507 project.update(cx, |project, cx| {
10508 assert_eq!(
10509 project.active_entry(),
10510 project
10511 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10512 .map(|e| e.id)
10513 );
10514 });
10515
10516 // Close the active item
10517 pane.update_in(cx, |pane, window, cx| {
10518 pane.close_active_item(&Default::default(), window, cx)
10519 })
10520 .await
10521 .unwrap();
10522 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10523 project.update(cx, |project, cx| {
10524 assert_eq!(
10525 project.active_entry(),
10526 project
10527 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10528 .map(|e| e.id)
10529 );
10530 });
10531
10532 // Add a project folder
10533 project
10534 .update(cx, |project, cx| {
10535 project.find_or_create_worktree("root2", true, cx)
10536 })
10537 .await
10538 .unwrap();
10539 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10540
10541 // Remove a project folder
10542 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10543 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10544 }
10545
10546 #[gpui::test]
10547 async fn test_close_window(cx: &mut TestAppContext) {
10548 init_test(cx);
10549
10550 let fs = FakeFs::new(cx.executor());
10551 fs.insert_tree("/root", json!({ "one": "" })).await;
10552
10553 let project = Project::test(fs, ["root".as_ref()], cx).await;
10554 let (workspace, cx) =
10555 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10556
10557 // When there are no dirty items, there's nothing to do.
10558 let item1 = cx.new(TestItem::new);
10559 workspace.update_in(cx, |w, window, cx| {
10560 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10561 });
10562 let task = workspace.update_in(cx, |w, window, cx| {
10563 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10564 });
10565 assert!(task.await.unwrap());
10566
10567 // When there are dirty untitled items, prompt to save each one. If the user
10568 // cancels any prompt, then abort.
10569 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10570 let item3 = cx.new(|cx| {
10571 TestItem::new(cx)
10572 .with_dirty(true)
10573 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10574 });
10575 workspace.update_in(cx, |w, window, cx| {
10576 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10577 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10578 });
10579 let task = workspace.update_in(cx, |w, window, cx| {
10580 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10581 });
10582 cx.executor().run_until_parked();
10583 cx.simulate_prompt_answer("Cancel"); // cancel save all
10584 cx.executor().run_until_parked();
10585 assert!(!cx.has_pending_prompt());
10586 assert!(!task.await.unwrap());
10587 }
10588
10589 #[gpui::test]
10590 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10591 init_test(cx);
10592
10593 let fs = FakeFs::new(cx.executor());
10594 fs.insert_tree("/root", json!({ "one": "" })).await;
10595
10596 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10597 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10598 let multi_workspace_handle =
10599 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10600 cx.run_until_parked();
10601
10602 let workspace_a = multi_workspace_handle
10603 .read_with(cx, |mw, _| mw.workspace().clone())
10604 .unwrap();
10605
10606 let workspace_b = multi_workspace_handle
10607 .update(cx, |mw, window, cx| {
10608 mw.test_add_workspace(project_b, window, cx)
10609 })
10610 .unwrap();
10611
10612 // Activate workspace A
10613 multi_workspace_handle
10614 .update(cx, |mw, window, cx| {
10615 mw.activate_index(0, window, cx);
10616 })
10617 .unwrap();
10618
10619 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10620
10621 // Workspace A has a clean item
10622 let item_a = cx.new(TestItem::new);
10623 workspace_a.update_in(cx, |w, window, cx| {
10624 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10625 });
10626
10627 // Workspace B has a dirty item
10628 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10629 workspace_b.update_in(cx, |w, window, cx| {
10630 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10631 });
10632
10633 // Verify workspace A is active
10634 multi_workspace_handle
10635 .read_with(cx, |mw, _| {
10636 assert_eq!(mw.active_workspace_index(), 0);
10637 })
10638 .unwrap();
10639
10640 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10641 multi_workspace_handle
10642 .update(cx, |mw, window, cx| {
10643 mw.close_window(&CloseWindow, window, cx);
10644 })
10645 .unwrap();
10646 cx.run_until_parked();
10647
10648 // Workspace B should now be active since it has dirty items that need attention
10649 multi_workspace_handle
10650 .read_with(cx, |mw, _| {
10651 assert_eq!(
10652 mw.active_workspace_index(),
10653 1,
10654 "workspace B should be activated when it prompts"
10655 );
10656 })
10657 .unwrap();
10658
10659 // User cancels the save prompt from workspace B
10660 cx.simulate_prompt_answer("Cancel");
10661 cx.run_until_parked();
10662
10663 // Window should still exist because workspace B's close was cancelled
10664 assert!(
10665 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10666 "window should still exist after cancelling one workspace's close"
10667 );
10668 }
10669
10670 #[gpui::test]
10671 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10672 init_test(cx);
10673
10674 // Register TestItem as a serializable item
10675 cx.update(|cx| {
10676 register_serializable_item::<TestItem>(cx);
10677 });
10678
10679 let fs = FakeFs::new(cx.executor());
10680 fs.insert_tree("/root", json!({ "one": "" })).await;
10681
10682 let project = Project::test(fs, ["root".as_ref()], cx).await;
10683 let (workspace, cx) =
10684 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10685
10686 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10687 let item1 = cx.new(|cx| {
10688 TestItem::new(cx)
10689 .with_dirty(true)
10690 .with_serialize(|| Some(Task::ready(Ok(()))))
10691 });
10692 let item2 = cx.new(|cx| {
10693 TestItem::new(cx)
10694 .with_dirty(true)
10695 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10696 .with_serialize(|| Some(Task::ready(Ok(()))))
10697 });
10698 workspace.update_in(cx, |w, window, cx| {
10699 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10700 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10701 });
10702 let task = workspace.update_in(cx, |w, window, cx| {
10703 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10704 });
10705 assert!(task.await.unwrap());
10706 }
10707
10708 #[gpui::test]
10709 async fn test_close_pane_items(cx: &mut TestAppContext) {
10710 init_test(cx);
10711
10712 let fs = FakeFs::new(cx.executor());
10713
10714 let project = Project::test(fs, None, cx).await;
10715 let (workspace, cx) =
10716 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10717
10718 let item1 = cx.new(|cx| {
10719 TestItem::new(cx)
10720 .with_dirty(true)
10721 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10722 });
10723 let item2 = cx.new(|cx| {
10724 TestItem::new(cx)
10725 .with_dirty(true)
10726 .with_conflict(true)
10727 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10728 });
10729 let item3 = cx.new(|cx| {
10730 TestItem::new(cx)
10731 .with_dirty(true)
10732 .with_conflict(true)
10733 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10734 });
10735 let item4 = cx.new(|cx| {
10736 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10737 let project_item = TestProjectItem::new_untitled(cx);
10738 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10739 project_item
10740 }])
10741 });
10742 let pane = workspace.update_in(cx, |workspace, window, cx| {
10743 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10744 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10745 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10746 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10747 workspace.active_pane().clone()
10748 });
10749
10750 let close_items = pane.update_in(cx, |pane, window, cx| {
10751 pane.activate_item(1, true, true, window, cx);
10752 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10753 let item1_id = item1.item_id();
10754 let item3_id = item3.item_id();
10755 let item4_id = item4.item_id();
10756 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10757 [item1_id, item3_id, item4_id].contains(&id)
10758 })
10759 });
10760 cx.executor().run_until_parked();
10761
10762 assert!(cx.has_pending_prompt());
10763 cx.simulate_prompt_answer("Save all");
10764
10765 cx.executor().run_until_parked();
10766
10767 // Item 1 is saved. There's a prompt to save item 3.
10768 pane.update(cx, |pane, cx| {
10769 assert_eq!(item1.read(cx).save_count, 1);
10770 assert_eq!(item1.read(cx).save_as_count, 0);
10771 assert_eq!(item1.read(cx).reload_count, 0);
10772 assert_eq!(pane.items_len(), 3);
10773 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10774 });
10775 assert!(cx.has_pending_prompt());
10776
10777 // Cancel saving item 3.
10778 cx.simulate_prompt_answer("Discard");
10779 cx.executor().run_until_parked();
10780
10781 // Item 3 is reloaded. There's a prompt to save item 4.
10782 pane.update(cx, |pane, cx| {
10783 assert_eq!(item3.read(cx).save_count, 0);
10784 assert_eq!(item3.read(cx).save_as_count, 0);
10785 assert_eq!(item3.read(cx).reload_count, 1);
10786 assert_eq!(pane.items_len(), 2);
10787 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10788 });
10789
10790 // There's a prompt for a path for item 4.
10791 cx.simulate_new_path_selection(|_| Some(Default::default()));
10792 close_items.await.unwrap();
10793
10794 // The requested items are closed.
10795 pane.update(cx, |pane, cx| {
10796 assert_eq!(item4.read(cx).save_count, 0);
10797 assert_eq!(item4.read(cx).save_as_count, 1);
10798 assert_eq!(item4.read(cx).reload_count, 0);
10799 assert_eq!(pane.items_len(), 1);
10800 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10801 });
10802 }
10803
10804 #[gpui::test]
10805 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10806 init_test(cx);
10807
10808 let fs = FakeFs::new(cx.executor());
10809 let project = Project::test(fs, [], cx).await;
10810 let (workspace, cx) =
10811 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10812
10813 // Create several workspace items with single project entries, and two
10814 // workspace items with multiple project entries.
10815 let single_entry_items = (0..=4)
10816 .map(|project_entry_id| {
10817 cx.new(|cx| {
10818 TestItem::new(cx)
10819 .with_dirty(true)
10820 .with_project_items(&[dirty_project_item(
10821 project_entry_id,
10822 &format!("{project_entry_id}.txt"),
10823 cx,
10824 )])
10825 })
10826 })
10827 .collect::<Vec<_>>();
10828 let item_2_3 = cx.new(|cx| {
10829 TestItem::new(cx)
10830 .with_dirty(true)
10831 .with_buffer_kind(ItemBufferKind::Multibuffer)
10832 .with_project_items(&[
10833 single_entry_items[2].read(cx).project_items[0].clone(),
10834 single_entry_items[3].read(cx).project_items[0].clone(),
10835 ])
10836 });
10837 let item_3_4 = cx.new(|cx| {
10838 TestItem::new(cx)
10839 .with_dirty(true)
10840 .with_buffer_kind(ItemBufferKind::Multibuffer)
10841 .with_project_items(&[
10842 single_entry_items[3].read(cx).project_items[0].clone(),
10843 single_entry_items[4].read(cx).project_items[0].clone(),
10844 ])
10845 });
10846
10847 // Create two panes that contain the following project entries:
10848 // left pane:
10849 // multi-entry items: (2, 3)
10850 // single-entry items: 0, 2, 3, 4
10851 // right pane:
10852 // single-entry items: 4, 1
10853 // multi-entry items: (3, 4)
10854 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10855 let left_pane = workspace.active_pane().clone();
10856 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10857 workspace.add_item_to_active_pane(
10858 single_entry_items[0].boxed_clone(),
10859 None,
10860 true,
10861 window,
10862 cx,
10863 );
10864 workspace.add_item_to_active_pane(
10865 single_entry_items[2].boxed_clone(),
10866 None,
10867 true,
10868 window,
10869 cx,
10870 );
10871 workspace.add_item_to_active_pane(
10872 single_entry_items[3].boxed_clone(),
10873 None,
10874 true,
10875 window,
10876 cx,
10877 );
10878 workspace.add_item_to_active_pane(
10879 single_entry_items[4].boxed_clone(),
10880 None,
10881 true,
10882 window,
10883 cx,
10884 );
10885
10886 let right_pane =
10887 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10888
10889 let boxed_clone = single_entry_items[1].boxed_clone();
10890 let right_pane = window.spawn(cx, async move |cx| {
10891 right_pane.await.inspect(|right_pane| {
10892 right_pane
10893 .update_in(cx, |pane, window, cx| {
10894 pane.add_item(boxed_clone, true, true, None, window, cx);
10895 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10896 })
10897 .unwrap();
10898 })
10899 });
10900
10901 (left_pane, right_pane)
10902 });
10903 let right_pane = right_pane.await.unwrap();
10904 cx.focus(&right_pane);
10905
10906 let close = right_pane.update_in(cx, |pane, window, cx| {
10907 pane.close_all_items(&CloseAllItems::default(), window, cx)
10908 .unwrap()
10909 });
10910 cx.executor().run_until_parked();
10911
10912 let msg = cx.pending_prompt().unwrap().0;
10913 assert!(msg.contains("1.txt"));
10914 assert!(!msg.contains("2.txt"));
10915 assert!(!msg.contains("3.txt"));
10916 assert!(!msg.contains("4.txt"));
10917
10918 // With best-effort close, cancelling item 1 keeps it open but items 4
10919 // and (3,4) still close since their entries exist in left pane.
10920 cx.simulate_prompt_answer("Cancel");
10921 close.await;
10922
10923 right_pane.read_with(cx, |pane, _| {
10924 assert_eq!(pane.items_len(), 1);
10925 });
10926
10927 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10928 left_pane
10929 .update_in(cx, |left_pane, window, cx| {
10930 left_pane.close_item_by_id(
10931 single_entry_items[3].entity_id(),
10932 SaveIntent::Skip,
10933 window,
10934 cx,
10935 )
10936 })
10937 .await
10938 .unwrap();
10939
10940 let close = left_pane.update_in(cx, |pane, window, cx| {
10941 pane.close_all_items(&CloseAllItems::default(), window, cx)
10942 .unwrap()
10943 });
10944 cx.executor().run_until_parked();
10945
10946 let details = cx.pending_prompt().unwrap().1;
10947 assert!(details.contains("0.txt"));
10948 assert!(details.contains("3.txt"));
10949 assert!(details.contains("4.txt"));
10950 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10951 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10952 // assert!(!details.contains("2.txt"));
10953
10954 cx.simulate_prompt_answer("Save all");
10955 cx.executor().run_until_parked();
10956 close.await;
10957
10958 left_pane.read_with(cx, |pane, _| {
10959 assert_eq!(pane.items_len(), 0);
10960 });
10961 }
10962
10963 #[gpui::test]
10964 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10965 init_test(cx);
10966
10967 let fs = FakeFs::new(cx.executor());
10968 let project = Project::test(fs, [], cx).await;
10969 let (workspace, cx) =
10970 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10971 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10972
10973 let item = cx.new(|cx| {
10974 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10975 });
10976 let item_id = item.entity_id();
10977 workspace.update_in(cx, |workspace, window, cx| {
10978 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10979 });
10980
10981 // Autosave on window change.
10982 item.update(cx, |item, cx| {
10983 SettingsStore::update_global(cx, |settings, cx| {
10984 settings.update_user_settings(cx, |settings| {
10985 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10986 })
10987 });
10988 item.is_dirty = true;
10989 });
10990
10991 // Deactivating the window saves the file.
10992 cx.deactivate_window();
10993 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10994
10995 // Re-activating the window doesn't save the file.
10996 cx.update(|window, _| window.activate_window());
10997 cx.executor().run_until_parked();
10998 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10999
11000 // Autosave on focus change.
11001 item.update_in(cx, |item, window, cx| {
11002 cx.focus_self(window);
11003 SettingsStore::update_global(cx, |settings, cx| {
11004 settings.update_user_settings(cx, |settings| {
11005 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11006 })
11007 });
11008 item.is_dirty = true;
11009 });
11010 // Blurring the item saves the file.
11011 item.update_in(cx, |_, window, _| window.blur());
11012 cx.executor().run_until_parked();
11013 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11014
11015 // Deactivating the window still saves the file.
11016 item.update_in(cx, |item, window, cx| {
11017 cx.focus_self(window);
11018 item.is_dirty = true;
11019 });
11020 cx.deactivate_window();
11021 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11022
11023 // Autosave after delay.
11024 item.update(cx, |item, cx| {
11025 SettingsStore::update_global(cx, |settings, cx| {
11026 settings.update_user_settings(cx, |settings| {
11027 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11028 milliseconds: 500.into(),
11029 });
11030 })
11031 });
11032 item.is_dirty = true;
11033 cx.emit(ItemEvent::Edit);
11034 });
11035
11036 // Delay hasn't fully expired, so the file is still dirty and unsaved.
11037 cx.executor().advance_clock(Duration::from_millis(250));
11038 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11039
11040 // After delay expires, the file is saved.
11041 cx.executor().advance_clock(Duration::from_millis(250));
11042 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11043
11044 // Autosave after delay, should save earlier than delay if tab is closed
11045 item.update(cx, |item, cx| {
11046 item.is_dirty = true;
11047 cx.emit(ItemEvent::Edit);
11048 });
11049 cx.executor().advance_clock(Duration::from_millis(250));
11050 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11051
11052 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11053 pane.update_in(cx, |pane, window, cx| {
11054 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11055 })
11056 .await
11057 .unwrap();
11058 assert!(!cx.has_pending_prompt());
11059 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11060
11061 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11062 workspace.update_in(cx, |workspace, window, cx| {
11063 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11064 });
11065 item.update_in(cx, |item, _window, cx| {
11066 item.is_dirty = true;
11067 for project_item in &mut item.project_items {
11068 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11069 }
11070 });
11071 cx.run_until_parked();
11072 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11073
11074 // Autosave on focus change, ensuring closing the tab counts as such.
11075 item.update(cx, |item, cx| {
11076 SettingsStore::update_global(cx, |settings, cx| {
11077 settings.update_user_settings(cx, |settings| {
11078 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11079 })
11080 });
11081 item.is_dirty = true;
11082 for project_item in &mut item.project_items {
11083 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11084 }
11085 });
11086
11087 pane.update_in(cx, |pane, window, cx| {
11088 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11089 })
11090 .await
11091 .unwrap();
11092 assert!(!cx.has_pending_prompt());
11093 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11094
11095 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11096 workspace.update_in(cx, |workspace, window, cx| {
11097 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11098 });
11099 item.update_in(cx, |item, window, cx| {
11100 item.project_items[0].update(cx, |item, _| {
11101 item.entry_id = None;
11102 });
11103 item.is_dirty = true;
11104 window.blur();
11105 });
11106 cx.run_until_parked();
11107 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11108
11109 // Ensure autosave is prevented for deleted files also when closing the buffer.
11110 let _close_items = pane.update_in(cx, |pane, window, cx| {
11111 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11112 });
11113 cx.run_until_parked();
11114 assert!(cx.has_pending_prompt());
11115 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11116 }
11117
11118 #[gpui::test]
11119 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11120 init_test(cx);
11121
11122 let fs = FakeFs::new(cx.executor());
11123 let project = Project::test(fs, [], cx).await;
11124 let (workspace, cx) =
11125 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11126
11127 // Create a multibuffer-like item with two child focus handles,
11128 // simulating individual buffer editors within a multibuffer.
11129 let item = cx.new(|cx| {
11130 TestItem::new(cx)
11131 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11132 .with_child_focus_handles(2, cx)
11133 });
11134 workspace.update_in(cx, |workspace, window, cx| {
11135 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11136 });
11137
11138 // Set autosave to OnFocusChange and focus the first child handle,
11139 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11140 item.update_in(cx, |item, window, cx| {
11141 SettingsStore::update_global(cx, |settings, cx| {
11142 settings.update_user_settings(cx, |settings| {
11143 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11144 })
11145 });
11146 item.is_dirty = true;
11147 window.focus(&item.child_focus_handles[0], cx);
11148 });
11149 cx.executor().run_until_parked();
11150 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11151
11152 // Moving focus from one child to another within the same item should
11153 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11154 item.update_in(cx, |item, window, cx| {
11155 window.focus(&item.child_focus_handles[1], cx);
11156 });
11157 cx.executor().run_until_parked();
11158 item.read_with(cx, |item, _| {
11159 assert_eq!(
11160 item.save_count, 0,
11161 "Switching focus between children within the same item should not autosave"
11162 );
11163 });
11164
11165 // Blurring the item saves the file. This is the core regression scenario:
11166 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11167 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11168 // the leaf is always a child focus handle, so `on_blur` never detected
11169 // focus leaving the item.
11170 item.update_in(cx, |_, window, _| window.blur());
11171 cx.executor().run_until_parked();
11172 item.read_with(cx, |item, _| {
11173 assert_eq!(
11174 item.save_count, 1,
11175 "Blurring should trigger autosave when focus was on a child of the item"
11176 );
11177 });
11178
11179 // Deactivating the window should also trigger autosave when a child of
11180 // the multibuffer item currently owns focus.
11181 item.update_in(cx, |item, window, cx| {
11182 item.is_dirty = true;
11183 window.focus(&item.child_focus_handles[0], cx);
11184 });
11185 cx.executor().run_until_parked();
11186 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11187
11188 cx.deactivate_window();
11189 item.read_with(cx, |item, _| {
11190 assert_eq!(
11191 item.save_count, 2,
11192 "Deactivating window should trigger autosave when focus was on a child"
11193 );
11194 });
11195 }
11196
11197 #[gpui::test]
11198 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11199 init_test(cx);
11200
11201 let fs = FakeFs::new(cx.executor());
11202
11203 let project = Project::test(fs, [], cx).await;
11204 let (workspace, cx) =
11205 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11206
11207 let item = cx.new(|cx| {
11208 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11209 });
11210 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11211 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11212 let toolbar_notify_count = Rc::new(RefCell::new(0));
11213
11214 workspace.update_in(cx, |workspace, window, cx| {
11215 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11216 let toolbar_notification_count = toolbar_notify_count.clone();
11217 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11218 *toolbar_notification_count.borrow_mut() += 1
11219 })
11220 .detach();
11221 });
11222
11223 pane.read_with(cx, |pane, _| {
11224 assert!(!pane.can_navigate_backward());
11225 assert!(!pane.can_navigate_forward());
11226 });
11227
11228 item.update_in(cx, |item, _, cx| {
11229 item.set_state("one".to_string(), cx);
11230 });
11231
11232 // Toolbar must be notified to re-render the navigation buttons
11233 assert_eq!(*toolbar_notify_count.borrow(), 1);
11234
11235 pane.read_with(cx, |pane, _| {
11236 assert!(pane.can_navigate_backward());
11237 assert!(!pane.can_navigate_forward());
11238 });
11239
11240 workspace
11241 .update_in(cx, |workspace, window, cx| {
11242 workspace.go_back(pane.downgrade(), window, cx)
11243 })
11244 .await
11245 .unwrap();
11246
11247 assert_eq!(*toolbar_notify_count.borrow(), 2);
11248 pane.read_with(cx, |pane, _| {
11249 assert!(!pane.can_navigate_backward());
11250 assert!(pane.can_navigate_forward());
11251 });
11252 }
11253
11254 /// Tests that the navigation history deduplicates entries for the same item.
11255 ///
11256 /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11257 /// the navigation history deduplicates by keeping only the most recent visit to each item,
11258 /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11259 /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11260 /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11261 ///
11262 /// This behavior prevents the navigation history from growing unnecessarily large and provides
11263 /// a better user experience by eliminating redundant navigation steps when jumping between files.
11264 #[gpui::test]
11265 async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11266 init_test(cx);
11267
11268 let fs = FakeFs::new(cx.executor());
11269 let project = Project::test(fs, [], cx).await;
11270 let (workspace, cx) =
11271 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11272
11273 let item_a = cx.new(|cx| {
11274 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11275 });
11276 let item_b = cx.new(|cx| {
11277 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11278 });
11279 let item_c = cx.new(|cx| {
11280 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11281 });
11282
11283 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11284
11285 workspace.update_in(cx, |workspace, window, cx| {
11286 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11287 workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11288 workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11289 });
11290
11291 workspace.update_in(cx, |workspace, window, cx| {
11292 workspace.activate_item(&item_a, false, false, window, cx);
11293 });
11294 cx.run_until_parked();
11295
11296 workspace.update_in(cx, |workspace, window, cx| {
11297 workspace.activate_item(&item_b, false, false, window, cx);
11298 });
11299 cx.run_until_parked();
11300
11301 workspace.update_in(cx, |workspace, window, cx| {
11302 workspace.activate_item(&item_a, false, false, window, cx);
11303 });
11304 cx.run_until_parked();
11305
11306 workspace.update_in(cx, |workspace, window, cx| {
11307 workspace.activate_item(&item_b, false, false, window, cx);
11308 });
11309 cx.run_until_parked();
11310
11311 workspace.update_in(cx, |workspace, window, cx| {
11312 workspace.activate_item(&item_a, false, false, window, cx);
11313 });
11314 cx.run_until_parked();
11315
11316 workspace.update_in(cx, |workspace, window, cx| {
11317 workspace.activate_item(&item_b, false, false, window, cx);
11318 });
11319 cx.run_until_parked();
11320
11321 workspace.update_in(cx, |workspace, window, cx| {
11322 workspace.activate_item(&item_c, false, false, window, cx);
11323 });
11324 cx.run_until_parked();
11325
11326 let backward_count = pane.read_with(cx, |pane, cx| {
11327 let mut count = 0;
11328 pane.nav_history().for_each_entry(cx, &mut |_, _| {
11329 count += 1;
11330 });
11331 count
11332 });
11333 assert!(
11334 backward_count <= 4,
11335 "Should have at most 4 entries, got {}",
11336 backward_count
11337 );
11338
11339 workspace
11340 .update_in(cx, |workspace, window, cx| {
11341 workspace.go_back(pane.downgrade(), window, cx)
11342 })
11343 .await
11344 .unwrap();
11345
11346 let active_item = workspace.read_with(cx, |workspace, cx| {
11347 workspace.active_item(cx).unwrap().item_id()
11348 });
11349 assert_eq!(
11350 active_item,
11351 item_b.entity_id(),
11352 "After first go_back, should be at item B"
11353 );
11354
11355 workspace
11356 .update_in(cx, |workspace, window, cx| {
11357 workspace.go_back(pane.downgrade(), window, cx)
11358 })
11359 .await
11360 .unwrap();
11361
11362 let active_item = workspace.read_with(cx, |workspace, cx| {
11363 workspace.active_item(cx).unwrap().item_id()
11364 });
11365 assert_eq!(
11366 active_item,
11367 item_a.entity_id(),
11368 "After second go_back, should be at item A"
11369 );
11370
11371 pane.read_with(cx, |pane, _| {
11372 assert!(pane.can_navigate_forward(), "Should be able to go forward");
11373 });
11374 }
11375
11376 #[gpui::test]
11377 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11378 init_test(cx);
11379 let fs = FakeFs::new(cx.executor());
11380 let project = Project::test(fs, [], cx).await;
11381 let (multi_workspace, cx) =
11382 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11383 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11384
11385 workspace.update_in(cx, |workspace, window, cx| {
11386 let first_item = cx.new(|cx| {
11387 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11388 });
11389 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11390 workspace.split_pane(
11391 workspace.active_pane().clone(),
11392 SplitDirection::Right,
11393 window,
11394 cx,
11395 );
11396 workspace.split_pane(
11397 workspace.active_pane().clone(),
11398 SplitDirection::Right,
11399 window,
11400 cx,
11401 );
11402 });
11403
11404 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11405 let panes = workspace.center.panes();
11406 assert!(panes.len() >= 2);
11407 (
11408 panes.first().expect("at least one pane").entity_id(),
11409 panes.last().expect("at least one pane").entity_id(),
11410 )
11411 });
11412
11413 workspace.update_in(cx, |workspace, window, cx| {
11414 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11415 });
11416 workspace.update(cx, |workspace, _| {
11417 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11418 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11419 });
11420
11421 cx.dispatch_action(ActivateLastPane);
11422
11423 workspace.update(cx, |workspace, _| {
11424 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11425 });
11426 }
11427
11428 #[gpui::test]
11429 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11430 init_test(cx);
11431 let fs = FakeFs::new(cx.executor());
11432
11433 let project = Project::test(fs, [], cx).await;
11434 let (workspace, cx) =
11435 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11436
11437 let panel = workspace.update_in(cx, |workspace, window, cx| {
11438 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11439 workspace.add_panel(panel.clone(), window, cx);
11440
11441 workspace
11442 .right_dock()
11443 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11444
11445 panel
11446 });
11447
11448 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11449 pane.update_in(cx, |pane, window, cx| {
11450 let item = cx.new(TestItem::new);
11451 pane.add_item(Box::new(item), true, true, None, window, cx);
11452 });
11453
11454 // Transfer focus from center to panel
11455 workspace.update_in(cx, |workspace, window, cx| {
11456 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11457 });
11458
11459 workspace.update_in(cx, |workspace, window, cx| {
11460 assert!(workspace.right_dock().read(cx).is_open());
11461 assert!(!panel.is_zoomed(window, cx));
11462 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11463 });
11464
11465 // Transfer focus from panel to center
11466 workspace.update_in(cx, |workspace, window, cx| {
11467 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11468 });
11469
11470 workspace.update_in(cx, |workspace, window, cx| {
11471 assert!(workspace.right_dock().read(cx).is_open());
11472 assert!(!panel.is_zoomed(window, cx));
11473 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11474 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11475 });
11476
11477 // Close the dock
11478 workspace.update_in(cx, |workspace, window, cx| {
11479 workspace.toggle_dock(DockPosition::Right, window, cx);
11480 });
11481
11482 workspace.update_in(cx, |workspace, window, cx| {
11483 assert!(!workspace.right_dock().read(cx).is_open());
11484 assert!(!panel.is_zoomed(window, cx));
11485 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11486 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11487 });
11488
11489 // Open the dock
11490 workspace.update_in(cx, |workspace, window, cx| {
11491 workspace.toggle_dock(DockPosition::Right, window, cx);
11492 });
11493
11494 workspace.update_in(cx, |workspace, window, cx| {
11495 assert!(workspace.right_dock().read(cx).is_open());
11496 assert!(!panel.is_zoomed(window, cx));
11497 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11498 });
11499
11500 // Focus and zoom panel
11501 panel.update_in(cx, |panel, window, cx| {
11502 cx.focus_self(window);
11503 panel.set_zoomed(true, window, cx)
11504 });
11505
11506 workspace.update_in(cx, |workspace, window, cx| {
11507 assert!(workspace.right_dock().read(cx).is_open());
11508 assert!(panel.is_zoomed(window, cx));
11509 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11510 });
11511
11512 // Transfer focus to the center closes the dock
11513 workspace.update_in(cx, |workspace, window, cx| {
11514 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11515 });
11516
11517 workspace.update_in(cx, |workspace, window, cx| {
11518 assert!(!workspace.right_dock().read(cx).is_open());
11519 assert!(panel.is_zoomed(window, cx));
11520 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11521 });
11522
11523 // Transferring focus back to the panel keeps it zoomed
11524 workspace.update_in(cx, |workspace, window, cx| {
11525 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11526 });
11527
11528 workspace.update_in(cx, |workspace, window, cx| {
11529 assert!(workspace.right_dock().read(cx).is_open());
11530 assert!(panel.is_zoomed(window, cx));
11531 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11532 });
11533
11534 // Close the dock while it is zoomed
11535 workspace.update_in(cx, |workspace, window, cx| {
11536 workspace.toggle_dock(DockPosition::Right, window, cx)
11537 });
11538
11539 workspace.update_in(cx, |workspace, window, cx| {
11540 assert!(!workspace.right_dock().read(cx).is_open());
11541 assert!(panel.is_zoomed(window, cx));
11542 assert!(workspace.zoomed.is_none());
11543 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11544 });
11545
11546 // Opening the dock, when it's zoomed, retains focus
11547 workspace.update_in(cx, |workspace, window, cx| {
11548 workspace.toggle_dock(DockPosition::Right, window, cx)
11549 });
11550
11551 workspace.update_in(cx, |workspace, window, cx| {
11552 assert!(workspace.right_dock().read(cx).is_open());
11553 assert!(panel.is_zoomed(window, cx));
11554 assert!(workspace.zoomed.is_some());
11555 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11556 });
11557
11558 // Unzoom and close the panel, zoom the active pane.
11559 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11560 workspace.update_in(cx, |workspace, window, cx| {
11561 workspace.toggle_dock(DockPosition::Right, window, cx)
11562 });
11563 pane.update_in(cx, |pane, window, cx| {
11564 pane.toggle_zoom(&Default::default(), window, cx)
11565 });
11566
11567 // Opening a dock unzooms the pane.
11568 workspace.update_in(cx, |workspace, window, cx| {
11569 workspace.toggle_dock(DockPosition::Right, window, cx)
11570 });
11571 workspace.update_in(cx, |workspace, window, cx| {
11572 let pane = pane.read(cx);
11573 assert!(!pane.is_zoomed());
11574 assert!(!pane.focus_handle(cx).is_focused(window));
11575 assert!(workspace.right_dock().read(cx).is_open());
11576 assert!(workspace.zoomed.is_none());
11577 });
11578 }
11579
11580 #[gpui::test]
11581 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11582 init_test(cx);
11583 let fs = FakeFs::new(cx.executor());
11584
11585 let project = Project::test(fs, [], cx).await;
11586 let (workspace, cx) =
11587 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11588
11589 let panel = workspace.update_in(cx, |workspace, window, cx| {
11590 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11591 workspace.add_panel(panel.clone(), window, cx);
11592 panel
11593 });
11594
11595 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11596 pane.update_in(cx, |pane, window, cx| {
11597 let item = cx.new(TestItem::new);
11598 pane.add_item(Box::new(item), true, true, None, window, cx);
11599 });
11600
11601 // Enable close_panel_on_toggle
11602 cx.update_global(|store: &mut SettingsStore, cx| {
11603 store.update_user_settings(cx, |settings| {
11604 settings.workspace.close_panel_on_toggle = Some(true);
11605 });
11606 });
11607
11608 // Panel starts closed. Toggling should open and focus it.
11609 workspace.update_in(cx, |workspace, window, cx| {
11610 assert!(!workspace.right_dock().read(cx).is_open());
11611 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11612 });
11613
11614 workspace.update_in(cx, |workspace, window, cx| {
11615 assert!(
11616 workspace.right_dock().read(cx).is_open(),
11617 "Dock should be open after toggling from center"
11618 );
11619 assert!(
11620 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11621 "Panel should be focused after toggling from center"
11622 );
11623 });
11624
11625 // Panel is open and focused. Toggling should close the panel and
11626 // return focus to the center.
11627 workspace.update_in(cx, |workspace, window, cx| {
11628 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11629 });
11630
11631 workspace.update_in(cx, |workspace, window, cx| {
11632 assert!(
11633 !workspace.right_dock().read(cx).is_open(),
11634 "Dock should be closed after toggling from focused panel"
11635 );
11636 assert!(
11637 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11638 "Panel should not be focused after toggling from focused panel"
11639 );
11640 });
11641
11642 // Open the dock and focus something else so the panel is open but not
11643 // focused. Toggling should focus the panel (not close it).
11644 workspace.update_in(cx, |workspace, window, cx| {
11645 workspace
11646 .right_dock()
11647 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11648 window.focus(&pane.read(cx).focus_handle(cx), cx);
11649 });
11650
11651 workspace.update_in(cx, |workspace, window, cx| {
11652 assert!(workspace.right_dock().read(cx).is_open());
11653 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11654 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11655 });
11656
11657 workspace.update_in(cx, |workspace, window, cx| {
11658 assert!(
11659 workspace.right_dock().read(cx).is_open(),
11660 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11661 );
11662 assert!(
11663 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11664 "Panel should be focused after toggling an open-but-unfocused panel"
11665 );
11666 });
11667
11668 // Now disable the setting and verify the original behavior: toggling
11669 // from a focused panel moves focus to center but leaves the dock open.
11670 cx.update_global(|store: &mut SettingsStore, cx| {
11671 store.update_user_settings(cx, |settings| {
11672 settings.workspace.close_panel_on_toggle = Some(false);
11673 });
11674 });
11675
11676 workspace.update_in(cx, |workspace, window, cx| {
11677 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11678 });
11679
11680 workspace.update_in(cx, |workspace, window, cx| {
11681 assert!(
11682 workspace.right_dock().read(cx).is_open(),
11683 "Dock should remain open when setting is disabled"
11684 );
11685 assert!(
11686 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11687 "Panel should not be focused after toggling with setting disabled"
11688 );
11689 });
11690 }
11691
11692 #[gpui::test]
11693 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11694 init_test(cx);
11695 let fs = FakeFs::new(cx.executor());
11696
11697 let project = Project::test(fs, [], cx).await;
11698 let (workspace, cx) =
11699 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11700
11701 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11702 workspace.active_pane().clone()
11703 });
11704
11705 // Add an item to the pane so it can be zoomed
11706 workspace.update_in(cx, |workspace, window, cx| {
11707 let item = cx.new(TestItem::new);
11708 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11709 });
11710
11711 // Initially not zoomed
11712 workspace.update_in(cx, |workspace, _window, cx| {
11713 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11714 assert!(
11715 workspace.zoomed.is_none(),
11716 "Workspace should track no zoomed pane"
11717 );
11718 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11719 });
11720
11721 // Zoom In
11722 pane.update_in(cx, |pane, window, cx| {
11723 pane.zoom_in(&crate::ZoomIn, window, cx);
11724 });
11725
11726 workspace.update_in(cx, |workspace, window, cx| {
11727 assert!(
11728 pane.read(cx).is_zoomed(),
11729 "Pane should be zoomed after ZoomIn"
11730 );
11731 assert!(
11732 workspace.zoomed.is_some(),
11733 "Workspace should track the zoomed pane"
11734 );
11735 assert!(
11736 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11737 "ZoomIn should focus the pane"
11738 );
11739 });
11740
11741 // Zoom In again is a no-op
11742 pane.update_in(cx, |pane, window, cx| {
11743 pane.zoom_in(&crate::ZoomIn, window, cx);
11744 });
11745
11746 workspace.update_in(cx, |workspace, window, cx| {
11747 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11748 assert!(
11749 workspace.zoomed.is_some(),
11750 "Workspace still tracks zoomed pane"
11751 );
11752 assert!(
11753 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11754 "Pane remains focused after repeated ZoomIn"
11755 );
11756 });
11757
11758 // Zoom Out
11759 pane.update_in(cx, |pane, window, cx| {
11760 pane.zoom_out(&crate::ZoomOut, window, cx);
11761 });
11762
11763 workspace.update_in(cx, |workspace, _window, cx| {
11764 assert!(
11765 !pane.read(cx).is_zoomed(),
11766 "Pane should unzoom after ZoomOut"
11767 );
11768 assert!(
11769 workspace.zoomed.is_none(),
11770 "Workspace clears zoom tracking after ZoomOut"
11771 );
11772 });
11773
11774 // Zoom Out again is a no-op
11775 pane.update_in(cx, |pane, window, cx| {
11776 pane.zoom_out(&crate::ZoomOut, window, cx);
11777 });
11778
11779 workspace.update_in(cx, |workspace, _window, cx| {
11780 assert!(
11781 !pane.read(cx).is_zoomed(),
11782 "Second ZoomOut keeps pane unzoomed"
11783 );
11784 assert!(
11785 workspace.zoomed.is_none(),
11786 "Workspace remains without zoomed pane"
11787 );
11788 });
11789 }
11790
11791 #[gpui::test]
11792 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11793 init_test(cx);
11794 let fs = FakeFs::new(cx.executor());
11795
11796 let project = Project::test(fs, [], cx).await;
11797 let (workspace, cx) =
11798 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11799 workspace.update_in(cx, |workspace, window, cx| {
11800 // Open two docks
11801 let left_dock = workspace.dock_at_position(DockPosition::Left);
11802 let right_dock = workspace.dock_at_position(DockPosition::Right);
11803
11804 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11805 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11806
11807 assert!(left_dock.read(cx).is_open());
11808 assert!(right_dock.read(cx).is_open());
11809 });
11810
11811 workspace.update_in(cx, |workspace, window, cx| {
11812 // Toggle all docks - should close both
11813 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11814
11815 let left_dock = workspace.dock_at_position(DockPosition::Left);
11816 let right_dock = workspace.dock_at_position(DockPosition::Right);
11817 assert!(!left_dock.read(cx).is_open());
11818 assert!(!right_dock.read(cx).is_open());
11819 });
11820
11821 workspace.update_in(cx, |workspace, window, cx| {
11822 // Toggle again - should reopen both
11823 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11824
11825 let left_dock = workspace.dock_at_position(DockPosition::Left);
11826 let right_dock = workspace.dock_at_position(DockPosition::Right);
11827 assert!(left_dock.read(cx).is_open());
11828 assert!(right_dock.read(cx).is_open());
11829 });
11830 }
11831
11832 #[gpui::test]
11833 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11834 init_test(cx);
11835 let fs = FakeFs::new(cx.executor());
11836
11837 let project = Project::test(fs, [], cx).await;
11838 let (workspace, cx) =
11839 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11840 workspace.update_in(cx, |workspace, window, cx| {
11841 // Open two docks
11842 let left_dock = workspace.dock_at_position(DockPosition::Left);
11843 let right_dock = workspace.dock_at_position(DockPosition::Right);
11844
11845 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11846 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11847
11848 assert!(left_dock.read(cx).is_open());
11849 assert!(right_dock.read(cx).is_open());
11850 });
11851
11852 workspace.update_in(cx, |workspace, window, cx| {
11853 // Close them manually
11854 workspace.toggle_dock(DockPosition::Left, window, cx);
11855 workspace.toggle_dock(DockPosition::Right, window, cx);
11856
11857 let left_dock = workspace.dock_at_position(DockPosition::Left);
11858 let right_dock = workspace.dock_at_position(DockPosition::Right);
11859 assert!(!left_dock.read(cx).is_open());
11860 assert!(!right_dock.read(cx).is_open());
11861 });
11862
11863 workspace.update_in(cx, |workspace, window, cx| {
11864 // Toggle all docks - only last closed (right dock) should reopen
11865 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11866
11867 let left_dock = workspace.dock_at_position(DockPosition::Left);
11868 let right_dock = workspace.dock_at_position(DockPosition::Right);
11869 assert!(!left_dock.read(cx).is_open());
11870 assert!(right_dock.read(cx).is_open());
11871 });
11872 }
11873
11874 #[gpui::test]
11875 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11876 init_test(cx);
11877 let fs = FakeFs::new(cx.executor());
11878 let project = Project::test(fs, [], cx).await;
11879 let (multi_workspace, cx) =
11880 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11881 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11882
11883 // Open two docks (left and right) with one panel each
11884 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11885 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11886 workspace.add_panel(left_panel.clone(), window, cx);
11887
11888 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11889 workspace.add_panel(right_panel.clone(), window, cx);
11890
11891 workspace.toggle_dock(DockPosition::Left, window, cx);
11892 workspace.toggle_dock(DockPosition::Right, window, cx);
11893
11894 // Verify initial state
11895 assert!(
11896 workspace.left_dock().read(cx).is_open(),
11897 "Left dock should be open"
11898 );
11899 assert_eq!(
11900 workspace
11901 .left_dock()
11902 .read(cx)
11903 .visible_panel()
11904 .unwrap()
11905 .panel_id(),
11906 left_panel.panel_id(),
11907 "Left panel should be visible in left dock"
11908 );
11909 assert!(
11910 workspace.right_dock().read(cx).is_open(),
11911 "Right dock should be open"
11912 );
11913 assert_eq!(
11914 workspace
11915 .right_dock()
11916 .read(cx)
11917 .visible_panel()
11918 .unwrap()
11919 .panel_id(),
11920 right_panel.panel_id(),
11921 "Right panel should be visible in right dock"
11922 );
11923 assert!(
11924 !workspace.bottom_dock().read(cx).is_open(),
11925 "Bottom dock should be closed"
11926 );
11927
11928 (left_panel, right_panel)
11929 });
11930
11931 // Focus the left panel and move it to the next position (bottom dock)
11932 workspace.update_in(cx, |workspace, window, cx| {
11933 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11934 assert!(
11935 left_panel.read(cx).focus_handle(cx).is_focused(window),
11936 "Left panel should be focused"
11937 );
11938 });
11939
11940 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11941
11942 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11943 workspace.update(cx, |workspace, cx| {
11944 assert!(
11945 !workspace.left_dock().read(cx).is_open(),
11946 "Left dock should be closed"
11947 );
11948 assert!(
11949 workspace.bottom_dock().read(cx).is_open(),
11950 "Bottom dock should now be open"
11951 );
11952 assert_eq!(
11953 left_panel.read(cx).position,
11954 DockPosition::Bottom,
11955 "Left panel should now be in the bottom dock"
11956 );
11957 assert_eq!(
11958 workspace
11959 .bottom_dock()
11960 .read(cx)
11961 .visible_panel()
11962 .unwrap()
11963 .panel_id(),
11964 left_panel.panel_id(),
11965 "Left panel should be the visible panel in the bottom dock"
11966 );
11967 });
11968
11969 // Toggle all docks off
11970 workspace.update_in(cx, |workspace, window, cx| {
11971 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11972 assert!(
11973 !workspace.left_dock().read(cx).is_open(),
11974 "Left dock should be closed"
11975 );
11976 assert!(
11977 !workspace.right_dock().read(cx).is_open(),
11978 "Right dock should be closed"
11979 );
11980 assert!(
11981 !workspace.bottom_dock().read(cx).is_open(),
11982 "Bottom dock should be closed"
11983 );
11984 });
11985
11986 // Toggle all docks back on and verify positions are restored
11987 workspace.update_in(cx, |workspace, window, cx| {
11988 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11989 assert!(
11990 !workspace.left_dock().read(cx).is_open(),
11991 "Left dock should remain closed"
11992 );
11993 assert!(
11994 workspace.right_dock().read(cx).is_open(),
11995 "Right dock should remain open"
11996 );
11997 assert!(
11998 workspace.bottom_dock().read(cx).is_open(),
11999 "Bottom dock should remain open"
12000 );
12001 assert_eq!(
12002 left_panel.read(cx).position,
12003 DockPosition::Bottom,
12004 "Left panel should remain in the bottom dock"
12005 );
12006 assert_eq!(
12007 right_panel.read(cx).position,
12008 DockPosition::Right,
12009 "Right panel should remain in the right dock"
12010 );
12011 assert_eq!(
12012 workspace
12013 .bottom_dock()
12014 .read(cx)
12015 .visible_panel()
12016 .unwrap()
12017 .panel_id(),
12018 left_panel.panel_id(),
12019 "Left panel should be the visible panel in the right dock"
12020 );
12021 });
12022 }
12023
12024 #[gpui::test]
12025 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12026 init_test(cx);
12027
12028 let fs = FakeFs::new(cx.executor());
12029
12030 let project = Project::test(fs, None, cx).await;
12031 let (workspace, cx) =
12032 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12033
12034 // Let's arrange the panes like this:
12035 //
12036 // +-----------------------+
12037 // | top |
12038 // +------+--------+-------+
12039 // | left | center | right |
12040 // +------+--------+-------+
12041 // | bottom |
12042 // +-----------------------+
12043
12044 let top_item = cx.new(|cx| {
12045 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12046 });
12047 let bottom_item = cx.new(|cx| {
12048 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12049 });
12050 let left_item = cx.new(|cx| {
12051 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12052 });
12053 let right_item = cx.new(|cx| {
12054 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12055 });
12056 let center_item = cx.new(|cx| {
12057 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12058 });
12059
12060 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12061 let top_pane_id = workspace.active_pane().entity_id();
12062 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12063 workspace.split_pane(
12064 workspace.active_pane().clone(),
12065 SplitDirection::Down,
12066 window,
12067 cx,
12068 );
12069 top_pane_id
12070 });
12071 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12072 let bottom_pane_id = workspace.active_pane().entity_id();
12073 workspace.add_item_to_active_pane(
12074 Box::new(bottom_item.clone()),
12075 None,
12076 false,
12077 window,
12078 cx,
12079 );
12080 workspace.split_pane(
12081 workspace.active_pane().clone(),
12082 SplitDirection::Up,
12083 window,
12084 cx,
12085 );
12086 bottom_pane_id
12087 });
12088 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12089 let left_pane_id = workspace.active_pane().entity_id();
12090 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12091 workspace.split_pane(
12092 workspace.active_pane().clone(),
12093 SplitDirection::Right,
12094 window,
12095 cx,
12096 );
12097 left_pane_id
12098 });
12099 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12100 let right_pane_id = workspace.active_pane().entity_id();
12101 workspace.add_item_to_active_pane(
12102 Box::new(right_item.clone()),
12103 None,
12104 false,
12105 window,
12106 cx,
12107 );
12108 workspace.split_pane(
12109 workspace.active_pane().clone(),
12110 SplitDirection::Left,
12111 window,
12112 cx,
12113 );
12114 right_pane_id
12115 });
12116 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12117 let center_pane_id = workspace.active_pane().entity_id();
12118 workspace.add_item_to_active_pane(
12119 Box::new(center_item.clone()),
12120 None,
12121 false,
12122 window,
12123 cx,
12124 );
12125 center_pane_id
12126 });
12127 cx.executor().run_until_parked();
12128
12129 workspace.update_in(cx, |workspace, window, cx| {
12130 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12131
12132 // Join into next from center pane into right
12133 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12134 });
12135
12136 workspace.update_in(cx, |workspace, window, cx| {
12137 let active_pane = workspace.active_pane();
12138 assert_eq!(right_pane_id, active_pane.entity_id());
12139 assert_eq!(2, active_pane.read(cx).items_len());
12140 let item_ids_in_pane =
12141 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12142 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12143 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12144
12145 // Join into next from right pane into bottom
12146 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12147 });
12148
12149 workspace.update_in(cx, |workspace, window, cx| {
12150 let active_pane = workspace.active_pane();
12151 assert_eq!(bottom_pane_id, active_pane.entity_id());
12152 assert_eq!(3, active_pane.read(cx).items_len());
12153 let item_ids_in_pane =
12154 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12155 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12156 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12157 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12158
12159 // Join into next from bottom pane into left
12160 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12161 });
12162
12163 workspace.update_in(cx, |workspace, window, cx| {
12164 let active_pane = workspace.active_pane();
12165 assert_eq!(left_pane_id, active_pane.entity_id());
12166 assert_eq!(4, active_pane.read(cx).items_len());
12167 let item_ids_in_pane =
12168 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12169 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12170 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12171 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12172 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12173
12174 // Join into next from left pane into top
12175 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12176 });
12177
12178 workspace.update_in(cx, |workspace, window, cx| {
12179 let active_pane = workspace.active_pane();
12180 assert_eq!(top_pane_id, active_pane.entity_id());
12181 assert_eq!(5, active_pane.read(cx).items_len());
12182 let item_ids_in_pane =
12183 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12184 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12185 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12186 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12187 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12188 assert!(item_ids_in_pane.contains(&top_item.item_id()));
12189
12190 // Single pane left: no-op
12191 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12192 });
12193
12194 workspace.update(cx, |workspace, _cx| {
12195 let active_pane = workspace.active_pane();
12196 assert_eq!(top_pane_id, active_pane.entity_id());
12197 });
12198 }
12199
12200 fn add_an_item_to_active_pane(
12201 cx: &mut VisualTestContext,
12202 workspace: &Entity<Workspace>,
12203 item_id: u64,
12204 ) -> Entity<TestItem> {
12205 let item = cx.new(|cx| {
12206 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12207 item_id,
12208 "item{item_id}.txt",
12209 cx,
12210 )])
12211 });
12212 workspace.update_in(cx, |workspace, window, cx| {
12213 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12214 });
12215 item
12216 }
12217
12218 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12219 workspace.update_in(cx, |workspace, window, cx| {
12220 workspace.split_pane(
12221 workspace.active_pane().clone(),
12222 SplitDirection::Right,
12223 window,
12224 cx,
12225 )
12226 })
12227 }
12228
12229 #[gpui::test]
12230 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12231 init_test(cx);
12232 let fs = FakeFs::new(cx.executor());
12233 let project = Project::test(fs, None, cx).await;
12234 let (workspace, cx) =
12235 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12236
12237 add_an_item_to_active_pane(cx, &workspace, 1);
12238 split_pane(cx, &workspace);
12239 add_an_item_to_active_pane(cx, &workspace, 2);
12240 split_pane(cx, &workspace); // empty pane
12241 split_pane(cx, &workspace);
12242 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12243
12244 cx.executor().run_until_parked();
12245
12246 workspace.update(cx, |workspace, cx| {
12247 let num_panes = workspace.panes().len();
12248 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12249 let active_item = workspace
12250 .active_pane()
12251 .read(cx)
12252 .active_item()
12253 .expect("item is in focus");
12254
12255 assert_eq!(num_panes, 4);
12256 assert_eq!(num_items_in_current_pane, 1);
12257 assert_eq!(active_item.item_id(), last_item.item_id());
12258 });
12259
12260 workspace.update_in(cx, |workspace, window, cx| {
12261 workspace.join_all_panes(window, cx);
12262 });
12263
12264 workspace.update(cx, |workspace, cx| {
12265 let num_panes = workspace.panes().len();
12266 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12267 let active_item = workspace
12268 .active_pane()
12269 .read(cx)
12270 .active_item()
12271 .expect("item is in focus");
12272
12273 assert_eq!(num_panes, 1);
12274 assert_eq!(num_items_in_current_pane, 3);
12275 assert_eq!(active_item.item_id(), last_item.item_id());
12276 });
12277 }
12278
12279 #[gpui::test]
12280 async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12281 init_test(cx);
12282 let fs = FakeFs::new(cx.executor());
12283
12284 let project = Project::test(fs, [], cx).await;
12285 let (multi_workspace, cx) =
12286 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12287 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12288
12289 workspace.update(cx, |workspace, _cx| {
12290 workspace.bounds.size.width = px(800.);
12291 });
12292
12293 workspace.update_in(cx, |workspace, window, cx| {
12294 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12295 workspace.add_panel(panel, window, cx);
12296 workspace.toggle_dock(DockPosition::Right, window, cx);
12297 });
12298
12299 let (panel, resized_width, ratio_basis_width) =
12300 workspace.update_in(cx, |workspace, window, cx| {
12301 let item = cx.new(|cx| {
12302 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12303 });
12304 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12305
12306 let dock = workspace.right_dock().read(cx);
12307 let workspace_width = workspace.bounds.size.width;
12308 let initial_width = workspace
12309 .dock_size(&dock, window, cx)
12310 .expect("flexible dock should have an initial width");
12311
12312 assert_eq!(initial_width, workspace_width / 2.);
12313
12314 workspace.resize_right_dock(px(300.), window, cx);
12315
12316 let dock = workspace.right_dock().read(cx);
12317 let resized_width = workspace
12318 .dock_size(&dock, window, cx)
12319 .expect("flexible dock should keep its resized width");
12320
12321 assert_eq!(resized_width, px(300.));
12322
12323 let panel = workspace
12324 .right_dock()
12325 .read(cx)
12326 .visible_panel()
12327 .expect("flexible dock should have a visible panel")
12328 .panel_id();
12329
12330 (panel, resized_width, workspace_width)
12331 });
12332
12333 workspace.update_in(cx, |workspace, window, cx| {
12334 workspace.toggle_dock(DockPosition::Right, window, cx);
12335 workspace.toggle_dock(DockPosition::Right, window, cx);
12336
12337 let dock = workspace.right_dock().read(cx);
12338 let reopened_width = workspace
12339 .dock_size(&dock, window, cx)
12340 .expect("flexible dock should restore when reopened");
12341
12342 assert_eq!(reopened_width, resized_width);
12343
12344 let right_dock = workspace.right_dock().read(cx);
12345 let flexible_panel = right_dock
12346 .visible_panel()
12347 .expect("flexible dock should still have a visible panel");
12348 assert_eq!(flexible_panel.panel_id(), panel);
12349 assert_eq!(
12350 right_dock
12351 .stored_panel_size_state(flexible_panel.as_ref())
12352 .and_then(|size_state| size_state.flexible_size_ratio),
12353 Some(resized_width.to_f64() as f32 / workspace.bounds.size.width.to_f64() as f32)
12354 );
12355 });
12356
12357 workspace.update_in(cx, |workspace, window, cx| {
12358 workspace.split_pane(
12359 workspace.active_pane().clone(),
12360 SplitDirection::Right,
12361 window,
12362 cx,
12363 );
12364
12365 let dock = workspace.right_dock().read(cx);
12366 let split_width = workspace
12367 .dock_size(&dock, window, cx)
12368 .expect("flexible dock should keep its user-resized proportion");
12369
12370 assert_eq!(split_width, px(300.));
12371
12372 workspace.bounds.size.width = px(1600.);
12373
12374 let dock = workspace.right_dock().read(cx);
12375 let resized_window_width = workspace
12376 .dock_size(&dock, window, cx)
12377 .expect("flexible dock should preserve proportional size on window resize");
12378
12379 assert_eq!(
12380 resized_window_width,
12381 workspace.bounds.size.width
12382 * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12383 );
12384 });
12385 }
12386
12387 #[gpui::test]
12388 async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12389 init_test(cx);
12390 let fs = FakeFs::new(cx.executor());
12391
12392 // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12393 {
12394 let project = Project::test(fs.clone(), [], cx).await;
12395 let (multi_workspace, cx) =
12396 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12397 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12398
12399 workspace.update(cx, |workspace, _cx| {
12400 workspace.set_random_database_id();
12401 workspace.bounds.size.width = px(800.);
12402 });
12403
12404 let panel = workspace.update_in(cx, |workspace, window, cx| {
12405 let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12406 workspace.add_panel(panel.clone(), window, cx);
12407 workspace.toggle_dock(DockPosition::Left, window, cx);
12408 panel
12409 });
12410
12411 workspace.update_in(cx, |workspace, window, cx| {
12412 workspace.resize_left_dock(px(350.), window, cx);
12413 });
12414
12415 cx.run_until_parked();
12416
12417 let persisted = workspace.read_with(cx, |workspace, cx| {
12418 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12419 });
12420 assert_eq!(
12421 persisted.and_then(|s| s.size),
12422 Some(px(350.)),
12423 "fixed-width panel size should be persisted to KVP"
12424 );
12425
12426 // Remove the panel and re-add a fresh instance with the same key.
12427 // The new instance should have its size state restored from KVP.
12428 workspace.update_in(cx, |workspace, window, cx| {
12429 workspace.remove_panel(&panel, window, cx);
12430 });
12431
12432 workspace.update_in(cx, |workspace, window, cx| {
12433 let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12434 workspace.add_panel(new_panel, window, cx);
12435
12436 let left_dock = workspace.left_dock().read(cx);
12437 let size_state = left_dock
12438 .panel::<TestPanel>()
12439 .and_then(|p| left_dock.stored_panel_size_state(&p));
12440 assert_eq!(
12441 size_state.and_then(|s| s.size),
12442 Some(px(350.)),
12443 "re-added fixed-width panel should restore persisted size from KVP"
12444 );
12445 });
12446 }
12447
12448 // Flexible panel: both pixel size and ratio are persisted and restored.
12449 {
12450 let project = Project::test(fs.clone(), [], cx).await;
12451 let (multi_workspace, cx) =
12452 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12453 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12454
12455 workspace.update(cx, |workspace, _cx| {
12456 workspace.set_random_database_id();
12457 workspace.bounds.size.width = px(800.);
12458 });
12459
12460 let panel = workspace.update_in(cx, |workspace, window, cx| {
12461 let item = cx.new(|cx| {
12462 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12463 });
12464 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12465
12466 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12467 workspace.add_panel(panel.clone(), window, cx);
12468 workspace.toggle_dock(DockPosition::Right, window, cx);
12469 panel
12470 });
12471
12472 workspace.update_in(cx, |workspace, window, cx| {
12473 workspace.resize_right_dock(px(300.), window, cx);
12474 });
12475
12476 cx.run_until_parked();
12477
12478 let persisted = workspace
12479 .read_with(cx, |workspace, cx| {
12480 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12481 })
12482 .expect("flexible panel state should be persisted to KVP");
12483 assert_eq!(
12484 persisted.size, None,
12485 "flexible panel should not persist a redundant pixel size"
12486 );
12487 let original_ratio = persisted
12488 .flexible_size_ratio
12489 .expect("flexible panel ratio should be persisted");
12490
12491 // Remove the panel and re-add: both size and ratio should be restored.
12492 workspace.update_in(cx, |workspace, window, cx| {
12493 workspace.remove_panel(&panel, window, cx);
12494 });
12495
12496 workspace.update_in(cx, |workspace, window, cx| {
12497 let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12498 workspace.add_panel(new_panel, window, cx);
12499
12500 let right_dock = workspace.right_dock().read(cx);
12501 let size_state = right_dock
12502 .panel::<TestPanel>()
12503 .and_then(|p| right_dock.stored_panel_size_state(&p))
12504 .expect("re-added flexible panel should have restored size state from KVP");
12505 assert_eq!(
12506 size_state.size, None,
12507 "re-added flexible panel should not have a persisted pixel size"
12508 );
12509 assert_eq!(
12510 size_state.flexible_size_ratio,
12511 Some(original_ratio),
12512 "re-added flexible panel should restore persisted ratio"
12513 );
12514 });
12515 }
12516 }
12517
12518 #[gpui::test]
12519 async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12520 init_test(cx);
12521 let fs = FakeFs::new(cx.executor());
12522
12523 let project = Project::test(fs, [], cx).await;
12524 let (multi_workspace, cx) =
12525 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12526 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12527
12528 workspace.update(cx, |workspace, _cx| {
12529 workspace.bounds.size.width = px(900.);
12530 });
12531
12532 // Step 1: Add a tab to the center pane then open a flexible panel in the left
12533 // dock. With one full-width center pane the default ratio is 0.5, so the panel
12534 // and the center pane each take half the workspace width.
12535 workspace.update_in(cx, |workspace, window, cx| {
12536 let item = cx.new(|cx| {
12537 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12538 });
12539 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12540
12541 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12542 workspace.add_panel(panel, window, cx);
12543 workspace.toggle_dock(DockPosition::Left, window, cx);
12544
12545 let left_dock = workspace.left_dock().read(cx);
12546 let left_width = workspace
12547 .dock_size(&left_dock, window, cx)
12548 .expect("left dock should have an active panel");
12549
12550 assert_eq!(
12551 left_width,
12552 workspace.bounds.size.width / 2.,
12553 "flexible left panel should split evenly with the center pane"
12554 );
12555 });
12556
12557 // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12558 // change horizontal width fractions, so the flexible panel stays at the same
12559 // width as each half of the split.
12560 workspace.update_in(cx, |workspace, window, cx| {
12561 workspace.split_pane(
12562 workspace.active_pane().clone(),
12563 SplitDirection::Down,
12564 window,
12565 cx,
12566 );
12567
12568 let left_dock = workspace.left_dock().read(cx);
12569 let left_width = workspace
12570 .dock_size(&left_dock, window, cx)
12571 .expect("left dock should still have an active panel after vertical split");
12572
12573 assert_eq!(
12574 left_width,
12575 workspace.bounds.size.width / 2.,
12576 "flexible left panel width should match each vertically-split pane"
12577 );
12578 });
12579
12580 // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12581 // size reduces the available width, so the flexible left panel and the center
12582 // panes all shrink proportionally to accommodate it.
12583 workspace.update_in(cx, |workspace, window, cx| {
12584 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12585 workspace.add_panel(panel, window, cx);
12586 workspace.toggle_dock(DockPosition::Right, window, cx);
12587
12588 let right_dock = workspace.right_dock().read(cx);
12589 let right_width = workspace
12590 .dock_size(&right_dock, window, cx)
12591 .expect("right dock should have an active panel");
12592
12593 let left_dock = workspace.left_dock().read(cx);
12594 let left_width = workspace
12595 .dock_size(&left_dock, window, cx)
12596 .expect("left dock should still have an active panel");
12597
12598 let available_width = workspace.bounds.size.width - right_width;
12599 assert_eq!(
12600 left_width,
12601 available_width / 2.,
12602 "flexible left panel should shrink proportionally as the right dock takes space"
12603 );
12604 });
12605 }
12606
12607 struct TestModal(FocusHandle);
12608
12609 impl TestModal {
12610 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12611 Self(cx.focus_handle())
12612 }
12613 }
12614
12615 impl EventEmitter<DismissEvent> for TestModal {}
12616
12617 impl Focusable for TestModal {
12618 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12619 self.0.clone()
12620 }
12621 }
12622
12623 impl ModalView for TestModal {}
12624
12625 impl Render for TestModal {
12626 fn render(
12627 &mut self,
12628 _window: &mut Window,
12629 _cx: &mut Context<TestModal>,
12630 ) -> impl IntoElement {
12631 div().track_focus(&self.0)
12632 }
12633 }
12634
12635 #[gpui::test]
12636 async fn test_panels(cx: &mut gpui::TestAppContext) {
12637 init_test(cx);
12638 let fs = FakeFs::new(cx.executor());
12639
12640 let project = Project::test(fs, [], cx).await;
12641 let (multi_workspace, cx) =
12642 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12643 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12644
12645 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12646 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12647 workspace.add_panel(panel_1.clone(), window, cx);
12648 workspace.toggle_dock(DockPosition::Left, window, cx);
12649 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12650 workspace.add_panel(panel_2.clone(), window, cx);
12651 workspace.toggle_dock(DockPosition::Right, window, cx);
12652
12653 let left_dock = workspace.left_dock();
12654 assert_eq!(
12655 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12656 panel_1.panel_id()
12657 );
12658 assert_eq!(
12659 workspace.dock_size(&left_dock.read(cx), window, cx),
12660 Some(px(300.))
12661 );
12662
12663 workspace.resize_left_dock(px(1337.), window, cx);
12664 assert_eq!(
12665 workspace
12666 .right_dock()
12667 .read(cx)
12668 .visible_panel()
12669 .unwrap()
12670 .panel_id(),
12671 panel_2.panel_id(),
12672 );
12673
12674 (panel_1, panel_2)
12675 });
12676
12677 // Move panel_1 to the right
12678 panel_1.update_in(cx, |panel_1, window, cx| {
12679 panel_1.set_position(DockPosition::Right, window, cx)
12680 });
12681
12682 workspace.update_in(cx, |workspace, window, cx| {
12683 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12684 // Since it was the only panel on the left, the left dock should now be closed.
12685 assert!(!workspace.left_dock().read(cx).is_open());
12686 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12687 let right_dock = workspace.right_dock();
12688 assert_eq!(
12689 right_dock.read(cx).visible_panel().unwrap().panel_id(),
12690 panel_1.panel_id()
12691 );
12692 assert_eq!(
12693 right_dock
12694 .read(cx)
12695 .active_panel_size()
12696 .unwrap()
12697 .size
12698 .unwrap(),
12699 px(1337.)
12700 );
12701
12702 // Now we move panel_2 to the left
12703 panel_2.set_position(DockPosition::Left, window, cx);
12704 });
12705
12706 workspace.update(cx, |workspace, cx| {
12707 // Since panel_2 was not visible on the right, we don't open the left dock.
12708 assert!(!workspace.left_dock().read(cx).is_open());
12709 // And the right dock is unaffected in its displaying of panel_1
12710 assert!(workspace.right_dock().read(cx).is_open());
12711 assert_eq!(
12712 workspace
12713 .right_dock()
12714 .read(cx)
12715 .visible_panel()
12716 .unwrap()
12717 .panel_id(),
12718 panel_1.panel_id(),
12719 );
12720 });
12721
12722 // Move panel_1 back to the left
12723 panel_1.update_in(cx, |panel_1, window, cx| {
12724 panel_1.set_position(DockPosition::Left, window, cx)
12725 });
12726
12727 workspace.update_in(cx, |workspace, window, cx| {
12728 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12729 let left_dock = workspace.left_dock();
12730 assert!(left_dock.read(cx).is_open());
12731 assert_eq!(
12732 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12733 panel_1.panel_id()
12734 );
12735 assert_eq!(
12736 workspace.dock_size(&left_dock.read(cx), window, cx),
12737 Some(px(1337.))
12738 );
12739 // And the right dock should be closed as it no longer has any panels.
12740 assert!(!workspace.right_dock().read(cx).is_open());
12741
12742 // Now we move panel_1 to the bottom
12743 panel_1.set_position(DockPosition::Bottom, window, cx);
12744 });
12745
12746 workspace.update_in(cx, |workspace, window, cx| {
12747 // Since panel_1 was visible on the left, we close the left dock.
12748 assert!(!workspace.left_dock().read(cx).is_open());
12749 // The bottom dock is sized based on the panel's default size,
12750 // since the panel orientation changed from vertical to horizontal.
12751 let bottom_dock = workspace.bottom_dock();
12752 assert_eq!(
12753 workspace.dock_size(&bottom_dock.read(cx), window, cx),
12754 Some(px(300.))
12755 );
12756 // Close bottom dock and move panel_1 back to the left.
12757 bottom_dock.update(cx, |bottom_dock, cx| {
12758 bottom_dock.set_open(false, window, cx)
12759 });
12760 panel_1.set_position(DockPosition::Left, window, cx);
12761 });
12762
12763 // Emit activated event on panel 1
12764 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12765
12766 // Now the left dock is open and panel_1 is active and focused.
12767 workspace.update_in(cx, |workspace, window, cx| {
12768 let left_dock = workspace.left_dock();
12769 assert!(left_dock.read(cx).is_open());
12770 assert_eq!(
12771 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12772 panel_1.panel_id(),
12773 );
12774 assert!(panel_1.focus_handle(cx).is_focused(window));
12775 });
12776
12777 // Emit closed event on panel 2, which is not active
12778 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12779
12780 // Wo don't close the left dock, because panel_2 wasn't the active panel
12781 workspace.update(cx, |workspace, cx| {
12782 let left_dock = workspace.left_dock();
12783 assert!(left_dock.read(cx).is_open());
12784 assert_eq!(
12785 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12786 panel_1.panel_id(),
12787 );
12788 });
12789
12790 // Emitting a ZoomIn event shows the panel as zoomed.
12791 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12792 workspace.read_with(cx, |workspace, _| {
12793 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12794 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12795 });
12796
12797 // Move panel to another dock while it is zoomed
12798 panel_1.update_in(cx, |panel, window, cx| {
12799 panel.set_position(DockPosition::Right, window, cx)
12800 });
12801 workspace.read_with(cx, |workspace, _| {
12802 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12803
12804 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12805 });
12806
12807 // This is a helper for getting a:
12808 // - valid focus on an element,
12809 // - that isn't a part of the panes and panels system of the Workspace,
12810 // - and doesn't trigger the 'on_focus_lost' API.
12811 let focus_other_view = {
12812 let workspace = workspace.clone();
12813 move |cx: &mut VisualTestContext| {
12814 workspace.update_in(cx, |workspace, window, cx| {
12815 if workspace.active_modal::<TestModal>(cx).is_some() {
12816 workspace.toggle_modal(window, cx, TestModal::new);
12817 workspace.toggle_modal(window, cx, TestModal::new);
12818 } else {
12819 workspace.toggle_modal(window, cx, TestModal::new);
12820 }
12821 })
12822 }
12823 };
12824
12825 // If focus is transferred to another view that's not a panel or another pane, we still show
12826 // the panel as zoomed.
12827 focus_other_view(cx);
12828 workspace.read_with(cx, |workspace, _| {
12829 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12830 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12831 });
12832
12833 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12834 workspace.update_in(cx, |_workspace, window, cx| {
12835 cx.focus_self(window);
12836 });
12837 workspace.read_with(cx, |workspace, _| {
12838 assert_eq!(workspace.zoomed, None);
12839 assert_eq!(workspace.zoomed_position, None);
12840 });
12841
12842 // If focus is transferred again to another view that's not a panel or a pane, we won't
12843 // show the panel as zoomed because it wasn't zoomed before.
12844 focus_other_view(cx);
12845 workspace.read_with(cx, |workspace, _| {
12846 assert_eq!(workspace.zoomed, None);
12847 assert_eq!(workspace.zoomed_position, None);
12848 });
12849
12850 // When the panel is activated, it is zoomed again.
12851 cx.dispatch_action(ToggleRightDock);
12852 workspace.read_with(cx, |workspace, _| {
12853 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12854 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12855 });
12856
12857 // Emitting a ZoomOut event unzooms the panel.
12858 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12859 workspace.read_with(cx, |workspace, _| {
12860 assert_eq!(workspace.zoomed, None);
12861 assert_eq!(workspace.zoomed_position, None);
12862 });
12863
12864 // Emit closed event on panel 1, which is active
12865 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12866
12867 // Now the left dock is closed, because panel_1 was the active panel
12868 workspace.update(cx, |workspace, cx| {
12869 let right_dock = workspace.right_dock();
12870 assert!(!right_dock.read(cx).is_open());
12871 });
12872 }
12873
12874 #[gpui::test]
12875 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12876 init_test(cx);
12877
12878 let fs = FakeFs::new(cx.background_executor.clone());
12879 let project = Project::test(fs, [], cx).await;
12880 let (workspace, cx) =
12881 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12882 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12883
12884 let dirty_regular_buffer = cx.new(|cx| {
12885 TestItem::new(cx)
12886 .with_dirty(true)
12887 .with_label("1.txt")
12888 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12889 });
12890 let dirty_regular_buffer_2 = cx.new(|cx| {
12891 TestItem::new(cx)
12892 .with_dirty(true)
12893 .with_label("2.txt")
12894 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12895 });
12896 let dirty_multi_buffer_with_both = cx.new(|cx| {
12897 TestItem::new(cx)
12898 .with_dirty(true)
12899 .with_buffer_kind(ItemBufferKind::Multibuffer)
12900 .with_label("Fake Project Search")
12901 .with_project_items(&[
12902 dirty_regular_buffer.read(cx).project_items[0].clone(),
12903 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12904 ])
12905 });
12906 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12907 workspace.update_in(cx, |workspace, window, cx| {
12908 workspace.add_item(
12909 pane.clone(),
12910 Box::new(dirty_regular_buffer.clone()),
12911 None,
12912 false,
12913 false,
12914 window,
12915 cx,
12916 );
12917 workspace.add_item(
12918 pane.clone(),
12919 Box::new(dirty_regular_buffer_2.clone()),
12920 None,
12921 false,
12922 false,
12923 window,
12924 cx,
12925 );
12926 workspace.add_item(
12927 pane.clone(),
12928 Box::new(dirty_multi_buffer_with_both.clone()),
12929 None,
12930 false,
12931 false,
12932 window,
12933 cx,
12934 );
12935 });
12936
12937 pane.update_in(cx, |pane, window, cx| {
12938 pane.activate_item(2, true, true, window, cx);
12939 assert_eq!(
12940 pane.active_item().unwrap().item_id(),
12941 multi_buffer_with_both_files_id,
12942 "Should select the multi buffer in the pane"
12943 );
12944 });
12945 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12946 pane.close_other_items(
12947 &CloseOtherItems {
12948 save_intent: Some(SaveIntent::Save),
12949 close_pinned: true,
12950 },
12951 None,
12952 window,
12953 cx,
12954 )
12955 });
12956 cx.background_executor.run_until_parked();
12957 assert!(!cx.has_pending_prompt());
12958 close_all_but_multi_buffer_task
12959 .await
12960 .expect("Closing all buffers but the multi buffer failed");
12961 pane.update(cx, |pane, cx| {
12962 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12963 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12964 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12965 assert_eq!(pane.items_len(), 1);
12966 assert_eq!(
12967 pane.active_item().unwrap().item_id(),
12968 multi_buffer_with_both_files_id,
12969 "Should have only the multi buffer left in the pane"
12970 );
12971 assert!(
12972 dirty_multi_buffer_with_both.read(cx).is_dirty,
12973 "The multi buffer containing the unsaved buffer should still be dirty"
12974 );
12975 });
12976
12977 dirty_regular_buffer.update(cx, |buffer, cx| {
12978 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12979 });
12980
12981 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12982 pane.close_active_item(
12983 &CloseActiveItem {
12984 save_intent: Some(SaveIntent::Close),
12985 close_pinned: false,
12986 },
12987 window,
12988 cx,
12989 )
12990 });
12991 cx.background_executor.run_until_parked();
12992 assert!(
12993 cx.has_pending_prompt(),
12994 "Dirty multi buffer should prompt a save dialog"
12995 );
12996 cx.simulate_prompt_answer("Save");
12997 cx.background_executor.run_until_parked();
12998 close_multi_buffer_task
12999 .await
13000 .expect("Closing the multi buffer failed");
13001 pane.update(cx, |pane, cx| {
13002 assert_eq!(
13003 dirty_multi_buffer_with_both.read(cx).save_count,
13004 1,
13005 "Multi buffer item should get be saved"
13006 );
13007 // Test impl does not save inner items, so we do not assert them
13008 assert_eq!(
13009 pane.items_len(),
13010 0,
13011 "No more items should be left in the pane"
13012 );
13013 assert!(pane.active_item().is_none());
13014 });
13015 }
13016
13017 #[gpui::test]
13018 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13019 cx: &mut TestAppContext,
13020 ) {
13021 init_test(cx);
13022
13023 let fs = FakeFs::new(cx.background_executor.clone());
13024 let project = Project::test(fs, [], cx).await;
13025 let (workspace, cx) =
13026 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13027 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13028
13029 let dirty_regular_buffer = cx.new(|cx| {
13030 TestItem::new(cx)
13031 .with_dirty(true)
13032 .with_label("1.txt")
13033 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13034 });
13035 let dirty_regular_buffer_2 = cx.new(|cx| {
13036 TestItem::new(cx)
13037 .with_dirty(true)
13038 .with_label("2.txt")
13039 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13040 });
13041 let clear_regular_buffer = cx.new(|cx| {
13042 TestItem::new(cx)
13043 .with_label("3.txt")
13044 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13045 });
13046
13047 let dirty_multi_buffer_with_both = cx.new(|cx| {
13048 TestItem::new(cx)
13049 .with_dirty(true)
13050 .with_buffer_kind(ItemBufferKind::Multibuffer)
13051 .with_label("Fake Project Search")
13052 .with_project_items(&[
13053 dirty_regular_buffer.read(cx).project_items[0].clone(),
13054 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13055 clear_regular_buffer.read(cx).project_items[0].clone(),
13056 ])
13057 });
13058 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13059 workspace.update_in(cx, |workspace, window, cx| {
13060 workspace.add_item(
13061 pane.clone(),
13062 Box::new(dirty_regular_buffer.clone()),
13063 None,
13064 false,
13065 false,
13066 window,
13067 cx,
13068 );
13069 workspace.add_item(
13070 pane.clone(),
13071 Box::new(dirty_multi_buffer_with_both.clone()),
13072 None,
13073 false,
13074 false,
13075 window,
13076 cx,
13077 );
13078 });
13079
13080 pane.update_in(cx, |pane, window, cx| {
13081 pane.activate_item(1, true, true, window, cx);
13082 assert_eq!(
13083 pane.active_item().unwrap().item_id(),
13084 multi_buffer_with_both_files_id,
13085 "Should select the multi buffer in the pane"
13086 );
13087 });
13088 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13089 pane.close_active_item(
13090 &CloseActiveItem {
13091 save_intent: None,
13092 close_pinned: false,
13093 },
13094 window,
13095 cx,
13096 )
13097 });
13098 cx.background_executor.run_until_parked();
13099 assert!(
13100 cx.has_pending_prompt(),
13101 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13102 );
13103 }
13104
13105 /// Tests that when `close_on_file_delete` is enabled, files are automatically
13106 /// closed when they are deleted from disk.
13107 #[gpui::test]
13108 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13109 init_test(cx);
13110
13111 // Enable the close_on_disk_deletion setting
13112 cx.update_global(|store: &mut SettingsStore, cx| {
13113 store.update_user_settings(cx, |settings| {
13114 settings.workspace.close_on_file_delete = Some(true);
13115 });
13116 });
13117
13118 let fs = FakeFs::new(cx.background_executor.clone());
13119 let project = Project::test(fs, [], cx).await;
13120 let (workspace, cx) =
13121 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13122 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13123
13124 // Create a test item that simulates a file
13125 let item = cx.new(|cx| {
13126 TestItem::new(cx)
13127 .with_label("test.txt")
13128 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13129 });
13130
13131 // Add item to workspace
13132 workspace.update_in(cx, |workspace, window, cx| {
13133 workspace.add_item(
13134 pane.clone(),
13135 Box::new(item.clone()),
13136 None,
13137 false,
13138 false,
13139 window,
13140 cx,
13141 );
13142 });
13143
13144 // Verify the item is in the pane
13145 pane.read_with(cx, |pane, _| {
13146 assert_eq!(pane.items().count(), 1);
13147 });
13148
13149 // Simulate file deletion by setting the item's deleted state
13150 item.update(cx, |item, _| {
13151 item.set_has_deleted_file(true);
13152 });
13153
13154 // Emit UpdateTab event to trigger the close behavior
13155 cx.run_until_parked();
13156 item.update(cx, |_, cx| {
13157 cx.emit(ItemEvent::UpdateTab);
13158 });
13159
13160 // Allow the close operation to complete
13161 cx.run_until_parked();
13162
13163 // Verify the item was automatically closed
13164 pane.read_with(cx, |pane, _| {
13165 assert_eq!(
13166 pane.items().count(),
13167 0,
13168 "Item should be automatically closed when file is deleted"
13169 );
13170 });
13171 }
13172
13173 /// Tests that when `close_on_file_delete` is disabled (default), files remain
13174 /// open with a strikethrough when they are deleted from disk.
13175 #[gpui::test]
13176 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13177 init_test(cx);
13178
13179 // Ensure close_on_disk_deletion is disabled (default)
13180 cx.update_global(|store: &mut SettingsStore, cx| {
13181 store.update_user_settings(cx, |settings| {
13182 settings.workspace.close_on_file_delete = Some(false);
13183 });
13184 });
13185
13186 let fs = FakeFs::new(cx.background_executor.clone());
13187 let project = Project::test(fs, [], cx).await;
13188 let (workspace, cx) =
13189 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13190 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13191
13192 // Create a test item that simulates a file
13193 let item = cx.new(|cx| {
13194 TestItem::new(cx)
13195 .with_label("test.txt")
13196 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13197 });
13198
13199 // Add item to workspace
13200 workspace.update_in(cx, |workspace, window, cx| {
13201 workspace.add_item(
13202 pane.clone(),
13203 Box::new(item.clone()),
13204 None,
13205 false,
13206 false,
13207 window,
13208 cx,
13209 );
13210 });
13211
13212 // Verify the item is in the pane
13213 pane.read_with(cx, |pane, _| {
13214 assert_eq!(pane.items().count(), 1);
13215 });
13216
13217 // Simulate file deletion
13218 item.update(cx, |item, _| {
13219 item.set_has_deleted_file(true);
13220 });
13221
13222 // Emit UpdateTab event
13223 cx.run_until_parked();
13224 item.update(cx, |_, cx| {
13225 cx.emit(ItemEvent::UpdateTab);
13226 });
13227
13228 // Allow any potential close operation to complete
13229 cx.run_until_parked();
13230
13231 // Verify the item remains open (with strikethrough)
13232 pane.read_with(cx, |pane, _| {
13233 assert_eq!(
13234 pane.items().count(),
13235 1,
13236 "Item should remain open when close_on_disk_deletion is disabled"
13237 );
13238 });
13239
13240 // Verify the item shows as deleted
13241 item.read_with(cx, |item, _| {
13242 assert!(
13243 item.has_deleted_file,
13244 "Item should be marked as having deleted file"
13245 );
13246 });
13247 }
13248
13249 /// Tests that dirty files are not automatically closed when deleted from disk,
13250 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13251 /// unsaved changes without being prompted.
13252 #[gpui::test]
13253 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13254 init_test(cx);
13255
13256 // Enable the close_on_file_delete setting
13257 cx.update_global(|store: &mut SettingsStore, cx| {
13258 store.update_user_settings(cx, |settings| {
13259 settings.workspace.close_on_file_delete = Some(true);
13260 });
13261 });
13262
13263 let fs = FakeFs::new(cx.background_executor.clone());
13264 let project = Project::test(fs, [], cx).await;
13265 let (workspace, cx) =
13266 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13267 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13268
13269 // Create a dirty test item
13270 let item = cx.new(|cx| {
13271 TestItem::new(cx)
13272 .with_dirty(true)
13273 .with_label("test.txt")
13274 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13275 });
13276
13277 // Add item to workspace
13278 workspace.update_in(cx, |workspace, window, cx| {
13279 workspace.add_item(
13280 pane.clone(),
13281 Box::new(item.clone()),
13282 None,
13283 false,
13284 false,
13285 window,
13286 cx,
13287 );
13288 });
13289
13290 // Simulate file deletion
13291 item.update(cx, |item, _| {
13292 item.set_has_deleted_file(true);
13293 });
13294
13295 // Emit UpdateTab event to trigger the close behavior
13296 cx.run_until_parked();
13297 item.update(cx, |_, cx| {
13298 cx.emit(ItemEvent::UpdateTab);
13299 });
13300
13301 // Allow any potential close operation to complete
13302 cx.run_until_parked();
13303
13304 // Verify the item remains open (dirty files are not auto-closed)
13305 pane.read_with(cx, |pane, _| {
13306 assert_eq!(
13307 pane.items().count(),
13308 1,
13309 "Dirty items should not be automatically closed even when file is deleted"
13310 );
13311 });
13312
13313 // Verify the item is marked as deleted and still dirty
13314 item.read_with(cx, |item, _| {
13315 assert!(
13316 item.has_deleted_file,
13317 "Item should be marked as having deleted file"
13318 );
13319 assert!(item.is_dirty, "Item should still be dirty");
13320 });
13321 }
13322
13323 /// Tests that navigation history is cleaned up when files are auto-closed
13324 /// due to deletion from disk.
13325 #[gpui::test]
13326 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13327 init_test(cx);
13328
13329 // Enable the close_on_file_delete setting
13330 cx.update_global(|store: &mut SettingsStore, cx| {
13331 store.update_user_settings(cx, |settings| {
13332 settings.workspace.close_on_file_delete = Some(true);
13333 });
13334 });
13335
13336 let fs = FakeFs::new(cx.background_executor.clone());
13337 let project = Project::test(fs, [], cx).await;
13338 let (workspace, cx) =
13339 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13340 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13341
13342 // Create test items
13343 let item1 = cx.new(|cx| {
13344 TestItem::new(cx)
13345 .with_label("test1.txt")
13346 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13347 });
13348 let item1_id = item1.item_id();
13349
13350 let item2 = cx.new(|cx| {
13351 TestItem::new(cx)
13352 .with_label("test2.txt")
13353 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13354 });
13355
13356 // Add items to workspace
13357 workspace.update_in(cx, |workspace, window, cx| {
13358 workspace.add_item(
13359 pane.clone(),
13360 Box::new(item1.clone()),
13361 None,
13362 false,
13363 false,
13364 window,
13365 cx,
13366 );
13367 workspace.add_item(
13368 pane.clone(),
13369 Box::new(item2.clone()),
13370 None,
13371 false,
13372 false,
13373 window,
13374 cx,
13375 );
13376 });
13377
13378 // Activate item1 to ensure it gets navigation entries
13379 pane.update_in(cx, |pane, window, cx| {
13380 pane.activate_item(0, true, true, window, cx);
13381 });
13382
13383 // Switch to item2 and back to create navigation history
13384 pane.update_in(cx, |pane, window, cx| {
13385 pane.activate_item(1, true, true, window, cx);
13386 });
13387 cx.run_until_parked();
13388
13389 pane.update_in(cx, |pane, window, cx| {
13390 pane.activate_item(0, true, true, window, cx);
13391 });
13392 cx.run_until_parked();
13393
13394 // Simulate file deletion for item1
13395 item1.update(cx, |item, _| {
13396 item.set_has_deleted_file(true);
13397 });
13398
13399 // Emit UpdateTab event to trigger the close behavior
13400 item1.update(cx, |_, cx| {
13401 cx.emit(ItemEvent::UpdateTab);
13402 });
13403 cx.run_until_parked();
13404
13405 // Verify item1 was closed
13406 pane.read_with(cx, |pane, _| {
13407 assert_eq!(
13408 pane.items().count(),
13409 1,
13410 "Should have 1 item remaining after auto-close"
13411 );
13412 });
13413
13414 // Check navigation history after close
13415 let has_item = pane.read_with(cx, |pane, cx| {
13416 let mut has_item = false;
13417 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13418 if entry.item.id() == item1_id {
13419 has_item = true;
13420 }
13421 });
13422 has_item
13423 });
13424
13425 assert!(
13426 !has_item,
13427 "Navigation history should not contain closed item entries"
13428 );
13429 }
13430
13431 #[gpui::test]
13432 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13433 cx: &mut TestAppContext,
13434 ) {
13435 init_test(cx);
13436
13437 let fs = FakeFs::new(cx.background_executor.clone());
13438 let project = Project::test(fs, [], cx).await;
13439 let (workspace, cx) =
13440 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13441 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13442
13443 let dirty_regular_buffer = cx.new(|cx| {
13444 TestItem::new(cx)
13445 .with_dirty(true)
13446 .with_label("1.txt")
13447 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13448 });
13449 let dirty_regular_buffer_2 = cx.new(|cx| {
13450 TestItem::new(cx)
13451 .with_dirty(true)
13452 .with_label("2.txt")
13453 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13454 });
13455 let clear_regular_buffer = cx.new(|cx| {
13456 TestItem::new(cx)
13457 .with_label("3.txt")
13458 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13459 });
13460
13461 let dirty_multi_buffer = cx.new(|cx| {
13462 TestItem::new(cx)
13463 .with_dirty(true)
13464 .with_buffer_kind(ItemBufferKind::Multibuffer)
13465 .with_label("Fake Project Search")
13466 .with_project_items(&[
13467 dirty_regular_buffer.read(cx).project_items[0].clone(),
13468 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13469 clear_regular_buffer.read(cx).project_items[0].clone(),
13470 ])
13471 });
13472 workspace.update_in(cx, |workspace, window, cx| {
13473 workspace.add_item(
13474 pane.clone(),
13475 Box::new(dirty_regular_buffer.clone()),
13476 None,
13477 false,
13478 false,
13479 window,
13480 cx,
13481 );
13482 workspace.add_item(
13483 pane.clone(),
13484 Box::new(dirty_regular_buffer_2.clone()),
13485 None,
13486 false,
13487 false,
13488 window,
13489 cx,
13490 );
13491 workspace.add_item(
13492 pane.clone(),
13493 Box::new(dirty_multi_buffer.clone()),
13494 None,
13495 false,
13496 false,
13497 window,
13498 cx,
13499 );
13500 });
13501
13502 pane.update_in(cx, |pane, window, cx| {
13503 pane.activate_item(2, true, true, window, cx);
13504 assert_eq!(
13505 pane.active_item().unwrap().item_id(),
13506 dirty_multi_buffer.item_id(),
13507 "Should select the multi buffer in the pane"
13508 );
13509 });
13510 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13511 pane.close_active_item(
13512 &CloseActiveItem {
13513 save_intent: None,
13514 close_pinned: false,
13515 },
13516 window,
13517 cx,
13518 )
13519 });
13520 cx.background_executor.run_until_parked();
13521 assert!(
13522 !cx.has_pending_prompt(),
13523 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13524 );
13525 close_multi_buffer_task
13526 .await
13527 .expect("Closing multi buffer failed");
13528 pane.update(cx, |pane, cx| {
13529 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13530 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13531 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13532 assert_eq!(
13533 pane.items()
13534 .map(|item| item.item_id())
13535 .sorted()
13536 .collect::<Vec<_>>(),
13537 vec![
13538 dirty_regular_buffer.item_id(),
13539 dirty_regular_buffer_2.item_id(),
13540 ],
13541 "Should have no multi buffer left in the pane"
13542 );
13543 assert!(dirty_regular_buffer.read(cx).is_dirty);
13544 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13545 });
13546 }
13547
13548 #[gpui::test]
13549 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13550 init_test(cx);
13551 let fs = FakeFs::new(cx.executor());
13552 let project = Project::test(fs, [], cx).await;
13553 let (multi_workspace, cx) =
13554 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13555 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13556
13557 // Add a new panel to the right dock, opening the dock and setting the
13558 // focus to the new panel.
13559 let panel = workspace.update_in(cx, |workspace, window, cx| {
13560 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13561 workspace.add_panel(panel.clone(), window, cx);
13562
13563 workspace
13564 .right_dock()
13565 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13566
13567 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13568
13569 panel
13570 });
13571
13572 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13573 // panel to the next valid position which, in this case, is the left
13574 // dock.
13575 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13576 workspace.update(cx, |workspace, cx| {
13577 assert!(workspace.left_dock().read(cx).is_open());
13578 assert_eq!(panel.read(cx).position, DockPosition::Left);
13579 });
13580
13581 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13582 // panel to the next valid position which, in this case, is the bottom
13583 // dock.
13584 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13585 workspace.update(cx, |workspace, cx| {
13586 assert!(workspace.bottom_dock().read(cx).is_open());
13587 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13588 });
13589
13590 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13591 // around moving the panel to its initial position, the right dock.
13592 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13593 workspace.update(cx, |workspace, cx| {
13594 assert!(workspace.right_dock().read(cx).is_open());
13595 assert_eq!(panel.read(cx).position, DockPosition::Right);
13596 });
13597
13598 // Remove focus from the panel, ensuring that, if the panel is not
13599 // focused, the `MoveFocusedPanelToNextPosition` action does not update
13600 // the panel's position, so the panel is still in the right dock.
13601 workspace.update_in(cx, |workspace, window, cx| {
13602 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13603 });
13604
13605 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13606 workspace.update(cx, |workspace, cx| {
13607 assert!(workspace.right_dock().read(cx).is_open());
13608 assert_eq!(panel.read(cx).position, DockPosition::Right);
13609 });
13610 }
13611
13612 #[gpui::test]
13613 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13614 init_test(cx);
13615
13616 let fs = FakeFs::new(cx.executor());
13617 let project = Project::test(fs, [], cx).await;
13618 let (workspace, cx) =
13619 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13620
13621 let item_1 = cx.new(|cx| {
13622 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13623 });
13624 workspace.update_in(cx, |workspace, window, cx| {
13625 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13626 workspace.move_item_to_pane_in_direction(
13627 &MoveItemToPaneInDirection {
13628 direction: SplitDirection::Right,
13629 focus: true,
13630 clone: false,
13631 },
13632 window,
13633 cx,
13634 );
13635 workspace.move_item_to_pane_at_index(
13636 &MoveItemToPane {
13637 destination: 3,
13638 focus: true,
13639 clone: false,
13640 },
13641 window,
13642 cx,
13643 );
13644
13645 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13646 assert_eq!(
13647 pane_items_paths(&workspace.active_pane, cx),
13648 vec!["first.txt".to_string()],
13649 "Single item was not moved anywhere"
13650 );
13651 });
13652
13653 let item_2 = cx.new(|cx| {
13654 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13655 });
13656 workspace.update_in(cx, |workspace, window, cx| {
13657 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13658 assert_eq!(
13659 pane_items_paths(&workspace.panes[0], cx),
13660 vec!["first.txt".to_string(), "second.txt".to_string()],
13661 );
13662 workspace.move_item_to_pane_in_direction(
13663 &MoveItemToPaneInDirection {
13664 direction: SplitDirection::Right,
13665 focus: true,
13666 clone: false,
13667 },
13668 window,
13669 cx,
13670 );
13671
13672 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13673 assert_eq!(
13674 pane_items_paths(&workspace.panes[0], cx),
13675 vec!["first.txt".to_string()],
13676 "After moving, one item should be left in the original pane"
13677 );
13678 assert_eq!(
13679 pane_items_paths(&workspace.panes[1], cx),
13680 vec!["second.txt".to_string()],
13681 "New item should have been moved to the new pane"
13682 );
13683 });
13684
13685 let item_3 = cx.new(|cx| {
13686 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13687 });
13688 workspace.update_in(cx, |workspace, window, cx| {
13689 let original_pane = workspace.panes[0].clone();
13690 workspace.set_active_pane(&original_pane, window, cx);
13691 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13692 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13693 assert_eq!(
13694 pane_items_paths(&workspace.active_pane, cx),
13695 vec!["first.txt".to_string(), "third.txt".to_string()],
13696 "New pane should be ready to move one item out"
13697 );
13698
13699 workspace.move_item_to_pane_at_index(
13700 &MoveItemToPane {
13701 destination: 3,
13702 focus: true,
13703 clone: false,
13704 },
13705 window,
13706 cx,
13707 );
13708 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13709 assert_eq!(
13710 pane_items_paths(&workspace.active_pane, cx),
13711 vec!["first.txt".to_string()],
13712 "After moving, one item should be left in the original pane"
13713 );
13714 assert_eq!(
13715 pane_items_paths(&workspace.panes[1], cx),
13716 vec!["second.txt".to_string()],
13717 "Previously created pane should be unchanged"
13718 );
13719 assert_eq!(
13720 pane_items_paths(&workspace.panes[2], cx),
13721 vec!["third.txt".to_string()],
13722 "New item should have been moved to the new pane"
13723 );
13724 });
13725 }
13726
13727 #[gpui::test]
13728 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13729 init_test(cx);
13730
13731 let fs = FakeFs::new(cx.executor());
13732 let project = Project::test(fs, [], cx).await;
13733 let (workspace, cx) =
13734 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13735
13736 let item_1 = cx.new(|cx| {
13737 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13738 });
13739 workspace.update_in(cx, |workspace, window, cx| {
13740 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13741 workspace.move_item_to_pane_in_direction(
13742 &MoveItemToPaneInDirection {
13743 direction: SplitDirection::Right,
13744 focus: true,
13745 clone: true,
13746 },
13747 window,
13748 cx,
13749 );
13750 });
13751 cx.run_until_parked();
13752 workspace.update_in(cx, |workspace, window, cx| {
13753 workspace.move_item_to_pane_at_index(
13754 &MoveItemToPane {
13755 destination: 3,
13756 focus: true,
13757 clone: true,
13758 },
13759 window,
13760 cx,
13761 );
13762 });
13763 cx.run_until_parked();
13764
13765 workspace.update(cx, |workspace, cx| {
13766 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13767 for pane in workspace.panes() {
13768 assert_eq!(
13769 pane_items_paths(pane, cx),
13770 vec!["first.txt".to_string()],
13771 "Single item exists in all panes"
13772 );
13773 }
13774 });
13775
13776 // verify that the active pane has been updated after waiting for the
13777 // pane focus event to fire and resolve
13778 workspace.read_with(cx, |workspace, _app| {
13779 assert_eq!(
13780 workspace.active_pane(),
13781 &workspace.panes[2],
13782 "The third pane should be the active one: {:?}",
13783 workspace.panes
13784 );
13785 })
13786 }
13787
13788 #[gpui::test]
13789 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13790 init_test(cx);
13791
13792 let fs = FakeFs::new(cx.executor());
13793 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13794
13795 let project = Project::test(fs, ["root".as_ref()], cx).await;
13796 let (workspace, cx) =
13797 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13798
13799 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13800 // Add item to pane A with project path
13801 let item_a = cx.new(|cx| {
13802 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13803 });
13804 workspace.update_in(cx, |workspace, window, cx| {
13805 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13806 });
13807
13808 // Split to create pane B
13809 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13810 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13811 });
13812
13813 // Add item with SAME project path to pane B, and pin it
13814 let item_b = cx.new(|cx| {
13815 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13816 });
13817 pane_b.update_in(cx, |pane, window, cx| {
13818 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13819 pane.set_pinned_count(1);
13820 });
13821
13822 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13823 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13824
13825 // close_pinned: false should only close the unpinned copy
13826 workspace.update_in(cx, |workspace, window, cx| {
13827 workspace.close_item_in_all_panes(
13828 &CloseItemInAllPanes {
13829 save_intent: Some(SaveIntent::Close),
13830 close_pinned: false,
13831 },
13832 window,
13833 cx,
13834 )
13835 });
13836 cx.executor().run_until_parked();
13837
13838 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13839 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13840 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13841 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13842
13843 // Split again, seeing as closing the previous item also closed its
13844 // pane, so only pane remains, which does not allow us to properly test
13845 // that both items close when `close_pinned: true`.
13846 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13847 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13848 });
13849
13850 // Add an item with the same project path to pane C so that
13851 // close_item_in_all_panes can determine what to close across all panes
13852 // (it reads the active item from the active pane, and split_pane
13853 // creates an empty pane).
13854 let item_c = cx.new(|cx| {
13855 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13856 });
13857 pane_c.update_in(cx, |pane, window, cx| {
13858 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13859 });
13860
13861 // close_pinned: true should close the pinned copy too
13862 workspace.update_in(cx, |workspace, window, cx| {
13863 let panes_count = workspace.panes().len();
13864 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13865
13866 workspace.close_item_in_all_panes(
13867 &CloseItemInAllPanes {
13868 save_intent: Some(SaveIntent::Close),
13869 close_pinned: true,
13870 },
13871 window,
13872 cx,
13873 )
13874 });
13875 cx.executor().run_until_parked();
13876
13877 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13878 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13879 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13880 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13881 }
13882
13883 mod register_project_item_tests {
13884
13885 use super::*;
13886
13887 // View
13888 struct TestPngItemView {
13889 focus_handle: FocusHandle,
13890 }
13891 // Model
13892 struct TestPngItem {}
13893
13894 impl project::ProjectItem for TestPngItem {
13895 fn try_open(
13896 _project: &Entity<Project>,
13897 path: &ProjectPath,
13898 cx: &mut App,
13899 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13900 if path.path.extension().unwrap() == "png" {
13901 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13902 } else {
13903 None
13904 }
13905 }
13906
13907 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13908 None
13909 }
13910
13911 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13912 None
13913 }
13914
13915 fn is_dirty(&self) -> bool {
13916 false
13917 }
13918 }
13919
13920 impl Item for TestPngItemView {
13921 type Event = ();
13922 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13923 "".into()
13924 }
13925 }
13926 impl EventEmitter<()> for TestPngItemView {}
13927 impl Focusable for TestPngItemView {
13928 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13929 self.focus_handle.clone()
13930 }
13931 }
13932
13933 impl Render for TestPngItemView {
13934 fn render(
13935 &mut self,
13936 _window: &mut Window,
13937 _cx: &mut Context<Self>,
13938 ) -> impl IntoElement {
13939 Empty
13940 }
13941 }
13942
13943 impl ProjectItem for TestPngItemView {
13944 type Item = TestPngItem;
13945
13946 fn for_project_item(
13947 _project: Entity<Project>,
13948 _pane: Option<&Pane>,
13949 _item: Entity<Self::Item>,
13950 _: &mut Window,
13951 cx: &mut Context<Self>,
13952 ) -> Self
13953 where
13954 Self: Sized,
13955 {
13956 Self {
13957 focus_handle: cx.focus_handle(),
13958 }
13959 }
13960 }
13961
13962 // View
13963 struct TestIpynbItemView {
13964 focus_handle: FocusHandle,
13965 }
13966 // Model
13967 struct TestIpynbItem {}
13968
13969 impl project::ProjectItem for TestIpynbItem {
13970 fn try_open(
13971 _project: &Entity<Project>,
13972 path: &ProjectPath,
13973 cx: &mut App,
13974 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13975 if path.path.extension().unwrap() == "ipynb" {
13976 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13977 } else {
13978 None
13979 }
13980 }
13981
13982 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13983 None
13984 }
13985
13986 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13987 None
13988 }
13989
13990 fn is_dirty(&self) -> bool {
13991 false
13992 }
13993 }
13994
13995 impl Item for TestIpynbItemView {
13996 type Event = ();
13997 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13998 "".into()
13999 }
14000 }
14001 impl EventEmitter<()> for TestIpynbItemView {}
14002 impl Focusable for TestIpynbItemView {
14003 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14004 self.focus_handle.clone()
14005 }
14006 }
14007
14008 impl Render for TestIpynbItemView {
14009 fn render(
14010 &mut self,
14011 _window: &mut Window,
14012 _cx: &mut Context<Self>,
14013 ) -> impl IntoElement {
14014 Empty
14015 }
14016 }
14017
14018 impl ProjectItem for TestIpynbItemView {
14019 type Item = TestIpynbItem;
14020
14021 fn for_project_item(
14022 _project: Entity<Project>,
14023 _pane: Option<&Pane>,
14024 _item: Entity<Self::Item>,
14025 _: &mut Window,
14026 cx: &mut Context<Self>,
14027 ) -> Self
14028 where
14029 Self: Sized,
14030 {
14031 Self {
14032 focus_handle: cx.focus_handle(),
14033 }
14034 }
14035 }
14036
14037 struct TestAlternatePngItemView {
14038 focus_handle: FocusHandle,
14039 }
14040
14041 impl Item for TestAlternatePngItemView {
14042 type Event = ();
14043 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14044 "".into()
14045 }
14046 }
14047
14048 impl EventEmitter<()> for TestAlternatePngItemView {}
14049 impl Focusable for TestAlternatePngItemView {
14050 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14051 self.focus_handle.clone()
14052 }
14053 }
14054
14055 impl Render for TestAlternatePngItemView {
14056 fn render(
14057 &mut self,
14058 _window: &mut Window,
14059 _cx: &mut Context<Self>,
14060 ) -> impl IntoElement {
14061 Empty
14062 }
14063 }
14064
14065 impl ProjectItem for TestAlternatePngItemView {
14066 type Item = TestPngItem;
14067
14068 fn for_project_item(
14069 _project: Entity<Project>,
14070 _pane: Option<&Pane>,
14071 _item: Entity<Self::Item>,
14072 _: &mut Window,
14073 cx: &mut Context<Self>,
14074 ) -> Self
14075 where
14076 Self: Sized,
14077 {
14078 Self {
14079 focus_handle: cx.focus_handle(),
14080 }
14081 }
14082 }
14083
14084 #[gpui::test]
14085 async fn test_register_project_item(cx: &mut TestAppContext) {
14086 init_test(cx);
14087
14088 cx.update(|cx| {
14089 register_project_item::<TestPngItemView>(cx);
14090 register_project_item::<TestIpynbItemView>(cx);
14091 });
14092
14093 let fs = FakeFs::new(cx.executor());
14094 fs.insert_tree(
14095 "/root1",
14096 json!({
14097 "one.png": "BINARYDATAHERE",
14098 "two.ipynb": "{ totally a notebook }",
14099 "three.txt": "editing text, sure why not?"
14100 }),
14101 )
14102 .await;
14103
14104 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14105 let (workspace, cx) =
14106 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14107
14108 let worktree_id = project.update(cx, |project, cx| {
14109 project.worktrees(cx).next().unwrap().read(cx).id()
14110 });
14111
14112 let handle = workspace
14113 .update_in(cx, |workspace, window, cx| {
14114 let project_path = (worktree_id, rel_path("one.png"));
14115 workspace.open_path(project_path, None, true, window, cx)
14116 })
14117 .await
14118 .unwrap();
14119
14120 // Now we can check if the handle we got back errored or not
14121 assert_eq!(
14122 handle.to_any_view().entity_type(),
14123 TypeId::of::<TestPngItemView>()
14124 );
14125
14126 let handle = workspace
14127 .update_in(cx, |workspace, window, cx| {
14128 let project_path = (worktree_id, rel_path("two.ipynb"));
14129 workspace.open_path(project_path, None, true, window, cx)
14130 })
14131 .await
14132 .unwrap();
14133
14134 assert_eq!(
14135 handle.to_any_view().entity_type(),
14136 TypeId::of::<TestIpynbItemView>()
14137 );
14138
14139 let handle = workspace
14140 .update_in(cx, |workspace, window, cx| {
14141 let project_path = (worktree_id, rel_path("three.txt"));
14142 workspace.open_path(project_path, None, true, window, cx)
14143 })
14144 .await;
14145 assert!(handle.is_err());
14146 }
14147
14148 #[gpui::test]
14149 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14150 init_test(cx);
14151
14152 cx.update(|cx| {
14153 register_project_item::<TestPngItemView>(cx);
14154 register_project_item::<TestAlternatePngItemView>(cx);
14155 });
14156
14157 let fs = FakeFs::new(cx.executor());
14158 fs.insert_tree(
14159 "/root1",
14160 json!({
14161 "one.png": "BINARYDATAHERE",
14162 "two.ipynb": "{ totally a notebook }",
14163 "three.txt": "editing text, sure why not?"
14164 }),
14165 )
14166 .await;
14167 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14168 let (workspace, cx) =
14169 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14170 let worktree_id = project.update(cx, |project, cx| {
14171 project.worktrees(cx).next().unwrap().read(cx).id()
14172 });
14173
14174 let handle = workspace
14175 .update_in(cx, |workspace, window, cx| {
14176 let project_path = (worktree_id, rel_path("one.png"));
14177 workspace.open_path(project_path, None, true, window, cx)
14178 })
14179 .await
14180 .unwrap();
14181
14182 // This _must_ be the second item registered
14183 assert_eq!(
14184 handle.to_any_view().entity_type(),
14185 TypeId::of::<TestAlternatePngItemView>()
14186 );
14187
14188 let handle = workspace
14189 .update_in(cx, |workspace, window, cx| {
14190 let project_path = (worktree_id, rel_path("three.txt"));
14191 workspace.open_path(project_path, None, true, window, cx)
14192 })
14193 .await;
14194 assert!(handle.is_err());
14195 }
14196 }
14197
14198 #[gpui::test]
14199 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14200 init_test(cx);
14201
14202 let fs = FakeFs::new(cx.executor());
14203 let project = Project::test(fs, [], cx).await;
14204 let (workspace, _cx) =
14205 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14206
14207 // Test with status bar shown (default)
14208 workspace.read_with(cx, |workspace, cx| {
14209 let visible = workspace.status_bar_visible(cx);
14210 assert!(visible, "Status bar should be visible by default");
14211 });
14212
14213 // Test with status bar hidden
14214 cx.update_global(|store: &mut SettingsStore, cx| {
14215 store.update_user_settings(cx, |settings| {
14216 settings.status_bar.get_or_insert_default().show = Some(false);
14217 });
14218 });
14219
14220 workspace.read_with(cx, |workspace, cx| {
14221 let visible = workspace.status_bar_visible(cx);
14222 assert!(!visible, "Status bar should be hidden when show is false");
14223 });
14224
14225 // Test with status bar shown explicitly
14226 cx.update_global(|store: &mut SettingsStore, cx| {
14227 store.update_user_settings(cx, |settings| {
14228 settings.status_bar.get_or_insert_default().show = Some(true);
14229 });
14230 });
14231
14232 workspace.read_with(cx, |workspace, cx| {
14233 let visible = workspace.status_bar_visible(cx);
14234 assert!(visible, "Status bar should be visible when show is true");
14235 });
14236 }
14237
14238 #[gpui::test]
14239 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14240 init_test(cx);
14241
14242 let fs = FakeFs::new(cx.executor());
14243 let project = Project::test(fs, [], cx).await;
14244 let (multi_workspace, cx) =
14245 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14246 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14247 let panel = workspace.update_in(cx, |workspace, window, cx| {
14248 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14249 workspace.add_panel(panel.clone(), window, cx);
14250
14251 workspace
14252 .right_dock()
14253 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14254
14255 panel
14256 });
14257
14258 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14259 let item_a = cx.new(TestItem::new);
14260 let item_b = cx.new(TestItem::new);
14261 let item_a_id = item_a.entity_id();
14262 let item_b_id = item_b.entity_id();
14263
14264 pane.update_in(cx, |pane, window, cx| {
14265 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14266 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14267 });
14268
14269 pane.read_with(cx, |pane, _| {
14270 assert_eq!(pane.items_len(), 2);
14271 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14272 });
14273
14274 workspace.update_in(cx, |workspace, window, cx| {
14275 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14276 });
14277
14278 workspace.update_in(cx, |_, window, cx| {
14279 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14280 });
14281
14282 // Assert that the `pane::CloseActiveItem` action is handled at the
14283 // workspace level when one of the dock panels is focused and, in that
14284 // case, the center pane's active item is closed but the focus is not
14285 // moved.
14286 cx.dispatch_action(pane::CloseActiveItem::default());
14287 cx.run_until_parked();
14288
14289 pane.read_with(cx, |pane, _| {
14290 assert_eq!(pane.items_len(), 1);
14291 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14292 });
14293
14294 workspace.update_in(cx, |workspace, window, cx| {
14295 assert!(workspace.right_dock().read(cx).is_open());
14296 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14297 });
14298 }
14299
14300 #[gpui::test]
14301 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14302 init_test(cx);
14303 let fs = FakeFs::new(cx.executor());
14304
14305 let project_a = Project::test(fs.clone(), [], cx).await;
14306 let project_b = Project::test(fs, [], cx).await;
14307
14308 let multi_workspace_handle =
14309 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14310 cx.run_until_parked();
14311
14312 let workspace_a = multi_workspace_handle
14313 .read_with(cx, |mw, _| mw.workspace().clone())
14314 .unwrap();
14315
14316 let _workspace_b = multi_workspace_handle
14317 .update(cx, |mw, window, cx| {
14318 mw.test_add_workspace(project_b, window, cx)
14319 })
14320 .unwrap();
14321
14322 // Switch to workspace A
14323 multi_workspace_handle
14324 .update(cx, |mw, window, cx| {
14325 mw.activate_index(0, window, cx);
14326 })
14327 .unwrap();
14328
14329 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14330
14331 // Add a panel to workspace A's right dock and open the dock
14332 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14333 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14334 workspace.add_panel(panel.clone(), window, cx);
14335 workspace
14336 .right_dock()
14337 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14338 panel
14339 });
14340
14341 // Focus the panel through the workspace (matching existing test pattern)
14342 workspace_a.update_in(cx, |workspace, window, cx| {
14343 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14344 });
14345
14346 // Zoom the panel
14347 panel.update_in(cx, |panel, window, cx| {
14348 panel.set_zoomed(true, window, cx);
14349 });
14350
14351 // Verify the panel is zoomed and the dock is open
14352 workspace_a.update_in(cx, |workspace, window, cx| {
14353 assert!(
14354 workspace.right_dock().read(cx).is_open(),
14355 "dock should be open before switch"
14356 );
14357 assert!(
14358 panel.is_zoomed(window, cx),
14359 "panel should be zoomed before switch"
14360 );
14361 assert!(
14362 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14363 "panel should be focused before switch"
14364 );
14365 });
14366
14367 // Switch to workspace B
14368 multi_workspace_handle
14369 .update(cx, |mw, window, cx| {
14370 mw.activate_index(1, window, cx);
14371 })
14372 .unwrap();
14373 cx.run_until_parked();
14374
14375 // Switch back to workspace A
14376 multi_workspace_handle
14377 .update(cx, |mw, window, cx| {
14378 mw.activate_index(0, window, cx);
14379 })
14380 .unwrap();
14381 cx.run_until_parked();
14382
14383 // Verify the panel is still zoomed and the dock is still open
14384 workspace_a.update_in(cx, |workspace, window, cx| {
14385 assert!(
14386 workspace.right_dock().read(cx).is_open(),
14387 "dock should still be open after switching back"
14388 );
14389 assert!(
14390 panel.is_zoomed(window, cx),
14391 "panel should still be zoomed after switching back"
14392 );
14393 });
14394 }
14395
14396 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14397 pane.read(cx)
14398 .items()
14399 .flat_map(|item| {
14400 item.project_paths(cx)
14401 .into_iter()
14402 .map(|path| path.path.display(PathStyle::local()).into_owned())
14403 })
14404 .collect()
14405 }
14406
14407 pub fn init_test(cx: &mut TestAppContext) {
14408 cx.update(|cx| {
14409 let settings_store = SettingsStore::test(cx);
14410 cx.set_global(settings_store);
14411 cx.set_global(db::AppDatabase::test_new());
14412 theme::init(theme::LoadThemes::JustBase, cx);
14413 });
14414 }
14415
14416 #[gpui::test]
14417 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14418 use settings::{ThemeName, ThemeSelection};
14419 use theme::SystemAppearance;
14420 use zed_actions::theme::ToggleMode;
14421
14422 init_test(cx);
14423
14424 let fs = FakeFs::new(cx.executor());
14425 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14426
14427 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14428 .await;
14429
14430 // Build a test project and workspace view so the test can invoke
14431 // the workspace action handler the same way the UI would.
14432 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14433 let (workspace, cx) =
14434 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14435
14436 // Seed the settings file with a plain static light theme so the
14437 // first toggle always starts from a known persisted state.
14438 workspace.update_in(cx, |_workspace, _window, cx| {
14439 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14440 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14441 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14442 });
14443 });
14444 cx.executor().advance_clock(Duration::from_millis(200));
14445 cx.run_until_parked();
14446
14447 // Confirm the initial persisted settings contain the static theme
14448 // we just wrote before any toggling happens.
14449 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14450 assert!(settings_text.contains(r#""theme": "One Light""#));
14451
14452 // Toggle once. This should migrate the persisted theme settings
14453 // into light/dark slots and enable system mode.
14454 workspace.update_in(cx, |workspace, window, cx| {
14455 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14456 });
14457 cx.executor().advance_clock(Duration::from_millis(200));
14458 cx.run_until_parked();
14459
14460 // 1. Static -> Dynamic
14461 // this assertion checks theme changed from static to dynamic.
14462 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14463 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14464 assert_eq!(
14465 parsed["theme"],
14466 serde_json::json!({
14467 "mode": "system",
14468 "light": "One Light",
14469 "dark": "One Dark"
14470 })
14471 );
14472
14473 // 2. Toggle again, suppose it will change the mode to light
14474 workspace.update_in(cx, |workspace, window, cx| {
14475 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14476 });
14477 cx.executor().advance_clock(Duration::from_millis(200));
14478 cx.run_until_parked();
14479
14480 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14481 assert!(settings_text.contains(r#""mode": "light""#));
14482 }
14483
14484 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14485 let item = TestProjectItem::new(id, path, cx);
14486 item.update(cx, |item, _| {
14487 item.is_dirty = true;
14488 });
14489 item
14490 }
14491
14492 #[gpui::test]
14493 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14494 cx: &mut gpui::TestAppContext,
14495 ) {
14496 init_test(cx);
14497 let fs = FakeFs::new(cx.executor());
14498
14499 let project = Project::test(fs, [], cx).await;
14500 let (workspace, cx) =
14501 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14502
14503 let panel = workspace.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 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14513 pane.update_in(cx, |pane, window, cx| {
14514 let item = cx.new(TestItem::new);
14515 pane.add_item(Box::new(item), true, true, None, window, cx);
14516 });
14517
14518 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14519 // mirrors the real-world flow and avoids side effects from directly
14520 // focusing the panel while the center pane is active.
14521 workspace.update_in(cx, |workspace, window, cx| {
14522 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14523 });
14524
14525 panel.update_in(cx, |panel, window, cx| {
14526 panel.set_zoomed(true, window, cx);
14527 });
14528
14529 workspace.update_in(cx, |workspace, window, cx| {
14530 assert!(workspace.right_dock().read(cx).is_open());
14531 assert!(panel.is_zoomed(window, cx));
14532 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14533 });
14534
14535 // Simulate a spurious pane::Event::Focus on the center pane while the
14536 // panel still has focus. This mirrors what happens during macOS window
14537 // activation: the center pane fires a focus event even though actual
14538 // focus remains on the dock panel.
14539 pane.update_in(cx, |_, _, cx| {
14540 cx.emit(pane::Event::Focus);
14541 });
14542
14543 // The dock must remain open because the panel had focus at the time the
14544 // event was processed. Before the fix, dock_to_preserve was None for
14545 // panels that don't implement pane(), causing the dock to close.
14546 workspace.update_in(cx, |workspace, window, cx| {
14547 assert!(
14548 workspace.right_dock().read(cx).is_open(),
14549 "Dock should stay open when its zoomed panel (without pane()) still has focus"
14550 );
14551 assert!(panel.is_zoomed(window, cx));
14552 });
14553 }
14554
14555 #[gpui::test]
14556 async fn test_panels_stay_open_after_position_change_and_settings_update(
14557 cx: &mut gpui::TestAppContext,
14558 ) {
14559 init_test(cx);
14560 let fs = FakeFs::new(cx.executor());
14561 let project = Project::test(fs, [], cx).await;
14562 let (workspace, cx) =
14563 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14564
14565 // Add two panels to the left dock and open it.
14566 let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14567 let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14568 let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14569 workspace.add_panel(panel_a.clone(), window, cx);
14570 workspace.add_panel(panel_b.clone(), window, cx);
14571 workspace.left_dock().update(cx, |dock, cx| {
14572 dock.set_open(true, window, cx);
14573 dock.activate_panel(0, window, cx);
14574 });
14575 (panel_a, panel_b)
14576 });
14577
14578 workspace.update_in(cx, |workspace, _, cx| {
14579 assert!(workspace.left_dock().read(cx).is_open());
14580 });
14581
14582 // Simulate a feature flag changing default dock positions: both panels
14583 // move from Left to Right.
14584 workspace.update_in(cx, |_workspace, _window, cx| {
14585 panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14586 panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14587 cx.update_global::<SettingsStore, _>(|_, _| {});
14588 });
14589
14590 // Both panels should now be in the right dock.
14591 workspace.update_in(cx, |workspace, _, cx| {
14592 let right_dock = workspace.right_dock().read(cx);
14593 assert_eq!(right_dock.panels_len(), 2);
14594 });
14595
14596 // Open the right dock and activate panel_b (simulating the user
14597 // opening the panel after it moved).
14598 workspace.update_in(cx, |workspace, window, cx| {
14599 workspace.right_dock().update(cx, |dock, cx| {
14600 dock.set_open(true, window, cx);
14601 dock.activate_panel(1, window, cx);
14602 });
14603 });
14604
14605 // Now trigger another SettingsStore change
14606 workspace.update_in(cx, |_workspace, _window, cx| {
14607 cx.update_global::<SettingsStore, _>(|_, _| {});
14608 });
14609
14610 workspace.update_in(cx, |workspace, _, cx| {
14611 assert!(
14612 workspace.right_dock().read(cx).is_open(),
14613 "Right dock should still be open after a settings change"
14614 );
14615 assert_eq!(
14616 workspace.right_dock().read(cx).panels_len(),
14617 2,
14618 "Both panels should still be in the right dock"
14619 );
14620 });
14621 }
14622}