1pub mod active_file_name;
2pub mod dock;
3pub mod history_manager;
4pub mod invalid_item_view;
5pub mod item;
6mod modal_layer;
7mod multi_workspace;
8#[cfg(test)]
9mod multi_workspace_tests;
10pub mod notifications;
11pub mod pane;
12pub mod pane_group;
13pub mod path_list {
14 pub use util::path_list::{PathList, SerializedPathList};
15}
16mod persistence;
17pub mod searchable;
18mod security_modal;
19pub mod shared_screen;
20use db::smol::future::yield_now;
21pub use shared_screen::SharedScreen;
22pub mod focus_follows_mouse;
23mod status_bar;
24pub mod tasks;
25mod theme_preview;
26mod toast_layer;
27mod toolbar;
28pub mod welcome;
29mod workspace_settings;
30
31pub use crate::notifications::NotificationFrame;
32pub use dock::Panel;
33pub use multi_workspace::{
34 CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
35 MultiWorkspaceEvent, NextWorkspace, PreviousWorkspace, Sidebar, SidebarEvent, SidebarHandle,
36 SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar, sidebar_side_context_menu,
37};
38pub use path_list::{PathList, SerializedPathList};
39pub use toast_layer::{ToastAction, ToastLayer, ToastView};
40
41use anyhow::{Context as _, Result, anyhow};
42use client::{
43 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
44 proto::{self, ErrorCode, PanelId, PeerId},
45};
46use collections::{HashMap, HashSet, hash_map};
47use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
48use fs::Fs;
49use futures::{
50 Future, FutureExt, StreamExt,
51 channel::{
52 mpsc::{self, UnboundedReceiver, UnboundedSender},
53 oneshot,
54 },
55 future::{Shared, try_join_all},
56};
57use gpui::{
58 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
59 Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
60 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
61 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
62 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
63 WindowOptions, actions, canvas, point, relative, size, transparent_black,
64};
65pub use history_manager::*;
66pub use item::{
67 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
68 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
69};
70use itertools::Itertools;
71use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
72pub use modal_layer::*;
73use node_runtime::NodeRuntime;
74use notifications::{
75 DetachAndPromptErr, Notifications, dismiss_app_notification,
76 simple_message_notification::MessageNotification,
77};
78pub use pane::*;
79pub use pane_group::{
80 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
81 SplitDirection,
82};
83use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
84pub use persistence::{
85 WorkspaceDb, delete_unloaded_items,
86 model::{
87 DockStructure, ItemId, MultiWorkspaceState, SerializedMultiWorkspace,
88 SerializedWorkspaceLocation, SessionWorkspace,
89 },
90 read_serialized_multi_workspaces, resolve_worktree_workspaces,
91};
92use postage::stream::Stream;
93use project::{
94 DirectoryLister, Project, ProjectEntryId, ProjectGroupKey, ProjectPath, ResolvedPath, Worktree,
95 WorktreeId, WorktreeSettings,
96 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
97 project_settings::ProjectSettings,
98 toolchain_store::ToolchainStoreEvent,
99 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
100};
101use remote::{
102 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
103 remote_client::ConnectionIdentifier,
104};
105use schemars::JsonSchema;
106use serde::Deserialize;
107use session::AppSession;
108use settings::{
109 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
110};
111
112use sqlez::{
113 bindable::{Bind, Column, StaticColumnCount},
114 statement::Statement,
115};
116use status_bar::StatusBar;
117pub use status_bar::StatusItemView;
118use std::{
119 any::TypeId,
120 borrow::Cow,
121 cell::RefCell,
122 cmp,
123 collections::VecDeque,
124 env,
125 hash::Hash,
126 path::{Path, PathBuf},
127 process::ExitStatus,
128 rc::Rc,
129 sync::{
130 Arc, LazyLock,
131 atomic::{AtomicBool, AtomicUsize},
132 },
133 time::Duration,
134};
135use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
136use theme::{ActiveTheme, SystemAppearance};
137use theme_settings::ThemeSettings;
138pub use toolbar::{
139 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
140};
141pub use ui;
142use ui::{Window, prelude::*};
143use util::{
144 ResultExt, TryFutureExt,
145 paths::{PathStyle, SanitizedPath},
146 rel_path::RelPath,
147 serde::default_true,
148};
149use uuid::Uuid;
150pub use workspace_settings::{
151 AutosaveSetting, BottomDockLayout, FocusFollowsMouse, RestoreOnStartupBehavior,
152 StatusBarSettings, TabBarSettings, WorkspaceSettings,
153};
154use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
155
156use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::NotificationId};
157use crate::{
158 persistence::{
159 SerializedAxis,
160 model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
161 },
162 security_modal::SecurityModal,
163};
164
165pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
166
167static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
168 env::var("ZED_WINDOW_SIZE")
169 .ok()
170 .as_deref()
171 .and_then(parse_pixel_size_env_var)
172});
173
174static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
175 env::var("ZED_WINDOW_POSITION")
176 .ok()
177 .as_deref()
178 .and_then(parse_pixel_position_env_var)
179});
180
181pub trait TerminalProvider {
182 fn spawn(
183 &self,
184 task: SpawnInTerminal,
185 window: &mut Window,
186 cx: &mut App,
187 ) -> Task<Option<Result<ExitStatus>>>;
188}
189
190pub trait DebuggerProvider {
191 // `active_buffer` is used to resolve build task's name against language-specific tasks.
192 fn start_session(
193 &self,
194 definition: DebugScenario,
195 task_context: SharedTaskContext,
196 active_buffer: Option<Entity<Buffer>>,
197 worktree_id: Option<WorktreeId>,
198 window: &mut Window,
199 cx: &mut App,
200 );
201
202 fn spawn_task_or_modal(
203 &self,
204 workspace: &mut Workspace,
205 action: &Spawn,
206 window: &mut Window,
207 cx: &mut Context<Workspace>,
208 );
209
210 fn task_scheduled(&self, cx: &mut App);
211 fn debug_scenario_scheduled(&self, cx: &mut App);
212 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
213
214 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
215}
216
217/// Opens a file or directory.
218#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
219#[action(namespace = workspace)]
220pub struct Open {
221 /// When true, opens in a new window. When false, adds to the current
222 /// window as a new workspace (multi-workspace).
223 #[serde(default = "Open::default_create_new_window")]
224 pub create_new_window: bool,
225}
226
227impl Open {
228 pub const DEFAULT: Self = Self {
229 create_new_window: true,
230 };
231
232 /// Used by `#[serde(default)]` on the `create_new_window` field so that
233 /// the serde default and `Open::DEFAULT` stay in sync.
234 fn default_create_new_window() -> bool {
235 Self::DEFAULT.create_new_window
236 }
237}
238
239impl Default for Open {
240 fn default() -> Self {
241 Self::DEFAULT
242 }
243}
244
245actions!(
246 workspace,
247 [
248 /// Activates the next pane in the workspace.
249 ActivateNextPane,
250 /// Activates the previous pane in the workspace.
251 ActivatePreviousPane,
252 /// Activates the last pane in the workspace.
253 ActivateLastPane,
254 /// Switches to the next window.
255 ActivateNextWindow,
256 /// Switches to the previous window.
257 ActivatePreviousWindow,
258 /// Adds a folder to the current project.
259 AddFolderToProject,
260 /// Clears all notifications.
261 ClearAllNotifications,
262 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
263 ClearNavigationHistory,
264 /// Closes the active dock.
265 CloseActiveDock,
266 /// Closes all docks.
267 CloseAllDocks,
268 /// Toggles all docks.
269 ToggleAllDocks,
270 /// Closes the current window.
271 CloseWindow,
272 /// Closes the current project.
273 CloseProject,
274 /// Opens the feedback dialog.
275 Feedback,
276 /// Follows the next collaborator in the session.
277 FollowNextCollaborator,
278 /// Moves the focused panel to the next position.
279 MoveFocusedPanelToNextPosition,
280 /// Creates a new file.
281 NewFile,
282 /// Creates a new file in a vertical split.
283 NewFileSplitVertical,
284 /// Creates a new file in a horizontal split.
285 NewFileSplitHorizontal,
286 /// Opens a new search.
287 NewSearch,
288 /// Opens a new window.
289 NewWindow,
290 /// Opens multiple files.
291 OpenFiles,
292 /// Opens the current location in terminal.
293 OpenInTerminal,
294 /// Opens the component preview.
295 OpenComponentPreview,
296 /// Reloads the active item.
297 ReloadActiveItem,
298 /// Resets the active dock to its default size.
299 ResetActiveDockSize,
300 /// Resets all open docks to their default sizes.
301 ResetOpenDocksSize,
302 /// Reloads the application
303 Reload,
304 /// Saves the current file with a new name.
305 SaveAs,
306 /// Saves without formatting.
307 SaveWithoutFormat,
308 /// Shuts down all debug adapters.
309 ShutdownDebugAdapters,
310 /// Suppresses the current notification.
311 SuppressNotification,
312 /// Toggles the bottom dock.
313 ToggleBottomDock,
314 /// Toggles centered layout mode.
315 ToggleCenteredLayout,
316 /// Toggles edit prediction feature globally for all files.
317 ToggleEditPrediction,
318 /// Toggles the left dock.
319 ToggleLeftDock,
320 /// Toggles the right dock.
321 ToggleRightDock,
322 /// Toggles zoom on the active pane.
323 ToggleZoom,
324 /// Toggles read-only mode for the active item (if supported by that item).
325 ToggleReadOnlyFile,
326 /// Zooms in on the active pane.
327 ZoomIn,
328 /// Zooms out of the active pane.
329 ZoomOut,
330 /// If any worktrees are in restricted mode, shows a modal with possible actions.
331 /// If the modal is shown already, closes it without trusting any worktree.
332 ToggleWorktreeSecurity,
333 /// Clears all trusted worktrees, placing them in restricted mode on next open.
334 /// Requires restart to take effect on already opened projects.
335 ClearTrustedWorktrees,
336 /// Stops following a collaborator.
337 Unfollow,
338 /// Restores the banner.
339 RestoreBanner,
340 /// Toggles expansion of the selected item.
341 ToggleExpandItem,
342 ]
343);
344
345/// Activates a specific pane by its index.
346#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
347#[action(namespace = workspace)]
348pub struct ActivatePane(pub usize);
349
350/// Moves an item to a specific pane by index.
351#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
352#[action(namespace = workspace)]
353#[serde(deny_unknown_fields)]
354pub struct MoveItemToPane {
355 #[serde(default = "default_1")]
356 pub destination: usize,
357 #[serde(default = "default_true")]
358 pub focus: bool,
359 #[serde(default)]
360 pub clone: bool,
361}
362
363fn default_1() -> usize {
364 1
365}
366
367/// Moves an item to a pane in the specified direction.
368#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
369#[action(namespace = workspace)]
370#[serde(deny_unknown_fields)]
371pub struct MoveItemToPaneInDirection {
372 #[serde(default = "default_right")]
373 pub direction: SplitDirection,
374 #[serde(default = "default_true")]
375 pub focus: bool,
376 #[serde(default)]
377 pub clone: bool,
378}
379
380/// Creates a new file in a split of the desired direction.
381#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
382#[action(namespace = workspace)]
383#[serde(deny_unknown_fields)]
384pub struct NewFileSplit(pub SplitDirection);
385
386fn default_right() -> SplitDirection {
387 SplitDirection::Right
388}
389
390/// Saves all open files in the workspace.
391#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
392#[action(namespace = workspace)]
393#[serde(deny_unknown_fields)]
394pub struct SaveAll {
395 #[serde(default)]
396 pub save_intent: Option<SaveIntent>,
397}
398
399/// Saves the current file with the specified options.
400#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
401#[action(namespace = workspace)]
402#[serde(deny_unknown_fields)]
403pub struct Save {
404 #[serde(default)]
405 pub save_intent: Option<SaveIntent>,
406}
407
408/// Moves Focus to the central panes in the workspace.
409#[derive(Clone, Debug, PartialEq, Eq, Action)]
410#[action(namespace = workspace)]
411pub struct FocusCenterPane;
412
413/// Closes all items and panes in the workspace.
414#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
415#[action(namespace = workspace)]
416#[serde(deny_unknown_fields)]
417pub struct CloseAllItemsAndPanes {
418 #[serde(default)]
419 pub save_intent: Option<SaveIntent>,
420}
421
422/// Closes all inactive tabs and panes in the workspace.
423#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
424#[action(namespace = workspace)]
425#[serde(deny_unknown_fields)]
426pub struct CloseInactiveTabsAndPanes {
427 #[serde(default)]
428 pub save_intent: Option<SaveIntent>,
429}
430
431/// Closes the active item across all panes.
432#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
433#[action(namespace = workspace)]
434#[serde(deny_unknown_fields)]
435pub struct CloseItemInAllPanes {
436 #[serde(default)]
437 pub save_intent: Option<SaveIntent>,
438 #[serde(default)]
439 pub close_pinned: bool,
440}
441
442/// Sends a sequence of keystrokes to the active element.
443#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
444#[action(namespace = workspace)]
445pub struct SendKeystrokes(pub String);
446
447actions!(
448 project_symbols,
449 [
450 /// Toggles the project symbols search.
451 #[action(name = "Toggle")]
452 ToggleProjectSymbols
453 ]
454);
455
456/// Toggles the file finder interface.
457#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
458#[action(namespace = file_finder, name = "Toggle")]
459#[serde(deny_unknown_fields)]
460pub struct ToggleFileFinder {
461 #[serde(default)]
462 pub separate_history: bool,
463}
464
465/// Opens a new terminal in the center.
466#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
467#[action(namespace = workspace)]
468#[serde(deny_unknown_fields)]
469pub struct NewCenterTerminal {
470 /// If true, creates a local terminal even in remote projects.
471 #[serde(default)]
472 pub local: bool,
473}
474
475/// Opens a new terminal.
476#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
477#[action(namespace = workspace)]
478#[serde(deny_unknown_fields)]
479pub struct NewTerminal {
480 /// If true, creates a local terminal even in remote projects.
481 #[serde(default)]
482 pub local: bool,
483}
484
485/// Increases size of a currently focused dock by a given amount of pixels.
486#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
487#[action(namespace = workspace)]
488#[serde(deny_unknown_fields)]
489pub struct IncreaseActiveDockSize {
490 /// For 0px parameter, uses UI font size value.
491 #[serde(default)]
492 pub px: u32,
493}
494
495/// Decreases size of a currently focused dock by a given amount of pixels.
496#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
497#[action(namespace = workspace)]
498#[serde(deny_unknown_fields)]
499pub struct DecreaseActiveDockSize {
500 /// For 0px parameter, uses UI font size value.
501 #[serde(default)]
502 pub px: u32,
503}
504
505/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
506#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
507#[action(namespace = workspace)]
508#[serde(deny_unknown_fields)]
509pub struct IncreaseOpenDocksSize {
510 /// For 0px parameter, uses UI font size value.
511 #[serde(default)]
512 pub px: u32,
513}
514
515/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
516#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
517#[action(namespace = workspace)]
518#[serde(deny_unknown_fields)]
519pub struct DecreaseOpenDocksSize {
520 /// For 0px parameter, uses UI font size value.
521 #[serde(default)]
522 pub px: u32,
523}
524
525actions!(
526 workspace,
527 [
528 /// Activates the pane to the left.
529 ActivatePaneLeft,
530 /// Activates the pane to the right.
531 ActivatePaneRight,
532 /// Activates the pane above.
533 ActivatePaneUp,
534 /// Activates the pane below.
535 ActivatePaneDown,
536 /// Swaps the current pane with the one to the left.
537 SwapPaneLeft,
538 /// Swaps the current pane with the one to the right.
539 SwapPaneRight,
540 /// Swaps the current pane with the one above.
541 SwapPaneUp,
542 /// Swaps the current pane with the one below.
543 SwapPaneDown,
544 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
545 SwapPaneAdjacent,
546 /// Move the current pane to be at the far left.
547 MovePaneLeft,
548 /// Move the current pane to be at the far right.
549 MovePaneRight,
550 /// Move the current pane to be at the very top.
551 MovePaneUp,
552 /// Move the current pane to be at the very bottom.
553 MovePaneDown,
554 ]
555);
556
557#[derive(PartialEq, Eq, Debug)]
558pub enum CloseIntent {
559 /// Quit the program entirely.
560 Quit,
561 /// Close a window.
562 CloseWindow,
563 /// Replace the workspace in an existing window.
564 ReplaceWindow,
565}
566
567#[derive(Clone)]
568pub struct Toast {
569 id: NotificationId,
570 msg: Cow<'static, str>,
571 autohide: bool,
572 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
573}
574
575impl Toast {
576 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
577 Toast {
578 id,
579 msg: msg.into(),
580 on_click: None,
581 autohide: false,
582 }
583 }
584
585 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
586 where
587 M: Into<Cow<'static, str>>,
588 F: Fn(&mut Window, &mut App) + 'static,
589 {
590 self.on_click = Some((message.into(), Arc::new(on_click)));
591 self
592 }
593
594 pub fn autohide(mut self) -> Self {
595 self.autohide = true;
596 self
597 }
598}
599
600impl PartialEq for Toast {
601 fn eq(&self, other: &Self) -> bool {
602 self.id == other.id
603 && self.msg == other.msg
604 && self.on_click.is_some() == other.on_click.is_some()
605 }
606}
607
608/// Opens a new terminal with the specified working directory.
609#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
610#[action(namespace = workspace)]
611#[serde(deny_unknown_fields)]
612pub struct OpenTerminal {
613 pub working_directory: PathBuf,
614 /// If true, creates a local terminal even in remote projects.
615 #[serde(default)]
616 pub local: bool,
617}
618
619#[derive(
620 Clone,
621 Copy,
622 Debug,
623 Default,
624 Hash,
625 PartialEq,
626 Eq,
627 PartialOrd,
628 Ord,
629 serde::Serialize,
630 serde::Deserialize,
631)]
632pub struct WorkspaceId(i64);
633
634impl WorkspaceId {
635 pub fn from_i64(value: i64) -> Self {
636 Self(value)
637 }
638}
639
640impl StaticColumnCount for WorkspaceId {}
641impl Bind for WorkspaceId {
642 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
643 self.0.bind(statement, start_index)
644 }
645}
646impl Column for WorkspaceId {
647 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
648 i64::column(statement, start_index)
649 .map(|(i, next_index)| (Self(i), next_index))
650 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
651 }
652}
653impl From<WorkspaceId> for i64 {
654 fn from(val: WorkspaceId) -> Self {
655 val.0
656 }
657}
658
659fn prompt_and_open_paths(
660 app_state: Arc<AppState>,
661 options: PathPromptOptions,
662 create_new_window: bool,
663 cx: &mut App,
664) {
665 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
666 workspace_window
667 .update(cx, |multi_workspace, window, cx| {
668 let workspace = multi_workspace.workspace().clone();
669 workspace.update(cx, |workspace, cx| {
670 prompt_for_open_path_and_open(
671 workspace,
672 app_state,
673 options,
674 create_new_window,
675 window,
676 cx,
677 );
678 });
679 })
680 .ok();
681 } else {
682 let task = Workspace::new_local(
683 Vec::new(),
684 app_state.clone(),
685 None,
686 None,
687 None,
688 OpenMode::Activate,
689 cx,
690 );
691 cx.spawn(async move |cx| {
692 let OpenResult { window, .. } = task.await?;
693 window.update(cx, |multi_workspace, window, cx| {
694 window.activate_window();
695 let workspace = multi_workspace.workspace().clone();
696 workspace.update(cx, |workspace, cx| {
697 prompt_for_open_path_and_open(
698 workspace,
699 app_state,
700 options,
701 create_new_window,
702 window,
703 cx,
704 );
705 });
706 })?;
707 anyhow::Ok(())
708 })
709 .detach_and_log_err(cx);
710 }
711}
712
713pub fn prompt_for_open_path_and_open(
714 workspace: &mut Workspace,
715 app_state: Arc<AppState>,
716 options: PathPromptOptions,
717 create_new_window: bool,
718 window: &mut Window,
719 cx: &mut Context<Workspace>,
720) {
721 let paths = workspace.prompt_for_open_path(
722 options,
723 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
724 window,
725 cx,
726 );
727 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
728 cx.spawn_in(window, async move |this, cx| {
729 let Some(paths) = paths.await.log_err().flatten() else {
730 return;
731 };
732 if !create_new_window {
733 if let Some(handle) = multi_workspace_handle {
734 if let Some(task) = handle
735 .update(cx, |multi_workspace, window, cx| {
736 multi_workspace.open_project(paths, OpenMode::Activate, window, cx)
737 })
738 .log_err()
739 {
740 task.await.log_err();
741 }
742 return;
743 }
744 }
745 if let Some(task) = this
746 .update_in(cx, |this, window, cx| {
747 this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
748 })
749 .log_err()
750 {
751 task.await.log_err();
752 }
753 })
754 .detach();
755}
756
757pub fn init(app_state: Arc<AppState>, cx: &mut App) {
758 component::init();
759 theme_preview::init(cx);
760 toast_layer::init(cx);
761 history_manager::init(app_state.fs.clone(), cx);
762
763 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
764 .on_action(|_: &Reload, cx| reload(cx))
765 .on_action(|action: &Open, cx: &mut App| {
766 let app_state = AppState::global(cx);
767 prompt_and_open_paths(
768 app_state,
769 PathPromptOptions {
770 files: true,
771 directories: true,
772 multiple: true,
773 prompt: None,
774 },
775 action.create_new_window,
776 cx,
777 );
778 })
779 .on_action(|_: &OpenFiles, cx: &mut App| {
780 let directories = cx.can_select_mixed_files_and_dirs();
781 let app_state = AppState::global(cx);
782 prompt_and_open_paths(
783 app_state,
784 PathPromptOptions {
785 files: true,
786 directories,
787 multiple: true,
788 prompt: None,
789 },
790 true,
791 cx,
792 );
793 });
794}
795
796type BuildProjectItemFn =
797 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
798
799type BuildProjectItemForPathFn =
800 fn(
801 &Entity<Project>,
802 &ProjectPath,
803 &mut Window,
804 &mut App,
805 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
806
807#[derive(Clone, Default)]
808struct ProjectItemRegistry {
809 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
810 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
811}
812
813impl ProjectItemRegistry {
814 fn register<T: ProjectItem>(&mut self) {
815 self.build_project_item_fns_by_type.insert(
816 TypeId::of::<T::Item>(),
817 |item, project, pane, window, cx| {
818 let item = item.downcast().unwrap();
819 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
820 as Box<dyn ItemHandle>
821 },
822 );
823 self.build_project_item_for_path_fns
824 .push(|project, project_path, window, cx| {
825 let project_path = project_path.clone();
826 let is_file = project
827 .read(cx)
828 .entry_for_path(&project_path, cx)
829 .is_some_and(|entry| entry.is_file());
830 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
831 let is_local = project.read(cx).is_local();
832 let project_item =
833 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
834 let project = project.clone();
835 Some(window.spawn(cx, async move |cx| {
836 match project_item.await.with_context(|| {
837 format!(
838 "opening project path {:?}",
839 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
840 )
841 }) {
842 Ok(project_item) => {
843 let project_item = project_item;
844 let project_entry_id: Option<ProjectEntryId> =
845 project_item.read_with(cx, project::ProjectItem::entry_id);
846 let build_workspace_item = Box::new(
847 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
848 Box::new(cx.new(|cx| {
849 T::for_project_item(
850 project,
851 Some(pane),
852 project_item,
853 window,
854 cx,
855 )
856 })) as Box<dyn ItemHandle>
857 },
858 ) as Box<_>;
859 Ok((project_entry_id, build_workspace_item))
860 }
861 Err(e) => {
862 log::warn!("Failed to open a project item: {e:#}");
863 if e.error_code() == ErrorCode::Internal {
864 if let Some(abs_path) =
865 entry_abs_path.as_deref().filter(|_| is_file)
866 {
867 if let Some(broken_project_item_view) =
868 cx.update(|window, cx| {
869 T::for_broken_project_item(
870 abs_path, is_local, &e, window, cx,
871 )
872 })?
873 {
874 let build_workspace_item = Box::new(
875 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
876 cx.new(|_| broken_project_item_view).boxed_clone()
877 },
878 )
879 as Box<_>;
880 return Ok((None, build_workspace_item));
881 }
882 }
883 }
884 Err(e)
885 }
886 }
887 }))
888 });
889 }
890
891 fn open_path(
892 &self,
893 project: &Entity<Project>,
894 path: &ProjectPath,
895 window: &mut Window,
896 cx: &mut App,
897 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
898 let Some(open_project_item) = self
899 .build_project_item_for_path_fns
900 .iter()
901 .rev()
902 .find_map(|open_project_item| open_project_item(project, path, window, cx))
903 else {
904 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
905 };
906 open_project_item
907 }
908
909 fn build_item<T: project::ProjectItem>(
910 &self,
911 item: Entity<T>,
912 project: Entity<Project>,
913 pane: Option<&Pane>,
914 window: &mut Window,
915 cx: &mut App,
916 ) -> Option<Box<dyn ItemHandle>> {
917 let build = self
918 .build_project_item_fns_by_type
919 .get(&TypeId::of::<T>())?;
920 Some(build(item.into_any(), project, pane, window, cx))
921 }
922}
923
924type WorkspaceItemBuilder =
925 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
926
927impl Global for ProjectItemRegistry {}
928
929/// Registers a [ProjectItem] for the app. When opening a file, all the registered
930/// items will get a chance to open the file, starting from the project item that
931/// was added last.
932pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
933 cx.default_global::<ProjectItemRegistry>().register::<I>();
934}
935
936#[derive(Default)]
937pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
938
939struct FollowableViewDescriptor {
940 from_state_proto: fn(
941 Entity<Workspace>,
942 ViewId,
943 &mut Option<proto::view::Variant>,
944 &mut Window,
945 &mut App,
946 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
947 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
948}
949
950impl Global for FollowableViewRegistry {}
951
952impl FollowableViewRegistry {
953 pub fn register<I: FollowableItem>(cx: &mut App) {
954 cx.default_global::<Self>().0.insert(
955 TypeId::of::<I>(),
956 FollowableViewDescriptor {
957 from_state_proto: |workspace, id, state, window, cx| {
958 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
959 cx.foreground_executor()
960 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
961 })
962 },
963 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
964 },
965 );
966 }
967
968 pub fn from_state_proto(
969 workspace: Entity<Workspace>,
970 view_id: ViewId,
971 mut state: Option<proto::view::Variant>,
972 window: &mut Window,
973 cx: &mut App,
974 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
975 cx.update_default_global(|this: &mut Self, cx| {
976 this.0.values().find_map(|descriptor| {
977 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
978 })
979 })
980 }
981
982 pub fn to_followable_view(
983 view: impl Into<AnyView>,
984 cx: &App,
985 ) -> Option<Box<dyn FollowableItemHandle>> {
986 let this = cx.try_global::<Self>()?;
987 let view = view.into();
988 let descriptor = this.0.get(&view.entity_type())?;
989 Some((descriptor.to_followable_view)(&view))
990 }
991}
992
993#[derive(Copy, Clone)]
994struct SerializableItemDescriptor {
995 deserialize: fn(
996 Entity<Project>,
997 WeakEntity<Workspace>,
998 WorkspaceId,
999 ItemId,
1000 &mut Window,
1001 &mut Context<Pane>,
1002 ) -> Task<Result<Box<dyn ItemHandle>>>,
1003 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
1004 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
1005}
1006
1007#[derive(Default)]
1008struct SerializableItemRegistry {
1009 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
1010 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
1011}
1012
1013impl Global for SerializableItemRegistry {}
1014
1015impl SerializableItemRegistry {
1016 fn deserialize(
1017 item_kind: &str,
1018 project: Entity<Project>,
1019 workspace: WeakEntity<Workspace>,
1020 workspace_id: WorkspaceId,
1021 item_item: ItemId,
1022 window: &mut Window,
1023 cx: &mut Context<Pane>,
1024 ) -> Task<Result<Box<dyn ItemHandle>>> {
1025 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1026 return Task::ready(Err(anyhow!(
1027 "cannot deserialize {}, descriptor not found",
1028 item_kind
1029 )));
1030 };
1031
1032 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1033 }
1034
1035 fn cleanup(
1036 item_kind: &str,
1037 workspace_id: WorkspaceId,
1038 loaded_items: Vec<ItemId>,
1039 window: &mut Window,
1040 cx: &mut App,
1041 ) -> Task<Result<()>> {
1042 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1043 return Task::ready(Err(anyhow!(
1044 "cannot cleanup {}, descriptor not found",
1045 item_kind
1046 )));
1047 };
1048
1049 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1050 }
1051
1052 fn view_to_serializable_item_handle(
1053 view: AnyView,
1054 cx: &App,
1055 ) -> Option<Box<dyn SerializableItemHandle>> {
1056 let this = cx.try_global::<Self>()?;
1057 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1058 Some((descriptor.view_to_serializable_item)(view))
1059 }
1060
1061 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1062 let this = cx.try_global::<Self>()?;
1063 this.descriptors_by_kind.get(item_kind).copied()
1064 }
1065}
1066
1067pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1068 let serialized_item_kind = I::serialized_item_kind();
1069
1070 let registry = cx.default_global::<SerializableItemRegistry>();
1071 let descriptor = SerializableItemDescriptor {
1072 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1073 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1074 cx.foreground_executor()
1075 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1076 },
1077 cleanup: |workspace_id, loaded_items, window, cx| {
1078 I::cleanup(workspace_id, loaded_items, window, cx)
1079 },
1080 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1081 };
1082 registry
1083 .descriptors_by_kind
1084 .insert(Arc::from(serialized_item_kind), descriptor);
1085 registry
1086 .descriptors_by_type
1087 .insert(TypeId::of::<I>(), descriptor);
1088}
1089
1090pub struct AppState {
1091 pub languages: Arc<LanguageRegistry>,
1092 pub client: Arc<Client>,
1093 pub user_store: Entity<UserStore>,
1094 pub workspace_store: Entity<WorkspaceStore>,
1095 pub fs: Arc<dyn fs::Fs>,
1096 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1097 pub node_runtime: NodeRuntime,
1098 pub session: Entity<AppSession>,
1099}
1100
1101struct GlobalAppState(Arc<AppState>);
1102
1103impl Global for GlobalAppState {}
1104
1105pub struct WorkspaceStore {
1106 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1107 client: Arc<Client>,
1108 _subscriptions: Vec<client::Subscription>,
1109}
1110
1111#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1112pub enum CollaboratorId {
1113 PeerId(PeerId),
1114 Agent,
1115}
1116
1117impl From<PeerId> for CollaboratorId {
1118 fn from(peer_id: PeerId) -> Self {
1119 CollaboratorId::PeerId(peer_id)
1120 }
1121}
1122
1123impl From<&PeerId> for CollaboratorId {
1124 fn from(peer_id: &PeerId) -> Self {
1125 CollaboratorId::PeerId(*peer_id)
1126 }
1127}
1128
1129#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1130struct Follower {
1131 project_id: Option<u64>,
1132 peer_id: PeerId,
1133}
1134
1135impl AppState {
1136 #[track_caller]
1137 pub fn global(cx: &App) -> Arc<Self> {
1138 cx.global::<GlobalAppState>().0.clone()
1139 }
1140 pub fn try_global(cx: &App) -> Option<Arc<Self>> {
1141 cx.try_global::<GlobalAppState>()
1142 .map(|state| state.0.clone())
1143 }
1144 pub fn set_global(state: Arc<AppState>, cx: &mut App) {
1145 cx.set_global(GlobalAppState(state));
1146 }
1147
1148 #[cfg(any(test, feature = "test-support"))]
1149 pub fn test(cx: &mut App) -> Arc<Self> {
1150 use fs::Fs;
1151 use node_runtime::NodeRuntime;
1152 use session::Session;
1153 use settings::SettingsStore;
1154
1155 if !cx.has_global::<SettingsStore>() {
1156 let settings_store = SettingsStore::test(cx);
1157 cx.set_global(settings_store);
1158 }
1159
1160 let fs = fs::FakeFs::new(cx.background_executor().clone());
1161 <dyn Fs>::set_global(fs.clone(), cx);
1162 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1163 let clock = Arc::new(clock::FakeSystemClock::new());
1164 let http_client = http_client::FakeHttpClient::with_404_response();
1165 let client = Client::new(clock, http_client, cx);
1166 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1167 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1168 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1169
1170 theme_settings::init(theme::LoadThemes::JustBase, cx);
1171 client::init(&client, cx);
1172
1173 Arc::new(Self {
1174 client,
1175 fs,
1176 languages,
1177 user_store,
1178 workspace_store,
1179 node_runtime: NodeRuntime::unavailable(),
1180 build_window_options: |_, _| Default::default(),
1181 session,
1182 })
1183 }
1184}
1185
1186struct DelayedDebouncedEditAction {
1187 task: Option<Task<()>>,
1188 cancel_channel: Option<oneshot::Sender<()>>,
1189}
1190
1191impl DelayedDebouncedEditAction {
1192 fn new() -> DelayedDebouncedEditAction {
1193 DelayedDebouncedEditAction {
1194 task: None,
1195 cancel_channel: None,
1196 }
1197 }
1198
1199 fn fire_new<F>(
1200 &mut self,
1201 delay: Duration,
1202 window: &mut Window,
1203 cx: &mut Context<Workspace>,
1204 func: F,
1205 ) where
1206 F: 'static
1207 + Send
1208 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1209 {
1210 if let Some(channel) = self.cancel_channel.take() {
1211 _ = channel.send(());
1212 }
1213
1214 let (sender, mut receiver) = oneshot::channel::<()>();
1215 self.cancel_channel = Some(sender);
1216
1217 let previous_task = self.task.take();
1218 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1219 let mut timer = cx.background_executor().timer(delay).fuse();
1220 if let Some(previous_task) = previous_task {
1221 previous_task.await;
1222 }
1223
1224 futures::select_biased! {
1225 _ = receiver => return,
1226 _ = timer => {}
1227 }
1228
1229 if let Some(result) = workspace
1230 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1231 .log_err()
1232 {
1233 result.await.log_err();
1234 }
1235 }));
1236 }
1237}
1238
1239pub enum Event {
1240 PaneAdded(Entity<Pane>),
1241 PaneRemoved,
1242 ItemAdded {
1243 item: Box<dyn ItemHandle>,
1244 },
1245 ActiveItemChanged,
1246 ItemRemoved {
1247 item_id: EntityId,
1248 },
1249 UserSavedItem {
1250 pane: WeakEntity<Pane>,
1251 item: Box<dyn WeakItemHandle>,
1252 save_intent: SaveIntent,
1253 },
1254 ContactRequestedJoin(u64),
1255 WorkspaceCreated(WeakEntity<Workspace>),
1256 OpenBundledFile {
1257 text: Cow<'static, str>,
1258 title: &'static str,
1259 language: &'static str,
1260 },
1261 ZoomChanged,
1262 ModalOpened,
1263 Activate,
1264 PanelAdded(AnyView),
1265}
1266
1267#[derive(Debug, Clone)]
1268pub enum OpenVisible {
1269 All,
1270 None,
1271 OnlyFiles,
1272 OnlyDirectories,
1273}
1274
1275enum WorkspaceLocation {
1276 // Valid local paths or SSH project to serialize
1277 Location(SerializedWorkspaceLocation, PathList),
1278 // No valid location found hence clear session id
1279 DetachFromSession,
1280 // No valid location found to serialize
1281 None,
1282}
1283
1284type PromptForNewPath = Box<
1285 dyn Fn(
1286 &mut Workspace,
1287 DirectoryLister,
1288 Option<String>,
1289 &mut Window,
1290 &mut Context<Workspace>,
1291 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1292>;
1293
1294type PromptForOpenPath = Box<
1295 dyn Fn(
1296 &mut Workspace,
1297 DirectoryLister,
1298 &mut Window,
1299 &mut Context<Workspace>,
1300 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1301>;
1302
1303#[derive(Default)]
1304struct DispatchingKeystrokes {
1305 dispatched: HashSet<Vec<Keystroke>>,
1306 queue: VecDeque<Keystroke>,
1307 task: Option<Shared<Task<()>>>,
1308}
1309
1310/// Collects everything project-related for a certain window opened.
1311/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1312///
1313/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1314/// The `Workspace` owns everybody's state and serves as a default, "global context",
1315/// that can be used to register a global action to be triggered from any place in the window.
1316pub struct Workspace {
1317 weak_self: WeakEntity<Self>,
1318 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1319 zoomed: Option<AnyWeakView>,
1320 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1321 zoomed_position: Option<DockPosition>,
1322 center: PaneGroup,
1323 left_dock: Entity<Dock>,
1324 bottom_dock: Entity<Dock>,
1325 right_dock: Entity<Dock>,
1326 panes: Vec<Entity<Pane>>,
1327 active_worktree_override: Option<WorktreeId>,
1328 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1329 active_pane: Entity<Pane>,
1330 last_active_center_pane: Option<WeakEntity<Pane>>,
1331 last_active_view_id: Option<proto::ViewId>,
1332 status_bar: Entity<StatusBar>,
1333 pub(crate) modal_layer: Entity<ModalLayer>,
1334 toast_layer: Entity<ToastLayer>,
1335 titlebar_item: Option<AnyView>,
1336 notifications: Notifications,
1337 suppressed_notifications: HashSet<NotificationId>,
1338 project: Entity<Project>,
1339 follower_states: HashMap<CollaboratorId, FollowerState>,
1340 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1341 window_edited: bool,
1342 last_window_title: Option<String>,
1343 dirty_items: HashMap<EntityId, Subscription>,
1344 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1345 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1346 database_id: Option<WorkspaceId>,
1347 app_state: Arc<AppState>,
1348 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1349 _subscriptions: Vec<Subscription>,
1350 _apply_leader_updates: Task<Result<()>>,
1351 _observe_current_user: Task<Result<()>>,
1352 _schedule_serialize_workspace: Option<Task<()>>,
1353 _serialize_workspace_task: Option<Task<()>>,
1354 _schedule_serialize_ssh_paths: Option<Task<()>>,
1355 pane_history_timestamp: Arc<AtomicUsize>,
1356 bounds: Bounds<Pixels>,
1357 pub centered_layout: bool,
1358 bounds_save_task_queued: Option<Task<()>>,
1359 on_prompt_for_new_path: Option<PromptForNewPath>,
1360 on_prompt_for_open_path: Option<PromptForOpenPath>,
1361 terminal_provider: Option<Box<dyn TerminalProvider>>,
1362 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1363 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1364 _items_serializer: Task<Result<()>>,
1365 session_id: Option<String>,
1366 scheduled_tasks: Vec<Task<()>>,
1367 last_open_dock_positions: Vec<DockPosition>,
1368 removing: bool,
1369 open_in_dev_container: bool,
1370 _dev_container_task: Option<Task<Result<()>>>,
1371 _panels_task: Option<Task<Result<()>>>,
1372 sidebar_focus_handle: Option<FocusHandle>,
1373 multi_workspace: Option<WeakEntity<MultiWorkspace>>,
1374}
1375
1376impl EventEmitter<Event> for Workspace {}
1377
1378#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1379pub struct ViewId {
1380 pub creator: CollaboratorId,
1381 pub id: u64,
1382}
1383
1384pub struct FollowerState {
1385 center_pane: Entity<Pane>,
1386 dock_pane: Option<Entity<Pane>>,
1387 active_view_id: Option<ViewId>,
1388 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1389}
1390
1391struct FollowerView {
1392 view: Box<dyn FollowableItemHandle>,
1393 location: Option<proto::PanelId>,
1394}
1395
1396#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1397pub enum OpenMode {
1398 /// Open the workspace in a new window.
1399 NewWindow,
1400 /// Add to the window's multi workspace without activating it (used during deserialization).
1401 Add,
1402 /// Add to the window's multi workspace and activate it.
1403 #[default]
1404 Activate,
1405}
1406
1407impl Workspace {
1408 pub fn new(
1409 workspace_id: Option<WorkspaceId>,
1410 project: Entity<Project>,
1411 app_state: Arc<AppState>,
1412 window: &mut Window,
1413 cx: &mut Context<Self>,
1414 ) -> Self {
1415 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1416 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1417 if let TrustedWorktreesEvent::Trusted(..) = e {
1418 // Do not persist auto trusted worktrees
1419 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1420 worktrees_store.update(cx, |worktrees_store, cx| {
1421 worktrees_store.schedule_serialization(
1422 cx,
1423 |new_trusted_worktrees, cx| {
1424 let timeout =
1425 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1426 let db = WorkspaceDb::global(cx);
1427 cx.background_spawn(async move {
1428 timeout.await;
1429 db.save_trusted_worktrees(new_trusted_worktrees)
1430 .await
1431 .log_err();
1432 })
1433 },
1434 )
1435 });
1436 }
1437 }
1438 })
1439 .detach();
1440
1441 cx.observe_global::<SettingsStore>(|_, cx| {
1442 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1443 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1444 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1445 trusted_worktrees.auto_trust_all(cx);
1446 })
1447 }
1448 }
1449 })
1450 .detach();
1451 }
1452
1453 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1454 match event {
1455 project::Event::RemoteIdChanged(_) => {
1456 this.update_window_title(window, cx);
1457 }
1458
1459 project::Event::CollaboratorLeft(peer_id) => {
1460 this.collaborator_left(*peer_id, window, cx);
1461 }
1462
1463 &project::Event::WorktreeRemoved(_) => {
1464 this.update_window_title(window, cx);
1465 this.serialize_workspace(window, cx);
1466 this.update_history(cx);
1467 }
1468
1469 &project::Event::WorktreeAdded(id) => {
1470 this.update_window_title(window, cx);
1471 if this
1472 .project()
1473 .read(cx)
1474 .worktree_for_id(id, cx)
1475 .is_some_and(|wt| wt.read(cx).is_visible())
1476 {
1477 this.serialize_workspace(window, cx);
1478 this.update_history(cx);
1479 }
1480 }
1481 project::Event::WorktreeUpdatedEntries(..) => {
1482 this.update_window_title(window, cx);
1483 this.serialize_workspace(window, cx);
1484 }
1485
1486 project::Event::DisconnectedFromHost => {
1487 this.update_window_edited(window, cx);
1488 let leaders_to_unfollow =
1489 this.follower_states.keys().copied().collect::<Vec<_>>();
1490 for leader_id in leaders_to_unfollow {
1491 this.unfollow(leader_id, window, cx);
1492 }
1493 }
1494
1495 project::Event::DisconnectedFromRemote {
1496 server_not_running: _,
1497 } => {
1498 this.update_window_edited(window, cx);
1499 }
1500
1501 project::Event::Closed => {
1502 window.remove_window();
1503 }
1504
1505 project::Event::DeletedEntry(_, entry_id) => {
1506 for pane in this.panes.iter() {
1507 pane.update(cx, |pane, cx| {
1508 pane.handle_deleted_project_item(*entry_id, window, cx)
1509 });
1510 }
1511 }
1512
1513 project::Event::Toast {
1514 notification_id,
1515 message,
1516 link,
1517 } => this.show_notification(
1518 NotificationId::named(notification_id.clone()),
1519 cx,
1520 |cx| {
1521 let mut notification = MessageNotification::new(message.clone(), cx);
1522 if let Some(link) = link {
1523 notification = notification
1524 .more_info_message(link.label)
1525 .more_info_url(link.url);
1526 }
1527
1528 cx.new(|_| notification)
1529 },
1530 ),
1531
1532 project::Event::HideToast { notification_id } => {
1533 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1534 }
1535
1536 project::Event::LanguageServerPrompt(request) => {
1537 struct LanguageServerPrompt;
1538
1539 this.show_notification(
1540 NotificationId::composite::<LanguageServerPrompt>(request.id),
1541 cx,
1542 |cx| {
1543 cx.new(|cx| {
1544 notifications::LanguageServerPrompt::new(request.clone(), cx)
1545 })
1546 },
1547 );
1548 }
1549
1550 project::Event::AgentLocationChanged => {
1551 this.handle_agent_location_changed(window, cx)
1552 }
1553
1554 _ => {}
1555 }
1556 cx.notify()
1557 })
1558 .detach();
1559
1560 cx.subscribe_in(
1561 &project.read(cx).breakpoint_store(),
1562 window,
1563 |workspace, _, event, window, cx| match event {
1564 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1565 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1566 workspace.serialize_workspace(window, cx);
1567 }
1568 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1569 },
1570 )
1571 .detach();
1572 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1573 cx.subscribe_in(
1574 &toolchain_store,
1575 window,
1576 |workspace, _, event, window, cx| match event {
1577 ToolchainStoreEvent::CustomToolchainsModified => {
1578 workspace.serialize_workspace(window, cx);
1579 }
1580 _ => {}
1581 },
1582 )
1583 .detach();
1584 }
1585
1586 cx.on_focus_lost(window, |this, window, cx| {
1587 let focus_handle = this.focus_handle(cx);
1588 window.focus(&focus_handle, cx);
1589 })
1590 .detach();
1591
1592 let weak_handle = cx.entity().downgrade();
1593 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1594
1595 let center_pane = cx.new(|cx| {
1596 let mut center_pane = Pane::new(
1597 weak_handle.clone(),
1598 project.clone(),
1599 pane_history_timestamp.clone(),
1600 None,
1601 NewFile.boxed_clone(),
1602 true,
1603 window,
1604 cx,
1605 );
1606 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1607 center_pane.set_should_display_welcome_page(true);
1608 center_pane
1609 });
1610 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1611 .detach();
1612
1613 window.focus(¢er_pane.focus_handle(cx), cx);
1614
1615 cx.emit(Event::PaneAdded(center_pane.clone()));
1616
1617 let any_window_handle = window.window_handle();
1618 app_state.workspace_store.update(cx, |store, _| {
1619 store
1620 .workspaces
1621 .insert((any_window_handle, weak_handle.clone()));
1622 });
1623
1624 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1625 let mut connection_status = app_state.client.status();
1626 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1627 current_user.next().await;
1628 connection_status.next().await;
1629 let mut stream =
1630 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1631
1632 while stream.recv().await.is_some() {
1633 this.update(cx, |_, cx| cx.notify())?;
1634 }
1635 anyhow::Ok(())
1636 });
1637
1638 // All leader updates are enqueued and then processed in a single task, so
1639 // that each asynchronous operation can be run in order.
1640 let (leader_updates_tx, mut leader_updates_rx) =
1641 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1642 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1643 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1644 Self::process_leader_update(&this, leader_id, update, cx)
1645 .await
1646 .log_err();
1647 }
1648
1649 Ok(())
1650 });
1651
1652 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1653 let modal_layer = cx.new(|_| ModalLayer::new());
1654 let toast_layer = cx.new(|_| ToastLayer::new());
1655 cx.subscribe(
1656 &modal_layer,
1657 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1658 cx.emit(Event::ModalOpened);
1659 },
1660 )
1661 .detach();
1662
1663 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1664 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1665 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1666 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1667 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1668 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1669 let multi_workspace = window
1670 .root::<MultiWorkspace>()
1671 .flatten()
1672 .map(|mw| mw.downgrade());
1673 let status_bar = cx.new(|cx| {
1674 let mut status_bar =
1675 StatusBar::new(¢er_pane.clone(), multi_workspace.clone(), window, cx);
1676 status_bar.add_left_item(left_dock_buttons, window, cx);
1677 status_bar.add_right_item(right_dock_buttons, window, cx);
1678 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1679 status_bar
1680 });
1681
1682 let session_id = app_state.session.read(cx).id().to_owned();
1683
1684 let mut active_call = None;
1685 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1686 let subscriptions =
1687 vec![
1688 call.0
1689 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1690 ];
1691 active_call = Some((call, subscriptions));
1692 }
1693
1694 let (serializable_items_tx, serializable_items_rx) =
1695 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1696 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1697 Self::serialize_items(&this, serializable_items_rx, cx).await
1698 });
1699
1700 let subscriptions = vec![
1701 cx.observe_window_activation(window, Self::on_window_activation_changed),
1702 cx.observe_window_bounds(window, move |this, window, cx| {
1703 if this.bounds_save_task_queued.is_some() {
1704 return;
1705 }
1706 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1707 cx.background_executor()
1708 .timer(Duration::from_millis(100))
1709 .await;
1710 this.update_in(cx, |this, window, cx| {
1711 this.save_window_bounds(window, cx).detach();
1712 this.bounds_save_task_queued.take();
1713 })
1714 .ok();
1715 }));
1716 cx.notify();
1717 }),
1718 cx.observe_window_appearance(window, |_, window, cx| {
1719 let window_appearance = window.appearance();
1720
1721 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1722
1723 theme_settings::reload_theme(cx);
1724 theme_settings::reload_icon_theme(cx);
1725 }),
1726 cx.on_release({
1727 let weak_handle = weak_handle.clone();
1728 move |this, cx| {
1729 this.app_state.workspace_store.update(cx, move |store, _| {
1730 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1731 })
1732 }
1733 }),
1734 ];
1735
1736 cx.defer_in(window, move |this, window, cx| {
1737 this.update_window_title(window, cx);
1738 this.show_initial_notifications(cx);
1739 });
1740
1741 let mut center = PaneGroup::new(center_pane.clone());
1742 center.set_is_center(true);
1743 center.mark_positions(cx);
1744
1745 Workspace {
1746 weak_self: weak_handle.clone(),
1747 zoomed: None,
1748 zoomed_position: None,
1749 previous_dock_drag_coordinates: None,
1750 center,
1751 panes: vec![center_pane.clone()],
1752 panes_by_item: Default::default(),
1753 active_pane: center_pane.clone(),
1754 last_active_center_pane: Some(center_pane.downgrade()),
1755 last_active_view_id: None,
1756 status_bar,
1757 modal_layer,
1758 toast_layer,
1759 titlebar_item: None,
1760 active_worktree_override: None,
1761 notifications: Notifications::default(),
1762 suppressed_notifications: HashSet::default(),
1763 left_dock,
1764 bottom_dock,
1765 right_dock,
1766 _panels_task: None,
1767 project: project.clone(),
1768 follower_states: Default::default(),
1769 last_leaders_by_pane: Default::default(),
1770 dispatching_keystrokes: Default::default(),
1771 window_edited: false,
1772 last_window_title: None,
1773 dirty_items: Default::default(),
1774 active_call,
1775 database_id: workspace_id,
1776 app_state,
1777 _observe_current_user,
1778 _apply_leader_updates,
1779 _schedule_serialize_workspace: None,
1780 _serialize_workspace_task: None,
1781 _schedule_serialize_ssh_paths: None,
1782 leader_updates_tx,
1783 _subscriptions: subscriptions,
1784 pane_history_timestamp,
1785 workspace_actions: Default::default(),
1786 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1787 bounds: Default::default(),
1788 centered_layout: false,
1789 bounds_save_task_queued: None,
1790 on_prompt_for_new_path: None,
1791 on_prompt_for_open_path: None,
1792 terminal_provider: None,
1793 debugger_provider: None,
1794 serializable_items_tx,
1795 _items_serializer,
1796 session_id: Some(session_id),
1797
1798 scheduled_tasks: Vec::new(),
1799 last_open_dock_positions: Vec::new(),
1800 removing: false,
1801 sidebar_focus_handle: None,
1802 multi_workspace,
1803 open_in_dev_container: false,
1804 _dev_container_task: None,
1805 }
1806 }
1807
1808 pub fn new_local(
1809 abs_paths: Vec<PathBuf>,
1810 app_state: Arc<AppState>,
1811 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1812 env: Option<HashMap<String, String>>,
1813 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1814 open_mode: OpenMode,
1815 cx: &mut App,
1816 ) -> Task<anyhow::Result<OpenResult>> {
1817 let project_handle = Project::local(
1818 app_state.client.clone(),
1819 app_state.node_runtime.clone(),
1820 app_state.user_store.clone(),
1821 app_state.languages.clone(),
1822 app_state.fs.clone(),
1823 env,
1824 Default::default(),
1825 cx,
1826 );
1827
1828 let db = WorkspaceDb::global(cx);
1829 let kvp = db::kvp::KeyValueStore::global(cx);
1830 cx.spawn(async move |cx| {
1831 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1832 for path in abs_paths.into_iter() {
1833 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1834 paths_to_open.push(canonical)
1835 } else {
1836 paths_to_open.push(path)
1837 }
1838 }
1839
1840 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1841
1842 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1843 paths_to_open = paths.ordered_paths().cloned().collect();
1844 if !paths.is_lexicographically_ordered() {
1845 project_handle.update(cx, |project, cx| {
1846 project.set_worktrees_reordered(true, cx);
1847 });
1848 }
1849 }
1850
1851 // Get project paths for all of the abs_paths
1852 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1853 Vec::with_capacity(paths_to_open.len());
1854
1855 for path in paths_to_open.into_iter() {
1856 if let Some((_, project_entry)) = cx
1857 .update(|cx| {
1858 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1859 })
1860 .await
1861 .log_err()
1862 {
1863 project_paths.push((path, Some(project_entry)));
1864 } else {
1865 project_paths.push((path, None));
1866 }
1867 }
1868
1869 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1870 serialized_workspace.id
1871 } else {
1872 db.next_id().await.unwrap_or_else(|_| Default::default())
1873 };
1874
1875 let toolchains = db.toolchains(workspace_id).await?;
1876
1877 for (toolchain, worktree_path, path) in toolchains {
1878 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1879 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1880 this.find_worktree(&worktree_path, cx)
1881 .and_then(|(worktree, rel_path)| {
1882 if rel_path.is_empty() {
1883 Some(worktree.read(cx).id())
1884 } else {
1885 None
1886 }
1887 })
1888 }) else {
1889 // We did not find a worktree with a given path, but that's whatever.
1890 continue;
1891 };
1892 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1893 continue;
1894 }
1895
1896 project_handle
1897 .update(cx, |this, cx| {
1898 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1899 })
1900 .await;
1901 }
1902 if let Some(workspace) = serialized_workspace.as_ref() {
1903 project_handle.update(cx, |this, cx| {
1904 for (scope, toolchains) in &workspace.user_toolchains {
1905 for toolchain in toolchains {
1906 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1907 }
1908 }
1909 });
1910 }
1911
1912 let window_to_replace = match open_mode {
1913 OpenMode::NewWindow => None,
1914 _ => requesting_window,
1915 };
1916
1917 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1918 if let Some(window) = window_to_replace {
1919 let centered_layout = serialized_workspace
1920 .as_ref()
1921 .map(|w| w.centered_layout)
1922 .unwrap_or(false);
1923
1924 let workspace = window.update(cx, |multi_workspace, window, cx| {
1925 let workspace = cx.new(|cx| {
1926 let mut workspace = Workspace::new(
1927 Some(workspace_id),
1928 project_handle.clone(),
1929 app_state.clone(),
1930 window,
1931 cx,
1932 );
1933
1934 workspace.centered_layout = centered_layout;
1935
1936 // Call init callback to add items before window renders
1937 if let Some(init) = init {
1938 init(&mut workspace, window, cx);
1939 }
1940
1941 workspace
1942 });
1943 match open_mode {
1944 OpenMode::Activate => {
1945 multi_workspace.activate(workspace.clone(), window, cx);
1946 }
1947 OpenMode::Add => {
1948 multi_workspace.add(workspace.clone(), &*window, cx);
1949 }
1950 OpenMode::NewWindow => {
1951 unreachable!()
1952 }
1953 }
1954 workspace
1955 })?;
1956 (window, workspace)
1957 } else {
1958 let window_bounds_override = window_bounds_env_override();
1959
1960 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1961 (Some(WindowBounds::Windowed(bounds)), None)
1962 } else if let Some(workspace) = serialized_workspace.as_ref()
1963 && let Some(display) = workspace.display
1964 && let Some(bounds) = workspace.window_bounds.as_ref()
1965 {
1966 // Reopening an existing workspace - restore its saved bounds
1967 (Some(bounds.0), Some(display))
1968 } else if let Some((display, bounds)) =
1969 persistence::read_default_window_bounds(&kvp)
1970 {
1971 // New or empty workspace - use the last known window bounds
1972 (Some(bounds), Some(display))
1973 } else {
1974 // New window - let GPUI's default_bounds() handle cascading
1975 (None, None)
1976 };
1977
1978 // Use the serialized workspace to construct the new window
1979 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1980 options.window_bounds = window_bounds;
1981 let centered_layout = serialized_workspace
1982 .as_ref()
1983 .map(|w| w.centered_layout)
1984 .unwrap_or(false);
1985 let window = cx.open_window(options, {
1986 let app_state = app_state.clone();
1987 let project_handle = project_handle.clone();
1988 move |window, cx| {
1989 let workspace = cx.new(|cx| {
1990 let mut workspace = Workspace::new(
1991 Some(workspace_id),
1992 project_handle,
1993 app_state,
1994 window,
1995 cx,
1996 );
1997 workspace.centered_layout = centered_layout;
1998
1999 // Call init callback to add items before window renders
2000 if let Some(init) = init {
2001 init(&mut workspace, window, cx);
2002 }
2003
2004 workspace
2005 });
2006 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
2007 }
2008 })?;
2009 let workspace =
2010 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
2011 multi_workspace.workspace().clone()
2012 })?;
2013 (window, workspace)
2014 };
2015
2016 notify_if_database_failed(window, cx);
2017 // Check if this is an empty workspace (no paths to open)
2018 // An empty workspace is one where project_paths is empty
2019 let is_empty_workspace = project_paths.is_empty();
2020 // Check if serialized workspace has paths before it's moved
2021 let serialized_workspace_has_paths = serialized_workspace
2022 .as_ref()
2023 .map(|ws| !ws.paths.is_empty())
2024 .unwrap_or(false);
2025
2026 let opened_items = window
2027 .update(cx, |_, window, cx| {
2028 workspace.update(cx, |_workspace: &mut Workspace, cx| {
2029 open_items(serialized_workspace, project_paths, window, cx)
2030 })
2031 })?
2032 .await
2033 .unwrap_or_default();
2034
2035 // Restore default dock state for empty workspaces
2036 // Only restore if:
2037 // 1. This is an empty workspace (no paths), AND
2038 // 2. The serialized workspace either doesn't exist or has no paths
2039 if is_empty_workspace && !serialized_workspace_has_paths {
2040 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
2041 window
2042 .update(cx, |_, window, cx| {
2043 workspace.update(cx, |workspace, cx| {
2044 for (dock, serialized_dock) in [
2045 (&workspace.right_dock, &default_docks.right),
2046 (&workspace.left_dock, &default_docks.left),
2047 (&workspace.bottom_dock, &default_docks.bottom),
2048 ] {
2049 dock.update(cx, |dock, cx| {
2050 dock.serialized_dock = Some(serialized_dock.clone());
2051 dock.restore_state(window, cx);
2052 });
2053 }
2054 cx.notify();
2055 });
2056 })
2057 .log_err();
2058 }
2059 }
2060
2061 window
2062 .update(cx, |_, _window, cx| {
2063 workspace.update(cx, |this: &mut Workspace, cx| {
2064 this.update_history(cx);
2065 });
2066 })
2067 .log_err();
2068 Ok(OpenResult {
2069 window,
2070 workspace,
2071 opened_items,
2072 })
2073 })
2074 }
2075
2076 pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
2077 self.project.read(cx).project_group_key(cx)
2078 }
2079
2080 pub fn weak_handle(&self) -> WeakEntity<Self> {
2081 self.weak_self.clone()
2082 }
2083
2084 pub fn left_dock(&self) -> &Entity<Dock> {
2085 &self.left_dock
2086 }
2087
2088 pub fn bottom_dock(&self) -> &Entity<Dock> {
2089 &self.bottom_dock
2090 }
2091
2092 pub fn set_bottom_dock_layout(
2093 &mut self,
2094 layout: BottomDockLayout,
2095 window: &mut Window,
2096 cx: &mut Context<Self>,
2097 ) {
2098 let fs = self.project().read(cx).fs();
2099 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2100 content.workspace.bottom_dock_layout = Some(layout);
2101 });
2102
2103 cx.notify();
2104 self.serialize_workspace(window, cx);
2105 }
2106
2107 pub fn right_dock(&self) -> &Entity<Dock> {
2108 &self.right_dock
2109 }
2110
2111 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2112 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2113 }
2114
2115 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2116 let left_dock = self.left_dock.read(cx);
2117 let left_visible = left_dock.is_open();
2118 let left_active_panel = left_dock
2119 .active_panel()
2120 .map(|panel| panel.persistent_name().to_string());
2121 // `zoomed_position` is kept in sync with individual panel zoom state
2122 // by the dock code in `Dock::new` and `Dock::add_panel`.
2123 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2124
2125 let right_dock = self.right_dock.read(cx);
2126 let right_visible = right_dock.is_open();
2127 let right_active_panel = right_dock
2128 .active_panel()
2129 .map(|panel| panel.persistent_name().to_string());
2130 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2131
2132 let bottom_dock = self.bottom_dock.read(cx);
2133 let bottom_visible = bottom_dock.is_open();
2134 let bottom_active_panel = bottom_dock
2135 .active_panel()
2136 .map(|panel| panel.persistent_name().to_string());
2137 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2138
2139 DockStructure {
2140 left: DockData {
2141 visible: left_visible,
2142 active_panel: left_active_panel,
2143 zoom: left_dock_zoom,
2144 },
2145 right: DockData {
2146 visible: right_visible,
2147 active_panel: right_active_panel,
2148 zoom: right_dock_zoom,
2149 },
2150 bottom: DockData {
2151 visible: bottom_visible,
2152 active_panel: bottom_active_panel,
2153 zoom: bottom_dock_zoom,
2154 },
2155 }
2156 }
2157
2158 pub fn set_dock_structure(
2159 &self,
2160 docks: DockStructure,
2161 window: &mut Window,
2162 cx: &mut Context<Self>,
2163 ) {
2164 for (dock, data) in [
2165 (&self.left_dock, docks.left),
2166 (&self.bottom_dock, docks.bottom),
2167 (&self.right_dock, docks.right),
2168 ] {
2169 dock.update(cx, |dock, cx| {
2170 dock.serialized_dock = Some(data);
2171 dock.restore_state(window, cx);
2172 });
2173 }
2174 }
2175
2176 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2177 self.items(cx)
2178 .filter_map(|item| {
2179 let project_path = item.project_path(cx)?;
2180 self.project.read(cx).absolute_path(&project_path, cx)
2181 })
2182 .collect()
2183 }
2184
2185 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2186 match position {
2187 DockPosition::Left => &self.left_dock,
2188 DockPosition::Bottom => &self.bottom_dock,
2189 DockPosition::Right => &self.right_dock,
2190 }
2191 }
2192
2193 pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
2194 self.all_docks().into_iter().find_map(|dock| {
2195 let dock = dock.read(cx);
2196 dock.has_agent_panel(cx).then_some(dock.position())
2197 })
2198 }
2199
2200 pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
2201 self.all_docks().into_iter().find_map(|dock| {
2202 let dock = dock.read(cx);
2203 let panel = dock.panel::<T>()?;
2204 dock.stored_panel_size_state(&panel)
2205 })
2206 }
2207
2208 pub fn persisted_panel_size_state(
2209 &self,
2210 panel_key: &'static str,
2211 cx: &App,
2212 ) -> Option<dock::PanelSizeState> {
2213 dock::Dock::load_persisted_size_state(self, panel_key, cx)
2214 }
2215
2216 pub fn persist_panel_size_state(
2217 &self,
2218 panel_key: &str,
2219 size_state: dock::PanelSizeState,
2220 cx: &mut App,
2221 ) {
2222 let Some(workspace_id) = self
2223 .database_id()
2224 .map(|id| i64::from(id).to_string())
2225 .or(self.session_id())
2226 else {
2227 return;
2228 };
2229
2230 let kvp = db::kvp::KeyValueStore::global(cx);
2231 let panel_key = panel_key.to_string();
2232 cx.background_spawn(async move {
2233 let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
2234 scope
2235 .write(
2236 format!("{workspace_id}:{panel_key}"),
2237 serde_json::to_string(&size_state)?,
2238 )
2239 .await
2240 })
2241 .detach_and_log_err(cx);
2242 }
2243
2244 pub fn set_panel_size_state<T: Panel>(
2245 &mut self,
2246 size_state: dock::PanelSizeState,
2247 window: &mut Window,
2248 cx: &mut Context<Self>,
2249 ) -> bool {
2250 let Some(panel) = self.panel::<T>(cx) else {
2251 return false;
2252 };
2253
2254 let dock = self.dock_at_position(panel.position(window, cx));
2255 let did_set = dock.update(cx, |dock, cx| {
2256 dock.set_panel_size_state(&panel, size_state, cx)
2257 });
2258
2259 if did_set {
2260 self.persist_panel_size_state(T::panel_key(), size_state, cx);
2261 }
2262
2263 did_set
2264 }
2265
2266 pub fn toggle_dock_panel_flexible_size(
2267 &self,
2268 dock: &Entity<Dock>,
2269 panel: &dyn PanelHandle,
2270 window: &mut Window,
2271 cx: &mut App,
2272 ) {
2273 let position = dock.read(cx).position();
2274 let current_size = self.dock_size(&dock.read(cx), window, cx);
2275 let current_flex =
2276 current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
2277 dock.update(cx, |dock, cx| {
2278 dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
2279 });
2280 }
2281
2282 fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
2283 let panel = dock.active_panel()?;
2284 let size_state = dock
2285 .stored_panel_size_state(panel.as_ref())
2286 .unwrap_or_default();
2287 let position = dock.position();
2288
2289 let use_flex = panel.has_flexible_size(window, cx);
2290
2291 if position.axis() == Axis::Horizontal
2292 && use_flex
2293 && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
2294 {
2295 let workspace_width = self.bounds.size.width;
2296 if workspace_width <= Pixels::ZERO {
2297 return None;
2298 }
2299 let flex = flex.max(0.001);
2300 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2301 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2302 // Both docks are flex items sharing the full workspace width.
2303 let total_flex = flex + 1.0 + opposite_flex;
2304 return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
2305 } else {
2306 // Opposite dock is fixed-width; flex items share (W - fixed).
2307 let opposite_fixed = opposite
2308 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2309 .unwrap_or_default();
2310 let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
2311 return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
2312 }
2313 }
2314
2315 Some(
2316 size_state
2317 .size
2318 .unwrap_or_else(|| panel.default_size(window, cx)),
2319 )
2320 }
2321
2322 pub fn dock_flex_for_size(
2323 &self,
2324 position: DockPosition,
2325 size: Pixels,
2326 window: &Window,
2327 cx: &App,
2328 ) -> Option<f32> {
2329 if position.axis() != Axis::Horizontal {
2330 return None;
2331 }
2332
2333 let workspace_width = self.bounds.size.width;
2334 if workspace_width <= Pixels::ZERO {
2335 return None;
2336 }
2337
2338 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2339 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2340 let size = size.clamp(px(0.), workspace_width - px(1.));
2341 Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
2342 } else {
2343 let opposite_width = opposite
2344 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2345 .unwrap_or_default();
2346 let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
2347 let remaining = (available - size).max(px(1.));
2348 Some((size / remaining).max(0.0))
2349 }
2350 }
2351
2352 fn opposite_dock_panel_and_size_state(
2353 &self,
2354 position: DockPosition,
2355 window: &Window,
2356 cx: &App,
2357 ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
2358 let opposite_position = match position {
2359 DockPosition::Left => DockPosition::Right,
2360 DockPosition::Right => DockPosition::Left,
2361 DockPosition::Bottom => return None,
2362 };
2363
2364 let opposite_dock = self.dock_at_position(opposite_position).read(cx);
2365 let panel = opposite_dock.visible_panel()?;
2366 let mut size_state = opposite_dock
2367 .stored_panel_size_state(panel.as_ref())
2368 .unwrap_or_default();
2369 if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
2370 size_state.flex = self.default_dock_flex(opposite_position);
2371 }
2372 Some((panel.clone(), size_state))
2373 }
2374
2375 pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
2376 if position.axis() != Axis::Horizontal {
2377 return None;
2378 }
2379
2380 let pane = self.last_active_center_pane.clone()?.upgrade()?;
2381 Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
2382 }
2383
2384 pub fn is_edited(&self) -> bool {
2385 self.window_edited
2386 }
2387
2388 pub fn add_panel<T: Panel>(
2389 &mut self,
2390 panel: Entity<T>,
2391 window: &mut Window,
2392 cx: &mut Context<Self>,
2393 ) {
2394 let focus_handle = panel.panel_focus_handle(cx);
2395 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2396 .detach();
2397
2398 let dock_position = panel.position(window, cx);
2399 let dock = self.dock_at_position(dock_position);
2400 let any_panel = panel.to_any();
2401 let persisted_size_state =
2402 self.persisted_panel_size_state(T::panel_key(), cx)
2403 .or_else(|| {
2404 load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
2405 let state = dock::PanelSizeState {
2406 size: Some(size),
2407 flex: None,
2408 };
2409 self.persist_panel_size_state(T::panel_key(), state, cx);
2410 state
2411 })
2412 });
2413
2414 dock.update(cx, |dock, cx| {
2415 let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
2416 if let Some(size_state) = persisted_size_state {
2417 dock.set_panel_size_state(&panel, size_state, cx);
2418 }
2419 index
2420 });
2421
2422 cx.emit(Event::PanelAdded(any_panel));
2423 }
2424
2425 pub fn remove_panel<T: Panel>(
2426 &mut self,
2427 panel: &Entity<T>,
2428 window: &mut Window,
2429 cx: &mut Context<Self>,
2430 ) {
2431 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2432 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2433 }
2434 }
2435
2436 pub fn status_bar(&self) -> &Entity<StatusBar> {
2437 &self.status_bar
2438 }
2439
2440 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2441 self.sidebar_focus_handle = handle;
2442 }
2443
2444 pub fn status_bar_visible(&self, cx: &App) -> bool {
2445 StatusBarSettings::get_global(cx).show
2446 }
2447
2448 pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
2449 self.multi_workspace.as_ref()
2450 }
2451
2452 pub fn set_multi_workspace(
2453 &mut self,
2454 multi_workspace: WeakEntity<MultiWorkspace>,
2455 cx: &mut App,
2456 ) {
2457 self.status_bar.update(cx, |status_bar, cx| {
2458 status_bar.set_multi_workspace(multi_workspace.clone(), cx);
2459 });
2460 self.multi_workspace = Some(multi_workspace);
2461 }
2462
2463 pub fn app_state(&self) -> &Arc<AppState> {
2464 &self.app_state
2465 }
2466
2467 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2468 self._panels_task = Some(task);
2469 }
2470
2471 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2472 self._panels_task.take()
2473 }
2474
2475 pub fn user_store(&self) -> &Entity<UserStore> {
2476 &self.app_state.user_store
2477 }
2478
2479 pub fn project(&self) -> &Entity<Project> {
2480 &self.project
2481 }
2482
2483 pub fn path_style(&self, cx: &App) -> PathStyle {
2484 self.project.read(cx).path_style(cx)
2485 }
2486
2487 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2488 let mut history: HashMap<EntityId, usize> = HashMap::default();
2489
2490 for pane_handle in &self.panes {
2491 let pane = pane_handle.read(cx);
2492
2493 for entry in pane.activation_history() {
2494 history.insert(
2495 entry.entity_id,
2496 history
2497 .get(&entry.entity_id)
2498 .cloned()
2499 .unwrap_or(0)
2500 .max(entry.timestamp),
2501 );
2502 }
2503 }
2504
2505 history
2506 }
2507
2508 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2509 let mut recent_item: Option<Entity<T>> = None;
2510 let mut recent_timestamp = 0;
2511 for pane_handle in &self.panes {
2512 let pane = pane_handle.read(cx);
2513 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2514 pane.items().map(|item| (item.item_id(), item)).collect();
2515 for entry in pane.activation_history() {
2516 if entry.timestamp > recent_timestamp
2517 && let Some(&item) = item_map.get(&entry.entity_id)
2518 && let Some(typed_item) = item.act_as::<T>(cx)
2519 {
2520 recent_timestamp = entry.timestamp;
2521 recent_item = Some(typed_item);
2522 }
2523 }
2524 }
2525 recent_item
2526 }
2527
2528 pub fn recent_navigation_history_iter(
2529 &self,
2530 cx: &App,
2531 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2532 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2533 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2534
2535 for pane in &self.panes {
2536 let pane = pane.read(cx);
2537
2538 pane.nav_history()
2539 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2540 if let Some(fs_path) = &fs_path {
2541 abs_paths_opened
2542 .entry(fs_path.clone())
2543 .or_default()
2544 .insert(project_path.clone());
2545 }
2546 let timestamp = entry.timestamp;
2547 match history.entry(project_path) {
2548 hash_map::Entry::Occupied(mut entry) => {
2549 let (_, old_timestamp) = entry.get();
2550 if ×tamp > old_timestamp {
2551 entry.insert((fs_path, timestamp));
2552 }
2553 }
2554 hash_map::Entry::Vacant(entry) => {
2555 entry.insert((fs_path, timestamp));
2556 }
2557 }
2558 });
2559
2560 if let Some(item) = pane.active_item()
2561 && let Some(project_path) = item.project_path(cx)
2562 {
2563 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2564
2565 if let Some(fs_path) = &fs_path {
2566 abs_paths_opened
2567 .entry(fs_path.clone())
2568 .or_default()
2569 .insert(project_path.clone());
2570 }
2571
2572 history.insert(project_path, (fs_path, std::usize::MAX));
2573 }
2574 }
2575
2576 history
2577 .into_iter()
2578 .sorted_by_key(|(_, (_, order))| *order)
2579 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2580 .rev()
2581 .filter(move |(history_path, abs_path)| {
2582 let latest_project_path_opened = abs_path
2583 .as_ref()
2584 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2585 .and_then(|project_paths| {
2586 project_paths
2587 .iter()
2588 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2589 });
2590
2591 latest_project_path_opened.is_none_or(|path| path == history_path)
2592 })
2593 }
2594
2595 pub fn recent_navigation_history(
2596 &self,
2597 limit: Option<usize>,
2598 cx: &App,
2599 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2600 self.recent_navigation_history_iter(cx)
2601 .take(limit.unwrap_or(usize::MAX))
2602 .collect()
2603 }
2604
2605 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2606 for pane in &self.panes {
2607 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2608 }
2609 }
2610
2611 fn navigate_history(
2612 &mut self,
2613 pane: WeakEntity<Pane>,
2614 mode: NavigationMode,
2615 window: &mut Window,
2616 cx: &mut Context<Workspace>,
2617 ) -> Task<Result<()>> {
2618 self.navigate_history_impl(
2619 pane,
2620 mode,
2621 window,
2622 &mut |history, cx| history.pop(mode, cx),
2623 cx,
2624 )
2625 }
2626
2627 fn navigate_tag_history(
2628 &mut self,
2629 pane: WeakEntity<Pane>,
2630 mode: TagNavigationMode,
2631 window: &mut Window,
2632 cx: &mut Context<Workspace>,
2633 ) -> Task<Result<()>> {
2634 self.navigate_history_impl(
2635 pane,
2636 NavigationMode::Normal,
2637 window,
2638 &mut |history, _cx| history.pop_tag(mode),
2639 cx,
2640 )
2641 }
2642
2643 fn navigate_history_impl(
2644 &mut self,
2645 pane: WeakEntity<Pane>,
2646 mode: NavigationMode,
2647 window: &mut Window,
2648 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2649 cx: &mut Context<Workspace>,
2650 ) -> Task<Result<()>> {
2651 let to_load = if let Some(pane) = pane.upgrade() {
2652 pane.update(cx, |pane, cx| {
2653 window.focus(&pane.focus_handle(cx), cx);
2654 loop {
2655 // Retrieve the weak item handle from the history.
2656 let entry = cb(pane.nav_history_mut(), cx)?;
2657
2658 // If the item is still present in this pane, then activate it.
2659 if let Some(index) = entry
2660 .item
2661 .upgrade()
2662 .and_then(|v| pane.index_for_item(v.as_ref()))
2663 {
2664 let prev_active_item_index = pane.active_item_index();
2665 pane.nav_history_mut().set_mode(mode);
2666 pane.activate_item(index, true, true, window, cx);
2667 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2668
2669 let mut navigated = prev_active_item_index != pane.active_item_index();
2670 if let Some(data) = entry.data {
2671 navigated |= pane.active_item()?.navigate(data, window, cx);
2672 }
2673
2674 if navigated {
2675 break None;
2676 }
2677 } else {
2678 // If the item is no longer present in this pane, then retrieve its
2679 // path info in order to reopen it.
2680 break pane
2681 .nav_history()
2682 .path_for_item(entry.item.id())
2683 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2684 }
2685 }
2686 })
2687 } else {
2688 None
2689 };
2690
2691 if let Some((project_path, abs_path, entry)) = to_load {
2692 // If the item was no longer present, then load it again from its previous path, first try the local path
2693 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2694
2695 cx.spawn_in(window, async move |workspace, cx| {
2696 let open_by_project_path = open_by_project_path.await;
2697 let mut navigated = false;
2698 match open_by_project_path
2699 .with_context(|| format!("Navigating to {project_path:?}"))
2700 {
2701 Ok((project_entry_id, build_item)) => {
2702 let prev_active_item_id = pane.update(cx, |pane, _| {
2703 pane.nav_history_mut().set_mode(mode);
2704 pane.active_item().map(|p| p.item_id())
2705 })?;
2706
2707 pane.update_in(cx, |pane, window, cx| {
2708 let item = pane.open_item(
2709 project_entry_id,
2710 project_path,
2711 true,
2712 entry.is_preview,
2713 true,
2714 None,
2715 window, cx,
2716 build_item,
2717 );
2718 navigated |= Some(item.item_id()) != prev_active_item_id;
2719 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2720 if let Some(data) = entry.data {
2721 navigated |= item.navigate(data, window, cx);
2722 }
2723 })?;
2724 }
2725 Err(open_by_project_path_e) => {
2726 // Fall back to opening by abs path, in case an external file was opened and closed,
2727 // and its worktree is now dropped
2728 if let Some(abs_path) = abs_path {
2729 let prev_active_item_id = pane.update(cx, |pane, _| {
2730 pane.nav_history_mut().set_mode(mode);
2731 pane.active_item().map(|p| p.item_id())
2732 })?;
2733 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2734 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2735 })?;
2736 match open_by_abs_path
2737 .await
2738 .with_context(|| format!("Navigating to {abs_path:?}"))
2739 {
2740 Ok(item) => {
2741 pane.update_in(cx, |pane, window, cx| {
2742 navigated |= Some(item.item_id()) != prev_active_item_id;
2743 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2744 if let Some(data) = entry.data {
2745 navigated |= item.navigate(data, window, cx);
2746 }
2747 })?;
2748 }
2749 Err(open_by_abs_path_e) => {
2750 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2751 }
2752 }
2753 }
2754 }
2755 }
2756
2757 if !navigated {
2758 workspace
2759 .update_in(cx, |workspace, window, cx| {
2760 Self::navigate_history(workspace, pane, mode, window, cx)
2761 })?
2762 .await?;
2763 }
2764
2765 Ok(())
2766 })
2767 } else {
2768 Task::ready(Ok(()))
2769 }
2770 }
2771
2772 pub fn go_back(
2773 &mut self,
2774 pane: WeakEntity<Pane>,
2775 window: &mut Window,
2776 cx: &mut Context<Workspace>,
2777 ) -> Task<Result<()>> {
2778 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2779 }
2780
2781 pub fn go_forward(
2782 &mut self,
2783 pane: WeakEntity<Pane>,
2784 window: &mut Window,
2785 cx: &mut Context<Workspace>,
2786 ) -> Task<Result<()>> {
2787 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2788 }
2789
2790 pub fn reopen_closed_item(
2791 &mut self,
2792 window: &mut Window,
2793 cx: &mut Context<Workspace>,
2794 ) -> Task<Result<()>> {
2795 self.navigate_history(
2796 self.active_pane().downgrade(),
2797 NavigationMode::ReopeningClosedItem,
2798 window,
2799 cx,
2800 )
2801 }
2802
2803 pub fn client(&self) -> &Arc<Client> {
2804 &self.app_state.client
2805 }
2806
2807 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2808 self.titlebar_item = Some(item);
2809 cx.notify();
2810 }
2811
2812 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2813 self.on_prompt_for_new_path = Some(prompt)
2814 }
2815
2816 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2817 self.on_prompt_for_open_path = Some(prompt)
2818 }
2819
2820 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2821 self.terminal_provider = Some(Box::new(provider));
2822 }
2823
2824 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2825 self.debugger_provider = Some(Arc::new(provider));
2826 }
2827
2828 pub fn set_open_in_dev_container(&mut self, value: bool) {
2829 self.open_in_dev_container = value;
2830 }
2831
2832 pub fn open_in_dev_container(&self) -> bool {
2833 self.open_in_dev_container
2834 }
2835
2836 pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
2837 self._dev_container_task = Some(task);
2838 }
2839
2840 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2841 self.debugger_provider.clone()
2842 }
2843
2844 pub fn prompt_for_open_path(
2845 &mut self,
2846 path_prompt_options: PathPromptOptions,
2847 lister: DirectoryLister,
2848 window: &mut Window,
2849 cx: &mut Context<Self>,
2850 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2851 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2852 let prompt = self.on_prompt_for_open_path.take().unwrap();
2853 let rx = prompt(self, lister, window, cx);
2854 self.on_prompt_for_open_path = Some(prompt);
2855 rx
2856 } else {
2857 let (tx, rx) = oneshot::channel();
2858 let abs_path = cx.prompt_for_paths(path_prompt_options);
2859
2860 cx.spawn_in(window, async move |workspace, cx| {
2861 let Ok(result) = abs_path.await else {
2862 return Ok(());
2863 };
2864
2865 match result {
2866 Ok(result) => {
2867 tx.send(result).ok();
2868 }
2869 Err(err) => {
2870 let rx = workspace.update_in(cx, |workspace, window, cx| {
2871 workspace.show_portal_error(err.to_string(), cx);
2872 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2873 let rx = prompt(workspace, lister, window, cx);
2874 workspace.on_prompt_for_open_path = Some(prompt);
2875 rx
2876 })?;
2877 if let Ok(path) = rx.await {
2878 tx.send(path).ok();
2879 }
2880 }
2881 };
2882 anyhow::Ok(())
2883 })
2884 .detach();
2885
2886 rx
2887 }
2888 }
2889
2890 pub fn prompt_for_new_path(
2891 &mut self,
2892 lister: DirectoryLister,
2893 suggested_name: Option<String>,
2894 window: &mut Window,
2895 cx: &mut Context<Self>,
2896 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2897 if self.project.read(cx).is_via_collab()
2898 || self.project.read(cx).is_via_remote_server()
2899 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2900 {
2901 let prompt = self.on_prompt_for_new_path.take().unwrap();
2902 let rx = prompt(self, lister, suggested_name, window, cx);
2903 self.on_prompt_for_new_path = Some(prompt);
2904 return rx;
2905 }
2906
2907 let (tx, rx) = oneshot::channel();
2908 cx.spawn_in(window, async move |workspace, cx| {
2909 let abs_path = workspace.update(cx, |workspace, cx| {
2910 let relative_to = workspace
2911 .most_recent_active_path(cx)
2912 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2913 .or_else(|| {
2914 let project = workspace.project.read(cx);
2915 project.visible_worktrees(cx).find_map(|worktree| {
2916 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2917 })
2918 })
2919 .or_else(std::env::home_dir)
2920 .unwrap_or_else(|| PathBuf::from(""));
2921 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2922 })?;
2923 let abs_path = match abs_path.await? {
2924 Ok(path) => path,
2925 Err(err) => {
2926 let rx = workspace.update_in(cx, |workspace, window, cx| {
2927 workspace.show_portal_error(err.to_string(), cx);
2928
2929 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2930 let rx = prompt(workspace, lister, suggested_name, window, cx);
2931 workspace.on_prompt_for_new_path = Some(prompt);
2932 rx
2933 })?;
2934 if let Ok(path) = rx.await {
2935 tx.send(path).ok();
2936 }
2937 return anyhow::Ok(());
2938 }
2939 };
2940
2941 tx.send(abs_path.map(|path| vec![path])).ok();
2942 anyhow::Ok(())
2943 })
2944 .detach();
2945
2946 rx
2947 }
2948
2949 pub fn titlebar_item(&self) -> Option<AnyView> {
2950 self.titlebar_item.clone()
2951 }
2952
2953 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2954 /// When set, git-related operations should use this worktree instead of deriving
2955 /// the active worktree from the focused file.
2956 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2957 self.active_worktree_override
2958 }
2959
2960 pub fn set_active_worktree_override(
2961 &mut self,
2962 worktree_id: Option<WorktreeId>,
2963 cx: &mut Context<Self>,
2964 ) {
2965 self.active_worktree_override = worktree_id;
2966 cx.notify();
2967 }
2968
2969 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2970 self.active_worktree_override = None;
2971 cx.notify();
2972 }
2973
2974 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2975 ///
2976 /// If the given workspace has a local project, then it will be passed
2977 /// to the callback. Otherwise, a new empty window will be created.
2978 pub fn with_local_workspace<T, F>(
2979 &mut self,
2980 window: &mut Window,
2981 cx: &mut Context<Self>,
2982 callback: F,
2983 ) -> Task<Result<T>>
2984 where
2985 T: 'static,
2986 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2987 {
2988 if self.project.read(cx).is_local() {
2989 Task::ready(Ok(callback(self, window, cx)))
2990 } else {
2991 let env = self.project.read(cx).cli_environment(cx);
2992 let task = Self::new_local(
2993 Vec::new(),
2994 self.app_state.clone(),
2995 None,
2996 env,
2997 None,
2998 OpenMode::Activate,
2999 cx,
3000 );
3001 cx.spawn_in(window, async move |_vh, cx| {
3002 let OpenResult {
3003 window: multi_workspace_window,
3004 ..
3005 } = task.await?;
3006 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
3007 let workspace = multi_workspace.workspace().clone();
3008 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3009 })
3010 })
3011 }
3012 }
3013
3014 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
3015 ///
3016 /// If the given workspace has a local project, then it will be passed
3017 /// to the callback. Otherwise, a new empty window will be created.
3018 pub fn with_local_or_wsl_workspace<T, F>(
3019 &mut self,
3020 window: &mut Window,
3021 cx: &mut Context<Self>,
3022 callback: F,
3023 ) -> Task<Result<T>>
3024 where
3025 T: 'static,
3026 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
3027 {
3028 let project = self.project.read(cx);
3029 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
3030 Task::ready(Ok(callback(self, window, cx)))
3031 } else {
3032 let env = self.project.read(cx).cli_environment(cx);
3033 let task = Self::new_local(
3034 Vec::new(),
3035 self.app_state.clone(),
3036 None,
3037 env,
3038 None,
3039 OpenMode::Activate,
3040 cx,
3041 );
3042 cx.spawn_in(window, async move |_vh, cx| {
3043 let OpenResult {
3044 window: multi_workspace_window,
3045 ..
3046 } = task.await?;
3047 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
3048 let workspace = multi_workspace.workspace().clone();
3049 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3050 })
3051 })
3052 }
3053 }
3054
3055 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3056 self.project.read(cx).worktrees(cx)
3057 }
3058
3059 pub fn visible_worktrees<'a>(
3060 &self,
3061 cx: &'a App,
3062 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3063 self.project.read(cx).visible_worktrees(cx)
3064 }
3065
3066 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
3067 let futures = self
3068 .worktrees(cx)
3069 .filter_map(|worktree| worktree.read(cx).as_local())
3070 .map(|worktree| worktree.scan_complete())
3071 .collect::<Vec<_>>();
3072 async move {
3073 for future in futures {
3074 future.await;
3075 }
3076 }
3077 }
3078
3079 pub fn close_global(cx: &mut App) {
3080 cx.defer(|cx| {
3081 cx.windows().iter().find(|window| {
3082 window
3083 .update(cx, |_, window, _| {
3084 if window.is_window_active() {
3085 //This can only get called when the window's project connection has been lost
3086 //so we don't need to prompt the user for anything and instead just close the window
3087 window.remove_window();
3088 true
3089 } else {
3090 false
3091 }
3092 })
3093 .unwrap_or(false)
3094 });
3095 });
3096 }
3097
3098 pub fn move_focused_panel_to_next_position(
3099 &mut self,
3100 _: &MoveFocusedPanelToNextPosition,
3101 window: &mut Window,
3102 cx: &mut Context<Self>,
3103 ) {
3104 let docks = self.all_docks();
3105 let active_dock = docks
3106 .into_iter()
3107 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
3108
3109 if let Some(dock) = active_dock {
3110 dock.update(cx, |dock, cx| {
3111 let active_panel = dock
3112 .active_panel()
3113 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
3114
3115 if let Some(panel) = active_panel {
3116 panel.move_to_next_position(window, cx);
3117 }
3118 })
3119 }
3120 }
3121
3122 pub fn prepare_to_close(
3123 &mut self,
3124 close_intent: CloseIntent,
3125 window: &mut Window,
3126 cx: &mut Context<Self>,
3127 ) -> Task<Result<bool>> {
3128 let active_call = self.active_global_call();
3129
3130 cx.spawn_in(window, async move |this, cx| {
3131 this.update(cx, |this, _| {
3132 if close_intent == CloseIntent::CloseWindow {
3133 this.removing = true;
3134 }
3135 })?;
3136
3137 let workspace_count = cx.update(|_window, cx| {
3138 cx.windows()
3139 .iter()
3140 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
3141 .count()
3142 })?;
3143
3144 #[cfg(target_os = "macos")]
3145 let save_last_workspace = false;
3146
3147 // On Linux and Windows, closing the last window should restore the last workspace.
3148 #[cfg(not(target_os = "macos"))]
3149 let save_last_workspace = {
3150 let remaining_workspaces = cx.update(|_window, cx| {
3151 cx.windows()
3152 .iter()
3153 .filter_map(|window| window.downcast::<MultiWorkspace>())
3154 .filter_map(|multi_workspace| {
3155 multi_workspace
3156 .update(cx, |multi_workspace, _, cx| {
3157 multi_workspace.workspace().read(cx).removing
3158 })
3159 .ok()
3160 })
3161 .filter(|removing| !removing)
3162 .count()
3163 })?;
3164
3165 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
3166 };
3167
3168 if let Some(active_call) = active_call
3169 && workspace_count == 1
3170 && cx
3171 .update(|_window, cx| active_call.0.is_in_room(cx))
3172 .unwrap_or(false)
3173 {
3174 if close_intent == CloseIntent::CloseWindow {
3175 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
3176 let answer = cx.update(|window, cx| {
3177 window.prompt(
3178 PromptLevel::Warning,
3179 "Do you want to leave the current call?",
3180 None,
3181 &["Close window and hang up", "Cancel"],
3182 cx,
3183 )
3184 })?;
3185
3186 if answer.await.log_err() == Some(1) {
3187 return anyhow::Ok(false);
3188 } else {
3189 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
3190 task.await.log_err();
3191 }
3192 }
3193 }
3194 if close_intent == CloseIntent::ReplaceWindow {
3195 _ = cx.update(|_window, cx| {
3196 let multi_workspace = cx
3197 .windows()
3198 .iter()
3199 .filter_map(|window| window.downcast::<MultiWorkspace>())
3200 .next()
3201 .unwrap();
3202 let project = multi_workspace
3203 .read(cx)?
3204 .workspace()
3205 .read(cx)
3206 .project
3207 .clone();
3208 if project.read(cx).is_shared() {
3209 active_call.0.unshare_project(project, cx)?;
3210 }
3211 Ok::<_, anyhow::Error>(())
3212 });
3213 }
3214 }
3215
3216 let save_result = this
3217 .update_in(cx, |this, window, cx| {
3218 this.save_all_internal(SaveIntent::Close, window, cx)
3219 })?
3220 .await;
3221
3222 // If we're not quitting, but closing, we remove the workspace from
3223 // the current session.
3224 if close_intent != CloseIntent::Quit
3225 && !save_last_workspace
3226 && save_result.as_ref().is_ok_and(|&res| res)
3227 {
3228 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
3229 .await;
3230 }
3231
3232 save_result
3233 })
3234 }
3235
3236 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
3237 self.save_all_internal(
3238 action.save_intent.unwrap_or(SaveIntent::SaveAll),
3239 window,
3240 cx,
3241 )
3242 .detach_and_log_err(cx);
3243 }
3244
3245 fn send_keystrokes(
3246 &mut self,
3247 action: &SendKeystrokes,
3248 window: &mut Window,
3249 cx: &mut Context<Self>,
3250 ) {
3251 let keystrokes: Vec<Keystroke> = action
3252 .0
3253 .split(' ')
3254 .flat_map(|k| Keystroke::parse(k).log_err())
3255 .map(|k| {
3256 cx.keyboard_mapper()
3257 .map_key_equivalent(k, false)
3258 .inner()
3259 .clone()
3260 })
3261 .collect();
3262 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
3263 }
3264
3265 pub fn send_keystrokes_impl(
3266 &mut self,
3267 keystrokes: Vec<Keystroke>,
3268 window: &mut Window,
3269 cx: &mut Context<Self>,
3270 ) -> Shared<Task<()>> {
3271 let mut state = self.dispatching_keystrokes.borrow_mut();
3272 if !state.dispatched.insert(keystrokes.clone()) {
3273 cx.propagate();
3274 return state.task.clone().unwrap();
3275 }
3276
3277 state.queue.extend(keystrokes);
3278
3279 let keystrokes = self.dispatching_keystrokes.clone();
3280 if state.task.is_none() {
3281 state.task = Some(
3282 window
3283 .spawn(cx, async move |cx| {
3284 // limit to 100 keystrokes to avoid infinite recursion.
3285 for _ in 0..100 {
3286 let keystroke = {
3287 let mut state = keystrokes.borrow_mut();
3288 let Some(keystroke) = state.queue.pop_front() else {
3289 state.dispatched.clear();
3290 state.task.take();
3291 return;
3292 };
3293 keystroke
3294 };
3295 cx.update(|window, cx| {
3296 let focused = window.focused(cx);
3297 window.dispatch_keystroke(keystroke.clone(), cx);
3298 if window.focused(cx) != focused {
3299 // dispatch_keystroke may cause the focus to change.
3300 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3301 // And we need that to happen before the next keystroke to keep vim mode happy...
3302 // (Note that the tests always do this implicitly, so you must manually test with something like:
3303 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3304 // )
3305 window.draw(cx).clear();
3306 }
3307 })
3308 .ok();
3309
3310 // Yield between synthetic keystrokes so deferred focus and
3311 // other effects can settle before dispatching the next key.
3312 yield_now().await;
3313 }
3314
3315 *keystrokes.borrow_mut() = Default::default();
3316 log::error!("over 100 keystrokes passed to send_keystrokes");
3317 })
3318 .shared(),
3319 );
3320 }
3321 state.task.clone().unwrap()
3322 }
3323
3324 fn save_all_internal(
3325 &mut self,
3326 mut save_intent: SaveIntent,
3327 window: &mut Window,
3328 cx: &mut Context<Self>,
3329 ) -> Task<Result<bool>> {
3330 if self.project.read(cx).is_disconnected(cx) {
3331 return Task::ready(Ok(true));
3332 }
3333 let dirty_items = self
3334 .panes
3335 .iter()
3336 .flat_map(|pane| {
3337 pane.read(cx).items().filter_map(|item| {
3338 if item.is_dirty(cx) {
3339 item.tab_content_text(0, cx);
3340 Some((pane.downgrade(), item.boxed_clone()))
3341 } else {
3342 None
3343 }
3344 })
3345 })
3346 .collect::<Vec<_>>();
3347
3348 let project = self.project.clone();
3349 cx.spawn_in(window, async move |workspace, cx| {
3350 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3351 let (serialize_tasks, remaining_dirty_items) =
3352 workspace.update_in(cx, |workspace, window, cx| {
3353 let mut remaining_dirty_items = Vec::new();
3354 let mut serialize_tasks = Vec::new();
3355 for (pane, item) in dirty_items {
3356 if let Some(task) = item
3357 .to_serializable_item_handle(cx)
3358 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3359 {
3360 serialize_tasks.push(task);
3361 } else {
3362 remaining_dirty_items.push((pane, item));
3363 }
3364 }
3365 (serialize_tasks, remaining_dirty_items)
3366 })?;
3367
3368 futures::future::try_join_all(serialize_tasks).await?;
3369
3370 if !remaining_dirty_items.is_empty() {
3371 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3372 }
3373
3374 if remaining_dirty_items.len() > 1 {
3375 let answer = workspace.update_in(cx, |_, window, cx| {
3376 let detail = Pane::file_names_for_prompt(
3377 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3378 cx,
3379 );
3380 window.prompt(
3381 PromptLevel::Warning,
3382 "Do you want to save all changes in the following files?",
3383 Some(&detail),
3384 &["Save all", "Discard all", "Cancel"],
3385 cx,
3386 )
3387 })?;
3388 match answer.await.log_err() {
3389 Some(0) => save_intent = SaveIntent::SaveAll,
3390 Some(1) => save_intent = SaveIntent::Skip,
3391 Some(2) => return Ok(false),
3392 _ => {}
3393 }
3394 }
3395
3396 remaining_dirty_items
3397 } else {
3398 dirty_items
3399 };
3400
3401 for (pane, item) in dirty_items {
3402 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3403 (
3404 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3405 item.project_entry_ids(cx),
3406 )
3407 })?;
3408 if (singleton || !project_entry_ids.is_empty())
3409 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3410 {
3411 return Ok(false);
3412 }
3413 }
3414 Ok(true)
3415 })
3416 }
3417
3418 pub fn open_workspace_for_paths(
3419 &mut self,
3420 // replace_current_window: bool,
3421 mut open_mode: OpenMode,
3422 paths: Vec<PathBuf>,
3423 window: &mut Window,
3424 cx: &mut Context<Self>,
3425 ) -> Task<Result<Entity<Workspace>>> {
3426 let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
3427 let is_remote = self.project.read(cx).is_via_collab();
3428 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3429 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3430
3431 let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
3432 if workspace_is_empty {
3433 open_mode = OpenMode::Activate;
3434 }
3435
3436 let app_state = self.app_state.clone();
3437
3438 cx.spawn(async move |_, cx| {
3439 let OpenResult { workspace, .. } = cx
3440 .update(|cx| {
3441 open_paths(
3442 &paths,
3443 app_state,
3444 OpenOptions {
3445 requesting_window,
3446 open_mode,
3447 ..Default::default()
3448 },
3449 cx,
3450 )
3451 })
3452 .await?;
3453 Ok(workspace)
3454 })
3455 }
3456
3457 #[allow(clippy::type_complexity)]
3458 pub fn open_paths(
3459 &mut self,
3460 mut abs_paths: Vec<PathBuf>,
3461 options: OpenOptions,
3462 pane: Option<WeakEntity<Pane>>,
3463 window: &mut Window,
3464 cx: &mut Context<Self>,
3465 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3466 let fs = self.app_state.fs.clone();
3467
3468 let caller_ordered_abs_paths = abs_paths.clone();
3469
3470 // Sort the paths to ensure we add worktrees for parents before their children.
3471 abs_paths.sort_unstable();
3472 cx.spawn_in(window, async move |this, cx| {
3473 let mut tasks = Vec::with_capacity(abs_paths.len());
3474
3475 for abs_path in &abs_paths {
3476 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3477 OpenVisible::All => Some(true),
3478 OpenVisible::None => Some(false),
3479 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3480 Some(Some(metadata)) => Some(!metadata.is_dir),
3481 Some(None) => Some(true),
3482 None => None,
3483 },
3484 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3485 Some(Some(metadata)) => Some(metadata.is_dir),
3486 Some(None) => Some(false),
3487 None => None,
3488 },
3489 };
3490 let project_path = match visible {
3491 Some(visible) => match this
3492 .update(cx, |this, cx| {
3493 Workspace::project_path_for_path(
3494 this.project.clone(),
3495 abs_path,
3496 visible,
3497 cx,
3498 )
3499 })
3500 .log_err()
3501 {
3502 Some(project_path) => project_path.await.log_err(),
3503 None => None,
3504 },
3505 None => None,
3506 };
3507
3508 let this = this.clone();
3509 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3510 let fs = fs.clone();
3511 let pane = pane.clone();
3512 let task = cx.spawn(async move |cx| {
3513 let (_worktree, project_path) = project_path?;
3514 if fs.is_dir(&abs_path).await {
3515 // Opening a directory should not race to update the active entry.
3516 // We'll select/reveal a deterministic final entry after all paths finish opening.
3517 None
3518 } else {
3519 Some(
3520 this.update_in(cx, |this, window, cx| {
3521 this.open_path(
3522 project_path,
3523 pane,
3524 options.focus.unwrap_or(true),
3525 window,
3526 cx,
3527 )
3528 })
3529 .ok()?
3530 .await,
3531 )
3532 }
3533 });
3534 tasks.push(task);
3535 }
3536
3537 let results = futures::future::join_all(tasks).await;
3538
3539 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3540 let mut winner: Option<(PathBuf, bool)> = None;
3541 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3542 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3543 if !metadata.is_dir {
3544 winner = Some((abs_path, false));
3545 break;
3546 }
3547 if winner.is_none() {
3548 winner = Some((abs_path, true));
3549 }
3550 } else if winner.is_none() {
3551 winner = Some((abs_path, false));
3552 }
3553 }
3554
3555 // Compute the winner entry id on the foreground thread and emit once, after all
3556 // paths finish opening. This avoids races between concurrently-opening paths
3557 // (directories in particular) and makes the resulting project panel selection
3558 // deterministic.
3559 if let Some((winner_abs_path, winner_is_dir)) = winner {
3560 'emit_winner: {
3561 let winner_abs_path: Arc<Path> =
3562 SanitizedPath::new(&winner_abs_path).as_path().into();
3563
3564 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3565 OpenVisible::All => true,
3566 OpenVisible::None => false,
3567 OpenVisible::OnlyFiles => !winner_is_dir,
3568 OpenVisible::OnlyDirectories => winner_is_dir,
3569 };
3570
3571 let Some(worktree_task) = this
3572 .update(cx, |workspace, cx| {
3573 workspace.project.update(cx, |project, cx| {
3574 project.find_or_create_worktree(
3575 winner_abs_path.as_ref(),
3576 visible,
3577 cx,
3578 )
3579 })
3580 })
3581 .ok()
3582 else {
3583 break 'emit_winner;
3584 };
3585
3586 let Ok((worktree, _)) = worktree_task.await else {
3587 break 'emit_winner;
3588 };
3589
3590 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3591 let worktree = worktree.read(cx);
3592 let worktree_abs_path = worktree.abs_path();
3593 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3594 worktree.root_entry()
3595 } else {
3596 winner_abs_path
3597 .strip_prefix(worktree_abs_path.as_ref())
3598 .ok()
3599 .and_then(|relative_path| {
3600 let relative_path =
3601 RelPath::new(relative_path, PathStyle::local())
3602 .log_err()?;
3603 worktree.entry_for_path(&relative_path)
3604 })
3605 }?;
3606 Some(entry.id)
3607 }) else {
3608 break 'emit_winner;
3609 };
3610
3611 this.update(cx, |workspace, cx| {
3612 workspace.project.update(cx, |_, cx| {
3613 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3614 });
3615 })
3616 .ok();
3617 }
3618 }
3619
3620 results
3621 })
3622 }
3623
3624 pub fn open_resolved_path(
3625 &mut self,
3626 path: ResolvedPath,
3627 window: &mut Window,
3628 cx: &mut Context<Self>,
3629 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3630 match path {
3631 ResolvedPath::ProjectPath { project_path, .. } => {
3632 self.open_path(project_path, None, true, window, cx)
3633 }
3634 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3635 PathBuf::from(path),
3636 OpenOptions {
3637 visible: Some(OpenVisible::None),
3638 ..Default::default()
3639 },
3640 window,
3641 cx,
3642 ),
3643 }
3644 }
3645
3646 pub fn absolute_path_of_worktree(
3647 &self,
3648 worktree_id: WorktreeId,
3649 cx: &mut Context<Self>,
3650 ) -> Option<PathBuf> {
3651 self.project
3652 .read(cx)
3653 .worktree_for_id(worktree_id, cx)
3654 // TODO: use `abs_path` or `root_dir`
3655 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3656 }
3657
3658 pub fn add_folder_to_project(
3659 &mut self,
3660 _: &AddFolderToProject,
3661 window: &mut Window,
3662 cx: &mut Context<Self>,
3663 ) {
3664 let project = self.project.read(cx);
3665 if project.is_via_collab() {
3666 self.show_error(
3667 &anyhow!("You cannot add folders to someone else's project"),
3668 cx,
3669 );
3670 return;
3671 }
3672 let paths = self.prompt_for_open_path(
3673 PathPromptOptions {
3674 files: false,
3675 directories: true,
3676 multiple: true,
3677 prompt: None,
3678 },
3679 DirectoryLister::Project(self.project.clone()),
3680 window,
3681 cx,
3682 );
3683 cx.spawn_in(window, async move |this, cx| {
3684 if let Some(paths) = paths.await.log_err().flatten() {
3685 let results = this
3686 .update_in(cx, |this, window, cx| {
3687 this.open_paths(
3688 paths,
3689 OpenOptions {
3690 visible: Some(OpenVisible::All),
3691 ..Default::default()
3692 },
3693 None,
3694 window,
3695 cx,
3696 )
3697 })?
3698 .await;
3699 for result in results.into_iter().flatten() {
3700 result.log_err();
3701 }
3702 }
3703 anyhow::Ok(())
3704 })
3705 .detach_and_log_err(cx);
3706 }
3707
3708 pub fn project_path_for_path(
3709 project: Entity<Project>,
3710 abs_path: &Path,
3711 visible: bool,
3712 cx: &mut App,
3713 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3714 let entry = project.update(cx, |project, cx| {
3715 project.find_or_create_worktree(abs_path, visible, cx)
3716 });
3717 cx.spawn(async move |cx| {
3718 let (worktree, path) = entry.await?;
3719 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3720 Ok((worktree, ProjectPath { worktree_id, path }))
3721 })
3722 }
3723
3724 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3725 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3726 }
3727
3728 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3729 self.items_of_type(cx).max_by_key(|item| item.item_id())
3730 }
3731
3732 pub fn items_of_type<'a, T: Item>(
3733 &'a self,
3734 cx: &'a App,
3735 ) -> impl 'a + Iterator<Item = Entity<T>> {
3736 self.panes
3737 .iter()
3738 .flat_map(|pane| pane.read(cx).items_of_type())
3739 }
3740
3741 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3742 self.active_pane().read(cx).active_item()
3743 }
3744
3745 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3746 let item = self.active_item(cx)?;
3747 item.to_any_view().downcast::<I>().ok()
3748 }
3749
3750 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3751 self.active_item(cx).and_then(|item| item.project_path(cx))
3752 }
3753
3754 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3755 self.recent_navigation_history_iter(cx)
3756 .filter_map(|(path, abs_path)| {
3757 let worktree = self
3758 .project
3759 .read(cx)
3760 .worktree_for_id(path.worktree_id, cx)?;
3761 if worktree.read(cx).is_visible() {
3762 abs_path
3763 } else {
3764 None
3765 }
3766 })
3767 .next()
3768 }
3769
3770 pub fn save_active_item(
3771 &mut self,
3772 save_intent: SaveIntent,
3773 window: &mut Window,
3774 cx: &mut App,
3775 ) -> Task<Result<()>> {
3776 let project = self.project.clone();
3777 let pane = self.active_pane();
3778 let item = pane.read(cx).active_item();
3779 let pane = pane.downgrade();
3780
3781 window.spawn(cx, async move |cx| {
3782 if let Some(item) = item {
3783 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3784 .await
3785 .map(|_| ())
3786 } else {
3787 Ok(())
3788 }
3789 })
3790 }
3791
3792 pub fn close_inactive_items_and_panes(
3793 &mut self,
3794 action: &CloseInactiveTabsAndPanes,
3795 window: &mut Window,
3796 cx: &mut Context<Self>,
3797 ) {
3798 if let Some(task) = self.close_all_internal(
3799 true,
3800 action.save_intent.unwrap_or(SaveIntent::Close),
3801 window,
3802 cx,
3803 ) {
3804 task.detach_and_log_err(cx)
3805 }
3806 }
3807
3808 pub fn close_all_items_and_panes(
3809 &mut self,
3810 action: &CloseAllItemsAndPanes,
3811 window: &mut Window,
3812 cx: &mut Context<Self>,
3813 ) {
3814 if let Some(task) = self.close_all_internal(
3815 false,
3816 action.save_intent.unwrap_or(SaveIntent::Close),
3817 window,
3818 cx,
3819 ) {
3820 task.detach_and_log_err(cx)
3821 }
3822 }
3823
3824 /// Closes the active item across all panes.
3825 pub fn close_item_in_all_panes(
3826 &mut self,
3827 action: &CloseItemInAllPanes,
3828 window: &mut Window,
3829 cx: &mut Context<Self>,
3830 ) {
3831 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3832 return;
3833 };
3834
3835 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3836 let close_pinned = action.close_pinned;
3837
3838 if let Some(project_path) = active_item.project_path(cx) {
3839 self.close_items_with_project_path(
3840 &project_path,
3841 save_intent,
3842 close_pinned,
3843 window,
3844 cx,
3845 );
3846 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3847 let item_id = active_item.item_id();
3848 self.active_pane().update(cx, |pane, cx| {
3849 pane.close_item_by_id(item_id, save_intent, window, cx)
3850 .detach_and_log_err(cx);
3851 });
3852 }
3853 }
3854
3855 /// Closes all items with the given project path across all panes.
3856 pub fn close_items_with_project_path(
3857 &mut self,
3858 project_path: &ProjectPath,
3859 save_intent: SaveIntent,
3860 close_pinned: bool,
3861 window: &mut Window,
3862 cx: &mut Context<Self>,
3863 ) {
3864 let panes = self.panes().to_vec();
3865 for pane in panes {
3866 pane.update(cx, |pane, cx| {
3867 pane.close_items_for_project_path(
3868 project_path,
3869 save_intent,
3870 close_pinned,
3871 window,
3872 cx,
3873 )
3874 .detach_and_log_err(cx);
3875 });
3876 }
3877 }
3878
3879 fn close_all_internal(
3880 &mut self,
3881 retain_active_pane: bool,
3882 save_intent: SaveIntent,
3883 window: &mut Window,
3884 cx: &mut Context<Self>,
3885 ) -> Option<Task<Result<()>>> {
3886 let current_pane = self.active_pane();
3887
3888 let mut tasks = Vec::new();
3889
3890 if retain_active_pane {
3891 let current_pane_close = current_pane.update(cx, |pane, cx| {
3892 pane.close_other_items(
3893 &CloseOtherItems {
3894 save_intent: None,
3895 close_pinned: false,
3896 },
3897 None,
3898 window,
3899 cx,
3900 )
3901 });
3902
3903 tasks.push(current_pane_close);
3904 }
3905
3906 for pane in self.panes() {
3907 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3908 continue;
3909 }
3910
3911 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3912 pane.close_all_items(
3913 &CloseAllItems {
3914 save_intent: Some(save_intent),
3915 close_pinned: false,
3916 },
3917 window,
3918 cx,
3919 )
3920 });
3921
3922 tasks.push(close_pane_items)
3923 }
3924
3925 if tasks.is_empty() {
3926 None
3927 } else {
3928 Some(cx.spawn_in(window, async move |_, _| {
3929 for task in tasks {
3930 task.await?
3931 }
3932 Ok(())
3933 }))
3934 }
3935 }
3936
3937 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3938 self.dock_at_position(position).read(cx).is_open()
3939 }
3940
3941 pub fn toggle_dock(
3942 &mut self,
3943 dock_side: DockPosition,
3944 window: &mut Window,
3945 cx: &mut Context<Self>,
3946 ) {
3947 let mut focus_center = false;
3948 let mut reveal_dock = false;
3949
3950 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3951 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3952
3953 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3954 telemetry::event!(
3955 "Panel Button Clicked",
3956 name = panel.persistent_name(),
3957 toggle_state = !was_visible
3958 );
3959 }
3960 if was_visible {
3961 self.save_open_dock_positions(cx);
3962 }
3963
3964 let dock = self.dock_at_position(dock_side);
3965 dock.update(cx, |dock, cx| {
3966 dock.set_open(!was_visible, window, cx);
3967
3968 if dock.active_panel().is_none() {
3969 let Some(panel_ix) = dock
3970 .first_enabled_panel_idx(cx)
3971 .log_with_level(log::Level::Info)
3972 else {
3973 return;
3974 };
3975 dock.activate_panel(panel_ix, window, cx);
3976 }
3977
3978 if let Some(active_panel) = dock.active_panel() {
3979 if was_visible {
3980 if active_panel
3981 .panel_focus_handle(cx)
3982 .contains_focused(window, cx)
3983 {
3984 focus_center = true;
3985 }
3986 } else {
3987 let focus_handle = &active_panel.panel_focus_handle(cx);
3988 window.focus(focus_handle, cx);
3989 reveal_dock = true;
3990 }
3991 }
3992 });
3993
3994 if reveal_dock {
3995 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3996 }
3997
3998 if focus_center {
3999 self.active_pane
4000 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4001 }
4002
4003 cx.notify();
4004 self.serialize_workspace(window, cx);
4005 }
4006
4007 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
4008 self.all_docks().into_iter().find(|&dock| {
4009 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
4010 })
4011 }
4012
4013 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
4014 if let Some(dock) = self.active_dock(window, cx).cloned() {
4015 self.save_open_dock_positions(cx);
4016 dock.update(cx, |dock, cx| {
4017 dock.set_open(false, window, cx);
4018 });
4019 return true;
4020 }
4021 false
4022 }
4023
4024 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4025 self.save_open_dock_positions(cx);
4026 for dock in self.all_docks() {
4027 dock.update(cx, |dock, cx| {
4028 dock.set_open(false, window, cx);
4029 });
4030 }
4031
4032 cx.focus_self(window);
4033 cx.notify();
4034 self.serialize_workspace(window, cx);
4035 }
4036
4037 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
4038 self.all_docks()
4039 .into_iter()
4040 .filter_map(|dock| {
4041 let dock_ref = dock.read(cx);
4042 if dock_ref.is_open() {
4043 Some(dock_ref.position())
4044 } else {
4045 None
4046 }
4047 })
4048 .collect()
4049 }
4050
4051 /// Saves the positions of currently open docks.
4052 ///
4053 /// Updates `last_open_dock_positions` with positions of all currently open
4054 /// docks, to later be restored by the 'Toggle All Docks' action.
4055 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
4056 let open_dock_positions = self.get_open_dock_positions(cx);
4057 if !open_dock_positions.is_empty() {
4058 self.last_open_dock_positions = open_dock_positions;
4059 }
4060 }
4061
4062 /// Toggles all docks between open and closed states.
4063 ///
4064 /// If any docks are open, closes all and remembers their positions. If all
4065 /// docks are closed, restores the last remembered dock configuration.
4066 fn toggle_all_docks(
4067 &mut self,
4068 _: &ToggleAllDocks,
4069 window: &mut Window,
4070 cx: &mut Context<Self>,
4071 ) {
4072 let open_dock_positions = self.get_open_dock_positions(cx);
4073
4074 if !open_dock_positions.is_empty() {
4075 self.close_all_docks(window, cx);
4076 } else if !self.last_open_dock_positions.is_empty() {
4077 self.restore_last_open_docks(window, cx);
4078 }
4079 }
4080
4081 /// Reopens docks from the most recently remembered configuration.
4082 ///
4083 /// Opens all docks whose positions are stored in `last_open_dock_positions`
4084 /// and clears the stored positions.
4085 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4086 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
4087
4088 for position in positions_to_open {
4089 let dock = self.dock_at_position(position);
4090 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
4091 }
4092
4093 cx.focus_self(window);
4094 cx.notify();
4095 self.serialize_workspace(window, cx);
4096 }
4097
4098 /// Transfer focus to the panel of the given type.
4099 pub fn focus_panel<T: Panel>(
4100 &mut self,
4101 window: &mut Window,
4102 cx: &mut Context<Self>,
4103 ) -> Option<Entity<T>> {
4104 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
4105 panel.to_any().downcast().ok()
4106 }
4107
4108 /// Focus the panel of the given type if it isn't already focused. If it is
4109 /// already focused, then transfer focus back to the workspace center.
4110 /// When the `close_panel_on_toggle` setting is enabled, also closes the
4111 /// panel when transferring focus back to the center.
4112 pub fn toggle_panel_focus<T: Panel>(
4113 &mut self,
4114 window: &mut Window,
4115 cx: &mut Context<Self>,
4116 ) -> bool {
4117 let mut did_focus_panel = false;
4118 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
4119 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
4120 did_focus_panel
4121 });
4122
4123 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
4124 self.close_panel::<T>(window, cx);
4125 }
4126
4127 telemetry::event!(
4128 "Panel Button Clicked",
4129 name = T::persistent_name(),
4130 toggle_state = did_focus_panel
4131 );
4132
4133 did_focus_panel
4134 }
4135
4136 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4137 if let Some(item) = self.active_item(cx) {
4138 item.item_focus_handle(cx).focus(window, cx);
4139 } else {
4140 log::error!("Could not find a focus target when switching focus to the center panes",);
4141 }
4142 }
4143
4144 pub fn activate_panel_for_proto_id(
4145 &mut self,
4146 panel_id: PanelId,
4147 window: &mut Window,
4148 cx: &mut Context<Self>,
4149 ) -> Option<Arc<dyn PanelHandle>> {
4150 let mut panel = None;
4151 for dock in self.all_docks() {
4152 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
4153 panel = dock.update(cx, |dock, cx| {
4154 dock.activate_panel(panel_index, window, cx);
4155 dock.set_open(true, window, cx);
4156 dock.active_panel().cloned()
4157 });
4158 break;
4159 }
4160 }
4161
4162 if panel.is_some() {
4163 cx.notify();
4164 self.serialize_workspace(window, cx);
4165 }
4166
4167 panel
4168 }
4169
4170 /// Focus or unfocus the given panel type, depending on the given callback.
4171 fn focus_or_unfocus_panel<T: Panel>(
4172 &mut self,
4173 window: &mut Window,
4174 cx: &mut Context<Self>,
4175 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
4176 ) -> Option<Arc<dyn PanelHandle>> {
4177 let mut result_panel = None;
4178 let mut serialize = false;
4179 for dock in self.all_docks() {
4180 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4181 let mut focus_center = false;
4182 let panel = dock.update(cx, |dock, cx| {
4183 dock.activate_panel(panel_index, window, cx);
4184
4185 let panel = dock.active_panel().cloned();
4186 if let Some(panel) = panel.as_ref() {
4187 if should_focus(&**panel, window, cx) {
4188 dock.set_open(true, window, cx);
4189 panel.panel_focus_handle(cx).focus(window, cx);
4190 } else {
4191 focus_center = true;
4192 }
4193 }
4194 panel
4195 });
4196
4197 if focus_center {
4198 self.active_pane
4199 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4200 }
4201
4202 result_panel = panel;
4203 serialize = true;
4204 break;
4205 }
4206 }
4207
4208 if serialize {
4209 self.serialize_workspace(window, cx);
4210 }
4211
4212 cx.notify();
4213 result_panel
4214 }
4215
4216 /// Open the panel of the given type
4217 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4218 for dock in self.all_docks() {
4219 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4220 dock.update(cx, |dock, cx| {
4221 dock.activate_panel(panel_index, window, cx);
4222 dock.set_open(true, window, cx);
4223 });
4224 }
4225 }
4226 }
4227
4228 /// Open the panel of the given type, dismissing any zoomed items that
4229 /// would obscure it (e.g. a zoomed terminal).
4230 pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4231 let dock_position = self.all_docks().iter().find_map(|dock| {
4232 let dock = dock.read(cx);
4233 dock.panel_index_for_type::<T>().map(|_| dock.position())
4234 });
4235 self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
4236 self.open_panel::<T>(window, cx);
4237 }
4238
4239 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
4240 for dock in self.all_docks().iter() {
4241 dock.update(cx, |dock, cx| {
4242 if dock.panel::<T>().is_some() {
4243 dock.set_open(false, window, cx)
4244 }
4245 })
4246 }
4247 }
4248
4249 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
4250 self.all_docks()
4251 .iter()
4252 .find_map(|dock| dock.read(cx).panel::<T>())
4253 }
4254
4255 fn dismiss_zoomed_items_to_reveal(
4256 &mut self,
4257 dock_to_reveal: Option<DockPosition>,
4258 window: &mut Window,
4259 cx: &mut Context<Self>,
4260 ) {
4261 // If a center pane is zoomed, unzoom it.
4262 for pane in &self.panes {
4263 if pane != &self.active_pane || dock_to_reveal.is_some() {
4264 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4265 }
4266 }
4267
4268 // If another dock is zoomed, hide it.
4269 let mut focus_center = false;
4270 for dock in self.all_docks() {
4271 dock.update(cx, |dock, cx| {
4272 if Some(dock.position()) != dock_to_reveal
4273 && let Some(panel) = dock.active_panel()
4274 && panel.is_zoomed(window, cx)
4275 {
4276 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
4277 dock.set_open(false, window, cx);
4278 }
4279 });
4280 }
4281
4282 if focus_center {
4283 self.active_pane
4284 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4285 }
4286
4287 if self.zoomed_position != dock_to_reveal {
4288 self.zoomed = None;
4289 self.zoomed_position = None;
4290 cx.emit(Event::ZoomChanged);
4291 }
4292
4293 cx.notify();
4294 }
4295
4296 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4297 let pane = cx.new(|cx| {
4298 let mut pane = Pane::new(
4299 self.weak_handle(),
4300 self.project.clone(),
4301 self.pane_history_timestamp.clone(),
4302 None,
4303 NewFile.boxed_clone(),
4304 true,
4305 window,
4306 cx,
4307 );
4308 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4309 pane
4310 });
4311 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4312 .detach();
4313 self.panes.push(pane.clone());
4314
4315 window.focus(&pane.focus_handle(cx), cx);
4316
4317 cx.emit(Event::PaneAdded(pane.clone()));
4318 pane
4319 }
4320
4321 pub fn add_item_to_center(
4322 &mut self,
4323 item: Box<dyn ItemHandle>,
4324 window: &mut Window,
4325 cx: &mut Context<Self>,
4326 ) -> bool {
4327 if let Some(center_pane) = self.last_active_center_pane.clone() {
4328 if let Some(center_pane) = center_pane.upgrade() {
4329 center_pane.update(cx, |pane, cx| {
4330 pane.add_item(item, true, true, None, window, cx)
4331 });
4332 true
4333 } else {
4334 false
4335 }
4336 } else {
4337 false
4338 }
4339 }
4340
4341 pub fn add_item_to_active_pane(
4342 &mut self,
4343 item: Box<dyn ItemHandle>,
4344 destination_index: Option<usize>,
4345 focus_item: bool,
4346 window: &mut Window,
4347 cx: &mut App,
4348 ) {
4349 self.add_item(
4350 self.active_pane.clone(),
4351 item,
4352 destination_index,
4353 false,
4354 focus_item,
4355 window,
4356 cx,
4357 )
4358 }
4359
4360 pub fn add_item(
4361 &mut self,
4362 pane: Entity<Pane>,
4363 item: Box<dyn ItemHandle>,
4364 destination_index: Option<usize>,
4365 activate_pane: bool,
4366 focus_item: bool,
4367 window: &mut Window,
4368 cx: &mut App,
4369 ) {
4370 pane.update(cx, |pane, cx| {
4371 pane.add_item(
4372 item,
4373 activate_pane,
4374 focus_item,
4375 destination_index,
4376 window,
4377 cx,
4378 )
4379 });
4380 }
4381
4382 pub fn split_item(
4383 &mut self,
4384 split_direction: SplitDirection,
4385 item: Box<dyn ItemHandle>,
4386 window: &mut Window,
4387 cx: &mut Context<Self>,
4388 ) {
4389 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4390 self.add_item(new_pane, item, None, true, true, window, cx);
4391 }
4392
4393 pub fn open_abs_path(
4394 &mut self,
4395 abs_path: PathBuf,
4396 options: OpenOptions,
4397 window: &mut Window,
4398 cx: &mut Context<Self>,
4399 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4400 cx.spawn_in(window, async move |workspace, cx| {
4401 let open_paths_task_result = workspace
4402 .update_in(cx, |workspace, window, cx| {
4403 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4404 })
4405 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4406 .await;
4407 anyhow::ensure!(
4408 open_paths_task_result.len() == 1,
4409 "open abs path {abs_path:?} task returned incorrect number of results"
4410 );
4411 match open_paths_task_result
4412 .into_iter()
4413 .next()
4414 .expect("ensured single task result")
4415 {
4416 Some(open_result) => {
4417 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4418 }
4419 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4420 }
4421 })
4422 }
4423
4424 pub fn split_abs_path(
4425 &mut self,
4426 abs_path: PathBuf,
4427 visible: bool,
4428 window: &mut Window,
4429 cx: &mut Context<Self>,
4430 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4431 let project_path_task =
4432 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4433 cx.spawn_in(window, async move |this, cx| {
4434 let (_, path) = project_path_task.await?;
4435 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4436 .await
4437 })
4438 }
4439
4440 pub fn open_path(
4441 &mut self,
4442 path: impl Into<ProjectPath>,
4443 pane: Option<WeakEntity<Pane>>,
4444 focus_item: bool,
4445 window: &mut Window,
4446 cx: &mut App,
4447 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4448 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4449 }
4450
4451 pub fn open_path_preview(
4452 &mut self,
4453 path: impl Into<ProjectPath>,
4454 pane: Option<WeakEntity<Pane>>,
4455 focus_item: bool,
4456 allow_preview: bool,
4457 activate: bool,
4458 window: &mut Window,
4459 cx: &mut App,
4460 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4461 let pane = pane.unwrap_or_else(|| {
4462 self.last_active_center_pane.clone().unwrap_or_else(|| {
4463 self.panes
4464 .first()
4465 .expect("There must be an active pane")
4466 .downgrade()
4467 })
4468 });
4469
4470 let project_path = path.into();
4471 let task = self.load_path(project_path.clone(), window, cx);
4472 window.spawn(cx, async move |cx| {
4473 let (project_entry_id, build_item) = task.await?;
4474
4475 pane.update_in(cx, |pane, window, cx| {
4476 pane.open_item(
4477 project_entry_id,
4478 project_path,
4479 focus_item,
4480 allow_preview,
4481 activate,
4482 None,
4483 window,
4484 cx,
4485 build_item,
4486 )
4487 })
4488 })
4489 }
4490
4491 pub fn split_path(
4492 &mut self,
4493 path: impl Into<ProjectPath>,
4494 window: &mut Window,
4495 cx: &mut Context<Self>,
4496 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4497 self.split_path_preview(path, false, None, window, cx)
4498 }
4499
4500 pub fn split_path_preview(
4501 &mut self,
4502 path: impl Into<ProjectPath>,
4503 allow_preview: bool,
4504 split_direction: Option<SplitDirection>,
4505 window: &mut Window,
4506 cx: &mut Context<Self>,
4507 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4508 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4509 self.panes
4510 .first()
4511 .expect("There must be an active pane")
4512 .downgrade()
4513 });
4514
4515 if let Member::Pane(center_pane) = &self.center.root
4516 && center_pane.read(cx).items_len() == 0
4517 {
4518 return self.open_path(path, Some(pane), true, window, cx);
4519 }
4520
4521 let project_path = path.into();
4522 let task = self.load_path(project_path.clone(), window, cx);
4523 cx.spawn_in(window, async move |this, cx| {
4524 let (project_entry_id, build_item) = task.await?;
4525 this.update_in(cx, move |this, window, cx| -> Option<_> {
4526 let pane = pane.upgrade()?;
4527 let new_pane = this.split_pane(
4528 pane,
4529 split_direction.unwrap_or(SplitDirection::Right),
4530 window,
4531 cx,
4532 );
4533 new_pane.update(cx, |new_pane, cx| {
4534 Some(new_pane.open_item(
4535 project_entry_id,
4536 project_path,
4537 true,
4538 allow_preview,
4539 true,
4540 None,
4541 window,
4542 cx,
4543 build_item,
4544 ))
4545 })
4546 })
4547 .map(|option| option.context("pane was dropped"))?
4548 })
4549 }
4550
4551 fn load_path(
4552 &mut self,
4553 path: ProjectPath,
4554 window: &mut Window,
4555 cx: &mut App,
4556 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4557 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4558 registry.open_path(self.project(), &path, window, cx)
4559 }
4560
4561 pub fn find_project_item<T>(
4562 &self,
4563 pane: &Entity<Pane>,
4564 project_item: &Entity<T::Item>,
4565 cx: &App,
4566 ) -> Option<Entity<T>>
4567 where
4568 T: ProjectItem,
4569 {
4570 use project::ProjectItem as _;
4571 let project_item = project_item.read(cx);
4572 let entry_id = project_item.entry_id(cx);
4573 let project_path = project_item.project_path(cx);
4574
4575 let mut item = None;
4576 if let Some(entry_id) = entry_id {
4577 item = pane.read(cx).item_for_entry(entry_id, cx);
4578 }
4579 if item.is_none()
4580 && let Some(project_path) = project_path
4581 {
4582 item = pane.read(cx).item_for_path(project_path, cx);
4583 }
4584
4585 item.and_then(|item| item.downcast::<T>())
4586 }
4587
4588 pub fn is_project_item_open<T>(
4589 &self,
4590 pane: &Entity<Pane>,
4591 project_item: &Entity<T::Item>,
4592 cx: &App,
4593 ) -> bool
4594 where
4595 T: ProjectItem,
4596 {
4597 self.find_project_item::<T>(pane, project_item, cx)
4598 .is_some()
4599 }
4600
4601 pub fn open_project_item<T>(
4602 &mut self,
4603 pane: Entity<Pane>,
4604 project_item: Entity<T::Item>,
4605 activate_pane: bool,
4606 focus_item: bool,
4607 keep_old_preview: bool,
4608 allow_new_preview: bool,
4609 window: &mut Window,
4610 cx: &mut Context<Self>,
4611 ) -> Entity<T>
4612 where
4613 T: ProjectItem,
4614 {
4615 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4616
4617 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4618 if !keep_old_preview
4619 && let Some(old_id) = old_item_id
4620 && old_id != item.item_id()
4621 {
4622 // switching to a different item, so unpreview old active item
4623 pane.update(cx, |pane, _| {
4624 pane.unpreview_item_if_preview(old_id);
4625 });
4626 }
4627
4628 self.activate_item(&item, activate_pane, focus_item, window, cx);
4629 if !allow_new_preview {
4630 pane.update(cx, |pane, _| {
4631 pane.unpreview_item_if_preview(item.item_id());
4632 });
4633 }
4634 return item;
4635 }
4636
4637 let item = pane.update(cx, |pane, cx| {
4638 cx.new(|cx| {
4639 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4640 })
4641 });
4642 let mut destination_index = None;
4643 pane.update(cx, |pane, cx| {
4644 if !keep_old_preview && let Some(old_id) = old_item_id {
4645 pane.unpreview_item_if_preview(old_id);
4646 }
4647 if allow_new_preview {
4648 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4649 }
4650 });
4651
4652 self.add_item(
4653 pane,
4654 Box::new(item.clone()),
4655 destination_index,
4656 activate_pane,
4657 focus_item,
4658 window,
4659 cx,
4660 );
4661 item
4662 }
4663
4664 pub fn open_shared_screen(
4665 &mut self,
4666 peer_id: PeerId,
4667 window: &mut Window,
4668 cx: &mut Context<Self>,
4669 ) {
4670 if let Some(shared_screen) =
4671 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4672 {
4673 self.active_pane.update(cx, |pane, cx| {
4674 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4675 });
4676 }
4677 }
4678
4679 pub fn activate_item(
4680 &mut self,
4681 item: &dyn ItemHandle,
4682 activate_pane: bool,
4683 focus_item: bool,
4684 window: &mut Window,
4685 cx: &mut App,
4686 ) -> bool {
4687 let result = self.panes.iter().find_map(|pane| {
4688 pane.read(cx)
4689 .index_for_item(item)
4690 .map(|ix| (pane.clone(), ix))
4691 });
4692 if let Some((pane, ix)) = result {
4693 pane.update(cx, |pane, cx| {
4694 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4695 });
4696 true
4697 } else {
4698 false
4699 }
4700 }
4701
4702 fn activate_pane_at_index(
4703 &mut self,
4704 action: &ActivatePane,
4705 window: &mut Window,
4706 cx: &mut Context<Self>,
4707 ) {
4708 let panes = self.center.panes();
4709 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4710 window.focus(&pane.focus_handle(cx), cx);
4711 } else {
4712 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4713 .detach();
4714 }
4715 }
4716
4717 fn move_item_to_pane_at_index(
4718 &mut self,
4719 action: &MoveItemToPane,
4720 window: &mut Window,
4721 cx: &mut Context<Self>,
4722 ) {
4723 let panes = self.center.panes();
4724 let destination = match panes.get(action.destination) {
4725 Some(&destination) => destination.clone(),
4726 None => {
4727 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4728 return;
4729 }
4730 let direction = SplitDirection::Right;
4731 let split_off_pane = self
4732 .find_pane_in_direction(direction, cx)
4733 .unwrap_or_else(|| self.active_pane.clone());
4734 let new_pane = self.add_pane(window, cx);
4735 self.center.split(&split_off_pane, &new_pane, direction, cx);
4736 new_pane
4737 }
4738 };
4739
4740 if action.clone {
4741 if self
4742 .active_pane
4743 .read(cx)
4744 .active_item()
4745 .is_some_and(|item| item.can_split(cx))
4746 {
4747 clone_active_item(
4748 self.database_id(),
4749 &self.active_pane,
4750 &destination,
4751 action.focus,
4752 window,
4753 cx,
4754 );
4755 return;
4756 }
4757 }
4758 move_active_item(
4759 &self.active_pane,
4760 &destination,
4761 action.focus,
4762 true,
4763 window,
4764 cx,
4765 )
4766 }
4767
4768 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4769 let panes = self.center.panes();
4770 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4771 let next_ix = (ix + 1) % panes.len();
4772 let next_pane = panes[next_ix].clone();
4773 window.focus(&next_pane.focus_handle(cx), cx);
4774 }
4775 }
4776
4777 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4778 let panes = self.center.panes();
4779 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4780 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4781 let prev_pane = panes[prev_ix].clone();
4782 window.focus(&prev_pane.focus_handle(cx), cx);
4783 }
4784 }
4785
4786 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4787 let last_pane = self.center.last_pane();
4788 window.focus(&last_pane.focus_handle(cx), cx);
4789 }
4790
4791 pub fn activate_pane_in_direction(
4792 &mut self,
4793 direction: SplitDirection,
4794 window: &mut Window,
4795 cx: &mut App,
4796 ) {
4797 use ActivateInDirectionTarget as Target;
4798 enum Origin {
4799 Sidebar,
4800 LeftDock,
4801 RightDock,
4802 BottomDock,
4803 Center,
4804 }
4805
4806 let origin: Origin = if self
4807 .sidebar_focus_handle
4808 .as_ref()
4809 .is_some_and(|h| h.contains_focused(window, cx))
4810 {
4811 Origin::Sidebar
4812 } else {
4813 [
4814 (&self.left_dock, Origin::LeftDock),
4815 (&self.right_dock, Origin::RightDock),
4816 (&self.bottom_dock, Origin::BottomDock),
4817 ]
4818 .into_iter()
4819 .find_map(|(dock, origin)| {
4820 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4821 Some(origin)
4822 } else {
4823 None
4824 }
4825 })
4826 .unwrap_or(Origin::Center)
4827 };
4828
4829 let get_last_active_pane = || {
4830 let pane = self
4831 .last_active_center_pane
4832 .clone()
4833 .unwrap_or_else(|| {
4834 self.panes
4835 .first()
4836 .expect("There must be an active pane")
4837 .downgrade()
4838 })
4839 .upgrade()?;
4840 (pane.read(cx).items_len() != 0).then_some(pane)
4841 };
4842
4843 let try_dock =
4844 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4845
4846 let sidebar_target = self
4847 .sidebar_focus_handle
4848 .as_ref()
4849 .map(|h| Target::Sidebar(h.clone()));
4850
4851 let target = match (origin, direction) {
4852 // From the sidebar, only Right navigates into the workspace.
4853 (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
4854 .or_else(|| get_last_active_pane().map(Target::Pane))
4855 .or_else(|| try_dock(&self.bottom_dock))
4856 .or_else(|| try_dock(&self.right_dock)),
4857
4858 (Origin::Sidebar, _) => None,
4859
4860 // We're in the center, so we first try to go to a different pane,
4861 // otherwise try to go to a dock.
4862 (Origin::Center, direction) => {
4863 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4864 Some(Target::Pane(pane))
4865 } else {
4866 match direction {
4867 SplitDirection::Up => None,
4868 SplitDirection::Down => try_dock(&self.bottom_dock),
4869 SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
4870 SplitDirection::Right => try_dock(&self.right_dock),
4871 }
4872 }
4873 }
4874
4875 (Origin::LeftDock, SplitDirection::Right) => {
4876 if let Some(last_active_pane) = get_last_active_pane() {
4877 Some(Target::Pane(last_active_pane))
4878 } else {
4879 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4880 }
4881 }
4882
4883 (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
4884
4885 (Origin::LeftDock, SplitDirection::Down)
4886 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4887
4888 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4889 (Origin::BottomDock, SplitDirection::Left) => {
4890 try_dock(&self.left_dock).or(sidebar_target)
4891 }
4892 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4893
4894 (Origin::RightDock, SplitDirection::Left) => {
4895 if let Some(last_active_pane) = get_last_active_pane() {
4896 Some(Target::Pane(last_active_pane))
4897 } else {
4898 try_dock(&self.bottom_dock)
4899 .or_else(|| try_dock(&self.left_dock))
4900 .or(sidebar_target)
4901 }
4902 }
4903
4904 _ => None,
4905 };
4906
4907 match target {
4908 Some(ActivateInDirectionTarget::Pane(pane)) => {
4909 let pane = pane.read(cx);
4910 if let Some(item) = pane.active_item() {
4911 item.item_focus_handle(cx).focus(window, cx);
4912 } else {
4913 log::error!(
4914 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4915 );
4916 }
4917 }
4918 Some(ActivateInDirectionTarget::Dock(dock)) => {
4919 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4920 window.defer(cx, move |window, cx| {
4921 let dock = dock.read(cx);
4922 if let Some(panel) = dock.active_panel() {
4923 panel.panel_focus_handle(cx).focus(window, cx);
4924 } else {
4925 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4926 }
4927 })
4928 }
4929 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4930 focus_handle.focus(window, cx);
4931 }
4932 None => {}
4933 }
4934 }
4935
4936 pub fn move_item_to_pane_in_direction(
4937 &mut self,
4938 action: &MoveItemToPaneInDirection,
4939 window: &mut Window,
4940 cx: &mut Context<Self>,
4941 ) {
4942 let destination = match self.find_pane_in_direction(action.direction, cx) {
4943 Some(destination) => destination,
4944 None => {
4945 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4946 return;
4947 }
4948 let new_pane = self.add_pane(window, cx);
4949 self.center
4950 .split(&self.active_pane, &new_pane, action.direction, cx);
4951 new_pane
4952 }
4953 };
4954
4955 if action.clone {
4956 if self
4957 .active_pane
4958 .read(cx)
4959 .active_item()
4960 .is_some_and(|item| item.can_split(cx))
4961 {
4962 clone_active_item(
4963 self.database_id(),
4964 &self.active_pane,
4965 &destination,
4966 action.focus,
4967 window,
4968 cx,
4969 );
4970 return;
4971 }
4972 }
4973 move_active_item(
4974 &self.active_pane,
4975 &destination,
4976 action.focus,
4977 true,
4978 window,
4979 cx,
4980 );
4981 }
4982
4983 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4984 self.center.bounding_box_for_pane(pane)
4985 }
4986
4987 pub fn find_pane_in_direction(
4988 &mut self,
4989 direction: SplitDirection,
4990 cx: &App,
4991 ) -> Option<Entity<Pane>> {
4992 self.center
4993 .find_pane_in_direction(&self.active_pane, direction, cx)
4994 .cloned()
4995 }
4996
4997 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4998 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4999 self.center.swap(&self.active_pane, &to, cx);
5000 cx.notify();
5001 }
5002 }
5003
5004 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
5005 if self
5006 .center
5007 .move_to_border(&self.active_pane, direction, cx)
5008 .unwrap()
5009 {
5010 cx.notify();
5011 }
5012 }
5013
5014 pub fn resize_pane(
5015 &mut self,
5016 axis: gpui::Axis,
5017 amount: Pixels,
5018 window: &mut Window,
5019 cx: &mut Context<Self>,
5020 ) {
5021 let docks = self.all_docks();
5022 let active_dock = docks
5023 .into_iter()
5024 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
5025
5026 if let Some(dock_entity) = active_dock {
5027 let dock = dock_entity.read(cx);
5028 let Some(panel_size) = self.dock_size(&dock, window, cx) else {
5029 return;
5030 };
5031 match dock.position() {
5032 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
5033 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
5034 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
5035 }
5036 } else {
5037 self.center
5038 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
5039 }
5040 cx.notify();
5041 }
5042
5043 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
5044 self.center.reset_pane_sizes(cx);
5045 cx.notify();
5046 }
5047
5048 fn handle_pane_focused(
5049 &mut self,
5050 pane: Entity<Pane>,
5051 window: &mut Window,
5052 cx: &mut Context<Self>,
5053 ) {
5054 // This is explicitly hoisted out of the following check for pane identity as
5055 // terminal panel panes are not registered as a center panes.
5056 self.status_bar.update(cx, |status_bar, cx| {
5057 status_bar.set_active_pane(&pane, window, cx);
5058 });
5059 if self.active_pane != pane {
5060 self.set_active_pane(&pane, window, cx);
5061 }
5062
5063 if self.last_active_center_pane.is_none() {
5064 self.last_active_center_pane = Some(pane.downgrade());
5065 }
5066
5067 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
5068 // This prevents the dock from closing when focus events fire during window activation.
5069 // We also preserve any dock whose active panel itself has focus — this covers
5070 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
5071 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
5072 let dock_read = dock.read(cx);
5073 if let Some(panel) = dock_read.active_panel() {
5074 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
5075 || panel.panel_focus_handle(cx).contains_focused(window, cx)
5076 {
5077 return Some(dock_read.position());
5078 }
5079 }
5080 None
5081 });
5082
5083 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
5084 if pane.read(cx).is_zoomed() {
5085 self.zoomed = Some(pane.downgrade().into());
5086 } else {
5087 self.zoomed = None;
5088 }
5089 self.zoomed_position = None;
5090 cx.emit(Event::ZoomChanged);
5091 self.update_active_view_for_followers(window, cx);
5092 pane.update(cx, |pane, _| {
5093 pane.track_alternate_file_items();
5094 });
5095
5096 cx.notify();
5097 }
5098
5099 fn set_active_pane(
5100 &mut self,
5101 pane: &Entity<Pane>,
5102 window: &mut Window,
5103 cx: &mut Context<Self>,
5104 ) {
5105 self.active_pane = pane.clone();
5106 self.active_item_path_changed(true, window, cx);
5107 self.last_active_center_pane = Some(pane.downgrade());
5108 }
5109
5110 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5111 self.update_active_view_for_followers(window, cx);
5112 }
5113
5114 fn handle_pane_event(
5115 &mut self,
5116 pane: &Entity<Pane>,
5117 event: &pane::Event,
5118 window: &mut Window,
5119 cx: &mut Context<Self>,
5120 ) {
5121 let mut serialize_workspace = true;
5122 match event {
5123 pane::Event::AddItem { item } => {
5124 item.added_to_pane(self, pane.clone(), window, cx);
5125 cx.emit(Event::ItemAdded {
5126 item: item.boxed_clone(),
5127 });
5128 }
5129 pane::Event::Split { direction, mode } => {
5130 match mode {
5131 SplitMode::ClonePane => {
5132 self.split_and_clone(pane.clone(), *direction, window, cx)
5133 .detach();
5134 }
5135 SplitMode::EmptyPane => {
5136 self.split_pane(pane.clone(), *direction, window, cx);
5137 }
5138 SplitMode::MovePane => {
5139 self.split_and_move(pane.clone(), *direction, window, cx);
5140 }
5141 };
5142 }
5143 pane::Event::JoinIntoNext => {
5144 self.join_pane_into_next(pane.clone(), window, cx);
5145 }
5146 pane::Event::JoinAll => {
5147 self.join_all_panes(window, cx);
5148 }
5149 pane::Event::Remove { focus_on_pane } => {
5150 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
5151 }
5152 pane::Event::ActivateItem {
5153 local,
5154 focus_changed,
5155 } => {
5156 window.invalidate_character_coordinates();
5157
5158 pane.update(cx, |pane, _| {
5159 pane.track_alternate_file_items();
5160 });
5161 if *local {
5162 self.unfollow_in_pane(pane, window, cx);
5163 }
5164 serialize_workspace = *focus_changed || pane != self.active_pane();
5165 if pane == self.active_pane() {
5166 self.active_item_path_changed(*focus_changed, window, cx);
5167 self.update_active_view_for_followers(window, cx);
5168 } else if *local {
5169 self.set_active_pane(pane, window, cx);
5170 }
5171 }
5172 pane::Event::UserSavedItem { item, save_intent } => {
5173 cx.emit(Event::UserSavedItem {
5174 pane: pane.downgrade(),
5175 item: item.boxed_clone(),
5176 save_intent: *save_intent,
5177 });
5178 serialize_workspace = false;
5179 }
5180 pane::Event::ChangeItemTitle => {
5181 if *pane == self.active_pane {
5182 self.active_item_path_changed(false, window, cx);
5183 }
5184 serialize_workspace = false;
5185 }
5186 pane::Event::RemovedItem { item } => {
5187 cx.emit(Event::ActiveItemChanged);
5188 self.update_window_edited(window, cx);
5189 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
5190 && entry.get().entity_id() == pane.entity_id()
5191 {
5192 entry.remove();
5193 }
5194 cx.emit(Event::ItemRemoved {
5195 item_id: item.item_id(),
5196 });
5197 }
5198 pane::Event::Focus => {
5199 window.invalidate_character_coordinates();
5200 self.handle_pane_focused(pane.clone(), window, cx);
5201 }
5202 pane::Event::ZoomIn => {
5203 if *pane == self.active_pane {
5204 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
5205 if pane.read(cx).has_focus(window, cx) {
5206 self.zoomed = Some(pane.downgrade().into());
5207 self.zoomed_position = None;
5208 cx.emit(Event::ZoomChanged);
5209 }
5210 cx.notify();
5211 }
5212 }
5213 pane::Event::ZoomOut => {
5214 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
5215 if self.zoomed_position.is_none() {
5216 self.zoomed = None;
5217 cx.emit(Event::ZoomChanged);
5218 }
5219 cx.notify();
5220 }
5221 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
5222 }
5223
5224 if serialize_workspace {
5225 self.serialize_workspace(window, cx);
5226 }
5227 }
5228
5229 pub fn unfollow_in_pane(
5230 &mut self,
5231 pane: &Entity<Pane>,
5232 window: &mut Window,
5233 cx: &mut Context<Workspace>,
5234 ) -> Option<CollaboratorId> {
5235 let leader_id = self.leader_for_pane(pane)?;
5236 self.unfollow(leader_id, window, cx);
5237 Some(leader_id)
5238 }
5239
5240 pub fn split_pane(
5241 &mut self,
5242 pane_to_split: Entity<Pane>,
5243 split_direction: SplitDirection,
5244 window: &mut Window,
5245 cx: &mut Context<Self>,
5246 ) -> Entity<Pane> {
5247 let new_pane = self.add_pane(window, cx);
5248 self.center
5249 .split(&pane_to_split, &new_pane, split_direction, cx);
5250 cx.notify();
5251 new_pane
5252 }
5253
5254 pub fn split_and_move(
5255 &mut self,
5256 pane: Entity<Pane>,
5257 direction: SplitDirection,
5258 window: &mut Window,
5259 cx: &mut Context<Self>,
5260 ) {
5261 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
5262 return;
5263 };
5264 let new_pane = self.add_pane(window, cx);
5265 new_pane.update(cx, |pane, cx| {
5266 pane.add_item(item, true, true, None, window, cx)
5267 });
5268 self.center.split(&pane, &new_pane, direction, cx);
5269 cx.notify();
5270 }
5271
5272 pub fn split_and_clone(
5273 &mut self,
5274 pane: Entity<Pane>,
5275 direction: SplitDirection,
5276 window: &mut Window,
5277 cx: &mut Context<Self>,
5278 ) -> Task<Option<Entity<Pane>>> {
5279 let Some(item) = pane.read(cx).active_item() else {
5280 return Task::ready(None);
5281 };
5282 if !item.can_split(cx) {
5283 return Task::ready(None);
5284 }
5285 let task = item.clone_on_split(self.database_id(), window, cx);
5286 cx.spawn_in(window, async move |this, cx| {
5287 if let Some(clone) = task.await {
5288 this.update_in(cx, |this, window, cx| {
5289 let new_pane = this.add_pane(window, cx);
5290 let nav_history = pane.read(cx).fork_nav_history();
5291 new_pane.update(cx, |pane, cx| {
5292 pane.set_nav_history(nav_history, cx);
5293 pane.add_item(clone, true, true, None, window, cx)
5294 });
5295 this.center.split(&pane, &new_pane, direction, cx);
5296 cx.notify();
5297 new_pane
5298 })
5299 .ok()
5300 } else {
5301 None
5302 }
5303 })
5304 }
5305
5306 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5307 let active_item = self.active_pane.read(cx).active_item();
5308 for pane in &self.panes {
5309 join_pane_into_active(&self.active_pane, pane, window, cx);
5310 }
5311 if let Some(active_item) = active_item {
5312 self.activate_item(active_item.as_ref(), true, true, window, cx);
5313 }
5314 cx.notify();
5315 }
5316
5317 pub fn join_pane_into_next(
5318 &mut self,
5319 pane: Entity<Pane>,
5320 window: &mut Window,
5321 cx: &mut Context<Self>,
5322 ) {
5323 let next_pane = self
5324 .find_pane_in_direction(SplitDirection::Right, cx)
5325 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5326 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5327 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5328 let Some(next_pane) = next_pane else {
5329 return;
5330 };
5331 move_all_items(&pane, &next_pane, window, cx);
5332 cx.notify();
5333 }
5334
5335 fn remove_pane(
5336 &mut self,
5337 pane: Entity<Pane>,
5338 focus_on: Option<Entity<Pane>>,
5339 window: &mut Window,
5340 cx: &mut Context<Self>,
5341 ) {
5342 if self.center.remove(&pane, cx).unwrap() {
5343 self.force_remove_pane(&pane, &focus_on, window, cx);
5344 self.unfollow_in_pane(&pane, window, cx);
5345 self.last_leaders_by_pane.remove(&pane.downgrade());
5346 for removed_item in pane.read(cx).items() {
5347 self.panes_by_item.remove(&removed_item.item_id());
5348 }
5349
5350 cx.notify();
5351 } else {
5352 self.active_item_path_changed(true, window, cx);
5353 }
5354 cx.emit(Event::PaneRemoved);
5355 }
5356
5357 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5358 &mut self.panes
5359 }
5360
5361 pub fn panes(&self) -> &[Entity<Pane>] {
5362 &self.panes
5363 }
5364
5365 pub fn active_pane(&self) -> &Entity<Pane> {
5366 &self.active_pane
5367 }
5368
5369 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5370 for dock in self.all_docks() {
5371 if dock.focus_handle(cx).contains_focused(window, cx)
5372 && let Some(pane) = dock
5373 .read(cx)
5374 .active_panel()
5375 .and_then(|panel| panel.pane(cx))
5376 {
5377 return pane;
5378 }
5379 }
5380 self.active_pane().clone()
5381 }
5382
5383 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5384 self.find_pane_in_direction(SplitDirection::Right, cx)
5385 .unwrap_or_else(|| {
5386 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5387 })
5388 }
5389
5390 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5391 self.pane_for_item_id(handle.item_id())
5392 }
5393
5394 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5395 let weak_pane = self.panes_by_item.get(&item_id)?;
5396 weak_pane.upgrade()
5397 }
5398
5399 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5400 self.panes
5401 .iter()
5402 .find(|pane| pane.entity_id() == entity_id)
5403 .cloned()
5404 }
5405
5406 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5407 self.follower_states.retain(|leader_id, state| {
5408 if *leader_id == CollaboratorId::PeerId(peer_id) {
5409 for item in state.items_by_leader_view_id.values() {
5410 item.view.set_leader_id(None, window, cx);
5411 }
5412 false
5413 } else {
5414 true
5415 }
5416 });
5417 cx.notify();
5418 }
5419
5420 pub fn start_following(
5421 &mut self,
5422 leader_id: impl Into<CollaboratorId>,
5423 window: &mut Window,
5424 cx: &mut Context<Self>,
5425 ) -> Option<Task<Result<()>>> {
5426 let leader_id = leader_id.into();
5427 let pane = self.active_pane().clone();
5428
5429 self.last_leaders_by_pane
5430 .insert(pane.downgrade(), leader_id);
5431 self.unfollow(leader_id, window, cx);
5432 self.unfollow_in_pane(&pane, window, cx);
5433 self.follower_states.insert(
5434 leader_id,
5435 FollowerState {
5436 center_pane: pane.clone(),
5437 dock_pane: None,
5438 active_view_id: None,
5439 items_by_leader_view_id: Default::default(),
5440 },
5441 );
5442 cx.notify();
5443
5444 match leader_id {
5445 CollaboratorId::PeerId(leader_peer_id) => {
5446 let room_id = self.active_call()?.room_id(cx)?;
5447 let project_id = self.project.read(cx).remote_id();
5448 let request = self.app_state.client.request(proto::Follow {
5449 room_id,
5450 project_id,
5451 leader_id: Some(leader_peer_id),
5452 });
5453
5454 Some(cx.spawn_in(window, async move |this, cx| {
5455 let response = request.await?;
5456 this.update(cx, |this, _| {
5457 let state = this
5458 .follower_states
5459 .get_mut(&leader_id)
5460 .context("following interrupted")?;
5461 state.active_view_id = response
5462 .active_view
5463 .as_ref()
5464 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5465 anyhow::Ok(())
5466 })??;
5467 if let Some(view) = response.active_view {
5468 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5469 }
5470 this.update_in(cx, |this, window, cx| {
5471 this.leader_updated(leader_id, window, cx)
5472 })?;
5473 Ok(())
5474 }))
5475 }
5476 CollaboratorId::Agent => {
5477 self.leader_updated(leader_id, window, cx)?;
5478 Some(Task::ready(Ok(())))
5479 }
5480 }
5481 }
5482
5483 pub fn follow_next_collaborator(
5484 &mut self,
5485 _: &FollowNextCollaborator,
5486 window: &mut Window,
5487 cx: &mut Context<Self>,
5488 ) {
5489 let collaborators = self.project.read(cx).collaborators();
5490 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5491 let mut collaborators = collaborators.keys().copied();
5492 for peer_id in collaborators.by_ref() {
5493 if CollaboratorId::PeerId(peer_id) == leader_id {
5494 break;
5495 }
5496 }
5497 collaborators.next().map(CollaboratorId::PeerId)
5498 } else if let Some(last_leader_id) =
5499 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5500 {
5501 match last_leader_id {
5502 CollaboratorId::PeerId(peer_id) => {
5503 if collaborators.contains_key(peer_id) {
5504 Some(*last_leader_id)
5505 } else {
5506 None
5507 }
5508 }
5509 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5510 }
5511 } else {
5512 None
5513 };
5514
5515 let pane = self.active_pane.clone();
5516 let Some(leader_id) = next_leader_id.or_else(|| {
5517 Some(CollaboratorId::PeerId(
5518 collaborators.keys().copied().next()?,
5519 ))
5520 }) else {
5521 return;
5522 };
5523 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5524 return;
5525 }
5526 if let Some(task) = self.start_following(leader_id, window, cx) {
5527 task.detach_and_log_err(cx)
5528 }
5529 }
5530
5531 pub fn follow(
5532 &mut self,
5533 leader_id: impl Into<CollaboratorId>,
5534 window: &mut Window,
5535 cx: &mut Context<Self>,
5536 ) {
5537 let leader_id = leader_id.into();
5538
5539 if let CollaboratorId::PeerId(peer_id) = leader_id {
5540 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5541 return;
5542 };
5543 let Some(remote_participant) =
5544 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5545 else {
5546 return;
5547 };
5548
5549 let project = self.project.read(cx);
5550
5551 let other_project_id = match remote_participant.location {
5552 ParticipantLocation::External => None,
5553 ParticipantLocation::UnsharedProject => None,
5554 ParticipantLocation::SharedProject { project_id } => {
5555 if Some(project_id) == project.remote_id() {
5556 None
5557 } else {
5558 Some(project_id)
5559 }
5560 }
5561 };
5562
5563 // if they are active in another project, follow there.
5564 if let Some(project_id) = other_project_id {
5565 let app_state = self.app_state.clone();
5566 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5567 .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
5568 Some(format!("{error:#}"))
5569 });
5570 }
5571 }
5572
5573 // if you're already following, find the right pane and focus it.
5574 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5575 window.focus(&follower_state.pane().focus_handle(cx), cx);
5576
5577 return;
5578 }
5579
5580 // Otherwise, follow.
5581 if let Some(task) = self.start_following(leader_id, window, cx) {
5582 task.detach_and_log_err(cx)
5583 }
5584 }
5585
5586 pub fn unfollow(
5587 &mut self,
5588 leader_id: impl Into<CollaboratorId>,
5589 window: &mut Window,
5590 cx: &mut Context<Self>,
5591 ) -> Option<()> {
5592 cx.notify();
5593
5594 let leader_id = leader_id.into();
5595 let state = self.follower_states.remove(&leader_id)?;
5596 for (_, item) in state.items_by_leader_view_id {
5597 item.view.set_leader_id(None, window, cx);
5598 }
5599
5600 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5601 let project_id = self.project.read(cx).remote_id();
5602 let room_id = self.active_call()?.room_id(cx)?;
5603 self.app_state
5604 .client
5605 .send(proto::Unfollow {
5606 room_id,
5607 project_id,
5608 leader_id: Some(leader_peer_id),
5609 })
5610 .log_err();
5611 }
5612
5613 Some(())
5614 }
5615
5616 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5617 self.follower_states.contains_key(&id.into())
5618 }
5619
5620 fn active_item_path_changed(
5621 &mut self,
5622 focus_changed: bool,
5623 window: &mut Window,
5624 cx: &mut Context<Self>,
5625 ) {
5626 cx.emit(Event::ActiveItemChanged);
5627 let active_entry = self.active_project_path(cx);
5628 self.project.update(cx, |project, cx| {
5629 project.set_active_path(active_entry.clone(), cx)
5630 });
5631
5632 if focus_changed && let Some(project_path) = &active_entry {
5633 let git_store_entity = self.project.read(cx).git_store().clone();
5634 git_store_entity.update(cx, |git_store, cx| {
5635 git_store.set_active_repo_for_path(project_path, cx);
5636 });
5637 }
5638
5639 self.update_window_title(window, cx);
5640 }
5641
5642 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5643 let project = self.project().read(cx);
5644 let mut title = String::new();
5645
5646 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5647 let name = {
5648 let settings_location = SettingsLocation {
5649 worktree_id: worktree.read(cx).id(),
5650 path: RelPath::empty(),
5651 };
5652
5653 let settings = WorktreeSettings::get(Some(settings_location), cx);
5654 match &settings.project_name {
5655 Some(name) => name.as_str(),
5656 None => worktree.read(cx).root_name_str(),
5657 }
5658 };
5659 if i > 0 {
5660 title.push_str(", ");
5661 }
5662 title.push_str(name);
5663 }
5664
5665 if title.is_empty() {
5666 title = "empty project".to_string();
5667 }
5668
5669 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5670 let filename = path.path.file_name().or_else(|| {
5671 Some(
5672 project
5673 .worktree_for_id(path.worktree_id, cx)?
5674 .read(cx)
5675 .root_name_str(),
5676 )
5677 });
5678
5679 if let Some(filename) = filename {
5680 title.push_str(" — ");
5681 title.push_str(filename.as_ref());
5682 }
5683 }
5684
5685 if project.is_via_collab() {
5686 title.push_str(" ↙");
5687 } else if project.is_shared() {
5688 title.push_str(" ↗");
5689 }
5690
5691 if let Some(last_title) = self.last_window_title.as_ref()
5692 && &title == last_title
5693 {
5694 return;
5695 }
5696 window.set_window_title(&title);
5697 SystemWindowTabController::update_tab_title(
5698 cx,
5699 window.window_handle().window_id(),
5700 SharedString::from(&title),
5701 );
5702 self.last_window_title = Some(title);
5703 }
5704
5705 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5706 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5707 if is_edited != self.window_edited {
5708 self.window_edited = is_edited;
5709 window.set_window_edited(self.window_edited)
5710 }
5711 }
5712
5713 fn update_item_dirty_state(
5714 &mut self,
5715 item: &dyn ItemHandle,
5716 window: &mut Window,
5717 cx: &mut App,
5718 ) {
5719 let is_dirty = item.is_dirty(cx);
5720 let item_id = item.item_id();
5721 let was_dirty = self.dirty_items.contains_key(&item_id);
5722 if is_dirty == was_dirty {
5723 return;
5724 }
5725 if was_dirty {
5726 self.dirty_items.remove(&item_id);
5727 self.update_window_edited(window, cx);
5728 return;
5729 }
5730
5731 let workspace = self.weak_handle();
5732 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5733 return;
5734 };
5735 let on_release_callback = Box::new(move |cx: &mut App| {
5736 window_handle
5737 .update(cx, |_, window, cx| {
5738 workspace
5739 .update(cx, |workspace, cx| {
5740 workspace.dirty_items.remove(&item_id);
5741 workspace.update_window_edited(window, cx)
5742 })
5743 .ok();
5744 })
5745 .ok();
5746 });
5747
5748 let s = item.on_release(cx, on_release_callback);
5749 self.dirty_items.insert(item_id, s);
5750 self.update_window_edited(window, cx);
5751 }
5752
5753 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5754 if self.notifications.is_empty() {
5755 None
5756 } else {
5757 Some(
5758 div()
5759 .absolute()
5760 .right_3()
5761 .bottom_3()
5762 .w_112()
5763 .h_full()
5764 .flex()
5765 .flex_col()
5766 .justify_end()
5767 .gap_2()
5768 .children(
5769 self.notifications
5770 .iter()
5771 .map(|(_, notification)| notification.clone().into_any()),
5772 ),
5773 )
5774 }
5775 }
5776
5777 // RPC handlers
5778
5779 fn active_view_for_follower(
5780 &self,
5781 follower_project_id: Option<u64>,
5782 window: &mut Window,
5783 cx: &mut Context<Self>,
5784 ) -> Option<proto::View> {
5785 let (item, panel_id) = self.active_item_for_followers(window, cx);
5786 let item = item?;
5787 let leader_id = self
5788 .pane_for(&*item)
5789 .and_then(|pane| self.leader_for_pane(&pane));
5790 let leader_peer_id = match leader_id {
5791 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5792 Some(CollaboratorId::Agent) | None => None,
5793 };
5794
5795 let item_handle = item.to_followable_item_handle(cx)?;
5796 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5797 let variant = item_handle.to_state_proto(window, cx)?;
5798
5799 if item_handle.is_project_item(window, cx)
5800 && (follower_project_id.is_none()
5801 || follower_project_id != self.project.read(cx).remote_id())
5802 {
5803 return None;
5804 }
5805
5806 Some(proto::View {
5807 id: id.to_proto(),
5808 leader_id: leader_peer_id,
5809 variant: Some(variant),
5810 panel_id: panel_id.map(|id| id as i32),
5811 })
5812 }
5813
5814 fn handle_follow(
5815 &mut self,
5816 follower_project_id: Option<u64>,
5817 window: &mut Window,
5818 cx: &mut Context<Self>,
5819 ) -> proto::FollowResponse {
5820 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5821
5822 cx.notify();
5823 proto::FollowResponse {
5824 views: active_view.iter().cloned().collect(),
5825 active_view,
5826 }
5827 }
5828
5829 fn handle_update_followers(
5830 &mut self,
5831 leader_id: PeerId,
5832 message: proto::UpdateFollowers,
5833 _window: &mut Window,
5834 _cx: &mut Context<Self>,
5835 ) {
5836 self.leader_updates_tx
5837 .unbounded_send((leader_id, message))
5838 .ok();
5839 }
5840
5841 async fn process_leader_update(
5842 this: &WeakEntity<Self>,
5843 leader_id: PeerId,
5844 update: proto::UpdateFollowers,
5845 cx: &mut AsyncWindowContext,
5846 ) -> Result<()> {
5847 match update.variant.context("invalid update")? {
5848 proto::update_followers::Variant::CreateView(view) => {
5849 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5850 let should_add_view = this.update(cx, |this, _| {
5851 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5852 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5853 } else {
5854 anyhow::Ok(false)
5855 }
5856 })??;
5857
5858 if should_add_view {
5859 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5860 }
5861 }
5862 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5863 let should_add_view = this.update(cx, |this, _| {
5864 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5865 state.active_view_id = update_active_view
5866 .view
5867 .as_ref()
5868 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5869
5870 if state.active_view_id.is_some_and(|view_id| {
5871 !state.items_by_leader_view_id.contains_key(&view_id)
5872 }) {
5873 anyhow::Ok(true)
5874 } else {
5875 anyhow::Ok(false)
5876 }
5877 } else {
5878 anyhow::Ok(false)
5879 }
5880 })??;
5881
5882 if should_add_view && let Some(view) = update_active_view.view {
5883 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5884 }
5885 }
5886 proto::update_followers::Variant::UpdateView(update_view) => {
5887 let variant = update_view.variant.context("missing update view variant")?;
5888 let id = update_view.id.context("missing update view id")?;
5889 let mut tasks = Vec::new();
5890 this.update_in(cx, |this, window, cx| {
5891 let project = this.project.clone();
5892 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5893 let view_id = ViewId::from_proto(id.clone())?;
5894 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5895 tasks.push(item.view.apply_update_proto(
5896 &project,
5897 variant.clone(),
5898 window,
5899 cx,
5900 ));
5901 }
5902 }
5903 anyhow::Ok(())
5904 })??;
5905 try_join_all(tasks).await.log_err();
5906 }
5907 }
5908 this.update_in(cx, |this, window, cx| {
5909 this.leader_updated(leader_id, window, cx)
5910 })?;
5911 Ok(())
5912 }
5913
5914 async fn add_view_from_leader(
5915 this: WeakEntity<Self>,
5916 leader_id: PeerId,
5917 view: &proto::View,
5918 cx: &mut AsyncWindowContext,
5919 ) -> Result<()> {
5920 let this = this.upgrade().context("workspace dropped")?;
5921
5922 let Some(id) = view.id.clone() else {
5923 anyhow::bail!("no id for view");
5924 };
5925 let id = ViewId::from_proto(id)?;
5926 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5927
5928 let pane = this.update(cx, |this, _cx| {
5929 let state = this
5930 .follower_states
5931 .get(&leader_id.into())
5932 .context("stopped following")?;
5933 anyhow::Ok(state.pane().clone())
5934 })?;
5935 let existing_item = pane.update_in(cx, |pane, window, cx| {
5936 let client = this.read(cx).client().clone();
5937 pane.items().find_map(|item| {
5938 let item = item.to_followable_item_handle(cx)?;
5939 if item.remote_id(&client, window, cx) == Some(id) {
5940 Some(item)
5941 } else {
5942 None
5943 }
5944 })
5945 })?;
5946 let item = if let Some(existing_item) = existing_item {
5947 existing_item
5948 } else {
5949 let variant = view.variant.clone();
5950 anyhow::ensure!(variant.is_some(), "missing view variant");
5951
5952 let task = cx.update(|window, cx| {
5953 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5954 })?;
5955
5956 let Some(task) = task else {
5957 anyhow::bail!(
5958 "failed to construct view from leader (maybe from a different version of zed?)"
5959 );
5960 };
5961
5962 let mut new_item = task.await?;
5963 pane.update_in(cx, |pane, window, cx| {
5964 let mut item_to_remove = None;
5965 for (ix, item) in pane.items().enumerate() {
5966 if let Some(item) = item.to_followable_item_handle(cx) {
5967 match new_item.dedup(item.as_ref(), window, cx) {
5968 Some(item::Dedup::KeepExisting) => {
5969 new_item =
5970 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5971 break;
5972 }
5973 Some(item::Dedup::ReplaceExisting) => {
5974 item_to_remove = Some((ix, item.item_id()));
5975 break;
5976 }
5977 None => {}
5978 }
5979 }
5980 }
5981
5982 if let Some((ix, id)) = item_to_remove {
5983 pane.remove_item(id, false, false, window, cx);
5984 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5985 }
5986 })?;
5987
5988 new_item
5989 };
5990
5991 this.update_in(cx, |this, window, cx| {
5992 let state = this.follower_states.get_mut(&leader_id.into())?;
5993 item.set_leader_id(Some(leader_id.into()), window, cx);
5994 state.items_by_leader_view_id.insert(
5995 id,
5996 FollowerView {
5997 view: item,
5998 location: panel_id,
5999 },
6000 );
6001
6002 Some(())
6003 })
6004 .context("no follower state")?;
6005
6006 Ok(())
6007 }
6008
6009 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6010 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
6011 return;
6012 };
6013
6014 if let Some(agent_location) = self.project.read(cx).agent_location() {
6015 let buffer_entity_id = agent_location.buffer.entity_id();
6016 let view_id = ViewId {
6017 creator: CollaboratorId::Agent,
6018 id: buffer_entity_id.as_u64(),
6019 };
6020 follower_state.active_view_id = Some(view_id);
6021
6022 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
6023 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
6024 hash_map::Entry::Vacant(entry) => {
6025 let existing_view =
6026 follower_state
6027 .center_pane
6028 .read(cx)
6029 .items()
6030 .find_map(|item| {
6031 let item = item.to_followable_item_handle(cx)?;
6032 if item.buffer_kind(cx) == ItemBufferKind::Singleton
6033 && item.project_item_model_ids(cx).as_slice()
6034 == [buffer_entity_id]
6035 {
6036 Some(item)
6037 } else {
6038 None
6039 }
6040 });
6041 let view = existing_view.or_else(|| {
6042 agent_location.buffer.upgrade().and_then(|buffer| {
6043 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
6044 registry.build_item(buffer, self.project.clone(), None, window, cx)
6045 })?
6046 .to_followable_item_handle(cx)
6047 })
6048 });
6049
6050 view.map(|view| {
6051 entry.insert(FollowerView {
6052 view,
6053 location: None,
6054 })
6055 })
6056 }
6057 };
6058
6059 if let Some(item) = item {
6060 item.view
6061 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
6062 item.view
6063 .update_agent_location(agent_location.position, window, cx);
6064 }
6065 } else {
6066 follower_state.active_view_id = None;
6067 }
6068
6069 self.leader_updated(CollaboratorId::Agent, window, cx);
6070 }
6071
6072 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
6073 let mut is_project_item = true;
6074 let mut update = proto::UpdateActiveView::default();
6075 if window.is_window_active() {
6076 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
6077
6078 if let Some(item) = active_item
6079 && item.item_focus_handle(cx).contains_focused(window, cx)
6080 {
6081 let leader_id = self
6082 .pane_for(&*item)
6083 .and_then(|pane| self.leader_for_pane(&pane));
6084 let leader_peer_id = match leader_id {
6085 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
6086 Some(CollaboratorId::Agent) | None => None,
6087 };
6088
6089 if let Some(item) = item.to_followable_item_handle(cx) {
6090 let id = item
6091 .remote_id(&self.app_state.client, window, cx)
6092 .map(|id| id.to_proto());
6093
6094 if let Some(id) = id
6095 && let Some(variant) = item.to_state_proto(window, cx)
6096 {
6097 let view = Some(proto::View {
6098 id,
6099 leader_id: leader_peer_id,
6100 variant: Some(variant),
6101 panel_id: panel_id.map(|id| id as i32),
6102 });
6103
6104 is_project_item = item.is_project_item(window, cx);
6105 update = proto::UpdateActiveView { view };
6106 };
6107 }
6108 }
6109 }
6110
6111 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
6112 if active_view_id != self.last_active_view_id.as_ref() {
6113 self.last_active_view_id = active_view_id.cloned();
6114 self.update_followers(
6115 is_project_item,
6116 proto::update_followers::Variant::UpdateActiveView(update),
6117 window,
6118 cx,
6119 );
6120 }
6121 }
6122
6123 fn active_item_for_followers(
6124 &self,
6125 window: &mut Window,
6126 cx: &mut App,
6127 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
6128 let mut active_item = None;
6129 let mut panel_id = None;
6130 for dock in self.all_docks() {
6131 if dock.focus_handle(cx).contains_focused(window, cx)
6132 && let Some(panel) = dock.read(cx).active_panel()
6133 && let Some(pane) = panel.pane(cx)
6134 && let Some(item) = pane.read(cx).active_item()
6135 {
6136 active_item = Some(item);
6137 panel_id = panel.remote_id();
6138 break;
6139 }
6140 }
6141
6142 if active_item.is_none() {
6143 active_item = self.active_pane().read(cx).active_item();
6144 }
6145 (active_item, panel_id)
6146 }
6147
6148 fn update_followers(
6149 &self,
6150 project_only: bool,
6151 update: proto::update_followers::Variant,
6152 _: &mut Window,
6153 cx: &mut App,
6154 ) -> Option<()> {
6155 // If this update only applies to for followers in the current project,
6156 // then skip it unless this project is shared. If it applies to all
6157 // followers, regardless of project, then set `project_id` to none,
6158 // indicating that it goes to all followers.
6159 let project_id = if project_only {
6160 Some(self.project.read(cx).remote_id()?)
6161 } else {
6162 None
6163 };
6164 self.app_state().workspace_store.update(cx, |store, cx| {
6165 store.update_followers(project_id, update, cx)
6166 })
6167 }
6168
6169 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
6170 self.follower_states.iter().find_map(|(leader_id, state)| {
6171 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
6172 Some(*leader_id)
6173 } else {
6174 None
6175 }
6176 })
6177 }
6178
6179 fn leader_updated(
6180 &mut self,
6181 leader_id: impl Into<CollaboratorId>,
6182 window: &mut Window,
6183 cx: &mut Context<Self>,
6184 ) -> Option<Box<dyn ItemHandle>> {
6185 cx.notify();
6186
6187 let leader_id = leader_id.into();
6188 let (panel_id, item) = match leader_id {
6189 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
6190 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
6191 };
6192
6193 let state = self.follower_states.get(&leader_id)?;
6194 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
6195 let pane;
6196 if let Some(panel_id) = panel_id {
6197 pane = self
6198 .activate_panel_for_proto_id(panel_id, window, cx)?
6199 .pane(cx)?;
6200 let state = self.follower_states.get_mut(&leader_id)?;
6201 state.dock_pane = Some(pane.clone());
6202 } else {
6203 pane = state.center_pane.clone();
6204 let state = self.follower_states.get_mut(&leader_id)?;
6205 if let Some(dock_pane) = state.dock_pane.take() {
6206 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
6207 }
6208 }
6209
6210 pane.update(cx, |pane, cx| {
6211 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
6212 if let Some(index) = pane.index_for_item(item.as_ref()) {
6213 pane.activate_item(index, false, false, window, cx);
6214 } else {
6215 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
6216 }
6217
6218 if focus_active_item {
6219 pane.focus_active_item(window, cx)
6220 }
6221 });
6222
6223 Some(item)
6224 }
6225
6226 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
6227 let state = self.follower_states.get(&CollaboratorId::Agent)?;
6228 let active_view_id = state.active_view_id?;
6229 Some(
6230 state
6231 .items_by_leader_view_id
6232 .get(&active_view_id)?
6233 .view
6234 .boxed_clone(),
6235 )
6236 }
6237
6238 fn active_item_for_peer(
6239 &self,
6240 peer_id: PeerId,
6241 window: &mut Window,
6242 cx: &mut Context<Self>,
6243 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
6244 let call = self.active_call()?;
6245 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
6246 let leader_in_this_app;
6247 let leader_in_this_project;
6248 match participant.location {
6249 ParticipantLocation::SharedProject { project_id } => {
6250 leader_in_this_app = true;
6251 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
6252 }
6253 ParticipantLocation::UnsharedProject => {
6254 leader_in_this_app = true;
6255 leader_in_this_project = false;
6256 }
6257 ParticipantLocation::External => {
6258 leader_in_this_app = false;
6259 leader_in_this_project = false;
6260 }
6261 };
6262 let state = self.follower_states.get(&peer_id.into())?;
6263 let mut item_to_activate = None;
6264 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
6265 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
6266 && (leader_in_this_project || !item.view.is_project_item(window, cx))
6267 {
6268 item_to_activate = Some((item.location, item.view.boxed_clone()));
6269 }
6270 } else if let Some(shared_screen) =
6271 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
6272 {
6273 item_to_activate = Some((None, Box::new(shared_screen)));
6274 }
6275 item_to_activate
6276 }
6277
6278 fn shared_screen_for_peer(
6279 &self,
6280 peer_id: PeerId,
6281 pane: &Entity<Pane>,
6282 window: &mut Window,
6283 cx: &mut App,
6284 ) -> Option<Entity<SharedScreen>> {
6285 self.active_call()?
6286 .create_shared_screen(peer_id, pane, window, cx)
6287 }
6288
6289 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6290 if window.is_window_active() {
6291 self.update_active_view_for_followers(window, cx);
6292
6293 if let Some(database_id) = self.database_id {
6294 let db = WorkspaceDb::global(cx);
6295 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6296 .detach();
6297 }
6298 } else {
6299 for pane in &self.panes {
6300 pane.update(cx, |pane, cx| {
6301 if let Some(item) = pane.active_item() {
6302 item.workspace_deactivated(window, cx);
6303 }
6304 for item in pane.items() {
6305 if matches!(
6306 item.workspace_settings(cx).autosave,
6307 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6308 ) {
6309 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6310 .detach_and_log_err(cx);
6311 }
6312 }
6313 });
6314 }
6315 }
6316 }
6317
6318 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6319 self.active_call.as_ref().map(|(call, _)| &*call.0)
6320 }
6321
6322 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6323 self.active_call.as_ref().map(|(call, _)| call.clone())
6324 }
6325
6326 fn on_active_call_event(
6327 &mut self,
6328 event: &ActiveCallEvent,
6329 window: &mut Window,
6330 cx: &mut Context<Self>,
6331 ) {
6332 match event {
6333 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6334 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6335 self.leader_updated(participant_id, window, cx);
6336 }
6337 }
6338 }
6339
6340 pub fn database_id(&self) -> Option<WorkspaceId> {
6341 self.database_id
6342 }
6343
6344 #[cfg(any(test, feature = "test-support"))]
6345 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6346 self.database_id = Some(id);
6347 }
6348
6349 pub fn session_id(&self) -> Option<String> {
6350 self.session_id.clone()
6351 }
6352
6353 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6354 let Some(display) = window.display(cx) else {
6355 return Task::ready(());
6356 };
6357 let Ok(display_uuid) = display.uuid() else {
6358 return Task::ready(());
6359 };
6360
6361 let window_bounds = window.inner_window_bounds();
6362 let database_id = self.database_id;
6363 let has_paths = !self.root_paths(cx).is_empty();
6364 let db = WorkspaceDb::global(cx);
6365 let kvp = db::kvp::KeyValueStore::global(cx);
6366
6367 cx.background_executor().spawn(async move {
6368 if !has_paths {
6369 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6370 .await
6371 .log_err();
6372 }
6373 if let Some(database_id) = database_id {
6374 db.set_window_open_status(
6375 database_id,
6376 SerializedWindowBounds(window_bounds),
6377 display_uuid,
6378 )
6379 .await
6380 .log_err();
6381 } else {
6382 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6383 .await
6384 .log_err();
6385 }
6386 })
6387 }
6388
6389 /// Bypass the 200ms serialization throttle and write workspace state to
6390 /// the DB immediately. Returns a task the caller can await to ensure the
6391 /// write completes. Used by the quit handler so the most recent state
6392 /// isn't lost to a pending throttle timer when the process exits.
6393 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6394 self._schedule_serialize_workspace.take();
6395 self._serialize_workspace_task.take();
6396 self.bounds_save_task_queued.take();
6397
6398 let bounds_task = self.save_window_bounds(window, cx);
6399 let serialize_task = self.serialize_workspace_internal(window, cx);
6400 cx.spawn(async move |_| {
6401 bounds_task.await;
6402 serialize_task.await;
6403 })
6404 }
6405
6406 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6407 let project = self.project().read(cx);
6408 project
6409 .visible_worktrees(cx)
6410 .map(|worktree| worktree.read(cx).abs_path())
6411 .collect::<Vec<_>>()
6412 }
6413
6414 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6415 match member {
6416 Member::Axis(PaneAxis { members, .. }) => {
6417 for child in members.iter() {
6418 self.remove_panes(child.clone(), window, cx)
6419 }
6420 }
6421 Member::Pane(pane) => {
6422 self.force_remove_pane(&pane, &None, window, cx);
6423 }
6424 }
6425 }
6426
6427 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6428 self.session_id.take();
6429 self.serialize_workspace_internal(window, cx)
6430 }
6431
6432 fn force_remove_pane(
6433 &mut self,
6434 pane: &Entity<Pane>,
6435 focus_on: &Option<Entity<Pane>>,
6436 window: &mut Window,
6437 cx: &mut Context<Workspace>,
6438 ) {
6439 self.panes.retain(|p| p != pane);
6440 if let Some(focus_on) = focus_on {
6441 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6442 } else if self.active_pane() == pane {
6443 self.panes
6444 .last()
6445 .unwrap()
6446 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6447 }
6448 if self.last_active_center_pane == Some(pane.downgrade()) {
6449 self.last_active_center_pane = None;
6450 }
6451 cx.notify();
6452 }
6453
6454 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6455 if self._schedule_serialize_workspace.is_none() {
6456 self._schedule_serialize_workspace =
6457 Some(cx.spawn_in(window, async move |this, cx| {
6458 cx.background_executor()
6459 .timer(SERIALIZATION_THROTTLE_TIME)
6460 .await;
6461 this.update_in(cx, |this, window, cx| {
6462 this._serialize_workspace_task =
6463 Some(this.serialize_workspace_internal(window, cx));
6464 this._schedule_serialize_workspace.take();
6465 })
6466 .log_err();
6467 }));
6468 }
6469 }
6470
6471 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6472 let Some(database_id) = self.database_id() else {
6473 return Task::ready(());
6474 };
6475
6476 fn serialize_pane_handle(
6477 pane_handle: &Entity<Pane>,
6478 window: &mut Window,
6479 cx: &mut App,
6480 ) -> SerializedPane {
6481 let (items, active, pinned_count) = {
6482 let pane = pane_handle.read(cx);
6483 let active_item_id = pane.active_item().map(|item| item.item_id());
6484 (
6485 pane.items()
6486 .filter_map(|handle| {
6487 let handle = handle.to_serializable_item_handle(cx)?;
6488
6489 Some(SerializedItem {
6490 kind: Arc::from(handle.serialized_item_kind()),
6491 item_id: handle.item_id().as_u64(),
6492 active: Some(handle.item_id()) == active_item_id,
6493 preview: pane.is_active_preview_item(handle.item_id()),
6494 })
6495 })
6496 .collect::<Vec<_>>(),
6497 pane.has_focus(window, cx),
6498 pane.pinned_count(),
6499 )
6500 };
6501
6502 SerializedPane::new(items, active, pinned_count)
6503 }
6504
6505 fn build_serialized_pane_group(
6506 pane_group: &Member,
6507 window: &mut Window,
6508 cx: &mut App,
6509 ) -> SerializedPaneGroup {
6510 match pane_group {
6511 Member::Axis(PaneAxis {
6512 axis,
6513 members,
6514 flexes,
6515 bounding_boxes: _,
6516 }) => SerializedPaneGroup::Group {
6517 axis: SerializedAxis(*axis),
6518 children: members
6519 .iter()
6520 .map(|member| build_serialized_pane_group(member, window, cx))
6521 .collect::<Vec<_>>(),
6522 flexes: Some(flexes.lock().clone()),
6523 },
6524 Member::Pane(pane_handle) => {
6525 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6526 }
6527 }
6528 }
6529
6530 fn build_serialized_docks(
6531 this: &Workspace,
6532 window: &mut Window,
6533 cx: &mut App,
6534 ) -> DockStructure {
6535 this.capture_dock_state(window, cx)
6536 }
6537
6538 match self.workspace_location(cx) {
6539 WorkspaceLocation::Location(location, paths) => {
6540 let breakpoints = self.project.update(cx, |project, cx| {
6541 project
6542 .breakpoint_store()
6543 .read(cx)
6544 .all_source_breakpoints(cx)
6545 });
6546 let user_toolchains = self
6547 .project
6548 .read(cx)
6549 .user_toolchains(cx)
6550 .unwrap_or_default();
6551
6552 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6553 let docks = build_serialized_docks(self, window, cx);
6554 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6555
6556 let serialized_workspace = SerializedWorkspace {
6557 id: database_id,
6558 location,
6559 paths,
6560 center_group,
6561 window_bounds,
6562 display: Default::default(),
6563 docks,
6564 centered_layout: self.centered_layout,
6565 session_id: self.session_id.clone(),
6566 breakpoints,
6567 window_id: Some(window.window_handle().window_id().as_u64()),
6568 user_toolchains,
6569 };
6570
6571 let db = WorkspaceDb::global(cx);
6572 window.spawn(cx, async move |_| {
6573 db.save_workspace(serialized_workspace).await;
6574 })
6575 }
6576 WorkspaceLocation::DetachFromSession => {
6577 let window_bounds = SerializedWindowBounds(window.window_bounds());
6578 let display = window.display(cx).and_then(|d| d.uuid().ok());
6579 // Save dock state for empty local workspaces
6580 let docks = build_serialized_docks(self, window, cx);
6581 let db = WorkspaceDb::global(cx);
6582 let kvp = db::kvp::KeyValueStore::global(cx);
6583 window.spawn(cx, async move |_| {
6584 db.set_window_open_status(
6585 database_id,
6586 window_bounds,
6587 display.unwrap_or_default(),
6588 )
6589 .await
6590 .log_err();
6591 db.set_session_id(database_id, None).await.log_err();
6592 persistence::write_default_dock_state(&kvp, docks)
6593 .await
6594 .log_err();
6595 })
6596 }
6597 WorkspaceLocation::None => {
6598 // Save dock state for empty non-local workspaces
6599 let docks = build_serialized_docks(self, window, cx);
6600 let kvp = db::kvp::KeyValueStore::global(cx);
6601 window.spawn(cx, async move |_| {
6602 persistence::write_default_dock_state(&kvp, docks)
6603 .await
6604 .log_err();
6605 })
6606 }
6607 }
6608 }
6609
6610 fn has_any_items_open(&self, cx: &App) -> bool {
6611 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6612 }
6613
6614 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6615 let paths = PathList::new(&self.root_paths(cx));
6616 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6617 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6618 } else if self.project.read(cx).is_local() {
6619 if !paths.is_empty() || self.has_any_items_open(cx) {
6620 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6621 } else {
6622 WorkspaceLocation::DetachFromSession
6623 }
6624 } else {
6625 WorkspaceLocation::None
6626 }
6627 }
6628
6629 fn update_history(&self, cx: &mut App) {
6630 let Some(id) = self.database_id() else {
6631 return;
6632 };
6633 if !self.project.read(cx).is_local() {
6634 return;
6635 }
6636 if let Some(manager) = HistoryManager::global(cx) {
6637 let paths = PathList::new(&self.root_paths(cx));
6638 manager.update(cx, |this, cx| {
6639 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6640 });
6641 }
6642 }
6643
6644 async fn serialize_items(
6645 this: &WeakEntity<Self>,
6646 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6647 cx: &mut AsyncWindowContext,
6648 ) -> Result<()> {
6649 const CHUNK_SIZE: usize = 200;
6650
6651 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6652
6653 while let Some(items_received) = serializable_items.next().await {
6654 let unique_items =
6655 items_received
6656 .into_iter()
6657 .fold(HashMap::default(), |mut acc, item| {
6658 acc.entry(item.item_id()).or_insert(item);
6659 acc
6660 });
6661
6662 // We use into_iter() here so that the references to the items are moved into
6663 // the tasks and not kept alive while we're sleeping.
6664 for (_, item) in unique_items.into_iter() {
6665 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6666 item.serialize(workspace, false, window, cx)
6667 }) {
6668 cx.background_spawn(async move { task.await.log_err() })
6669 .detach();
6670 }
6671 }
6672
6673 cx.background_executor()
6674 .timer(SERIALIZATION_THROTTLE_TIME)
6675 .await;
6676 }
6677
6678 Ok(())
6679 }
6680
6681 pub(crate) fn enqueue_item_serialization(
6682 &mut self,
6683 item: Box<dyn SerializableItemHandle>,
6684 ) -> Result<()> {
6685 self.serializable_items_tx
6686 .unbounded_send(item)
6687 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6688 }
6689
6690 pub(crate) fn load_workspace(
6691 serialized_workspace: SerializedWorkspace,
6692 paths_to_open: Vec<Option<ProjectPath>>,
6693 window: &mut Window,
6694 cx: &mut Context<Workspace>,
6695 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6696 cx.spawn_in(window, async move |workspace, cx| {
6697 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6698
6699 let mut center_group = None;
6700 let mut center_items = None;
6701
6702 // Traverse the splits tree and add to things
6703 if let Some((group, active_pane, items)) = serialized_workspace
6704 .center_group
6705 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6706 .await
6707 {
6708 center_items = Some(items);
6709 center_group = Some((group, active_pane))
6710 }
6711
6712 let mut items_by_project_path = HashMap::default();
6713 let mut item_ids_by_kind = HashMap::default();
6714 let mut all_deserialized_items = Vec::default();
6715 cx.update(|_, cx| {
6716 for item in center_items.unwrap_or_default().into_iter().flatten() {
6717 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6718 item_ids_by_kind
6719 .entry(serializable_item_handle.serialized_item_kind())
6720 .or_insert(Vec::new())
6721 .push(item.item_id().as_u64() as ItemId);
6722 }
6723
6724 if let Some(project_path) = item.project_path(cx) {
6725 items_by_project_path.insert(project_path, item.clone());
6726 }
6727 all_deserialized_items.push(item);
6728 }
6729 })?;
6730
6731 let opened_items = paths_to_open
6732 .into_iter()
6733 .map(|path_to_open| {
6734 path_to_open
6735 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6736 })
6737 .collect::<Vec<_>>();
6738
6739 // Remove old panes from workspace panes list
6740 workspace.update_in(cx, |workspace, window, cx| {
6741 if let Some((center_group, active_pane)) = center_group {
6742 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6743
6744 // Swap workspace center group
6745 workspace.center = PaneGroup::with_root(center_group);
6746 workspace.center.set_is_center(true);
6747 workspace.center.mark_positions(cx);
6748
6749 if let Some(active_pane) = active_pane {
6750 workspace.set_active_pane(&active_pane, window, cx);
6751 cx.focus_self(window);
6752 } else {
6753 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6754 }
6755 }
6756
6757 let docks = serialized_workspace.docks;
6758
6759 for (dock, serialized_dock) in [
6760 (&mut workspace.right_dock, docks.right),
6761 (&mut workspace.left_dock, docks.left),
6762 (&mut workspace.bottom_dock, docks.bottom),
6763 ]
6764 .iter_mut()
6765 {
6766 dock.update(cx, |dock, cx| {
6767 dock.serialized_dock = Some(serialized_dock.clone());
6768 dock.restore_state(window, cx);
6769 });
6770 }
6771
6772 cx.notify();
6773 })?;
6774
6775 let _ = project
6776 .update(cx, |project, cx| {
6777 project
6778 .breakpoint_store()
6779 .update(cx, |breakpoint_store, cx| {
6780 breakpoint_store
6781 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6782 })
6783 })
6784 .await;
6785
6786 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6787 // after loading the items, we might have different items and in order to avoid
6788 // the database filling up, we delete items that haven't been loaded now.
6789 //
6790 // The items that have been loaded, have been saved after they've been added to the workspace.
6791 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6792 item_ids_by_kind
6793 .into_iter()
6794 .map(|(item_kind, loaded_items)| {
6795 SerializableItemRegistry::cleanup(
6796 item_kind,
6797 serialized_workspace.id,
6798 loaded_items,
6799 window,
6800 cx,
6801 )
6802 .log_err()
6803 })
6804 .collect::<Vec<_>>()
6805 })?;
6806
6807 futures::future::join_all(clean_up_tasks).await;
6808
6809 workspace
6810 .update_in(cx, |workspace, window, cx| {
6811 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6812 workspace.serialize_workspace_internal(window, cx).detach();
6813
6814 // Ensure that we mark the window as edited if we did load dirty items
6815 workspace.update_window_edited(window, cx);
6816 })
6817 .ok();
6818
6819 Ok(opened_items)
6820 })
6821 }
6822
6823 pub fn key_context(&self, cx: &App) -> KeyContext {
6824 let mut context = KeyContext::new_with_defaults();
6825 context.add("Workspace");
6826 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6827 if let Some(status) = self
6828 .debugger_provider
6829 .as_ref()
6830 .and_then(|provider| provider.active_thread_state(cx))
6831 {
6832 match status {
6833 ThreadStatus::Running | ThreadStatus::Stepping => {
6834 context.add("debugger_running");
6835 }
6836 ThreadStatus::Stopped => context.add("debugger_stopped"),
6837 ThreadStatus::Exited | ThreadStatus::Ended => {}
6838 }
6839 }
6840
6841 if self.left_dock.read(cx).is_open() {
6842 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6843 context.set("left_dock", active_panel.panel_key());
6844 }
6845 }
6846
6847 if self.right_dock.read(cx).is_open() {
6848 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6849 context.set("right_dock", active_panel.panel_key());
6850 }
6851 }
6852
6853 if self.bottom_dock.read(cx).is_open() {
6854 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6855 context.set("bottom_dock", active_panel.panel_key());
6856 }
6857 }
6858
6859 context
6860 }
6861
6862 /// Multiworkspace uses this to add workspace action handling to itself
6863 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6864 self.add_workspace_actions_listeners(div, window, cx)
6865 .on_action(cx.listener(
6866 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6867 for action in &action_sequence.0 {
6868 window.dispatch_action(action.boxed_clone(), cx);
6869 }
6870 },
6871 ))
6872 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6873 .on_action(cx.listener(Self::close_all_items_and_panes))
6874 .on_action(cx.listener(Self::close_item_in_all_panes))
6875 .on_action(cx.listener(Self::save_all))
6876 .on_action(cx.listener(Self::send_keystrokes))
6877 .on_action(cx.listener(Self::add_folder_to_project))
6878 .on_action(cx.listener(Self::follow_next_collaborator))
6879 .on_action(cx.listener(Self::activate_pane_at_index))
6880 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6881 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6882 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6883 .on_action(cx.listener(Self::toggle_theme_mode))
6884 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6885 let pane = workspace.active_pane().clone();
6886 workspace.unfollow_in_pane(&pane, window, cx);
6887 }))
6888 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6889 workspace
6890 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6891 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6892 }))
6893 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6894 workspace
6895 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6896 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6897 }))
6898 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6899 workspace
6900 .save_active_item(SaveIntent::SaveAs, window, cx)
6901 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6902 }))
6903 .on_action(
6904 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6905 workspace.activate_previous_pane(window, cx)
6906 }),
6907 )
6908 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6909 workspace.activate_next_pane(window, cx)
6910 }))
6911 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6912 workspace.activate_last_pane(window, cx)
6913 }))
6914 .on_action(
6915 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6916 workspace.activate_next_window(cx)
6917 }),
6918 )
6919 .on_action(
6920 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6921 workspace.activate_previous_window(cx)
6922 }),
6923 )
6924 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6925 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6926 }))
6927 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6928 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6929 }))
6930 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6931 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6932 }))
6933 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6934 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6935 }))
6936 .on_action(cx.listener(
6937 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6938 workspace.move_item_to_pane_in_direction(action, window, cx)
6939 },
6940 ))
6941 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6942 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6943 }))
6944 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6945 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6946 }))
6947 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6948 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6949 }))
6950 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6951 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6952 }))
6953 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6954 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6955 SplitDirection::Down,
6956 SplitDirection::Up,
6957 SplitDirection::Right,
6958 SplitDirection::Left,
6959 ];
6960 for dir in DIRECTION_PRIORITY {
6961 if workspace.find_pane_in_direction(dir, cx).is_some() {
6962 workspace.swap_pane_in_direction(dir, cx);
6963 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6964 break;
6965 }
6966 }
6967 }))
6968 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6969 workspace.move_pane_to_border(SplitDirection::Left, cx)
6970 }))
6971 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6972 workspace.move_pane_to_border(SplitDirection::Right, cx)
6973 }))
6974 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6975 workspace.move_pane_to_border(SplitDirection::Up, cx)
6976 }))
6977 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6978 workspace.move_pane_to_border(SplitDirection::Down, cx)
6979 }))
6980 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6981 this.toggle_dock(DockPosition::Left, window, cx);
6982 }))
6983 .on_action(cx.listener(
6984 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6985 workspace.toggle_dock(DockPosition::Right, window, cx);
6986 },
6987 ))
6988 .on_action(cx.listener(
6989 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6990 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6991 },
6992 ))
6993 .on_action(cx.listener(
6994 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6995 if !workspace.close_active_dock(window, cx) {
6996 cx.propagate();
6997 }
6998 },
6999 ))
7000 .on_action(
7001 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
7002 workspace.close_all_docks(window, cx);
7003 }),
7004 )
7005 .on_action(cx.listener(Self::toggle_all_docks))
7006 .on_action(cx.listener(
7007 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
7008 workspace.clear_all_notifications(cx);
7009 },
7010 ))
7011 .on_action(cx.listener(
7012 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
7013 workspace.clear_navigation_history(window, cx);
7014 },
7015 ))
7016 .on_action(cx.listener(
7017 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
7018 if let Some((notification_id, _)) = workspace.notifications.pop() {
7019 workspace.suppress_notification(¬ification_id, cx);
7020 }
7021 },
7022 ))
7023 .on_action(cx.listener(
7024 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
7025 workspace.show_worktree_trust_security_modal(true, window, cx);
7026 },
7027 ))
7028 .on_action(
7029 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
7030 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
7031 trusted_worktrees.update(cx, |trusted_worktrees, _| {
7032 trusted_worktrees.clear_trusted_paths()
7033 });
7034 let db = WorkspaceDb::global(cx);
7035 cx.spawn(async move |_, cx| {
7036 if db.clear_trusted_worktrees().await.log_err().is_some() {
7037 cx.update(|cx| reload(cx));
7038 }
7039 })
7040 .detach();
7041 }
7042 }),
7043 )
7044 .on_action(cx.listener(
7045 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
7046 workspace.reopen_closed_item(window, cx).detach();
7047 },
7048 ))
7049 .on_action(cx.listener(
7050 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
7051 for dock in workspace.all_docks() {
7052 if dock.focus_handle(cx).contains_focused(window, cx) {
7053 let panel = dock.read(cx).active_panel().cloned();
7054 if let Some(panel) = panel {
7055 dock.update(cx, |dock, cx| {
7056 dock.set_panel_size_state(
7057 panel.as_ref(),
7058 dock::PanelSizeState::default(),
7059 cx,
7060 );
7061 });
7062 }
7063 return;
7064 }
7065 }
7066 },
7067 ))
7068 .on_action(cx.listener(
7069 |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
7070 for dock in workspace.all_docks() {
7071 let panel = dock.read(cx).visible_panel().cloned();
7072 if let Some(panel) = panel {
7073 dock.update(cx, |dock, cx| {
7074 dock.set_panel_size_state(
7075 panel.as_ref(),
7076 dock::PanelSizeState::default(),
7077 cx,
7078 );
7079 });
7080 }
7081 }
7082 },
7083 ))
7084 .on_action(cx.listener(
7085 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
7086 adjust_active_dock_size_by_px(
7087 px_with_ui_font_fallback(act.px, cx),
7088 workspace,
7089 window,
7090 cx,
7091 );
7092 },
7093 ))
7094 .on_action(cx.listener(
7095 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
7096 adjust_active_dock_size_by_px(
7097 px_with_ui_font_fallback(act.px, cx) * -1.,
7098 workspace,
7099 window,
7100 cx,
7101 );
7102 },
7103 ))
7104 .on_action(cx.listener(
7105 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
7106 adjust_open_docks_size_by_px(
7107 px_with_ui_font_fallback(act.px, cx),
7108 workspace,
7109 window,
7110 cx,
7111 );
7112 },
7113 ))
7114 .on_action(cx.listener(
7115 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
7116 adjust_open_docks_size_by_px(
7117 px_with_ui_font_fallback(act.px, cx) * -1.,
7118 workspace,
7119 window,
7120 cx,
7121 );
7122 },
7123 ))
7124 .on_action(cx.listener(Workspace::toggle_centered_layout))
7125 .on_action(cx.listener(
7126 |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
7127 if let Some(active_dock) = workspace.active_dock(window, cx) {
7128 let dock = active_dock.read(cx);
7129 if let Some(active_panel) = dock.active_panel() {
7130 if active_panel.pane(cx).is_none() {
7131 let mut recent_pane: Option<Entity<Pane>> = None;
7132 let mut recent_timestamp = 0;
7133 for pane_handle in workspace.panes() {
7134 let pane = pane_handle.read(cx);
7135 for entry in pane.activation_history() {
7136 if entry.timestamp > recent_timestamp {
7137 recent_timestamp = entry.timestamp;
7138 recent_pane = Some(pane_handle.clone());
7139 }
7140 }
7141 }
7142
7143 if let Some(pane) = recent_pane {
7144 let wrap_around = action.wrap_around;
7145 pane.update(cx, |pane, cx| {
7146 let current_index = pane.active_item_index();
7147 let items_len = pane.items_len();
7148 if items_len > 0 {
7149 let next_index = if current_index + 1 < items_len {
7150 current_index + 1
7151 } else if wrap_around {
7152 0
7153 } else {
7154 return;
7155 };
7156 pane.activate_item(
7157 next_index, false, false, window, cx,
7158 );
7159 }
7160 });
7161 return;
7162 }
7163 }
7164 }
7165 }
7166 cx.propagate();
7167 },
7168 ))
7169 .on_action(cx.listener(
7170 |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
7171 if let Some(active_dock) = workspace.active_dock(window, cx) {
7172 let dock = active_dock.read(cx);
7173 if let Some(active_panel) = dock.active_panel() {
7174 if active_panel.pane(cx).is_none() {
7175 let mut recent_pane: Option<Entity<Pane>> = None;
7176 let mut recent_timestamp = 0;
7177 for pane_handle in workspace.panes() {
7178 let pane = pane_handle.read(cx);
7179 for entry in pane.activation_history() {
7180 if entry.timestamp > recent_timestamp {
7181 recent_timestamp = entry.timestamp;
7182 recent_pane = Some(pane_handle.clone());
7183 }
7184 }
7185 }
7186
7187 if let Some(pane) = recent_pane {
7188 let wrap_around = action.wrap_around;
7189 pane.update(cx, |pane, cx| {
7190 let current_index = pane.active_item_index();
7191 let items_len = pane.items_len();
7192 if items_len > 0 {
7193 let prev_index = if current_index > 0 {
7194 current_index - 1
7195 } else if wrap_around {
7196 items_len.saturating_sub(1)
7197 } else {
7198 return;
7199 };
7200 pane.activate_item(
7201 prev_index, false, false, window, cx,
7202 );
7203 }
7204 });
7205 return;
7206 }
7207 }
7208 }
7209 }
7210 cx.propagate();
7211 },
7212 ))
7213 .on_action(cx.listener(
7214 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
7215 if let Some(active_dock) = workspace.active_dock(window, cx) {
7216 let dock = active_dock.read(cx);
7217 if let Some(active_panel) = dock.active_panel() {
7218 if active_panel.pane(cx).is_none() {
7219 let active_pane = workspace.active_pane().clone();
7220 active_pane.update(cx, |pane, cx| {
7221 pane.close_active_item(action, window, cx)
7222 .detach_and_log_err(cx);
7223 });
7224 return;
7225 }
7226 }
7227 }
7228 cx.propagate();
7229 },
7230 ))
7231 .on_action(
7232 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
7233 let pane = workspace.active_pane().clone();
7234 if let Some(item) = pane.read(cx).active_item() {
7235 item.toggle_read_only(window, cx);
7236 }
7237 }),
7238 )
7239 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
7240 workspace.focus_center_pane(window, cx);
7241 }))
7242 .on_action(cx.listener(Workspace::cancel))
7243 }
7244
7245 #[cfg(any(test, feature = "test-support"))]
7246 pub fn set_random_database_id(&mut self) {
7247 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
7248 }
7249
7250 #[cfg(any(test, feature = "test-support"))]
7251 pub(crate) fn test_new(
7252 project: Entity<Project>,
7253 window: &mut Window,
7254 cx: &mut Context<Self>,
7255 ) -> Self {
7256 use node_runtime::NodeRuntime;
7257 use session::Session;
7258
7259 let client = project.read(cx).client();
7260 let user_store = project.read(cx).user_store();
7261 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
7262 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
7263 window.activate_window();
7264 let app_state = Arc::new(AppState {
7265 languages: project.read(cx).languages().clone(),
7266 workspace_store,
7267 client,
7268 user_store,
7269 fs: project.read(cx).fs().clone(),
7270 build_window_options: |_, _| Default::default(),
7271 node_runtime: NodeRuntime::unavailable(),
7272 session,
7273 });
7274 let workspace = Self::new(Default::default(), project, app_state, window, cx);
7275 workspace
7276 .active_pane
7277 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
7278 workspace
7279 }
7280
7281 pub fn register_action<A: Action>(
7282 &mut self,
7283 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
7284 ) -> &mut Self {
7285 let callback = Arc::new(callback);
7286
7287 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
7288 let callback = callback.clone();
7289 div.on_action(cx.listener(move |workspace, event, window, cx| {
7290 (callback)(workspace, event, window, cx)
7291 }))
7292 }));
7293 self
7294 }
7295 pub fn register_action_renderer(
7296 &mut self,
7297 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
7298 ) -> &mut Self {
7299 self.workspace_actions.push(Box::new(callback));
7300 self
7301 }
7302
7303 fn add_workspace_actions_listeners(
7304 &self,
7305 mut div: Div,
7306 window: &mut Window,
7307 cx: &mut Context<Self>,
7308 ) -> Div {
7309 for action in self.workspace_actions.iter() {
7310 div = (action)(div, self, window, cx)
7311 }
7312 div
7313 }
7314
7315 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7316 self.modal_layer.read(cx).has_active_modal()
7317 }
7318
7319 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7320 self.modal_layer
7321 .read(cx)
7322 .is_active_modal_command_palette(cx)
7323 }
7324
7325 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7326 self.modal_layer.read(cx).active_modal()
7327 }
7328
7329 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7330 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7331 /// If no modal is active, the new modal will be shown.
7332 ///
7333 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7334 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7335 /// will not be shown.
7336 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7337 where
7338 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7339 {
7340 self.modal_layer.update(cx, |modal_layer, cx| {
7341 modal_layer.toggle_modal(window, cx, build)
7342 })
7343 }
7344
7345 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7346 self.modal_layer
7347 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7348 }
7349
7350 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7351 self.toast_layer
7352 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7353 }
7354
7355 pub fn toggle_centered_layout(
7356 &mut self,
7357 _: &ToggleCenteredLayout,
7358 _: &mut Window,
7359 cx: &mut Context<Self>,
7360 ) {
7361 self.centered_layout = !self.centered_layout;
7362 if let Some(database_id) = self.database_id() {
7363 let db = WorkspaceDb::global(cx);
7364 let centered_layout = self.centered_layout;
7365 cx.background_spawn(async move {
7366 db.set_centered_layout(database_id, centered_layout).await
7367 })
7368 .detach_and_log_err(cx);
7369 }
7370 cx.notify();
7371 }
7372
7373 fn adjust_padding(padding: Option<f32>) -> f32 {
7374 padding
7375 .unwrap_or(CenteredPaddingSettings::default().0)
7376 .clamp(
7377 CenteredPaddingSettings::MIN_PADDING,
7378 CenteredPaddingSettings::MAX_PADDING,
7379 )
7380 }
7381
7382 fn render_dock(
7383 &self,
7384 position: DockPosition,
7385 dock: &Entity<Dock>,
7386 window: &mut Window,
7387 cx: &mut App,
7388 ) -> Option<Div> {
7389 if self.zoomed_position == Some(position) {
7390 return None;
7391 }
7392
7393 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7394 let pane = panel.pane(cx)?;
7395 let follower_states = &self.follower_states;
7396 leader_border_for_pane(follower_states, &pane, window, cx)
7397 });
7398
7399 let mut container = div()
7400 .flex()
7401 .overflow_hidden()
7402 .flex_none()
7403 .child(dock.clone())
7404 .children(leader_border);
7405
7406 // Apply sizing only when the dock is open. When closed the dock is still
7407 // included in the element tree so its focus handle remains mounted — without
7408 // this, toggle_panel_focus cannot focus the panel when the dock is closed.
7409 let dock = dock.read(cx);
7410 if let Some(panel) = dock.visible_panel() {
7411 let size_state = dock.stored_panel_size_state(panel.as_ref());
7412 if position.axis() == Axis::Horizontal {
7413 let use_flexible = panel.has_flexible_size(window, cx);
7414 let flex_grow = if use_flexible {
7415 size_state
7416 .and_then(|state| state.flex)
7417 .or_else(|| self.default_dock_flex(position))
7418 } else {
7419 None
7420 };
7421 if let Some(grow) = flex_grow {
7422 let grow = grow.max(0.001);
7423 let style = container.style();
7424 style.flex_grow = Some(grow);
7425 style.flex_shrink = Some(1.0);
7426 style.flex_basis = Some(relative(0.).into());
7427 } else {
7428 let size = size_state
7429 .and_then(|state| state.size)
7430 .unwrap_or_else(|| panel.default_size(window, cx));
7431 container = container.w(size);
7432 }
7433 } else {
7434 let size = size_state
7435 .and_then(|state| state.size)
7436 .unwrap_or_else(|| panel.default_size(window, cx));
7437 container = container.h(size);
7438 }
7439 }
7440
7441 Some(container)
7442 }
7443
7444 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7445 window
7446 .root::<MultiWorkspace>()
7447 .flatten()
7448 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7449 }
7450
7451 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7452 self.zoomed.as_ref()
7453 }
7454
7455 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7456 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7457 return;
7458 };
7459 let windows = cx.windows();
7460 let next_window =
7461 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7462 || {
7463 windows
7464 .iter()
7465 .cycle()
7466 .skip_while(|window| window.window_id() != current_window_id)
7467 .nth(1)
7468 },
7469 );
7470
7471 if let Some(window) = next_window {
7472 window
7473 .update(cx, |_, window, _| window.activate_window())
7474 .ok();
7475 }
7476 }
7477
7478 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7479 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7480 return;
7481 };
7482 let windows = cx.windows();
7483 let prev_window =
7484 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7485 || {
7486 windows
7487 .iter()
7488 .rev()
7489 .cycle()
7490 .skip_while(|window| window.window_id() != current_window_id)
7491 .nth(1)
7492 },
7493 );
7494
7495 if let Some(window) = prev_window {
7496 window
7497 .update(cx, |_, window, _| window.activate_window())
7498 .ok();
7499 }
7500 }
7501
7502 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7503 if cx.stop_active_drag(window) {
7504 } else if let Some((notification_id, _)) = self.notifications.pop() {
7505 dismiss_app_notification(¬ification_id, cx);
7506 } else {
7507 cx.propagate();
7508 }
7509 }
7510
7511 fn resize_dock(
7512 &mut self,
7513 dock_pos: DockPosition,
7514 new_size: Pixels,
7515 window: &mut Window,
7516 cx: &mut Context<Self>,
7517 ) {
7518 match dock_pos {
7519 DockPosition::Left => self.resize_left_dock(new_size, window, cx),
7520 DockPosition::Right => self.resize_right_dock(new_size, window, cx),
7521 DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
7522 }
7523 }
7524
7525 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7526 let workspace_width = self.bounds.size.width;
7527 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7528
7529 self.right_dock.read_with(cx, |right_dock, cx| {
7530 let right_dock_size = right_dock
7531 .stored_active_panel_size(window, cx)
7532 .unwrap_or(Pixels::ZERO);
7533 if right_dock_size + size > workspace_width {
7534 size = workspace_width - right_dock_size
7535 }
7536 });
7537
7538 let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
7539 self.left_dock.update(cx, |left_dock, cx| {
7540 if WorkspaceSettings::get_global(cx)
7541 .resize_all_panels_in_dock
7542 .contains(&DockPosition::Left)
7543 {
7544 left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7545 } else {
7546 left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7547 }
7548 });
7549 }
7550
7551 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7552 let workspace_width = self.bounds.size.width;
7553 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7554 self.left_dock.read_with(cx, |left_dock, cx| {
7555 let left_dock_size = left_dock
7556 .stored_active_panel_size(window, cx)
7557 .unwrap_or(Pixels::ZERO);
7558 if left_dock_size + size > workspace_width {
7559 size = workspace_width - left_dock_size
7560 }
7561 });
7562 let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
7563 self.right_dock.update(cx, |right_dock, cx| {
7564 if WorkspaceSettings::get_global(cx)
7565 .resize_all_panels_in_dock
7566 .contains(&DockPosition::Right)
7567 {
7568 right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7569 } else {
7570 right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7571 }
7572 });
7573 }
7574
7575 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7576 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7577 self.bottom_dock.update(cx, |bottom_dock, cx| {
7578 if WorkspaceSettings::get_global(cx)
7579 .resize_all_panels_in_dock
7580 .contains(&DockPosition::Bottom)
7581 {
7582 bottom_dock.resize_all_panels(Some(size), None, window, cx);
7583 } else {
7584 bottom_dock.resize_active_panel(Some(size), None, window, cx);
7585 }
7586 });
7587 }
7588
7589 fn toggle_edit_predictions_all_files(
7590 &mut self,
7591 _: &ToggleEditPrediction,
7592 _window: &mut Window,
7593 cx: &mut Context<Self>,
7594 ) {
7595 let fs = self.project().read(cx).fs().clone();
7596 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7597 update_settings_file(fs, cx, move |file, _| {
7598 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7599 });
7600 }
7601
7602 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7603 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7604 let next_mode = match current_mode {
7605 Some(theme_settings::ThemeAppearanceMode::Light) => {
7606 theme_settings::ThemeAppearanceMode::Dark
7607 }
7608 Some(theme_settings::ThemeAppearanceMode::Dark) => {
7609 theme_settings::ThemeAppearanceMode::Light
7610 }
7611 Some(theme_settings::ThemeAppearanceMode::System) | None => {
7612 match cx.theme().appearance() {
7613 theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
7614 theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
7615 }
7616 }
7617 };
7618
7619 let fs = self.project().read(cx).fs().clone();
7620 settings::update_settings_file(fs, cx, move |settings, _cx| {
7621 theme_settings::set_mode(settings, next_mode);
7622 });
7623 }
7624
7625 pub fn show_worktree_trust_security_modal(
7626 &mut self,
7627 toggle: bool,
7628 window: &mut Window,
7629 cx: &mut Context<Self>,
7630 ) {
7631 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7632 if toggle {
7633 security_modal.update(cx, |security_modal, cx| {
7634 security_modal.dismiss(cx);
7635 })
7636 } else {
7637 security_modal.update(cx, |security_modal, cx| {
7638 security_modal.refresh_restricted_paths(cx);
7639 });
7640 }
7641 } else {
7642 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7643 .map(|trusted_worktrees| {
7644 trusted_worktrees
7645 .read(cx)
7646 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7647 })
7648 .unwrap_or(false);
7649 if has_restricted_worktrees {
7650 let project = self.project().read(cx);
7651 let remote_host = project
7652 .remote_connection_options(cx)
7653 .map(RemoteHostLocation::from);
7654 let worktree_store = project.worktree_store().downgrade();
7655 self.toggle_modal(window, cx, |_, cx| {
7656 SecurityModal::new(worktree_store, remote_host, cx)
7657 });
7658 }
7659 }
7660 }
7661}
7662
7663pub trait AnyActiveCall {
7664 fn entity(&self) -> AnyEntity;
7665 fn is_in_room(&self, _: &App) -> bool;
7666 fn room_id(&self, _: &App) -> Option<u64>;
7667 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7668 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7669 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7670 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7671 fn is_sharing_project(&self, _: &App) -> bool;
7672 fn has_remote_participants(&self, _: &App) -> bool;
7673 fn local_participant_is_guest(&self, _: &App) -> bool;
7674 fn client(&self, _: &App) -> Arc<Client>;
7675 fn share_on_join(&self, _: &App) -> bool;
7676 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7677 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7678 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7679 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7680 fn join_project(
7681 &self,
7682 _: u64,
7683 _: Arc<LanguageRegistry>,
7684 _: Arc<dyn Fs>,
7685 _: &mut App,
7686 ) -> Task<Result<Entity<Project>>>;
7687 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7688 fn subscribe(
7689 &self,
7690 _: &mut Window,
7691 _: &mut Context<Workspace>,
7692 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7693 ) -> Subscription;
7694 fn create_shared_screen(
7695 &self,
7696 _: PeerId,
7697 _: &Entity<Pane>,
7698 _: &mut Window,
7699 _: &mut App,
7700 ) -> Option<Entity<SharedScreen>>;
7701}
7702
7703#[derive(Clone)]
7704pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7705impl Global for GlobalAnyActiveCall {}
7706
7707impl GlobalAnyActiveCall {
7708 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7709 cx.try_global()
7710 }
7711
7712 pub(crate) fn global(cx: &App) -> &Self {
7713 cx.global()
7714 }
7715}
7716
7717/// Workspace-local view of a remote participant's location.
7718#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7719pub enum ParticipantLocation {
7720 SharedProject { project_id: u64 },
7721 UnsharedProject,
7722 External,
7723}
7724
7725impl ParticipantLocation {
7726 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7727 match location
7728 .and_then(|l| l.variant)
7729 .context("participant location was not provided")?
7730 {
7731 proto::participant_location::Variant::SharedProject(project) => {
7732 Ok(Self::SharedProject {
7733 project_id: project.id,
7734 })
7735 }
7736 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7737 proto::participant_location::Variant::External(_) => Ok(Self::External),
7738 }
7739 }
7740}
7741/// Workspace-local view of a remote collaborator's state.
7742/// This is the subset of `call::RemoteParticipant` that workspace needs.
7743#[derive(Clone)]
7744pub struct RemoteCollaborator {
7745 pub user: Arc<User>,
7746 pub peer_id: PeerId,
7747 pub location: ParticipantLocation,
7748 pub participant_index: ParticipantIndex,
7749}
7750
7751pub enum ActiveCallEvent {
7752 ParticipantLocationChanged { participant_id: PeerId },
7753 RemoteVideoTracksChanged { participant_id: PeerId },
7754}
7755
7756fn leader_border_for_pane(
7757 follower_states: &HashMap<CollaboratorId, FollowerState>,
7758 pane: &Entity<Pane>,
7759 _: &Window,
7760 cx: &App,
7761) -> Option<Div> {
7762 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7763 if state.pane() == pane {
7764 Some((*leader_id, state))
7765 } else {
7766 None
7767 }
7768 })?;
7769
7770 let mut leader_color = match leader_id {
7771 CollaboratorId::PeerId(leader_peer_id) => {
7772 let leader = GlobalAnyActiveCall::try_global(cx)?
7773 .0
7774 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7775
7776 cx.theme()
7777 .players()
7778 .color_for_participant(leader.participant_index.0)
7779 .cursor
7780 }
7781 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7782 };
7783 leader_color.fade_out(0.3);
7784 Some(
7785 div()
7786 .absolute()
7787 .size_full()
7788 .left_0()
7789 .top_0()
7790 .border_2()
7791 .border_color(leader_color),
7792 )
7793}
7794
7795fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7796 ZED_WINDOW_POSITION
7797 .zip(*ZED_WINDOW_SIZE)
7798 .map(|(position, size)| Bounds {
7799 origin: position,
7800 size,
7801 })
7802}
7803
7804fn open_items(
7805 serialized_workspace: Option<SerializedWorkspace>,
7806 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7807 window: &mut Window,
7808 cx: &mut Context<Workspace>,
7809) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7810 let restored_items = serialized_workspace.map(|serialized_workspace| {
7811 Workspace::load_workspace(
7812 serialized_workspace,
7813 project_paths_to_open
7814 .iter()
7815 .map(|(_, project_path)| project_path)
7816 .cloned()
7817 .collect(),
7818 window,
7819 cx,
7820 )
7821 });
7822
7823 cx.spawn_in(window, async move |workspace, cx| {
7824 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7825
7826 if let Some(restored_items) = restored_items {
7827 let restored_items = restored_items.await?;
7828
7829 let restored_project_paths = restored_items
7830 .iter()
7831 .filter_map(|item| {
7832 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7833 .ok()
7834 .flatten()
7835 })
7836 .collect::<HashSet<_>>();
7837
7838 for restored_item in restored_items {
7839 opened_items.push(restored_item.map(Ok));
7840 }
7841
7842 project_paths_to_open
7843 .iter_mut()
7844 .for_each(|(_, project_path)| {
7845 if let Some(project_path_to_open) = project_path
7846 && restored_project_paths.contains(project_path_to_open)
7847 {
7848 *project_path = None;
7849 }
7850 });
7851 } else {
7852 for _ in 0..project_paths_to_open.len() {
7853 opened_items.push(None);
7854 }
7855 }
7856 assert!(opened_items.len() == project_paths_to_open.len());
7857
7858 let tasks =
7859 project_paths_to_open
7860 .into_iter()
7861 .enumerate()
7862 .map(|(ix, (abs_path, project_path))| {
7863 let workspace = workspace.clone();
7864 cx.spawn(async move |cx| {
7865 let file_project_path = project_path?;
7866 let abs_path_task = workspace.update(cx, |workspace, cx| {
7867 workspace.project().update(cx, |project, cx| {
7868 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7869 })
7870 });
7871
7872 // We only want to open file paths here. If one of the items
7873 // here is a directory, it was already opened further above
7874 // with a `find_or_create_worktree`.
7875 if let Ok(task) = abs_path_task
7876 && task.await.is_none_or(|p| p.is_file())
7877 {
7878 return Some((
7879 ix,
7880 workspace
7881 .update_in(cx, |workspace, window, cx| {
7882 workspace.open_path(
7883 file_project_path,
7884 None,
7885 true,
7886 window,
7887 cx,
7888 )
7889 })
7890 .log_err()?
7891 .await,
7892 ));
7893 }
7894 None
7895 })
7896 });
7897
7898 let tasks = tasks.collect::<Vec<_>>();
7899
7900 let tasks = futures::future::join_all(tasks);
7901 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7902 opened_items[ix] = Some(path_open_result);
7903 }
7904
7905 Ok(opened_items)
7906 })
7907}
7908
7909#[derive(Clone)]
7910enum ActivateInDirectionTarget {
7911 Pane(Entity<Pane>),
7912 Dock(Entity<Dock>),
7913 Sidebar(FocusHandle),
7914}
7915
7916fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7917 window
7918 .update(cx, |multi_workspace, _, cx| {
7919 let workspace = multi_workspace.workspace().clone();
7920 workspace.update(cx, |workspace, cx| {
7921 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7922 struct DatabaseFailedNotification;
7923
7924 workspace.show_notification(
7925 NotificationId::unique::<DatabaseFailedNotification>(),
7926 cx,
7927 |cx| {
7928 cx.new(|cx| {
7929 MessageNotification::new("Failed to load the database file.", cx)
7930 .primary_message("File an Issue")
7931 .primary_icon(IconName::Plus)
7932 .primary_on_click(|window, cx| {
7933 window.dispatch_action(Box::new(FileBugReport), cx)
7934 })
7935 })
7936 },
7937 );
7938 }
7939 });
7940 })
7941 .log_err();
7942}
7943
7944fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7945 if val == 0 {
7946 ThemeSettings::get_global(cx).ui_font_size(cx)
7947 } else {
7948 px(val as f32)
7949 }
7950}
7951
7952fn adjust_active_dock_size_by_px(
7953 px: Pixels,
7954 workspace: &mut Workspace,
7955 window: &mut Window,
7956 cx: &mut Context<Workspace>,
7957) {
7958 let Some(active_dock) = workspace
7959 .all_docks()
7960 .into_iter()
7961 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7962 else {
7963 return;
7964 };
7965 let dock = active_dock.read(cx);
7966 let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
7967 return;
7968 };
7969 workspace.resize_dock(dock.position(), panel_size + px, window, cx);
7970}
7971
7972fn adjust_open_docks_size_by_px(
7973 px: Pixels,
7974 workspace: &mut Workspace,
7975 window: &mut Window,
7976 cx: &mut Context<Workspace>,
7977) {
7978 let docks = workspace
7979 .all_docks()
7980 .into_iter()
7981 .filter_map(|dock_entity| {
7982 let dock = dock_entity.read(cx);
7983 if dock.is_open() {
7984 let dock_pos = dock.position();
7985 let panel_size = workspace.dock_size(&dock, window, cx)?;
7986 Some((dock_pos, panel_size + px))
7987 } else {
7988 None
7989 }
7990 })
7991 .collect::<Vec<_>>();
7992
7993 for (position, new_size) in docks {
7994 workspace.resize_dock(position, new_size, window, cx);
7995 }
7996}
7997
7998impl Focusable for Workspace {
7999 fn focus_handle(&self, cx: &App) -> FocusHandle {
8000 self.active_pane.focus_handle(cx)
8001 }
8002}
8003
8004#[derive(Clone)]
8005struct DraggedDock(DockPosition);
8006
8007impl Render for DraggedDock {
8008 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8009 gpui::Empty
8010 }
8011}
8012
8013impl Render for Workspace {
8014 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8015 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
8016 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
8017 log::info!("Rendered first frame");
8018 }
8019
8020 let centered_layout = self.centered_layout
8021 && self.center.panes().len() == 1
8022 && self.active_item(cx).is_some();
8023 let render_padding = |size| {
8024 (size > 0.0).then(|| {
8025 div()
8026 .h_full()
8027 .w(relative(size))
8028 .bg(cx.theme().colors().editor_background)
8029 .border_color(cx.theme().colors().pane_group_border)
8030 })
8031 };
8032 let paddings = if centered_layout {
8033 let settings = WorkspaceSettings::get_global(cx).centered_layout;
8034 (
8035 render_padding(Self::adjust_padding(
8036 settings.left_padding.map(|padding| padding.0),
8037 )),
8038 render_padding(Self::adjust_padding(
8039 settings.right_padding.map(|padding| padding.0),
8040 )),
8041 )
8042 } else {
8043 (None, None)
8044 };
8045 let ui_font = theme_settings::setup_ui_font(window, cx);
8046
8047 let theme = cx.theme().clone();
8048 let colors = theme.colors();
8049 let notification_entities = self
8050 .notifications
8051 .iter()
8052 .map(|(_, notification)| notification.entity_id())
8053 .collect::<Vec<_>>();
8054 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
8055
8056 div()
8057 .relative()
8058 .size_full()
8059 .flex()
8060 .flex_col()
8061 .font(ui_font)
8062 .gap_0()
8063 .justify_start()
8064 .items_start()
8065 .text_color(colors.text)
8066 .overflow_hidden()
8067 .children(self.titlebar_item.clone())
8068 .on_modifiers_changed(move |_, _, cx| {
8069 for &id in ¬ification_entities {
8070 cx.notify(id);
8071 }
8072 })
8073 .child(
8074 div()
8075 .size_full()
8076 .relative()
8077 .flex_1()
8078 .flex()
8079 .flex_col()
8080 .child(
8081 div()
8082 .id("workspace")
8083 .bg(colors.background)
8084 .relative()
8085 .flex_1()
8086 .w_full()
8087 .flex()
8088 .flex_col()
8089 .overflow_hidden()
8090 .border_t_1()
8091 .border_b_1()
8092 .border_color(colors.border)
8093 .child({
8094 let this = cx.entity();
8095 canvas(
8096 move |bounds, window, cx| {
8097 this.update(cx, |this, cx| {
8098 let bounds_changed = this.bounds != bounds;
8099 this.bounds = bounds;
8100
8101 if bounds_changed {
8102 this.left_dock.update(cx, |dock, cx| {
8103 dock.clamp_panel_size(
8104 bounds.size.width,
8105 window,
8106 cx,
8107 )
8108 });
8109
8110 this.right_dock.update(cx, |dock, cx| {
8111 dock.clamp_panel_size(
8112 bounds.size.width,
8113 window,
8114 cx,
8115 )
8116 });
8117
8118 this.bottom_dock.update(cx, |dock, cx| {
8119 dock.clamp_panel_size(
8120 bounds.size.height,
8121 window,
8122 cx,
8123 )
8124 });
8125 }
8126 })
8127 },
8128 |_, _, _, _| {},
8129 )
8130 .absolute()
8131 .size_full()
8132 })
8133 .when(self.zoomed.is_none(), |this| {
8134 this.on_drag_move(cx.listener(
8135 move |workspace,
8136 e: &DragMoveEvent<DraggedDock>,
8137 window,
8138 cx| {
8139 if workspace.previous_dock_drag_coordinates
8140 != Some(e.event.position)
8141 {
8142 workspace.previous_dock_drag_coordinates =
8143 Some(e.event.position);
8144
8145 match e.drag(cx).0 {
8146 DockPosition::Left => {
8147 workspace.resize_left_dock(
8148 e.event.position.x
8149 - workspace.bounds.left(),
8150 window,
8151 cx,
8152 );
8153 }
8154 DockPosition::Right => {
8155 workspace.resize_right_dock(
8156 workspace.bounds.right()
8157 - e.event.position.x,
8158 window,
8159 cx,
8160 );
8161 }
8162 DockPosition::Bottom => {
8163 workspace.resize_bottom_dock(
8164 workspace.bounds.bottom()
8165 - e.event.position.y,
8166 window,
8167 cx,
8168 );
8169 }
8170 };
8171 workspace.serialize_workspace(window, cx);
8172 }
8173 },
8174 ))
8175
8176 })
8177 .child({
8178 match bottom_dock_layout {
8179 BottomDockLayout::Full => div()
8180 .flex()
8181 .flex_col()
8182 .h_full()
8183 .child(
8184 div()
8185 .flex()
8186 .flex_row()
8187 .flex_1()
8188 .overflow_hidden()
8189 .children(self.render_dock(
8190 DockPosition::Left,
8191 &self.left_dock,
8192 window,
8193 cx,
8194 ))
8195
8196 .child(
8197 div()
8198 .flex()
8199 .flex_col()
8200 .flex_1()
8201 .overflow_hidden()
8202 .child(
8203 h_flex()
8204 .flex_1()
8205 .when_some(
8206 paddings.0,
8207 |this, p| {
8208 this.child(
8209 p.border_r_1(),
8210 )
8211 },
8212 )
8213 .child(self.center.render(
8214 self.zoomed.as_ref(),
8215 &PaneRenderContext {
8216 follower_states:
8217 &self.follower_states,
8218 active_call: self.active_call(),
8219 active_pane: &self.active_pane,
8220 app_state: &self.app_state,
8221 project: &self.project,
8222 workspace: &self.weak_self,
8223 },
8224 window,
8225 cx,
8226 ))
8227 .when_some(
8228 paddings.1,
8229 |this, p| {
8230 this.child(
8231 p.border_l_1(),
8232 )
8233 },
8234 ),
8235 ),
8236 )
8237
8238 .children(self.render_dock(
8239 DockPosition::Right,
8240 &self.right_dock,
8241 window,
8242 cx,
8243 )),
8244 )
8245 .child(div().w_full().children(self.render_dock(
8246 DockPosition::Bottom,
8247 &self.bottom_dock,
8248 window,
8249 cx
8250 ))),
8251
8252 BottomDockLayout::LeftAligned => div()
8253 .flex()
8254 .flex_row()
8255 .h_full()
8256 .child(
8257 div()
8258 .flex()
8259 .flex_col()
8260 .flex_1()
8261 .h_full()
8262 .child(
8263 div()
8264 .flex()
8265 .flex_row()
8266 .flex_1()
8267 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
8268
8269 .child(
8270 div()
8271 .flex()
8272 .flex_col()
8273 .flex_1()
8274 .overflow_hidden()
8275 .child(
8276 h_flex()
8277 .flex_1()
8278 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8279 .child(self.center.render(
8280 self.zoomed.as_ref(),
8281 &PaneRenderContext {
8282 follower_states:
8283 &self.follower_states,
8284 active_call: self.active_call(),
8285 active_pane: &self.active_pane,
8286 app_state: &self.app_state,
8287 project: &self.project,
8288 workspace: &self.weak_self,
8289 },
8290 window,
8291 cx,
8292 ))
8293 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8294 )
8295 )
8296
8297 )
8298 .child(
8299 div()
8300 .w_full()
8301 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8302 ),
8303 )
8304 .children(self.render_dock(
8305 DockPosition::Right,
8306 &self.right_dock,
8307 window,
8308 cx,
8309 )),
8310 BottomDockLayout::RightAligned => div()
8311 .flex()
8312 .flex_row()
8313 .h_full()
8314 .children(self.render_dock(
8315 DockPosition::Left,
8316 &self.left_dock,
8317 window,
8318 cx,
8319 ))
8320
8321 .child(
8322 div()
8323 .flex()
8324 .flex_col()
8325 .flex_1()
8326 .h_full()
8327 .child(
8328 div()
8329 .flex()
8330 .flex_row()
8331 .flex_1()
8332 .child(
8333 div()
8334 .flex()
8335 .flex_col()
8336 .flex_1()
8337 .overflow_hidden()
8338 .child(
8339 h_flex()
8340 .flex_1()
8341 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8342 .child(self.center.render(
8343 self.zoomed.as_ref(),
8344 &PaneRenderContext {
8345 follower_states:
8346 &self.follower_states,
8347 active_call: self.active_call(),
8348 active_pane: &self.active_pane,
8349 app_state: &self.app_state,
8350 project: &self.project,
8351 workspace: &self.weak_self,
8352 },
8353 window,
8354 cx,
8355 ))
8356 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8357 )
8358 )
8359
8360 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8361 )
8362 .child(
8363 div()
8364 .w_full()
8365 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8366 ),
8367 ),
8368 BottomDockLayout::Contained => div()
8369 .flex()
8370 .flex_row()
8371 .h_full()
8372 .children(self.render_dock(
8373 DockPosition::Left,
8374 &self.left_dock,
8375 window,
8376 cx,
8377 ))
8378
8379 .child(
8380 div()
8381 .flex()
8382 .flex_col()
8383 .flex_1()
8384 .overflow_hidden()
8385 .child(
8386 h_flex()
8387 .flex_1()
8388 .when_some(paddings.0, |this, p| {
8389 this.child(p.border_r_1())
8390 })
8391 .child(self.center.render(
8392 self.zoomed.as_ref(),
8393 &PaneRenderContext {
8394 follower_states:
8395 &self.follower_states,
8396 active_call: self.active_call(),
8397 active_pane: &self.active_pane,
8398 app_state: &self.app_state,
8399 project: &self.project,
8400 workspace: &self.weak_self,
8401 },
8402 window,
8403 cx,
8404 ))
8405 .when_some(paddings.1, |this, p| {
8406 this.child(p.border_l_1())
8407 }),
8408 )
8409 .children(self.render_dock(
8410 DockPosition::Bottom,
8411 &self.bottom_dock,
8412 window,
8413 cx,
8414 )),
8415 )
8416
8417 .children(self.render_dock(
8418 DockPosition::Right,
8419 &self.right_dock,
8420 window,
8421 cx,
8422 )),
8423 }
8424 })
8425 .children(self.zoomed.as_ref().and_then(|view| {
8426 let zoomed_view = view.upgrade()?;
8427 let div = div()
8428 .occlude()
8429 .absolute()
8430 .overflow_hidden()
8431 .border_color(colors.border)
8432 .bg(colors.background)
8433 .child(zoomed_view)
8434 .inset_0()
8435 .shadow_lg();
8436
8437 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8438 return Some(div);
8439 }
8440
8441 Some(match self.zoomed_position {
8442 Some(DockPosition::Left) => div.right_2().border_r_1(),
8443 Some(DockPosition::Right) => div.left_2().border_l_1(),
8444 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8445 None => {
8446 div.top_2().bottom_2().left_2().right_2().border_1()
8447 }
8448 })
8449 }))
8450 .children(self.render_notifications(window, cx)),
8451 )
8452 .when(self.status_bar_visible(cx), |parent| {
8453 parent.child(self.status_bar.clone())
8454 })
8455 .child(self.toast_layer.clone()),
8456 )
8457 }
8458}
8459
8460impl WorkspaceStore {
8461 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8462 Self {
8463 workspaces: Default::default(),
8464 _subscriptions: vec![
8465 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8466 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8467 ],
8468 client,
8469 }
8470 }
8471
8472 pub fn update_followers(
8473 &self,
8474 project_id: Option<u64>,
8475 update: proto::update_followers::Variant,
8476 cx: &App,
8477 ) -> Option<()> {
8478 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8479 let room_id = active_call.0.room_id(cx)?;
8480 self.client
8481 .send(proto::UpdateFollowers {
8482 room_id,
8483 project_id,
8484 variant: Some(update),
8485 })
8486 .log_err()
8487 }
8488
8489 pub async fn handle_follow(
8490 this: Entity<Self>,
8491 envelope: TypedEnvelope<proto::Follow>,
8492 mut cx: AsyncApp,
8493 ) -> Result<proto::FollowResponse> {
8494 this.update(&mut cx, |this, cx| {
8495 let follower = Follower {
8496 project_id: envelope.payload.project_id,
8497 peer_id: envelope.original_sender_id()?,
8498 };
8499
8500 let mut response = proto::FollowResponse::default();
8501
8502 this.workspaces.retain(|(window_handle, weak_workspace)| {
8503 let Some(workspace) = weak_workspace.upgrade() else {
8504 return false;
8505 };
8506 window_handle
8507 .update(cx, |_, window, cx| {
8508 workspace.update(cx, |workspace, cx| {
8509 let handler_response =
8510 workspace.handle_follow(follower.project_id, window, cx);
8511 if let Some(active_view) = handler_response.active_view
8512 && workspace.project.read(cx).remote_id() == follower.project_id
8513 {
8514 response.active_view = Some(active_view)
8515 }
8516 });
8517 })
8518 .is_ok()
8519 });
8520
8521 Ok(response)
8522 })
8523 }
8524
8525 async fn handle_update_followers(
8526 this: Entity<Self>,
8527 envelope: TypedEnvelope<proto::UpdateFollowers>,
8528 mut cx: AsyncApp,
8529 ) -> Result<()> {
8530 let leader_id = envelope.original_sender_id()?;
8531 let update = envelope.payload;
8532
8533 this.update(&mut cx, |this, cx| {
8534 this.workspaces.retain(|(window_handle, weak_workspace)| {
8535 let Some(workspace) = weak_workspace.upgrade() else {
8536 return false;
8537 };
8538 window_handle
8539 .update(cx, |_, window, cx| {
8540 workspace.update(cx, |workspace, cx| {
8541 let project_id = workspace.project.read(cx).remote_id();
8542 if update.project_id != project_id && update.project_id.is_some() {
8543 return;
8544 }
8545 workspace.handle_update_followers(
8546 leader_id,
8547 update.clone(),
8548 window,
8549 cx,
8550 );
8551 });
8552 })
8553 .is_ok()
8554 });
8555 Ok(())
8556 })
8557 }
8558
8559 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8560 self.workspaces.iter().map(|(_, weak)| weak)
8561 }
8562
8563 pub fn workspaces_with_windows(
8564 &self,
8565 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8566 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8567 }
8568}
8569
8570impl ViewId {
8571 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8572 Ok(Self {
8573 creator: message
8574 .creator
8575 .map(CollaboratorId::PeerId)
8576 .context("creator is missing")?,
8577 id: message.id,
8578 })
8579 }
8580
8581 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8582 if let CollaboratorId::PeerId(peer_id) = self.creator {
8583 Some(proto::ViewId {
8584 creator: Some(peer_id),
8585 id: self.id,
8586 })
8587 } else {
8588 None
8589 }
8590 }
8591}
8592
8593impl FollowerState {
8594 fn pane(&self) -> &Entity<Pane> {
8595 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8596 }
8597}
8598
8599pub trait WorkspaceHandle {
8600 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8601}
8602
8603impl WorkspaceHandle for Entity<Workspace> {
8604 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8605 self.read(cx)
8606 .worktrees(cx)
8607 .flat_map(|worktree| {
8608 let worktree_id = worktree.read(cx).id();
8609 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8610 worktree_id,
8611 path: f.path.clone(),
8612 })
8613 })
8614 .collect::<Vec<_>>()
8615 }
8616}
8617
8618pub async fn last_opened_workspace_location(
8619 db: &WorkspaceDb,
8620 fs: &dyn fs::Fs,
8621) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8622 db.last_workspace(fs)
8623 .await
8624 .log_err()
8625 .flatten()
8626 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8627}
8628
8629pub async fn last_session_workspace_locations(
8630 db: &WorkspaceDb,
8631 last_session_id: &str,
8632 last_session_window_stack: Option<Vec<WindowId>>,
8633 fs: &dyn fs::Fs,
8634) -> Option<Vec<SessionWorkspace>> {
8635 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8636 .await
8637 .log_err()
8638}
8639
8640pub async fn restore_multiworkspace(
8641 multi_workspace: SerializedMultiWorkspace,
8642 app_state: Arc<AppState>,
8643 cx: &mut AsyncApp,
8644) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8645 let SerializedMultiWorkspace {
8646 active_workspace,
8647 state,
8648 } = multi_workspace;
8649 let MultiWorkspaceState {
8650 sidebar_open,
8651 project_group_keys,
8652 sidebar_state,
8653 ..
8654 } = state;
8655
8656 let window_handle = if active_workspace.paths.is_empty() {
8657 cx.update(|cx| {
8658 open_workspace_by_id(active_workspace.workspace_id, app_state.clone(), None, cx)
8659 })
8660 .await?
8661 } else {
8662 let OpenResult { window, .. } = cx
8663 .update(|cx| {
8664 Workspace::new_local(
8665 active_workspace.paths.paths().to_vec(),
8666 app_state.clone(),
8667 None,
8668 None,
8669 None,
8670 OpenMode::Activate,
8671 cx,
8672 )
8673 })
8674 .await?;
8675 window
8676 };
8677
8678 if !project_group_keys.is_empty() {
8679 let restored_keys: Vec<ProjectGroupKey> =
8680 project_group_keys.into_iter().map(Into::into).collect();
8681 window_handle
8682 .update(cx, |multi_workspace, _window, _cx| {
8683 multi_workspace.restore_project_group_keys(restored_keys);
8684 })
8685 .ok();
8686 }
8687
8688 if sidebar_open {
8689 window_handle
8690 .update(cx, |multi_workspace, _, cx| {
8691 multi_workspace.open_sidebar(cx);
8692 })
8693 .ok();
8694 }
8695
8696 if let Some(sidebar_state) = sidebar_state {
8697 window_handle
8698 .update(cx, |multi_workspace, window, cx| {
8699 if let Some(sidebar) = multi_workspace.sidebar() {
8700 sidebar.restore_serialized_state(&sidebar_state, window, cx);
8701 }
8702 multi_workspace.serialize(cx);
8703 })
8704 .ok();
8705 }
8706
8707 window_handle
8708 .update(cx, |_, window, _cx| {
8709 window.activate_window();
8710 })
8711 .ok();
8712
8713 Ok(window_handle)
8714}
8715
8716actions!(
8717 collab,
8718 [
8719 /// Opens the channel notes for the current call.
8720 ///
8721 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8722 /// channel in the collab panel.
8723 ///
8724 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8725 /// can be copied via "Copy link to section" in the context menu of the channel notes
8726 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8727 OpenChannelNotes,
8728 /// Mutes your microphone.
8729 Mute,
8730 /// Deafens yourself (mute both microphone and speakers).
8731 Deafen,
8732 /// Leaves the current call.
8733 LeaveCall,
8734 /// Shares the current project with collaborators.
8735 ShareProject,
8736 /// Shares your screen with collaborators.
8737 ScreenShare,
8738 /// Copies the current room name and session id for debugging purposes.
8739 CopyRoomId,
8740 ]
8741);
8742
8743/// Opens the channel notes for a specific channel by its ID.
8744#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8745#[action(namespace = collab)]
8746#[serde(deny_unknown_fields)]
8747pub struct OpenChannelNotesById {
8748 pub channel_id: u64,
8749}
8750
8751actions!(
8752 zed,
8753 [
8754 /// Opens the Zed log file.
8755 OpenLog,
8756 /// Reveals the Zed log file in the system file manager.
8757 RevealLogInFileManager
8758 ]
8759);
8760
8761async fn join_channel_internal(
8762 channel_id: ChannelId,
8763 app_state: &Arc<AppState>,
8764 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8765 requesting_workspace: Option<WeakEntity<Workspace>>,
8766 active_call: &dyn AnyActiveCall,
8767 cx: &mut AsyncApp,
8768) -> Result<bool> {
8769 let (should_prompt, already_in_channel) = cx.update(|cx| {
8770 if !active_call.is_in_room(cx) {
8771 return (false, false);
8772 }
8773
8774 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8775 let should_prompt = active_call.is_sharing_project(cx)
8776 && active_call.has_remote_participants(cx)
8777 && !already_in_channel;
8778 (should_prompt, already_in_channel)
8779 });
8780
8781 if already_in_channel {
8782 let task = cx.update(|cx| {
8783 if let Some((project, host)) = active_call.most_active_project(cx) {
8784 Some(join_in_room_project(project, host, app_state.clone(), cx))
8785 } else {
8786 None
8787 }
8788 });
8789 if let Some(task) = task {
8790 task.await?;
8791 }
8792 return anyhow::Ok(true);
8793 }
8794
8795 if should_prompt {
8796 if let Some(multi_workspace) = requesting_window {
8797 let answer = multi_workspace
8798 .update(cx, |_, window, cx| {
8799 window.prompt(
8800 PromptLevel::Warning,
8801 "Do you want to switch channels?",
8802 Some("Leaving this call will unshare your current project."),
8803 &["Yes, Join Channel", "Cancel"],
8804 cx,
8805 )
8806 })?
8807 .await;
8808
8809 if answer == Ok(1) {
8810 return Ok(false);
8811 }
8812 } else {
8813 return Ok(false);
8814 }
8815 }
8816
8817 let client = cx.update(|cx| active_call.client(cx));
8818
8819 let mut client_status = client.status();
8820
8821 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8822 'outer: loop {
8823 let Some(status) = client_status.recv().await else {
8824 anyhow::bail!("error connecting");
8825 };
8826
8827 match status {
8828 Status::Connecting
8829 | Status::Authenticating
8830 | Status::Authenticated
8831 | Status::Reconnecting
8832 | Status::Reauthenticating
8833 | Status::Reauthenticated => continue,
8834 Status::Connected { .. } => break 'outer,
8835 Status::SignedOut | Status::AuthenticationError => {
8836 return Err(ErrorCode::SignedOut.into());
8837 }
8838 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8839 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8840 return Err(ErrorCode::Disconnected.into());
8841 }
8842 }
8843 }
8844
8845 let joined = cx
8846 .update(|cx| active_call.join_channel(channel_id, cx))
8847 .await?;
8848
8849 if !joined {
8850 return anyhow::Ok(true);
8851 }
8852
8853 cx.update(|cx| active_call.room_update_completed(cx)).await;
8854
8855 let task = cx.update(|cx| {
8856 if let Some((project, host)) = active_call.most_active_project(cx) {
8857 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8858 }
8859
8860 // If you are the first to join a channel, see if you should share your project.
8861 if !active_call.has_remote_participants(cx)
8862 && !active_call.local_participant_is_guest(cx)
8863 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8864 {
8865 let project = workspace.update(cx, |workspace, cx| {
8866 let project = workspace.project.read(cx);
8867
8868 if !active_call.share_on_join(cx) {
8869 return None;
8870 }
8871
8872 if (project.is_local() || project.is_via_remote_server())
8873 && project.visible_worktrees(cx).any(|tree| {
8874 tree.read(cx)
8875 .root_entry()
8876 .is_some_and(|entry| entry.is_dir())
8877 })
8878 {
8879 Some(workspace.project.clone())
8880 } else {
8881 None
8882 }
8883 });
8884 if let Some(project) = project {
8885 let share_task = active_call.share_project(project, cx);
8886 return Some(cx.spawn(async move |_cx| -> Result<()> {
8887 share_task.await?;
8888 Ok(())
8889 }));
8890 }
8891 }
8892
8893 None
8894 });
8895 if let Some(task) = task {
8896 task.await?;
8897 return anyhow::Ok(true);
8898 }
8899 anyhow::Ok(false)
8900}
8901
8902pub fn join_channel(
8903 channel_id: ChannelId,
8904 app_state: Arc<AppState>,
8905 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8906 requesting_workspace: Option<WeakEntity<Workspace>>,
8907 cx: &mut App,
8908) -> Task<Result<()>> {
8909 let active_call = GlobalAnyActiveCall::global(cx).clone();
8910 cx.spawn(async move |cx| {
8911 let result = join_channel_internal(
8912 channel_id,
8913 &app_state,
8914 requesting_window,
8915 requesting_workspace,
8916 &*active_call.0,
8917 cx,
8918 )
8919 .await;
8920
8921 // join channel succeeded, and opened a window
8922 if matches!(result, Ok(true)) {
8923 return anyhow::Ok(());
8924 }
8925
8926 // find an existing workspace to focus and show call controls
8927 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8928 if active_window.is_none() {
8929 // no open workspaces, make one to show the error in (blergh)
8930 let OpenResult {
8931 window: window_handle,
8932 ..
8933 } = cx
8934 .update(|cx| {
8935 Workspace::new_local(
8936 vec![],
8937 app_state.clone(),
8938 requesting_window,
8939 None,
8940 None,
8941 OpenMode::Activate,
8942 cx,
8943 )
8944 })
8945 .await?;
8946
8947 window_handle
8948 .update(cx, |_, window, _cx| {
8949 window.activate_window();
8950 })
8951 .ok();
8952
8953 if result.is_ok() {
8954 cx.update(|cx| {
8955 cx.dispatch_action(&OpenChannelNotes);
8956 });
8957 }
8958
8959 active_window = Some(window_handle);
8960 }
8961
8962 if let Err(err) = result {
8963 log::error!("failed to join channel: {}", err);
8964 if let Some(active_window) = active_window {
8965 active_window
8966 .update(cx, |_, window, cx| {
8967 let detail: SharedString = match err.error_code() {
8968 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8969 ErrorCode::UpgradeRequired => concat!(
8970 "Your are running an unsupported version of Zed. ",
8971 "Please update to continue."
8972 )
8973 .into(),
8974 ErrorCode::NoSuchChannel => concat!(
8975 "No matching channel was found. ",
8976 "Please check the link and try again."
8977 )
8978 .into(),
8979 ErrorCode::Forbidden => concat!(
8980 "This channel is private, and you do not have access. ",
8981 "Please ask someone to add you and try again."
8982 )
8983 .into(),
8984 ErrorCode::Disconnected => {
8985 "Please check your internet connection and try again.".into()
8986 }
8987 _ => format!("{}\n\nPlease try again.", err).into(),
8988 };
8989 window.prompt(
8990 PromptLevel::Critical,
8991 "Failed to join channel",
8992 Some(&detail),
8993 &["Ok"],
8994 cx,
8995 )
8996 })?
8997 .await
8998 .ok();
8999 }
9000 }
9001
9002 // return ok, we showed the error to the user.
9003 anyhow::Ok(())
9004 })
9005}
9006
9007pub async fn get_any_active_multi_workspace(
9008 app_state: Arc<AppState>,
9009 mut cx: AsyncApp,
9010) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
9011 // find an existing workspace to focus and show call controls
9012 let active_window = activate_any_workspace_window(&mut cx);
9013 if active_window.is_none() {
9014 cx.update(|cx| {
9015 Workspace::new_local(
9016 vec![],
9017 app_state.clone(),
9018 None,
9019 None,
9020 None,
9021 OpenMode::Activate,
9022 cx,
9023 )
9024 })
9025 .await?;
9026 }
9027 activate_any_workspace_window(&mut cx).context("could not open zed")
9028}
9029
9030fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
9031 cx.update(|cx| {
9032 if let Some(workspace_window) = cx
9033 .active_window()
9034 .and_then(|window| window.downcast::<MultiWorkspace>())
9035 {
9036 return Some(workspace_window);
9037 }
9038
9039 for window in cx.windows() {
9040 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
9041 workspace_window
9042 .update(cx, |_, window, _| window.activate_window())
9043 .ok();
9044 return Some(workspace_window);
9045 }
9046 }
9047 None
9048 })
9049}
9050
9051pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
9052 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
9053}
9054
9055pub fn workspace_windows_for_location(
9056 serialized_location: &SerializedWorkspaceLocation,
9057 cx: &App,
9058) -> Vec<WindowHandle<MultiWorkspace>> {
9059 cx.windows()
9060 .into_iter()
9061 .filter_map(|window| window.downcast::<MultiWorkspace>())
9062 .filter(|multi_workspace| {
9063 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
9064 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
9065 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
9066 }
9067 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
9068 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
9069 a.distro_name == b.distro_name
9070 }
9071 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
9072 a.container_id == b.container_id
9073 }
9074 #[cfg(any(test, feature = "test-support"))]
9075 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
9076 a.id == b.id
9077 }
9078 _ => false,
9079 };
9080
9081 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
9082 multi_workspace.workspaces().iter().any(|workspace| {
9083 match workspace.read(cx).workspace_location(cx) {
9084 WorkspaceLocation::Location(location, _) => {
9085 match (&location, serialized_location) {
9086 (
9087 SerializedWorkspaceLocation::Local,
9088 SerializedWorkspaceLocation::Local,
9089 ) => true,
9090 (
9091 SerializedWorkspaceLocation::Remote(a),
9092 SerializedWorkspaceLocation::Remote(b),
9093 ) => same_host(a, b),
9094 _ => false,
9095 }
9096 }
9097 _ => false,
9098 }
9099 })
9100 })
9101 })
9102 .collect()
9103}
9104
9105pub async fn find_existing_workspace(
9106 abs_paths: &[PathBuf],
9107 open_options: &OpenOptions,
9108 location: &SerializedWorkspaceLocation,
9109 cx: &mut AsyncApp,
9110) -> (
9111 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
9112 OpenVisible,
9113) {
9114 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
9115 let mut open_visible = OpenVisible::All;
9116 let mut best_match = None;
9117
9118 if open_options.open_new_workspace != Some(true) {
9119 cx.update(|cx| {
9120 for window in workspace_windows_for_location(location, cx) {
9121 if let Ok(multi_workspace) = window.read(cx) {
9122 for workspace in multi_workspace.workspaces() {
9123 let project = workspace.read(cx).project.read(cx);
9124 let m = project.visibility_for_paths(
9125 abs_paths,
9126 open_options.open_new_workspace == None,
9127 cx,
9128 );
9129 if m > best_match {
9130 existing = Some((window, workspace.clone()));
9131 best_match = m;
9132 } else if best_match.is_none()
9133 && open_options.open_new_workspace == Some(false)
9134 {
9135 existing = Some((window, workspace.clone()))
9136 }
9137 }
9138 }
9139 }
9140 });
9141
9142 let all_paths_are_files = existing
9143 .as_ref()
9144 .and_then(|(_, target_workspace)| {
9145 cx.update(|cx| {
9146 let workspace = target_workspace.read(cx);
9147 let project = workspace.project.read(cx);
9148 let path_style = workspace.path_style(cx);
9149 Some(!abs_paths.iter().any(|path| {
9150 let path = util::paths::SanitizedPath::new(path);
9151 project.worktrees(cx).any(|worktree| {
9152 let worktree = worktree.read(cx);
9153 let abs_path = worktree.abs_path();
9154 path_style
9155 .strip_prefix(path.as_ref(), abs_path.as_ref())
9156 .and_then(|rel| worktree.entry_for_path(&rel))
9157 .is_some_and(|e| e.is_dir())
9158 })
9159 }))
9160 })
9161 })
9162 .unwrap_or(false);
9163
9164 if open_options.open_new_workspace.is_none()
9165 && existing.is_some()
9166 && open_options.wait
9167 && all_paths_are_files
9168 {
9169 cx.update(|cx| {
9170 let windows = workspace_windows_for_location(location, cx);
9171 let window = cx
9172 .active_window()
9173 .and_then(|window| window.downcast::<MultiWorkspace>())
9174 .filter(|window| windows.contains(window))
9175 .or_else(|| windows.into_iter().next());
9176 if let Some(window) = window {
9177 if let Ok(multi_workspace) = window.read(cx) {
9178 let active_workspace = multi_workspace.workspace().clone();
9179 existing = Some((window, active_workspace));
9180 open_visible = OpenVisible::None;
9181 }
9182 }
9183 });
9184 }
9185 }
9186 (existing, open_visible)
9187}
9188
9189#[derive(Default, Clone)]
9190pub struct OpenOptions {
9191 pub visible: Option<OpenVisible>,
9192 pub focus: Option<bool>,
9193 pub open_new_workspace: Option<bool>,
9194 pub wait: bool,
9195 pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
9196 pub open_mode: OpenMode,
9197 pub env: Option<HashMap<String, String>>,
9198 pub open_in_dev_container: bool,
9199}
9200
9201/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
9202/// or [`Workspace::open_workspace_for_paths`].
9203pub struct OpenResult {
9204 pub window: WindowHandle<MultiWorkspace>,
9205 pub workspace: Entity<Workspace>,
9206 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
9207}
9208
9209/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
9210pub fn open_workspace_by_id(
9211 workspace_id: WorkspaceId,
9212 app_state: Arc<AppState>,
9213 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9214 cx: &mut App,
9215) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
9216 let project_handle = Project::local(
9217 app_state.client.clone(),
9218 app_state.node_runtime.clone(),
9219 app_state.user_store.clone(),
9220 app_state.languages.clone(),
9221 app_state.fs.clone(),
9222 None,
9223 project::LocalProjectFlags {
9224 init_worktree_trust: true,
9225 ..project::LocalProjectFlags::default()
9226 },
9227 cx,
9228 );
9229
9230 let db = WorkspaceDb::global(cx);
9231 let kvp = db::kvp::KeyValueStore::global(cx);
9232 cx.spawn(async move |cx| {
9233 let serialized_workspace = db
9234 .workspace_for_id(workspace_id)
9235 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
9236
9237 let centered_layout = serialized_workspace.centered_layout;
9238
9239 let (window, workspace) = if let Some(window) = requesting_window {
9240 let workspace = window.update(cx, |multi_workspace, window, cx| {
9241 let workspace = cx.new(|cx| {
9242 let mut workspace = Workspace::new(
9243 Some(workspace_id),
9244 project_handle.clone(),
9245 app_state.clone(),
9246 window,
9247 cx,
9248 );
9249 workspace.centered_layout = centered_layout;
9250 workspace
9251 });
9252 multi_workspace.add(workspace.clone(), &*window, cx);
9253 workspace
9254 })?;
9255 (window, workspace)
9256 } else {
9257 let window_bounds_override = window_bounds_env_override();
9258
9259 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
9260 (Some(WindowBounds::Windowed(bounds)), None)
9261 } else if let Some(display) = serialized_workspace.display
9262 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
9263 {
9264 (Some(bounds.0), Some(display))
9265 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
9266 (Some(bounds), Some(display))
9267 } else {
9268 (None, None)
9269 };
9270
9271 let options = cx.update(|cx| {
9272 let mut options = (app_state.build_window_options)(display, cx);
9273 options.window_bounds = window_bounds;
9274 options
9275 });
9276
9277 let window = cx.open_window(options, {
9278 let app_state = app_state.clone();
9279 let project_handle = project_handle.clone();
9280 move |window, cx| {
9281 let workspace = cx.new(|cx| {
9282 let mut workspace = Workspace::new(
9283 Some(workspace_id),
9284 project_handle,
9285 app_state,
9286 window,
9287 cx,
9288 );
9289 workspace.centered_layout = centered_layout;
9290 workspace
9291 });
9292 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9293 }
9294 })?;
9295
9296 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9297 multi_workspace.workspace().clone()
9298 })?;
9299
9300 (window, workspace)
9301 };
9302
9303 notify_if_database_failed(window, cx);
9304
9305 // Restore items from the serialized workspace
9306 window
9307 .update(cx, |_, window, cx| {
9308 workspace.update(cx, |_workspace, cx| {
9309 open_items(Some(serialized_workspace), vec![], window, cx)
9310 })
9311 })?
9312 .await?;
9313
9314 window.update(cx, |_, window, cx| {
9315 workspace.update(cx, |workspace, cx| {
9316 workspace.serialize_workspace(window, cx);
9317 });
9318 })?;
9319
9320 Ok(window)
9321 })
9322}
9323
9324#[allow(clippy::type_complexity)]
9325pub fn open_paths(
9326 abs_paths: &[PathBuf],
9327 app_state: Arc<AppState>,
9328 open_options: OpenOptions,
9329 cx: &mut App,
9330) -> Task<anyhow::Result<OpenResult>> {
9331 let abs_paths = abs_paths.to_vec();
9332 #[cfg(target_os = "windows")]
9333 let wsl_path = abs_paths
9334 .iter()
9335 .find_map(|p| util::paths::WslPath::from_path(p));
9336
9337 cx.spawn(async move |cx| {
9338 let (mut existing, mut open_visible) = find_existing_workspace(
9339 &abs_paths,
9340 &open_options,
9341 &SerializedWorkspaceLocation::Local,
9342 cx,
9343 )
9344 .await;
9345
9346 // Fallback: if no workspace contains the paths and all paths are files,
9347 // prefer an existing local workspace window (active window first).
9348 if open_options.open_new_workspace.is_none() && existing.is_none() {
9349 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9350 let all_metadatas = futures::future::join_all(all_paths)
9351 .await
9352 .into_iter()
9353 .filter_map(|result| result.ok().flatten())
9354 .collect::<Vec<_>>();
9355
9356 if all_metadatas.iter().all(|file| !file.is_dir) {
9357 cx.update(|cx| {
9358 let windows = workspace_windows_for_location(
9359 &SerializedWorkspaceLocation::Local,
9360 cx,
9361 );
9362 let window = cx
9363 .active_window()
9364 .and_then(|window| window.downcast::<MultiWorkspace>())
9365 .filter(|window| windows.contains(window))
9366 .or_else(|| windows.into_iter().next());
9367 if let Some(window) = window {
9368 if let Ok(multi_workspace) = window.read(cx) {
9369 let active_workspace = multi_workspace.workspace().clone();
9370 existing = Some((window, active_workspace));
9371 open_visible = OpenVisible::None;
9372 }
9373 }
9374 });
9375 }
9376 }
9377
9378 let open_in_dev_container = open_options.open_in_dev_container;
9379
9380 let result = if let Some((existing, target_workspace)) = existing {
9381 let open_task = existing
9382 .update(cx, |multi_workspace, window, cx| {
9383 window.activate_window();
9384 multi_workspace.activate(target_workspace.clone(), window, cx);
9385 target_workspace.update(cx, |workspace, cx| {
9386 if open_in_dev_container {
9387 workspace.set_open_in_dev_container(true);
9388 }
9389 workspace.open_paths(
9390 abs_paths,
9391 OpenOptions {
9392 visible: Some(open_visible),
9393 ..Default::default()
9394 },
9395 None,
9396 window,
9397 cx,
9398 )
9399 })
9400 })?
9401 .await;
9402
9403 _ = existing.update(cx, |multi_workspace, _, cx| {
9404 let workspace = multi_workspace.workspace().clone();
9405 workspace.update(cx, |workspace, cx| {
9406 for item in open_task.iter().flatten() {
9407 if let Err(e) = item {
9408 workspace.show_error(&e, cx);
9409 }
9410 }
9411 });
9412 });
9413
9414 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9415 } else {
9416 let init = if open_in_dev_container {
9417 Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {
9418 workspace.set_open_in_dev_container(true);
9419 }) as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>)
9420 } else {
9421 None
9422 };
9423 let result = cx
9424 .update(move |cx| {
9425 Workspace::new_local(
9426 abs_paths,
9427 app_state.clone(),
9428 open_options.requesting_window,
9429 open_options.env,
9430 init,
9431 open_options.open_mode,
9432 cx,
9433 )
9434 })
9435 .await;
9436
9437 if let Ok(ref result) = result {
9438 result.window
9439 .update(cx, |_, window, _cx| {
9440 window.activate_window();
9441 })
9442 .log_err();
9443 }
9444
9445 result
9446 };
9447
9448 #[cfg(target_os = "windows")]
9449 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9450 && let Ok(ref result) = result
9451 {
9452 result.window
9453 .update(cx, move |multi_workspace, _window, cx| {
9454 struct OpenInWsl;
9455 let workspace = multi_workspace.workspace().clone();
9456 workspace.update(cx, |workspace, cx| {
9457 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9458 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9459 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9460 cx.new(move |cx| {
9461 MessageNotification::new(msg, cx)
9462 .primary_message("Open in WSL")
9463 .primary_icon(IconName::FolderOpen)
9464 .primary_on_click(move |window, cx| {
9465 window.dispatch_action(Box::new(remote::OpenWslPath {
9466 distro: remote::WslConnectionOptions {
9467 distro_name: distro.clone(),
9468 user: None,
9469 },
9470 paths: vec![path.clone().into()],
9471 }), cx)
9472 })
9473 })
9474 });
9475 });
9476 })
9477 .unwrap();
9478 };
9479 result
9480 })
9481}
9482
9483pub fn open_new(
9484 open_options: OpenOptions,
9485 app_state: Arc<AppState>,
9486 cx: &mut App,
9487 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9488) -> Task<anyhow::Result<()>> {
9489 let addition = open_options.open_mode;
9490 let task = Workspace::new_local(
9491 Vec::new(),
9492 app_state,
9493 open_options.requesting_window,
9494 open_options.env,
9495 Some(Box::new(init)),
9496 addition,
9497 cx,
9498 );
9499 cx.spawn(async move |cx| {
9500 let OpenResult { window, .. } = task.await?;
9501 window
9502 .update(cx, |_, window, _cx| {
9503 window.activate_window();
9504 })
9505 .ok();
9506 Ok(())
9507 })
9508}
9509
9510pub fn create_and_open_local_file(
9511 path: &'static Path,
9512 window: &mut Window,
9513 cx: &mut Context<Workspace>,
9514 default_content: impl 'static + Send + FnOnce() -> Rope,
9515) -> Task<Result<Box<dyn ItemHandle>>> {
9516 cx.spawn_in(window, async move |workspace, cx| {
9517 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9518 if !fs.is_file(path).await {
9519 fs.create_file(path, Default::default()).await?;
9520 fs.save(path, &default_content(), Default::default())
9521 .await?;
9522 }
9523
9524 workspace
9525 .update_in(cx, |workspace, window, cx| {
9526 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9527 let path = workspace
9528 .project
9529 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9530 cx.spawn_in(window, async move |workspace, cx| {
9531 let path = path.await?;
9532
9533 let path = fs.canonicalize(&path).await.unwrap_or(path);
9534
9535 let mut items = workspace
9536 .update_in(cx, |workspace, window, cx| {
9537 workspace.open_paths(
9538 vec![path.to_path_buf()],
9539 OpenOptions {
9540 visible: Some(OpenVisible::None),
9541 ..Default::default()
9542 },
9543 None,
9544 window,
9545 cx,
9546 )
9547 })?
9548 .await;
9549 let item = items.pop().flatten();
9550 item.with_context(|| format!("path {path:?} is not a file"))?
9551 })
9552 })
9553 })?
9554 .await?
9555 .await
9556 })
9557}
9558
9559pub fn open_remote_project_with_new_connection(
9560 window: WindowHandle<MultiWorkspace>,
9561 remote_connection: Arc<dyn RemoteConnection>,
9562 cancel_rx: oneshot::Receiver<()>,
9563 delegate: Arc<dyn RemoteClientDelegate>,
9564 app_state: Arc<AppState>,
9565 paths: Vec<PathBuf>,
9566 cx: &mut App,
9567) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9568 cx.spawn(async move |cx| {
9569 let (workspace_id, serialized_workspace) =
9570 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9571 .await?;
9572
9573 let session = match cx
9574 .update(|cx| {
9575 remote::RemoteClient::new(
9576 ConnectionIdentifier::Workspace(workspace_id.0),
9577 remote_connection,
9578 cancel_rx,
9579 delegate,
9580 cx,
9581 )
9582 })
9583 .await?
9584 {
9585 Some(result) => result,
9586 None => return Ok(Vec::new()),
9587 };
9588
9589 let project = cx.update(|cx| {
9590 project::Project::remote(
9591 session,
9592 app_state.client.clone(),
9593 app_state.node_runtime.clone(),
9594 app_state.user_store.clone(),
9595 app_state.languages.clone(),
9596 app_state.fs.clone(),
9597 true,
9598 cx,
9599 )
9600 });
9601
9602 open_remote_project_inner(
9603 project,
9604 paths,
9605 workspace_id,
9606 serialized_workspace,
9607 app_state,
9608 window,
9609 cx,
9610 )
9611 .await
9612 })
9613}
9614
9615pub fn open_remote_project_with_existing_connection(
9616 connection_options: RemoteConnectionOptions,
9617 project: Entity<Project>,
9618 paths: Vec<PathBuf>,
9619 app_state: Arc<AppState>,
9620 window: WindowHandle<MultiWorkspace>,
9621 cx: &mut AsyncApp,
9622) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9623 cx.spawn(async move |cx| {
9624 let (workspace_id, serialized_workspace) =
9625 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9626
9627 open_remote_project_inner(
9628 project,
9629 paths,
9630 workspace_id,
9631 serialized_workspace,
9632 app_state,
9633 window,
9634 cx,
9635 )
9636 .await
9637 })
9638}
9639
9640async fn open_remote_project_inner(
9641 project: Entity<Project>,
9642 paths: Vec<PathBuf>,
9643 workspace_id: WorkspaceId,
9644 serialized_workspace: Option<SerializedWorkspace>,
9645 app_state: Arc<AppState>,
9646 window: WindowHandle<MultiWorkspace>,
9647 cx: &mut AsyncApp,
9648) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9649 let db = cx.update(|cx| WorkspaceDb::global(cx));
9650 let toolchains = db.toolchains(workspace_id).await?;
9651 for (toolchain, worktree_path, path) in toolchains {
9652 project
9653 .update(cx, |this, cx| {
9654 let Some(worktree_id) =
9655 this.find_worktree(&worktree_path, cx)
9656 .and_then(|(worktree, rel_path)| {
9657 if rel_path.is_empty() {
9658 Some(worktree.read(cx).id())
9659 } else {
9660 None
9661 }
9662 })
9663 else {
9664 return Task::ready(None);
9665 };
9666
9667 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9668 })
9669 .await;
9670 }
9671 let mut project_paths_to_open = vec![];
9672 let mut project_path_errors = vec![];
9673
9674 for path in paths {
9675 let result = cx
9676 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9677 .await;
9678 match result {
9679 Ok((_, project_path)) => {
9680 project_paths_to_open.push((path.clone(), Some(project_path)));
9681 }
9682 Err(error) => {
9683 project_path_errors.push(error);
9684 }
9685 };
9686 }
9687
9688 if project_paths_to_open.is_empty() {
9689 return Err(project_path_errors.pop().context("no paths given")?);
9690 }
9691
9692 let workspace = window.update(cx, |multi_workspace, window, cx| {
9693 telemetry::event!("SSH Project Opened");
9694
9695 let new_workspace = cx.new(|cx| {
9696 let mut workspace =
9697 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9698 workspace.update_history(cx);
9699
9700 if let Some(ref serialized) = serialized_workspace {
9701 workspace.centered_layout = serialized.centered_layout;
9702 }
9703
9704 workspace
9705 });
9706
9707 multi_workspace.activate(new_workspace.clone(), window, cx);
9708 new_workspace
9709 })?;
9710
9711 let items = window
9712 .update(cx, |_, window, cx| {
9713 window.activate_window();
9714 workspace.update(cx, |_workspace, cx| {
9715 open_items(serialized_workspace, project_paths_to_open, window, cx)
9716 })
9717 })?
9718 .await?;
9719
9720 workspace.update(cx, |workspace, cx| {
9721 for error in project_path_errors {
9722 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9723 if let Some(path) = error.error_tag("path") {
9724 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9725 }
9726 } else {
9727 workspace.show_error(&error, cx)
9728 }
9729 }
9730 });
9731
9732 Ok(items.into_iter().map(|item| item?.ok()).collect())
9733}
9734
9735fn deserialize_remote_project(
9736 connection_options: RemoteConnectionOptions,
9737 paths: Vec<PathBuf>,
9738 cx: &AsyncApp,
9739) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9740 let db = cx.update(|cx| WorkspaceDb::global(cx));
9741 cx.background_spawn(async move {
9742 let remote_connection_id = db
9743 .get_or_create_remote_connection(connection_options)
9744 .await?;
9745
9746 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9747
9748 let workspace_id = if let Some(workspace_id) =
9749 serialized_workspace.as_ref().map(|workspace| workspace.id)
9750 {
9751 workspace_id
9752 } else {
9753 db.next_id().await?
9754 };
9755
9756 Ok((workspace_id, serialized_workspace))
9757 })
9758}
9759
9760pub fn join_in_room_project(
9761 project_id: u64,
9762 follow_user_id: u64,
9763 app_state: Arc<AppState>,
9764 cx: &mut App,
9765) -> Task<Result<()>> {
9766 let windows = cx.windows();
9767 cx.spawn(async move |cx| {
9768 let existing_window_and_workspace: Option<(
9769 WindowHandle<MultiWorkspace>,
9770 Entity<Workspace>,
9771 )> = windows.into_iter().find_map(|window_handle| {
9772 window_handle
9773 .downcast::<MultiWorkspace>()
9774 .and_then(|window_handle| {
9775 window_handle
9776 .update(cx, |multi_workspace, _window, cx| {
9777 for workspace in multi_workspace.workspaces() {
9778 if workspace.read(cx).project().read(cx).remote_id()
9779 == Some(project_id)
9780 {
9781 return Some((window_handle, workspace.clone()));
9782 }
9783 }
9784 None
9785 })
9786 .unwrap_or(None)
9787 })
9788 });
9789
9790 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9791 existing_window_and_workspace
9792 {
9793 existing_window
9794 .update(cx, |multi_workspace, window, cx| {
9795 multi_workspace.activate(target_workspace, window, cx);
9796 })
9797 .ok();
9798 existing_window
9799 } else {
9800 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9801 let project = cx
9802 .update(|cx| {
9803 active_call.0.join_project(
9804 project_id,
9805 app_state.languages.clone(),
9806 app_state.fs.clone(),
9807 cx,
9808 )
9809 })
9810 .await?;
9811
9812 let window_bounds_override = window_bounds_env_override();
9813 cx.update(|cx| {
9814 let mut options = (app_state.build_window_options)(None, cx);
9815 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9816 cx.open_window(options, |window, cx| {
9817 let workspace = cx.new(|cx| {
9818 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9819 });
9820 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9821 })
9822 })?
9823 };
9824
9825 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9826 cx.activate(true);
9827 window.activate_window();
9828
9829 // We set the active workspace above, so this is the correct workspace.
9830 let workspace = multi_workspace.workspace().clone();
9831 workspace.update(cx, |workspace, cx| {
9832 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9833 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9834 .or_else(|| {
9835 // If we couldn't follow the given user, follow the host instead.
9836 let collaborator = workspace
9837 .project()
9838 .read(cx)
9839 .collaborators()
9840 .values()
9841 .find(|collaborator| collaborator.is_host)?;
9842 Some(collaborator.peer_id)
9843 });
9844
9845 if let Some(follow_peer_id) = follow_peer_id {
9846 workspace.follow(follow_peer_id, window, cx);
9847 }
9848 });
9849 })?;
9850
9851 anyhow::Ok(())
9852 })
9853}
9854
9855pub fn reload(cx: &mut App) {
9856 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9857 let mut workspace_windows = cx
9858 .windows()
9859 .into_iter()
9860 .filter_map(|window| window.downcast::<MultiWorkspace>())
9861 .collect::<Vec<_>>();
9862
9863 // If multiple windows have unsaved changes, and need a save prompt,
9864 // prompt in the active window before switching to a different window.
9865 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9866
9867 let mut prompt = None;
9868 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9869 prompt = window
9870 .update(cx, |_, window, cx| {
9871 window.prompt(
9872 PromptLevel::Info,
9873 "Are you sure you want to restart?",
9874 None,
9875 &["Restart", "Cancel"],
9876 cx,
9877 )
9878 })
9879 .ok();
9880 }
9881
9882 cx.spawn(async move |cx| {
9883 if let Some(prompt) = prompt {
9884 let answer = prompt.await?;
9885 if answer != 0 {
9886 return anyhow::Ok(());
9887 }
9888 }
9889
9890 // If the user cancels any save prompt, then keep the app open.
9891 for window in workspace_windows {
9892 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9893 let workspace = multi_workspace.workspace().clone();
9894 workspace.update(cx, |workspace, cx| {
9895 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9896 })
9897 }) && !should_close.await?
9898 {
9899 return anyhow::Ok(());
9900 }
9901 }
9902 cx.update(|cx| cx.restart());
9903 anyhow::Ok(())
9904 })
9905 .detach_and_log_err(cx);
9906}
9907
9908fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9909 let mut parts = value.split(',');
9910 let x: usize = parts.next()?.parse().ok()?;
9911 let y: usize = parts.next()?.parse().ok()?;
9912 Some(point(px(x as f32), px(y as f32)))
9913}
9914
9915fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9916 let mut parts = value.split(',');
9917 let width: usize = parts.next()?.parse().ok()?;
9918 let height: usize = parts.next()?.parse().ok()?;
9919 Some(size(px(width as f32), px(height as f32)))
9920}
9921
9922/// Add client-side decorations (rounded corners, shadows, resize handling) when
9923/// appropriate.
9924///
9925/// The `border_radius_tiling` parameter allows overriding which corners get
9926/// rounded, independently of the actual window tiling state. This is used
9927/// specifically for the workspace switcher sidebar: when the sidebar is open,
9928/// we want square corners on the left (so the sidebar appears flush with the
9929/// window edge) but we still need the shadow padding for proper visual
9930/// appearance. Unlike actual window tiling, this only affects border radius -
9931/// not padding or shadows.
9932pub fn client_side_decorations(
9933 element: impl IntoElement,
9934 window: &mut Window,
9935 cx: &mut App,
9936 border_radius_tiling: Tiling,
9937) -> Stateful<Div> {
9938 const BORDER_SIZE: Pixels = px(1.0);
9939 let decorations = window.window_decorations();
9940 let tiling = match decorations {
9941 Decorations::Server => Tiling::default(),
9942 Decorations::Client { tiling } => tiling,
9943 };
9944
9945 match decorations {
9946 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9947 Decorations::Server => window.set_client_inset(px(0.0)),
9948 }
9949
9950 struct GlobalResizeEdge(ResizeEdge);
9951 impl Global for GlobalResizeEdge {}
9952
9953 div()
9954 .id("window-backdrop")
9955 .bg(transparent_black())
9956 .map(|div| match decorations {
9957 Decorations::Server => div,
9958 Decorations::Client { .. } => div
9959 .when(
9960 !(tiling.top
9961 || tiling.right
9962 || border_radius_tiling.top
9963 || border_radius_tiling.right),
9964 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9965 )
9966 .when(
9967 !(tiling.top
9968 || tiling.left
9969 || border_radius_tiling.top
9970 || border_radius_tiling.left),
9971 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9972 )
9973 .when(
9974 !(tiling.bottom
9975 || tiling.right
9976 || border_radius_tiling.bottom
9977 || border_radius_tiling.right),
9978 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9979 )
9980 .when(
9981 !(tiling.bottom
9982 || tiling.left
9983 || border_radius_tiling.bottom
9984 || border_radius_tiling.left),
9985 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9986 )
9987 .when(!tiling.top, |div| {
9988 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9989 })
9990 .when(!tiling.bottom, |div| {
9991 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9992 })
9993 .when(!tiling.left, |div| {
9994 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9995 })
9996 .when(!tiling.right, |div| {
9997 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9998 })
9999 .on_mouse_move(move |e, window, cx| {
10000 let size = window.window_bounds().get_bounds().size;
10001 let pos = e.position;
10002
10003 let new_edge =
10004 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10005
10006 let edge = cx.try_global::<GlobalResizeEdge>();
10007 if new_edge != edge.map(|edge| edge.0) {
10008 window
10009 .window_handle()
10010 .update(cx, |workspace, _, cx| {
10011 cx.notify(workspace.entity_id());
10012 })
10013 .ok();
10014 }
10015 })
10016 .on_mouse_down(MouseButton::Left, move |e, window, _| {
10017 let size = window.window_bounds().get_bounds().size;
10018 let pos = e.position;
10019
10020 let edge = match resize_edge(
10021 pos,
10022 theme::CLIENT_SIDE_DECORATION_SHADOW,
10023 size,
10024 tiling,
10025 ) {
10026 Some(value) => value,
10027 None => return,
10028 };
10029
10030 window.start_window_resize(edge);
10031 }),
10032 })
10033 .size_full()
10034 .child(
10035 div()
10036 .cursor(CursorStyle::Arrow)
10037 .map(|div| match decorations {
10038 Decorations::Server => div,
10039 Decorations::Client { .. } => div
10040 .border_color(cx.theme().colors().border)
10041 .when(
10042 !(tiling.top
10043 || tiling.right
10044 || border_radius_tiling.top
10045 || border_radius_tiling.right),
10046 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10047 )
10048 .when(
10049 !(tiling.top
10050 || tiling.left
10051 || border_radius_tiling.top
10052 || border_radius_tiling.left),
10053 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10054 )
10055 .when(
10056 !(tiling.bottom
10057 || tiling.right
10058 || border_radius_tiling.bottom
10059 || border_radius_tiling.right),
10060 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10061 )
10062 .when(
10063 !(tiling.bottom
10064 || tiling.left
10065 || border_radius_tiling.bottom
10066 || border_radius_tiling.left),
10067 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10068 )
10069 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10070 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10071 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10072 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10073 .when(!tiling.is_tiled(), |div| {
10074 div.shadow(vec![gpui::BoxShadow {
10075 color: Hsla {
10076 h: 0.,
10077 s: 0.,
10078 l: 0.,
10079 a: 0.4,
10080 },
10081 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10082 spread_radius: px(0.),
10083 offset: point(px(0.0), px(0.0)),
10084 }])
10085 }),
10086 })
10087 .on_mouse_move(|_e, _, cx| {
10088 cx.stop_propagation();
10089 })
10090 .size_full()
10091 .child(element),
10092 )
10093 .map(|div| match decorations {
10094 Decorations::Server => div,
10095 Decorations::Client { tiling, .. } => div.child(
10096 canvas(
10097 |_bounds, window, _| {
10098 window.insert_hitbox(
10099 Bounds::new(
10100 point(px(0.0), px(0.0)),
10101 window.window_bounds().get_bounds().size,
10102 ),
10103 HitboxBehavior::Normal,
10104 )
10105 },
10106 move |_bounds, hitbox, window, cx| {
10107 let mouse = window.mouse_position();
10108 let size = window.window_bounds().get_bounds().size;
10109 let Some(edge) =
10110 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10111 else {
10112 return;
10113 };
10114 cx.set_global(GlobalResizeEdge(edge));
10115 window.set_cursor_style(
10116 match edge {
10117 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10118 ResizeEdge::Left | ResizeEdge::Right => {
10119 CursorStyle::ResizeLeftRight
10120 }
10121 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10122 CursorStyle::ResizeUpLeftDownRight
10123 }
10124 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10125 CursorStyle::ResizeUpRightDownLeft
10126 }
10127 },
10128 &hitbox,
10129 );
10130 },
10131 )
10132 .size_full()
10133 .absolute(),
10134 ),
10135 })
10136}
10137
10138fn resize_edge(
10139 pos: Point<Pixels>,
10140 shadow_size: Pixels,
10141 window_size: Size<Pixels>,
10142 tiling: Tiling,
10143) -> Option<ResizeEdge> {
10144 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10145 if bounds.contains(&pos) {
10146 return None;
10147 }
10148
10149 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10150 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10151 if !tiling.top && top_left_bounds.contains(&pos) {
10152 return Some(ResizeEdge::TopLeft);
10153 }
10154
10155 let top_right_bounds = Bounds::new(
10156 Point::new(window_size.width - corner_size.width, px(0.)),
10157 corner_size,
10158 );
10159 if !tiling.top && top_right_bounds.contains(&pos) {
10160 return Some(ResizeEdge::TopRight);
10161 }
10162
10163 let bottom_left_bounds = Bounds::new(
10164 Point::new(px(0.), window_size.height - corner_size.height),
10165 corner_size,
10166 );
10167 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10168 return Some(ResizeEdge::BottomLeft);
10169 }
10170
10171 let bottom_right_bounds = Bounds::new(
10172 Point::new(
10173 window_size.width - corner_size.width,
10174 window_size.height - corner_size.height,
10175 ),
10176 corner_size,
10177 );
10178 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10179 return Some(ResizeEdge::BottomRight);
10180 }
10181
10182 if !tiling.top && pos.y < shadow_size {
10183 Some(ResizeEdge::Top)
10184 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10185 Some(ResizeEdge::Bottom)
10186 } else if !tiling.left && pos.x < shadow_size {
10187 Some(ResizeEdge::Left)
10188 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10189 Some(ResizeEdge::Right)
10190 } else {
10191 None
10192 }
10193}
10194
10195fn join_pane_into_active(
10196 active_pane: &Entity<Pane>,
10197 pane: &Entity<Pane>,
10198 window: &mut Window,
10199 cx: &mut App,
10200) {
10201 if pane == active_pane {
10202 } else if pane.read(cx).items_len() == 0 {
10203 pane.update(cx, |_, cx| {
10204 cx.emit(pane::Event::Remove {
10205 focus_on_pane: None,
10206 });
10207 })
10208 } else {
10209 move_all_items(pane, active_pane, window, cx);
10210 }
10211}
10212
10213fn move_all_items(
10214 from_pane: &Entity<Pane>,
10215 to_pane: &Entity<Pane>,
10216 window: &mut Window,
10217 cx: &mut App,
10218) {
10219 let destination_is_different = from_pane != to_pane;
10220 let mut moved_items = 0;
10221 for (item_ix, item_handle) in from_pane
10222 .read(cx)
10223 .items()
10224 .enumerate()
10225 .map(|(ix, item)| (ix, item.clone()))
10226 .collect::<Vec<_>>()
10227 {
10228 let ix = item_ix - moved_items;
10229 if destination_is_different {
10230 // Close item from previous pane
10231 from_pane.update(cx, |source, cx| {
10232 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10233 });
10234 moved_items += 1;
10235 }
10236
10237 // This automatically removes duplicate items in the pane
10238 to_pane.update(cx, |destination, cx| {
10239 destination.add_item(item_handle, true, true, None, window, cx);
10240 window.focus(&destination.focus_handle(cx), cx)
10241 });
10242 }
10243}
10244
10245pub fn move_item(
10246 source: &Entity<Pane>,
10247 destination: &Entity<Pane>,
10248 item_id_to_move: EntityId,
10249 destination_index: usize,
10250 activate: bool,
10251 window: &mut Window,
10252 cx: &mut App,
10253) {
10254 let Some((item_ix, item_handle)) = source
10255 .read(cx)
10256 .items()
10257 .enumerate()
10258 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10259 .map(|(ix, item)| (ix, item.clone()))
10260 else {
10261 // Tab was closed during drag
10262 return;
10263 };
10264
10265 if source != destination {
10266 // Close item from previous pane
10267 source.update(cx, |source, cx| {
10268 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10269 });
10270 }
10271
10272 // This automatically removes duplicate items in the pane
10273 destination.update(cx, |destination, cx| {
10274 destination.add_item_inner(
10275 item_handle,
10276 activate,
10277 activate,
10278 activate,
10279 Some(destination_index),
10280 window,
10281 cx,
10282 );
10283 if activate {
10284 window.focus(&destination.focus_handle(cx), cx)
10285 }
10286 });
10287}
10288
10289pub fn move_active_item(
10290 source: &Entity<Pane>,
10291 destination: &Entity<Pane>,
10292 focus_destination: bool,
10293 close_if_empty: bool,
10294 window: &mut Window,
10295 cx: &mut App,
10296) {
10297 if source == destination {
10298 return;
10299 }
10300 let Some(active_item) = source.read(cx).active_item() else {
10301 return;
10302 };
10303 source.update(cx, |source_pane, cx| {
10304 let item_id = active_item.item_id();
10305 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10306 destination.update(cx, |target_pane, cx| {
10307 target_pane.add_item(
10308 active_item,
10309 focus_destination,
10310 focus_destination,
10311 Some(target_pane.items_len()),
10312 window,
10313 cx,
10314 );
10315 });
10316 });
10317}
10318
10319pub fn clone_active_item(
10320 workspace_id: Option<WorkspaceId>,
10321 source: &Entity<Pane>,
10322 destination: &Entity<Pane>,
10323 focus_destination: bool,
10324 window: &mut Window,
10325 cx: &mut App,
10326) {
10327 if source == destination {
10328 return;
10329 }
10330 let Some(active_item) = source.read(cx).active_item() else {
10331 return;
10332 };
10333 if !active_item.can_split(cx) {
10334 return;
10335 }
10336 let destination = destination.downgrade();
10337 let task = active_item.clone_on_split(workspace_id, window, cx);
10338 window
10339 .spawn(cx, async move |cx| {
10340 let Some(clone) = task.await else {
10341 return;
10342 };
10343 destination
10344 .update_in(cx, |target_pane, window, cx| {
10345 target_pane.add_item(
10346 clone,
10347 focus_destination,
10348 focus_destination,
10349 Some(target_pane.items_len()),
10350 window,
10351 cx,
10352 );
10353 })
10354 .log_err();
10355 })
10356 .detach();
10357}
10358
10359#[derive(Debug)]
10360pub struct WorkspacePosition {
10361 pub window_bounds: Option<WindowBounds>,
10362 pub display: Option<Uuid>,
10363 pub centered_layout: bool,
10364}
10365
10366pub fn remote_workspace_position_from_db(
10367 connection_options: RemoteConnectionOptions,
10368 paths_to_open: &[PathBuf],
10369 cx: &App,
10370) -> Task<Result<WorkspacePosition>> {
10371 let paths = paths_to_open.to_vec();
10372 let db = WorkspaceDb::global(cx);
10373 let kvp = db::kvp::KeyValueStore::global(cx);
10374
10375 cx.background_spawn(async move {
10376 let remote_connection_id = db
10377 .get_or_create_remote_connection(connection_options)
10378 .await
10379 .context("fetching serialized ssh project")?;
10380 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10381
10382 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10383 (Some(WindowBounds::Windowed(bounds)), None)
10384 } else {
10385 let restorable_bounds = serialized_workspace
10386 .as_ref()
10387 .and_then(|workspace| {
10388 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10389 })
10390 .or_else(|| persistence::read_default_window_bounds(&kvp));
10391
10392 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10393 (Some(serialized_bounds), Some(serialized_display))
10394 } else {
10395 (None, None)
10396 }
10397 };
10398
10399 let centered_layout = serialized_workspace
10400 .as_ref()
10401 .map(|w| w.centered_layout)
10402 .unwrap_or(false);
10403
10404 Ok(WorkspacePosition {
10405 window_bounds,
10406 display,
10407 centered_layout,
10408 })
10409 })
10410}
10411
10412pub fn with_active_or_new_workspace(
10413 cx: &mut App,
10414 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10415) {
10416 match cx
10417 .active_window()
10418 .and_then(|w| w.downcast::<MultiWorkspace>())
10419 {
10420 Some(multi_workspace) => {
10421 cx.defer(move |cx| {
10422 multi_workspace
10423 .update(cx, |multi_workspace, window, cx| {
10424 let workspace = multi_workspace.workspace().clone();
10425 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10426 })
10427 .log_err();
10428 });
10429 }
10430 None => {
10431 let app_state = AppState::global(cx);
10432 open_new(
10433 OpenOptions::default(),
10434 app_state,
10435 cx,
10436 move |workspace, window, cx| f(workspace, window, cx),
10437 )
10438 .detach_and_log_err(cx);
10439 }
10440 }
10441}
10442
10443/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10444/// key. This migration path only runs once per panel per workspace.
10445fn load_legacy_panel_size(
10446 panel_key: &str,
10447 dock_position: DockPosition,
10448 workspace: &Workspace,
10449 cx: &mut App,
10450) -> Option<Pixels> {
10451 #[derive(Deserialize)]
10452 struct LegacyPanelState {
10453 #[serde(default)]
10454 width: Option<Pixels>,
10455 #[serde(default)]
10456 height: Option<Pixels>,
10457 }
10458
10459 let workspace_id = workspace
10460 .database_id()
10461 .map(|id| i64::from(id).to_string())
10462 .or_else(|| workspace.session_id())?;
10463
10464 let legacy_key = match panel_key {
10465 "ProjectPanel" => {
10466 format!("{}-{:?}", "ProjectPanel", workspace_id)
10467 }
10468 "OutlinePanel" => {
10469 format!("{}-{:?}", "OutlinePanel", workspace_id)
10470 }
10471 "GitPanel" => {
10472 format!("{}-{:?}", "GitPanel", workspace_id)
10473 }
10474 "TerminalPanel" => {
10475 format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10476 }
10477 _ => return None,
10478 };
10479
10480 let kvp = db::kvp::KeyValueStore::global(cx);
10481 let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10482 let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10483 let size = match dock_position {
10484 DockPosition::Bottom => state.height,
10485 DockPosition::Left | DockPosition::Right => state.width,
10486 }?;
10487
10488 cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10489 .detach_and_log_err(cx);
10490
10491 Some(size)
10492}
10493
10494#[cfg(test)]
10495mod tests {
10496 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10497
10498 use super::*;
10499 use crate::{
10500 dock::{PanelEvent, test::TestPanel},
10501 item::{
10502 ItemBufferKind, ItemEvent,
10503 test::{TestItem, TestProjectItem},
10504 },
10505 };
10506 use fs::FakeFs;
10507 use gpui::{
10508 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10509 UpdateGlobal, VisualTestContext, px,
10510 };
10511 use project::{Project, ProjectEntryId};
10512 use serde_json::json;
10513 use settings::SettingsStore;
10514 use util::path;
10515 use util::rel_path::rel_path;
10516
10517 #[gpui::test]
10518 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10519 init_test(cx);
10520
10521 let fs = FakeFs::new(cx.executor());
10522 let project = Project::test(fs, [], cx).await;
10523 let (workspace, cx) =
10524 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10525
10526 // Adding an item with no ambiguity renders the tab without detail.
10527 let item1 = cx.new(|cx| {
10528 let mut item = TestItem::new(cx);
10529 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10530 item
10531 });
10532 workspace.update_in(cx, |workspace, window, cx| {
10533 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10534 });
10535 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10536
10537 // Adding an item that creates ambiguity increases the level of detail on
10538 // both tabs.
10539 let item2 = cx.new_window_entity(|_window, cx| {
10540 let mut item = TestItem::new(cx);
10541 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10542 item
10543 });
10544 workspace.update_in(cx, |workspace, window, cx| {
10545 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10546 });
10547 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10548 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10549
10550 // Adding an item that creates ambiguity increases the level of detail only
10551 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10552 // we stop at the highest detail available.
10553 let item3 = cx.new(|cx| {
10554 let mut item = TestItem::new(cx);
10555 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10556 item
10557 });
10558 workspace.update_in(cx, |workspace, window, cx| {
10559 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10560 });
10561 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10562 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10563 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10564 }
10565
10566 #[gpui::test]
10567 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10568 init_test(cx);
10569
10570 let fs = FakeFs::new(cx.executor());
10571 fs.insert_tree(
10572 "/root1",
10573 json!({
10574 "one.txt": "",
10575 "two.txt": "",
10576 }),
10577 )
10578 .await;
10579 fs.insert_tree(
10580 "/root2",
10581 json!({
10582 "three.txt": "",
10583 }),
10584 )
10585 .await;
10586
10587 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10588 let (workspace, cx) =
10589 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10590 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10591 let worktree_id = project.update(cx, |project, cx| {
10592 project.worktrees(cx).next().unwrap().read(cx).id()
10593 });
10594
10595 let item1 = cx.new(|cx| {
10596 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10597 });
10598 let item2 = cx.new(|cx| {
10599 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10600 });
10601
10602 // Add an item to an empty pane
10603 workspace.update_in(cx, |workspace, window, cx| {
10604 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10605 });
10606 project.update(cx, |project, cx| {
10607 assert_eq!(
10608 project.active_entry(),
10609 project
10610 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10611 .map(|e| e.id)
10612 );
10613 });
10614 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10615
10616 // Add a second item to a non-empty pane
10617 workspace.update_in(cx, |workspace, window, cx| {
10618 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10619 });
10620 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10621 project.update(cx, |project, cx| {
10622 assert_eq!(
10623 project.active_entry(),
10624 project
10625 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10626 .map(|e| e.id)
10627 );
10628 });
10629
10630 // Close the active item
10631 pane.update_in(cx, |pane, window, cx| {
10632 pane.close_active_item(&Default::default(), window, cx)
10633 })
10634 .await
10635 .unwrap();
10636 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10637 project.update(cx, |project, cx| {
10638 assert_eq!(
10639 project.active_entry(),
10640 project
10641 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10642 .map(|e| e.id)
10643 );
10644 });
10645
10646 // Add a project folder
10647 project
10648 .update(cx, |project, cx| {
10649 project.find_or_create_worktree("root2", true, cx)
10650 })
10651 .await
10652 .unwrap();
10653 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10654
10655 // Remove a project folder
10656 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10657 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10658 }
10659
10660 #[gpui::test]
10661 async fn test_close_window(cx: &mut TestAppContext) {
10662 init_test(cx);
10663
10664 let fs = FakeFs::new(cx.executor());
10665 fs.insert_tree("/root", json!({ "one": "" })).await;
10666
10667 let project = Project::test(fs, ["root".as_ref()], cx).await;
10668 let (workspace, cx) =
10669 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10670
10671 // When there are no dirty items, there's nothing to do.
10672 let item1 = cx.new(TestItem::new);
10673 workspace.update_in(cx, |w, window, cx| {
10674 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10675 });
10676 let task = workspace.update_in(cx, |w, window, cx| {
10677 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10678 });
10679 assert!(task.await.unwrap());
10680
10681 // When there are dirty untitled items, prompt to save each one. If the user
10682 // cancels any prompt, then abort.
10683 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10684 let item3 = cx.new(|cx| {
10685 TestItem::new(cx)
10686 .with_dirty(true)
10687 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10688 });
10689 workspace.update_in(cx, |w, window, cx| {
10690 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10691 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10692 });
10693 let task = workspace.update_in(cx, |w, window, cx| {
10694 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10695 });
10696 cx.executor().run_until_parked();
10697 cx.simulate_prompt_answer("Cancel"); // cancel save all
10698 cx.executor().run_until_parked();
10699 assert!(!cx.has_pending_prompt());
10700 assert!(!task.await.unwrap());
10701 }
10702
10703 #[gpui::test]
10704 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10705 init_test(cx);
10706
10707 let fs = FakeFs::new(cx.executor());
10708 fs.insert_tree("/root", json!({ "one": "" })).await;
10709
10710 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10711 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10712 let multi_workspace_handle =
10713 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10714 cx.run_until_parked();
10715
10716 let workspace_a = multi_workspace_handle
10717 .read_with(cx, |mw, _| mw.workspace().clone())
10718 .unwrap();
10719
10720 let workspace_b = multi_workspace_handle
10721 .update(cx, |mw, window, cx| {
10722 mw.test_add_workspace(project_b, window, cx)
10723 })
10724 .unwrap();
10725
10726 // Activate workspace A
10727 multi_workspace_handle
10728 .update(cx, |mw, window, cx| {
10729 let workspace = mw.workspaces()[0].clone();
10730 mw.activate(workspace, window, cx);
10731 })
10732 .unwrap();
10733
10734 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10735
10736 // Workspace A has a clean item
10737 let item_a = cx.new(TestItem::new);
10738 workspace_a.update_in(cx, |w, window, cx| {
10739 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10740 });
10741
10742 // Workspace B has a dirty item
10743 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10744 workspace_b.update_in(cx, |w, window, cx| {
10745 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10746 });
10747
10748 // Verify workspace A is active
10749 multi_workspace_handle
10750 .read_with(cx, |mw, _| {
10751 assert_eq!(mw.active_workspace_index(), 0);
10752 })
10753 .unwrap();
10754
10755 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10756 multi_workspace_handle
10757 .update(cx, |mw, window, cx| {
10758 mw.close_window(&CloseWindow, window, cx);
10759 })
10760 .unwrap();
10761 cx.run_until_parked();
10762
10763 // Workspace B should now be active since it has dirty items that need attention
10764 multi_workspace_handle
10765 .read_with(cx, |mw, _| {
10766 assert_eq!(
10767 mw.active_workspace_index(),
10768 1,
10769 "workspace B should be activated when it prompts"
10770 );
10771 })
10772 .unwrap();
10773
10774 // User cancels the save prompt from workspace B
10775 cx.simulate_prompt_answer("Cancel");
10776 cx.run_until_parked();
10777
10778 // Window should still exist because workspace B's close was cancelled
10779 assert!(
10780 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10781 "window should still exist after cancelling one workspace's close"
10782 );
10783 }
10784
10785 #[gpui::test]
10786 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10787 init_test(cx);
10788
10789 // Register TestItem as a serializable item
10790 cx.update(|cx| {
10791 register_serializable_item::<TestItem>(cx);
10792 });
10793
10794 let fs = FakeFs::new(cx.executor());
10795 fs.insert_tree("/root", json!({ "one": "" })).await;
10796
10797 let project = Project::test(fs, ["root".as_ref()], cx).await;
10798 let (workspace, cx) =
10799 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10800
10801 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10802 let item1 = cx.new(|cx| {
10803 TestItem::new(cx)
10804 .with_dirty(true)
10805 .with_serialize(|| Some(Task::ready(Ok(()))))
10806 });
10807 let item2 = cx.new(|cx| {
10808 TestItem::new(cx)
10809 .with_dirty(true)
10810 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10811 .with_serialize(|| Some(Task::ready(Ok(()))))
10812 });
10813 workspace.update_in(cx, |w, window, cx| {
10814 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10815 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10816 });
10817 let task = workspace.update_in(cx, |w, window, cx| {
10818 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10819 });
10820 assert!(task.await.unwrap());
10821 }
10822
10823 #[gpui::test]
10824 async fn test_close_pane_items(cx: &mut TestAppContext) {
10825 init_test(cx);
10826
10827 let fs = FakeFs::new(cx.executor());
10828
10829 let project = Project::test(fs, None, cx).await;
10830 let (workspace, cx) =
10831 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10832
10833 let item1 = cx.new(|cx| {
10834 TestItem::new(cx)
10835 .with_dirty(true)
10836 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10837 });
10838 let item2 = cx.new(|cx| {
10839 TestItem::new(cx)
10840 .with_dirty(true)
10841 .with_conflict(true)
10842 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10843 });
10844 let item3 = cx.new(|cx| {
10845 TestItem::new(cx)
10846 .with_dirty(true)
10847 .with_conflict(true)
10848 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10849 });
10850 let item4 = cx.new(|cx| {
10851 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10852 let project_item = TestProjectItem::new_untitled(cx);
10853 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10854 project_item
10855 }])
10856 });
10857 let pane = workspace.update_in(cx, |workspace, window, cx| {
10858 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10859 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10860 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10861 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10862 workspace.active_pane().clone()
10863 });
10864
10865 let close_items = pane.update_in(cx, |pane, window, cx| {
10866 pane.activate_item(1, true, true, window, cx);
10867 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10868 let item1_id = item1.item_id();
10869 let item3_id = item3.item_id();
10870 let item4_id = item4.item_id();
10871 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10872 [item1_id, item3_id, item4_id].contains(&id)
10873 })
10874 });
10875 cx.executor().run_until_parked();
10876
10877 assert!(cx.has_pending_prompt());
10878 cx.simulate_prompt_answer("Save all");
10879
10880 cx.executor().run_until_parked();
10881
10882 // Item 1 is saved. There's a prompt to save item 3.
10883 pane.update(cx, |pane, cx| {
10884 assert_eq!(item1.read(cx).save_count, 1);
10885 assert_eq!(item1.read(cx).save_as_count, 0);
10886 assert_eq!(item1.read(cx).reload_count, 0);
10887 assert_eq!(pane.items_len(), 3);
10888 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10889 });
10890 assert!(cx.has_pending_prompt());
10891
10892 // Cancel saving item 3.
10893 cx.simulate_prompt_answer("Discard");
10894 cx.executor().run_until_parked();
10895
10896 // Item 3 is reloaded. There's a prompt to save item 4.
10897 pane.update(cx, |pane, cx| {
10898 assert_eq!(item3.read(cx).save_count, 0);
10899 assert_eq!(item3.read(cx).save_as_count, 0);
10900 assert_eq!(item3.read(cx).reload_count, 1);
10901 assert_eq!(pane.items_len(), 2);
10902 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10903 });
10904
10905 // There's a prompt for a path for item 4.
10906 cx.simulate_new_path_selection(|_| Some(Default::default()));
10907 close_items.await.unwrap();
10908
10909 // The requested items are closed.
10910 pane.update(cx, |pane, cx| {
10911 assert_eq!(item4.read(cx).save_count, 0);
10912 assert_eq!(item4.read(cx).save_as_count, 1);
10913 assert_eq!(item4.read(cx).reload_count, 0);
10914 assert_eq!(pane.items_len(), 1);
10915 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10916 });
10917 }
10918
10919 #[gpui::test]
10920 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10921 init_test(cx);
10922
10923 let fs = FakeFs::new(cx.executor());
10924 let project = Project::test(fs, [], cx).await;
10925 let (workspace, cx) =
10926 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10927
10928 // Create several workspace items with single project entries, and two
10929 // workspace items with multiple project entries.
10930 let single_entry_items = (0..=4)
10931 .map(|project_entry_id| {
10932 cx.new(|cx| {
10933 TestItem::new(cx)
10934 .with_dirty(true)
10935 .with_project_items(&[dirty_project_item(
10936 project_entry_id,
10937 &format!("{project_entry_id}.txt"),
10938 cx,
10939 )])
10940 })
10941 })
10942 .collect::<Vec<_>>();
10943 let item_2_3 = cx.new(|cx| {
10944 TestItem::new(cx)
10945 .with_dirty(true)
10946 .with_buffer_kind(ItemBufferKind::Multibuffer)
10947 .with_project_items(&[
10948 single_entry_items[2].read(cx).project_items[0].clone(),
10949 single_entry_items[3].read(cx).project_items[0].clone(),
10950 ])
10951 });
10952 let item_3_4 = cx.new(|cx| {
10953 TestItem::new(cx)
10954 .with_dirty(true)
10955 .with_buffer_kind(ItemBufferKind::Multibuffer)
10956 .with_project_items(&[
10957 single_entry_items[3].read(cx).project_items[0].clone(),
10958 single_entry_items[4].read(cx).project_items[0].clone(),
10959 ])
10960 });
10961
10962 // Create two panes that contain the following project entries:
10963 // left pane:
10964 // multi-entry items: (2, 3)
10965 // single-entry items: 0, 2, 3, 4
10966 // right pane:
10967 // single-entry items: 4, 1
10968 // multi-entry items: (3, 4)
10969 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10970 let left_pane = workspace.active_pane().clone();
10971 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10972 workspace.add_item_to_active_pane(
10973 single_entry_items[0].boxed_clone(),
10974 None,
10975 true,
10976 window,
10977 cx,
10978 );
10979 workspace.add_item_to_active_pane(
10980 single_entry_items[2].boxed_clone(),
10981 None,
10982 true,
10983 window,
10984 cx,
10985 );
10986 workspace.add_item_to_active_pane(
10987 single_entry_items[3].boxed_clone(),
10988 None,
10989 true,
10990 window,
10991 cx,
10992 );
10993 workspace.add_item_to_active_pane(
10994 single_entry_items[4].boxed_clone(),
10995 None,
10996 true,
10997 window,
10998 cx,
10999 );
11000
11001 let right_pane =
11002 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11003
11004 let boxed_clone = single_entry_items[1].boxed_clone();
11005 let right_pane = window.spawn(cx, async move |cx| {
11006 right_pane.await.inspect(|right_pane| {
11007 right_pane
11008 .update_in(cx, |pane, window, cx| {
11009 pane.add_item(boxed_clone, true, true, None, window, cx);
11010 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11011 })
11012 .unwrap();
11013 })
11014 });
11015
11016 (left_pane, right_pane)
11017 });
11018 let right_pane = right_pane.await.unwrap();
11019 cx.focus(&right_pane);
11020
11021 let close = right_pane.update_in(cx, |pane, window, cx| {
11022 pane.close_all_items(&CloseAllItems::default(), window, cx)
11023 .unwrap()
11024 });
11025 cx.executor().run_until_parked();
11026
11027 let msg = cx.pending_prompt().unwrap().0;
11028 assert!(msg.contains("1.txt"));
11029 assert!(!msg.contains("2.txt"));
11030 assert!(!msg.contains("3.txt"));
11031 assert!(!msg.contains("4.txt"));
11032
11033 // With best-effort close, cancelling item 1 keeps it open but items 4
11034 // and (3,4) still close since their entries exist in left pane.
11035 cx.simulate_prompt_answer("Cancel");
11036 close.await;
11037
11038 right_pane.read_with(cx, |pane, _| {
11039 assert_eq!(pane.items_len(), 1);
11040 });
11041
11042 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11043 left_pane
11044 .update_in(cx, |left_pane, window, cx| {
11045 left_pane.close_item_by_id(
11046 single_entry_items[3].entity_id(),
11047 SaveIntent::Skip,
11048 window,
11049 cx,
11050 )
11051 })
11052 .await
11053 .unwrap();
11054
11055 let close = left_pane.update_in(cx, |pane, window, cx| {
11056 pane.close_all_items(&CloseAllItems::default(), window, cx)
11057 .unwrap()
11058 });
11059 cx.executor().run_until_parked();
11060
11061 let details = cx.pending_prompt().unwrap().1;
11062 assert!(details.contains("0.txt"));
11063 assert!(details.contains("3.txt"));
11064 assert!(details.contains("4.txt"));
11065 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11066 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11067 // assert!(!details.contains("2.txt"));
11068
11069 cx.simulate_prompt_answer("Save all");
11070 cx.executor().run_until_parked();
11071 close.await;
11072
11073 left_pane.read_with(cx, |pane, _| {
11074 assert_eq!(pane.items_len(), 0);
11075 });
11076 }
11077
11078 #[gpui::test]
11079 async fn test_autosave(cx: &mut gpui::TestAppContext) {
11080 init_test(cx);
11081
11082 let fs = FakeFs::new(cx.executor());
11083 let project = Project::test(fs, [], cx).await;
11084 let (workspace, cx) =
11085 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11086 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11087
11088 let item = cx.new(|cx| {
11089 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11090 });
11091 let item_id = item.entity_id();
11092 workspace.update_in(cx, |workspace, window, cx| {
11093 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11094 });
11095
11096 // Autosave on window change.
11097 item.update(cx, |item, cx| {
11098 SettingsStore::update_global(cx, |settings, cx| {
11099 settings.update_user_settings(cx, |settings| {
11100 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11101 })
11102 });
11103 item.is_dirty = true;
11104 });
11105
11106 // Deactivating the window saves the file.
11107 cx.deactivate_window();
11108 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11109
11110 // Re-activating the window doesn't save the file.
11111 cx.update(|window, _| window.activate_window());
11112 cx.executor().run_until_parked();
11113 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11114
11115 // Autosave on focus change.
11116 item.update_in(cx, |item, window, cx| {
11117 cx.focus_self(window);
11118 SettingsStore::update_global(cx, |settings, cx| {
11119 settings.update_user_settings(cx, |settings| {
11120 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11121 })
11122 });
11123 item.is_dirty = true;
11124 });
11125 // Blurring the item saves the file.
11126 item.update_in(cx, |_, window, _| window.blur());
11127 cx.executor().run_until_parked();
11128 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11129
11130 // Deactivating the window still saves the file.
11131 item.update_in(cx, |item, window, cx| {
11132 cx.focus_self(window);
11133 item.is_dirty = true;
11134 });
11135 cx.deactivate_window();
11136 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11137
11138 // Autosave after delay.
11139 item.update(cx, |item, cx| {
11140 SettingsStore::update_global(cx, |settings, cx| {
11141 settings.update_user_settings(cx, |settings| {
11142 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11143 milliseconds: 500.into(),
11144 });
11145 })
11146 });
11147 item.is_dirty = true;
11148 cx.emit(ItemEvent::Edit);
11149 });
11150
11151 // Delay hasn't fully expired, so the file is still dirty and unsaved.
11152 cx.executor().advance_clock(Duration::from_millis(250));
11153 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11154
11155 // After delay expires, the file is saved.
11156 cx.executor().advance_clock(Duration::from_millis(250));
11157 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11158
11159 // Autosave after delay, should save earlier than delay if tab is closed
11160 item.update(cx, |item, cx| {
11161 item.is_dirty = true;
11162 cx.emit(ItemEvent::Edit);
11163 });
11164 cx.executor().advance_clock(Duration::from_millis(250));
11165 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11166
11167 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11168 pane.update_in(cx, |pane, window, cx| {
11169 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11170 })
11171 .await
11172 .unwrap();
11173 assert!(!cx.has_pending_prompt());
11174 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11175
11176 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11177 workspace.update_in(cx, |workspace, window, cx| {
11178 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11179 });
11180 item.update_in(cx, |item, _window, cx| {
11181 item.is_dirty = true;
11182 for project_item in &mut item.project_items {
11183 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11184 }
11185 });
11186 cx.run_until_parked();
11187 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11188
11189 // Autosave on focus change, ensuring closing the tab counts as such.
11190 item.update(cx, |item, cx| {
11191 SettingsStore::update_global(cx, |settings, cx| {
11192 settings.update_user_settings(cx, |settings| {
11193 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11194 })
11195 });
11196 item.is_dirty = true;
11197 for project_item in &mut item.project_items {
11198 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11199 }
11200 });
11201
11202 pane.update_in(cx, |pane, window, cx| {
11203 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11204 })
11205 .await
11206 .unwrap();
11207 assert!(!cx.has_pending_prompt());
11208 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11209
11210 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11211 workspace.update_in(cx, |workspace, window, cx| {
11212 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11213 });
11214 item.update_in(cx, |item, window, cx| {
11215 item.project_items[0].update(cx, |item, _| {
11216 item.entry_id = None;
11217 });
11218 item.is_dirty = true;
11219 window.blur();
11220 });
11221 cx.run_until_parked();
11222 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11223
11224 // Ensure autosave is prevented for deleted files also when closing the buffer.
11225 let _close_items = pane.update_in(cx, |pane, window, cx| {
11226 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11227 });
11228 cx.run_until_parked();
11229 assert!(cx.has_pending_prompt());
11230 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11231 }
11232
11233 #[gpui::test]
11234 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11235 init_test(cx);
11236
11237 let fs = FakeFs::new(cx.executor());
11238 let project = Project::test(fs, [], cx).await;
11239 let (workspace, cx) =
11240 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11241
11242 // Create a multibuffer-like item with two child focus handles,
11243 // simulating individual buffer editors within a multibuffer.
11244 let item = cx.new(|cx| {
11245 TestItem::new(cx)
11246 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11247 .with_child_focus_handles(2, cx)
11248 });
11249 workspace.update_in(cx, |workspace, window, cx| {
11250 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11251 });
11252
11253 // Set autosave to OnFocusChange and focus the first child handle,
11254 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11255 item.update_in(cx, |item, window, cx| {
11256 SettingsStore::update_global(cx, |settings, cx| {
11257 settings.update_user_settings(cx, |settings| {
11258 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11259 })
11260 });
11261 item.is_dirty = true;
11262 window.focus(&item.child_focus_handles[0], cx);
11263 });
11264 cx.executor().run_until_parked();
11265 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11266
11267 // Moving focus from one child to another within the same item should
11268 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11269 item.update_in(cx, |item, window, cx| {
11270 window.focus(&item.child_focus_handles[1], cx);
11271 });
11272 cx.executor().run_until_parked();
11273 item.read_with(cx, |item, _| {
11274 assert_eq!(
11275 item.save_count, 0,
11276 "Switching focus between children within the same item should not autosave"
11277 );
11278 });
11279
11280 // Blurring the item saves the file. This is the core regression scenario:
11281 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11282 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11283 // the leaf is always a child focus handle, so `on_blur` never detected
11284 // focus leaving the item.
11285 item.update_in(cx, |_, window, _| window.blur());
11286 cx.executor().run_until_parked();
11287 item.read_with(cx, |item, _| {
11288 assert_eq!(
11289 item.save_count, 1,
11290 "Blurring should trigger autosave when focus was on a child of the item"
11291 );
11292 });
11293
11294 // Deactivating the window should also trigger autosave when a child of
11295 // the multibuffer item currently owns focus.
11296 item.update_in(cx, |item, window, cx| {
11297 item.is_dirty = true;
11298 window.focus(&item.child_focus_handles[0], cx);
11299 });
11300 cx.executor().run_until_parked();
11301 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11302
11303 cx.deactivate_window();
11304 item.read_with(cx, |item, _| {
11305 assert_eq!(
11306 item.save_count, 2,
11307 "Deactivating window should trigger autosave when focus was on a child"
11308 );
11309 });
11310 }
11311
11312 #[gpui::test]
11313 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11314 init_test(cx);
11315
11316 let fs = FakeFs::new(cx.executor());
11317
11318 let project = Project::test(fs, [], cx).await;
11319 let (workspace, cx) =
11320 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11321
11322 let item = cx.new(|cx| {
11323 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11324 });
11325 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11326 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11327 let toolbar_notify_count = Rc::new(RefCell::new(0));
11328
11329 workspace.update_in(cx, |workspace, window, cx| {
11330 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11331 let toolbar_notification_count = toolbar_notify_count.clone();
11332 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11333 *toolbar_notification_count.borrow_mut() += 1
11334 })
11335 .detach();
11336 });
11337
11338 pane.read_with(cx, |pane, _| {
11339 assert!(!pane.can_navigate_backward());
11340 assert!(!pane.can_navigate_forward());
11341 });
11342
11343 item.update_in(cx, |item, _, cx| {
11344 item.set_state("one".to_string(), cx);
11345 });
11346
11347 // Toolbar must be notified to re-render the navigation buttons
11348 assert_eq!(*toolbar_notify_count.borrow(), 1);
11349
11350 pane.read_with(cx, |pane, _| {
11351 assert!(pane.can_navigate_backward());
11352 assert!(!pane.can_navigate_forward());
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 assert_eq!(*toolbar_notify_count.borrow(), 2);
11363 pane.read_with(cx, |pane, _| {
11364 assert!(!pane.can_navigate_backward());
11365 assert!(pane.can_navigate_forward());
11366 });
11367 }
11368
11369 /// Tests that the navigation history deduplicates entries for the same item.
11370 ///
11371 /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11372 /// the navigation history deduplicates by keeping only the most recent visit to each item,
11373 /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11374 /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11375 /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11376 ///
11377 /// This behavior prevents the navigation history from growing unnecessarily large and provides
11378 /// a better user experience by eliminating redundant navigation steps when jumping between files.
11379 #[gpui::test]
11380 async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11381 init_test(cx);
11382
11383 let fs = FakeFs::new(cx.executor());
11384 let project = Project::test(fs, [], cx).await;
11385 let (workspace, cx) =
11386 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11387
11388 let item_a = cx.new(|cx| {
11389 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11390 });
11391 let item_b = cx.new(|cx| {
11392 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11393 });
11394 let item_c = cx.new(|cx| {
11395 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11396 });
11397
11398 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11399
11400 workspace.update_in(cx, |workspace, window, cx| {
11401 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11402 workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11403 workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11404 });
11405
11406 workspace.update_in(cx, |workspace, window, cx| {
11407 workspace.activate_item(&item_a, false, false, window, cx);
11408 });
11409 cx.run_until_parked();
11410
11411 workspace.update_in(cx, |workspace, window, cx| {
11412 workspace.activate_item(&item_b, false, false, window, cx);
11413 });
11414 cx.run_until_parked();
11415
11416 workspace.update_in(cx, |workspace, window, cx| {
11417 workspace.activate_item(&item_a, false, false, window, cx);
11418 });
11419 cx.run_until_parked();
11420
11421 workspace.update_in(cx, |workspace, window, cx| {
11422 workspace.activate_item(&item_b, false, false, window, cx);
11423 });
11424 cx.run_until_parked();
11425
11426 workspace.update_in(cx, |workspace, window, cx| {
11427 workspace.activate_item(&item_a, false, false, window, cx);
11428 });
11429 cx.run_until_parked();
11430
11431 workspace.update_in(cx, |workspace, window, cx| {
11432 workspace.activate_item(&item_b, false, false, window, cx);
11433 });
11434 cx.run_until_parked();
11435
11436 workspace.update_in(cx, |workspace, window, cx| {
11437 workspace.activate_item(&item_c, false, false, window, cx);
11438 });
11439 cx.run_until_parked();
11440
11441 let backward_count = pane.read_with(cx, |pane, cx| {
11442 let mut count = 0;
11443 pane.nav_history().for_each_entry(cx, &mut |_, _| {
11444 count += 1;
11445 });
11446 count
11447 });
11448 assert!(
11449 backward_count <= 4,
11450 "Should have at most 4 entries, got {}",
11451 backward_count
11452 );
11453
11454 workspace
11455 .update_in(cx, |workspace, window, cx| {
11456 workspace.go_back(pane.downgrade(), window, cx)
11457 })
11458 .await
11459 .unwrap();
11460
11461 let active_item = workspace.read_with(cx, |workspace, cx| {
11462 workspace.active_item(cx).unwrap().item_id()
11463 });
11464 assert_eq!(
11465 active_item,
11466 item_b.entity_id(),
11467 "After first go_back, should be at item B"
11468 );
11469
11470 workspace
11471 .update_in(cx, |workspace, window, cx| {
11472 workspace.go_back(pane.downgrade(), window, cx)
11473 })
11474 .await
11475 .unwrap();
11476
11477 let active_item = workspace.read_with(cx, |workspace, cx| {
11478 workspace.active_item(cx).unwrap().item_id()
11479 });
11480 assert_eq!(
11481 active_item,
11482 item_a.entity_id(),
11483 "After second go_back, should be at item A"
11484 );
11485
11486 pane.read_with(cx, |pane, _| {
11487 assert!(pane.can_navigate_forward(), "Should be able to go forward");
11488 });
11489 }
11490
11491 #[gpui::test]
11492 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11493 init_test(cx);
11494 let fs = FakeFs::new(cx.executor());
11495 let project = Project::test(fs, [], cx).await;
11496 let (multi_workspace, cx) =
11497 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11498 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11499
11500 workspace.update_in(cx, |workspace, window, cx| {
11501 let first_item = cx.new(|cx| {
11502 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11503 });
11504 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11505 workspace.split_pane(
11506 workspace.active_pane().clone(),
11507 SplitDirection::Right,
11508 window,
11509 cx,
11510 );
11511 workspace.split_pane(
11512 workspace.active_pane().clone(),
11513 SplitDirection::Right,
11514 window,
11515 cx,
11516 );
11517 });
11518
11519 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11520 let panes = workspace.center.panes();
11521 assert!(panes.len() >= 2);
11522 (
11523 panes.first().expect("at least one pane").entity_id(),
11524 panes.last().expect("at least one pane").entity_id(),
11525 )
11526 });
11527
11528 workspace.update_in(cx, |workspace, window, cx| {
11529 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11530 });
11531 workspace.update(cx, |workspace, _| {
11532 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11533 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11534 });
11535
11536 cx.dispatch_action(ActivateLastPane);
11537
11538 workspace.update(cx, |workspace, _| {
11539 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11540 });
11541 }
11542
11543 #[gpui::test]
11544 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11545 init_test(cx);
11546 let fs = FakeFs::new(cx.executor());
11547
11548 let project = Project::test(fs, [], cx).await;
11549 let (workspace, cx) =
11550 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11551
11552 let panel = workspace.update_in(cx, |workspace, window, cx| {
11553 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11554 workspace.add_panel(panel.clone(), window, cx);
11555
11556 workspace
11557 .right_dock()
11558 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11559
11560 panel
11561 });
11562
11563 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11564 pane.update_in(cx, |pane, window, cx| {
11565 let item = cx.new(TestItem::new);
11566 pane.add_item(Box::new(item), true, true, None, window, cx);
11567 });
11568
11569 // Transfer focus from center to panel
11570 workspace.update_in(cx, |workspace, window, cx| {
11571 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11572 });
11573
11574 workspace.update_in(cx, |workspace, window, cx| {
11575 assert!(workspace.right_dock().read(cx).is_open());
11576 assert!(!panel.is_zoomed(window, cx));
11577 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11578 });
11579
11580 // Transfer focus from panel to center
11581 workspace.update_in(cx, |workspace, window, cx| {
11582 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11583 });
11584
11585 workspace.update_in(cx, |workspace, window, cx| {
11586 assert!(workspace.right_dock().read(cx).is_open());
11587 assert!(!panel.is_zoomed(window, cx));
11588 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11589 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11590 });
11591
11592 // Close the dock
11593 workspace.update_in(cx, |workspace, window, cx| {
11594 workspace.toggle_dock(DockPosition::Right, window, cx);
11595 });
11596
11597 workspace.update_in(cx, |workspace, window, cx| {
11598 assert!(!workspace.right_dock().read(cx).is_open());
11599 assert!(!panel.is_zoomed(window, cx));
11600 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11601 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11602 });
11603
11604 // Open the dock
11605 workspace.update_in(cx, |workspace, window, cx| {
11606 workspace.toggle_dock(DockPosition::Right, window, cx);
11607 });
11608
11609 workspace.update_in(cx, |workspace, window, cx| {
11610 assert!(workspace.right_dock().read(cx).is_open());
11611 assert!(!panel.is_zoomed(window, cx));
11612 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11613 });
11614
11615 // Focus and zoom panel
11616 panel.update_in(cx, |panel, window, cx| {
11617 cx.focus_self(window);
11618 panel.set_zoomed(true, window, cx)
11619 });
11620
11621 workspace.update_in(cx, |workspace, window, cx| {
11622 assert!(workspace.right_dock().read(cx).is_open());
11623 assert!(panel.is_zoomed(window, cx));
11624 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11625 });
11626
11627 // Transfer focus to the center closes the dock
11628 workspace.update_in(cx, |workspace, window, cx| {
11629 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11630 });
11631
11632 workspace.update_in(cx, |workspace, window, cx| {
11633 assert!(!workspace.right_dock().read(cx).is_open());
11634 assert!(panel.is_zoomed(window, cx));
11635 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11636 });
11637
11638 // Transferring focus back to the panel keeps it zoomed
11639 workspace.update_in(cx, |workspace, window, cx| {
11640 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11641 });
11642
11643 workspace.update_in(cx, |workspace, window, cx| {
11644 assert!(workspace.right_dock().read(cx).is_open());
11645 assert!(panel.is_zoomed(window, cx));
11646 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11647 });
11648
11649 // Close the dock while it is zoomed
11650 workspace.update_in(cx, |workspace, window, cx| {
11651 workspace.toggle_dock(DockPosition::Right, window, cx)
11652 });
11653
11654 workspace.update_in(cx, |workspace, window, cx| {
11655 assert!(!workspace.right_dock().read(cx).is_open());
11656 assert!(panel.is_zoomed(window, cx));
11657 assert!(workspace.zoomed.is_none());
11658 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11659 });
11660
11661 // Opening the dock, when it's zoomed, retains focus
11662 workspace.update_in(cx, |workspace, window, cx| {
11663 workspace.toggle_dock(DockPosition::Right, window, cx)
11664 });
11665
11666 workspace.update_in(cx, |workspace, window, cx| {
11667 assert!(workspace.right_dock().read(cx).is_open());
11668 assert!(panel.is_zoomed(window, cx));
11669 assert!(workspace.zoomed.is_some());
11670 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11671 });
11672
11673 // Unzoom and close the panel, zoom the active pane.
11674 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11675 workspace.update_in(cx, |workspace, window, cx| {
11676 workspace.toggle_dock(DockPosition::Right, window, cx)
11677 });
11678 pane.update_in(cx, |pane, window, cx| {
11679 pane.toggle_zoom(&Default::default(), window, cx)
11680 });
11681
11682 // Opening a dock unzooms the pane.
11683 workspace.update_in(cx, |workspace, window, cx| {
11684 workspace.toggle_dock(DockPosition::Right, window, cx)
11685 });
11686 workspace.update_in(cx, |workspace, window, cx| {
11687 let pane = pane.read(cx);
11688 assert!(!pane.is_zoomed());
11689 assert!(!pane.focus_handle(cx).is_focused(window));
11690 assert!(workspace.right_dock().read(cx).is_open());
11691 assert!(workspace.zoomed.is_none());
11692 });
11693 }
11694
11695 #[gpui::test]
11696 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11697 init_test(cx);
11698 let fs = FakeFs::new(cx.executor());
11699
11700 let project = Project::test(fs, [], cx).await;
11701 let (workspace, cx) =
11702 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11703
11704 let panel = workspace.update_in(cx, |workspace, window, cx| {
11705 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11706 workspace.add_panel(panel.clone(), window, cx);
11707 panel
11708 });
11709
11710 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11711 pane.update_in(cx, |pane, window, cx| {
11712 let item = cx.new(TestItem::new);
11713 pane.add_item(Box::new(item), true, true, None, window, cx);
11714 });
11715
11716 // Enable close_panel_on_toggle
11717 cx.update_global(|store: &mut SettingsStore, cx| {
11718 store.update_user_settings(cx, |settings| {
11719 settings.workspace.close_panel_on_toggle = Some(true);
11720 });
11721 });
11722
11723 // Panel starts closed. Toggling should open and focus it.
11724 workspace.update_in(cx, |workspace, window, cx| {
11725 assert!(!workspace.right_dock().read(cx).is_open());
11726 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11727 });
11728
11729 workspace.update_in(cx, |workspace, window, cx| {
11730 assert!(
11731 workspace.right_dock().read(cx).is_open(),
11732 "Dock should be open after toggling from center"
11733 );
11734 assert!(
11735 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11736 "Panel should be focused after toggling from center"
11737 );
11738 });
11739
11740 // Panel is open and focused. Toggling should close the panel and
11741 // return focus to the center.
11742 workspace.update_in(cx, |workspace, window, cx| {
11743 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11744 });
11745
11746 workspace.update_in(cx, |workspace, window, cx| {
11747 assert!(
11748 !workspace.right_dock().read(cx).is_open(),
11749 "Dock should be closed after toggling from focused panel"
11750 );
11751 assert!(
11752 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11753 "Panel should not be focused after toggling from focused panel"
11754 );
11755 });
11756
11757 // Open the dock and focus something else so the panel is open but not
11758 // focused. Toggling should focus the panel (not close it).
11759 workspace.update_in(cx, |workspace, window, cx| {
11760 workspace
11761 .right_dock()
11762 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11763 window.focus(&pane.read(cx).focus_handle(cx), cx);
11764 });
11765
11766 workspace.update_in(cx, |workspace, window, cx| {
11767 assert!(workspace.right_dock().read(cx).is_open());
11768 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11769 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11770 });
11771
11772 workspace.update_in(cx, |workspace, window, cx| {
11773 assert!(
11774 workspace.right_dock().read(cx).is_open(),
11775 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11776 );
11777 assert!(
11778 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11779 "Panel should be focused after toggling an open-but-unfocused panel"
11780 );
11781 });
11782
11783 // Now disable the setting and verify the original behavior: toggling
11784 // from a focused panel moves focus to center but leaves the dock open.
11785 cx.update_global(|store: &mut SettingsStore, cx| {
11786 store.update_user_settings(cx, |settings| {
11787 settings.workspace.close_panel_on_toggle = Some(false);
11788 });
11789 });
11790
11791 workspace.update_in(cx, |workspace, window, cx| {
11792 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11793 });
11794
11795 workspace.update_in(cx, |workspace, window, cx| {
11796 assert!(
11797 workspace.right_dock().read(cx).is_open(),
11798 "Dock should remain open when setting is disabled"
11799 );
11800 assert!(
11801 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11802 "Panel should not be focused after toggling with setting disabled"
11803 );
11804 });
11805 }
11806
11807 #[gpui::test]
11808 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11809 init_test(cx);
11810 let fs = FakeFs::new(cx.executor());
11811
11812 let project = Project::test(fs, [], cx).await;
11813 let (workspace, cx) =
11814 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11815
11816 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11817 workspace.active_pane().clone()
11818 });
11819
11820 // Add an item to the pane so it can be zoomed
11821 workspace.update_in(cx, |workspace, window, cx| {
11822 let item = cx.new(TestItem::new);
11823 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11824 });
11825
11826 // Initially not zoomed
11827 workspace.update_in(cx, |workspace, _window, cx| {
11828 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11829 assert!(
11830 workspace.zoomed.is_none(),
11831 "Workspace should track no zoomed pane"
11832 );
11833 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11834 });
11835
11836 // Zoom In
11837 pane.update_in(cx, |pane, window, cx| {
11838 pane.zoom_in(&crate::ZoomIn, window, cx);
11839 });
11840
11841 workspace.update_in(cx, |workspace, window, cx| {
11842 assert!(
11843 pane.read(cx).is_zoomed(),
11844 "Pane should be zoomed after ZoomIn"
11845 );
11846 assert!(
11847 workspace.zoomed.is_some(),
11848 "Workspace should track the zoomed pane"
11849 );
11850 assert!(
11851 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11852 "ZoomIn should focus the pane"
11853 );
11854 });
11855
11856 // Zoom In again is a no-op
11857 pane.update_in(cx, |pane, window, cx| {
11858 pane.zoom_in(&crate::ZoomIn, window, cx);
11859 });
11860
11861 workspace.update_in(cx, |workspace, window, cx| {
11862 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11863 assert!(
11864 workspace.zoomed.is_some(),
11865 "Workspace still tracks zoomed pane"
11866 );
11867 assert!(
11868 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11869 "Pane remains focused after repeated ZoomIn"
11870 );
11871 });
11872
11873 // Zoom Out
11874 pane.update_in(cx, |pane, window, cx| {
11875 pane.zoom_out(&crate::ZoomOut, window, cx);
11876 });
11877
11878 workspace.update_in(cx, |workspace, _window, cx| {
11879 assert!(
11880 !pane.read(cx).is_zoomed(),
11881 "Pane should unzoom after ZoomOut"
11882 );
11883 assert!(
11884 workspace.zoomed.is_none(),
11885 "Workspace clears zoom tracking after ZoomOut"
11886 );
11887 });
11888
11889 // Zoom Out again is a no-op
11890 pane.update_in(cx, |pane, window, cx| {
11891 pane.zoom_out(&crate::ZoomOut, window, cx);
11892 });
11893
11894 workspace.update_in(cx, |workspace, _window, cx| {
11895 assert!(
11896 !pane.read(cx).is_zoomed(),
11897 "Second ZoomOut keeps pane unzoomed"
11898 );
11899 assert!(
11900 workspace.zoomed.is_none(),
11901 "Workspace remains without zoomed pane"
11902 );
11903 });
11904 }
11905
11906 #[gpui::test]
11907 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11908 init_test(cx);
11909 let fs = FakeFs::new(cx.executor());
11910
11911 let project = Project::test(fs, [], cx).await;
11912 let (workspace, cx) =
11913 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11914 workspace.update_in(cx, |workspace, window, cx| {
11915 // Open two docks
11916 let left_dock = workspace.dock_at_position(DockPosition::Left);
11917 let right_dock = workspace.dock_at_position(DockPosition::Right);
11918
11919 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11920 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11921
11922 assert!(left_dock.read(cx).is_open());
11923 assert!(right_dock.read(cx).is_open());
11924 });
11925
11926 workspace.update_in(cx, |workspace, window, cx| {
11927 // Toggle all docks - should close both
11928 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11929
11930 let left_dock = workspace.dock_at_position(DockPosition::Left);
11931 let right_dock = workspace.dock_at_position(DockPosition::Right);
11932 assert!(!left_dock.read(cx).is_open());
11933 assert!(!right_dock.read(cx).is_open());
11934 });
11935
11936 workspace.update_in(cx, |workspace, window, cx| {
11937 // Toggle again - should reopen both
11938 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11939
11940 let left_dock = workspace.dock_at_position(DockPosition::Left);
11941 let right_dock = workspace.dock_at_position(DockPosition::Right);
11942 assert!(left_dock.read(cx).is_open());
11943 assert!(right_dock.read(cx).is_open());
11944 });
11945 }
11946
11947 #[gpui::test]
11948 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11949 init_test(cx);
11950 let fs = FakeFs::new(cx.executor());
11951
11952 let project = Project::test(fs, [], cx).await;
11953 let (workspace, cx) =
11954 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11955 workspace.update_in(cx, |workspace, window, cx| {
11956 // Open two docks
11957 let left_dock = workspace.dock_at_position(DockPosition::Left);
11958 let right_dock = workspace.dock_at_position(DockPosition::Right);
11959
11960 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11961 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11962
11963 assert!(left_dock.read(cx).is_open());
11964 assert!(right_dock.read(cx).is_open());
11965 });
11966
11967 workspace.update_in(cx, |workspace, window, cx| {
11968 // Close them manually
11969 workspace.toggle_dock(DockPosition::Left, window, cx);
11970 workspace.toggle_dock(DockPosition::Right, window, cx);
11971
11972 let left_dock = workspace.dock_at_position(DockPosition::Left);
11973 let right_dock = workspace.dock_at_position(DockPosition::Right);
11974 assert!(!left_dock.read(cx).is_open());
11975 assert!(!right_dock.read(cx).is_open());
11976 });
11977
11978 workspace.update_in(cx, |workspace, window, cx| {
11979 // Toggle all docks - only last closed (right dock) should reopen
11980 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11981
11982 let left_dock = workspace.dock_at_position(DockPosition::Left);
11983 let right_dock = workspace.dock_at_position(DockPosition::Right);
11984 assert!(!left_dock.read(cx).is_open());
11985 assert!(right_dock.read(cx).is_open());
11986 });
11987 }
11988
11989 #[gpui::test]
11990 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11991 init_test(cx);
11992 let fs = FakeFs::new(cx.executor());
11993 let project = Project::test(fs, [], cx).await;
11994 let (multi_workspace, cx) =
11995 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11996 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11997
11998 // Open two docks (left and right) with one panel each
11999 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12000 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12001 workspace.add_panel(left_panel.clone(), window, cx);
12002
12003 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12004 workspace.add_panel(right_panel.clone(), window, cx);
12005
12006 workspace.toggle_dock(DockPosition::Left, window, cx);
12007 workspace.toggle_dock(DockPosition::Right, window, cx);
12008
12009 // Verify initial state
12010 assert!(
12011 workspace.left_dock().read(cx).is_open(),
12012 "Left dock should be open"
12013 );
12014 assert_eq!(
12015 workspace
12016 .left_dock()
12017 .read(cx)
12018 .visible_panel()
12019 .unwrap()
12020 .panel_id(),
12021 left_panel.panel_id(),
12022 "Left panel should be visible in left dock"
12023 );
12024 assert!(
12025 workspace.right_dock().read(cx).is_open(),
12026 "Right dock should be open"
12027 );
12028 assert_eq!(
12029 workspace
12030 .right_dock()
12031 .read(cx)
12032 .visible_panel()
12033 .unwrap()
12034 .panel_id(),
12035 right_panel.panel_id(),
12036 "Right panel should be visible in right dock"
12037 );
12038 assert!(
12039 !workspace.bottom_dock().read(cx).is_open(),
12040 "Bottom dock should be closed"
12041 );
12042
12043 (left_panel, right_panel)
12044 });
12045
12046 // Focus the left panel and move it to the next position (bottom dock)
12047 workspace.update_in(cx, |workspace, window, cx| {
12048 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12049 assert!(
12050 left_panel.read(cx).focus_handle(cx).is_focused(window),
12051 "Left panel should be focused"
12052 );
12053 });
12054
12055 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12056
12057 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12058 workspace.update(cx, |workspace, cx| {
12059 assert!(
12060 !workspace.left_dock().read(cx).is_open(),
12061 "Left dock should be closed"
12062 );
12063 assert!(
12064 workspace.bottom_dock().read(cx).is_open(),
12065 "Bottom dock should now be open"
12066 );
12067 assert_eq!(
12068 left_panel.read(cx).position,
12069 DockPosition::Bottom,
12070 "Left panel should now be in the bottom dock"
12071 );
12072 assert_eq!(
12073 workspace
12074 .bottom_dock()
12075 .read(cx)
12076 .visible_panel()
12077 .unwrap()
12078 .panel_id(),
12079 left_panel.panel_id(),
12080 "Left panel should be the visible panel in the bottom dock"
12081 );
12082 });
12083
12084 // Toggle all docks off
12085 workspace.update_in(cx, |workspace, window, cx| {
12086 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12087 assert!(
12088 !workspace.left_dock().read(cx).is_open(),
12089 "Left dock should be closed"
12090 );
12091 assert!(
12092 !workspace.right_dock().read(cx).is_open(),
12093 "Right dock should be closed"
12094 );
12095 assert!(
12096 !workspace.bottom_dock().read(cx).is_open(),
12097 "Bottom dock should be closed"
12098 );
12099 });
12100
12101 // Toggle all docks back on and verify positions are restored
12102 workspace.update_in(cx, |workspace, window, cx| {
12103 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12104 assert!(
12105 !workspace.left_dock().read(cx).is_open(),
12106 "Left dock should remain closed"
12107 );
12108 assert!(
12109 workspace.right_dock().read(cx).is_open(),
12110 "Right dock should remain open"
12111 );
12112 assert!(
12113 workspace.bottom_dock().read(cx).is_open(),
12114 "Bottom dock should remain open"
12115 );
12116 assert_eq!(
12117 left_panel.read(cx).position,
12118 DockPosition::Bottom,
12119 "Left panel should remain in the bottom dock"
12120 );
12121 assert_eq!(
12122 right_panel.read(cx).position,
12123 DockPosition::Right,
12124 "Right panel should remain in the right dock"
12125 );
12126 assert_eq!(
12127 workspace
12128 .bottom_dock()
12129 .read(cx)
12130 .visible_panel()
12131 .unwrap()
12132 .panel_id(),
12133 left_panel.panel_id(),
12134 "Left panel should be the visible panel in the right dock"
12135 );
12136 });
12137 }
12138
12139 #[gpui::test]
12140 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12141 init_test(cx);
12142
12143 let fs = FakeFs::new(cx.executor());
12144
12145 let project = Project::test(fs, None, cx).await;
12146 let (workspace, cx) =
12147 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12148
12149 // Let's arrange the panes like this:
12150 //
12151 // +-----------------------+
12152 // | top |
12153 // +------+--------+-------+
12154 // | left | center | right |
12155 // +------+--------+-------+
12156 // | bottom |
12157 // +-----------------------+
12158
12159 let top_item = cx.new(|cx| {
12160 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12161 });
12162 let bottom_item = cx.new(|cx| {
12163 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12164 });
12165 let left_item = cx.new(|cx| {
12166 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12167 });
12168 let right_item = cx.new(|cx| {
12169 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12170 });
12171 let center_item = cx.new(|cx| {
12172 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12173 });
12174
12175 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12176 let top_pane_id = workspace.active_pane().entity_id();
12177 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12178 workspace.split_pane(
12179 workspace.active_pane().clone(),
12180 SplitDirection::Down,
12181 window,
12182 cx,
12183 );
12184 top_pane_id
12185 });
12186 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12187 let bottom_pane_id = workspace.active_pane().entity_id();
12188 workspace.add_item_to_active_pane(
12189 Box::new(bottom_item.clone()),
12190 None,
12191 false,
12192 window,
12193 cx,
12194 );
12195 workspace.split_pane(
12196 workspace.active_pane().clone(),
12197 SplitDirection::Up,
12198 window,
12199 cx,
12200 );
12201 bottom_pane_id
12202 });
12203 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12204 let left_pane_id = workspace.active_pane().entity_id();
12205 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12206 workspace.split_pane(
12207 workspace.active_pane().clone(),
12208 SplitDirection::Right,
12209 window,
12210 cx,
12211 );
12212 left_pane_id
12213 });
12214 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12215 let right_pane_id = workspace.active_pane().entity_id();
12216 workspace.add_item_to_active_pane(
12217 Box::new(right_item.clone()),
12218 None,
12219 false,
12220 window,
12221 cx,
12222 );
12223 workspace.split_pane(
12224 workspace.active_pane().clone(),
12225 SplitDirection::Left,
12226 window,
12227 cx,
12228 );
12229 right_pane_id
12230 });
12231 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12232 let center_pane_id = workspace.active_pane().entity_id();
12233 workspace.add_item_to_active_pane(
12234 Box::new(center_item.clone()),
12235 None,
12236 false,
12237 window,
12238 cx,
12239 );
12240 center_pane_id
12241 });
12242 cx.executor().run_until_parked();
12243
12244 workspace.update_in(cx, |workspace, window, cx| {
12245 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12246
12247 // Join into next from center pane into right
12248 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12249 });
12250
12251 workspace.update_in(cx, |workspace, window, cx| {
12252 let active_pane = workspace.active_pane();
12253 assert_eq!(right_pane_id, active_pane.entity_id());
12254 assert_eq!(2, active_pane.read(cx).items_len());
12255 let item_ids_in_pane =
12256 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12257 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12258 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12259
12260 // Join into next from right pane into bottom
12261 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12262 });
12263
12264 workspace.update_in(cx, |workspace, window, cx| {
12265 let active_pane = workspace.active_pane();
12266 assert_eq!(bottom_pane_id, active_pane.entity_id());
12267 assert_eq!(3, active_pane.read(cx).items_len());
12268 let item_ids_in_pane =
12269 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12270 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12271 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12272 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12273
12274 // Join into next from bottom pane into left
12275 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12276 });
12277
12278 workspace.update_in(cx, |workspace, window, cx| {
12279 let active_pane = workspace.active_pane();
12280 assert_eq!(left_pane_id, active_pane.entity_id());
12281 assert_eq!(4, active_pane.read(cx).items_len());
12282 let item_ids_in_pane =
12283 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12284 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12285 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12286 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12287 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12288
12289 // Join into next from left pane into top
12290 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12291 });
12292
12293 workspace.update_in(cx, |workspace, window, cx| {
12294 let active_pane = workspace.active_pane();
12295 assert_eq!(top_pane_id, active_pane.entity_id());
12296 assert_eq!(5, active_pane.read(cx).items_len());
12297 let item_ids_in_pane =
12298 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12299 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12300 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12301 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12302 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12303 assert!(item_ids_in_pane.contains(&top_item.item_id()));
12304
12305 // Single pane left: no-op
12306 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12307 });
12308
12309 workspace.update(cx, |workspace, _cx| {
12310 let active_pane = workspace.active_pane();
12311 assert_eq!(top_pane_id, active_pane.entity_id());
12312 });
12313 }
12314
12315 fn add_an_item_to_active_pane(
12316 cx: &mut VisualTestContext,
12317 workspace: &Entity<Workspace>,
12318 item_id: u64,
12319 ) -> Entity<TestItem> {
12320 let item = cx.new(|cx| {
12321 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12322 item_id,
12323 "item{item_id}.txt",
12324 cx,
12325 )])
12326 });
12327 workspace.update_in(cx, |workspace, window, cx| {
12328 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12329 });
12330 item
12331 }
12332
12333 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12334 workspace.update_in(cx, |workspace, window, cx| {
12335 workspace.split_pane(
12336 workspace.active_pane().clone(),
12337 SplitDirection::Right,
12338 window,
12339 cx,
12340 )
12341 })
12342 }
12343
12344 #[gpui::test]
12345 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12346 init_test(cx);
12347 let fs = FakeFs::new(cx.executor());
12348 let project = Project::test(fs, None, cx).await;
12349 let (workspace, cx) =
12350 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12351
12352 add_an_item_to_active_pane(cx, &workspace, 1);
12353 split_pane(cx, &workspace);
12354 add_an_item_to_active_pane(cx, &workspace, 2);
12355 split_pane(cx, &workspace); // empty pane
12356 split_pane(cx, &workspace);
12357 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12358
12359 cx.executor().run_until_parked();
12360
12361 workspace.update(cx, |workspace, cx| {
12362 let num_panes = workspace.panes().len();
12363 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12364 let active_item = workspace
12365 .active_pane()
12366 .read(cx)
12367 .active_item()
12368 .expect("item is in focus");
12369
12370 assert_eq!(num_panes, 4);
12371 assert_eq!(num_items_in_current_pane, 1);
12372 assert_eq!(active_item.item_id(), last_item.item_id());
12373 });
12374
12375 workspace.update_in(cx, |workspace, window, cx| {
12376 workspace.join_all_panes(window, cx);
12377 });
12378
12379 workspace.update(cx, |workspace, cx| {
12380 let num_panes = workspace.panes().len();
12381 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12382 let active_item = workspace
12383 .active_pane()
12384 .read(cx)
12385 .active_item()
12386 .expect("item is in focus");
12387
12388 assert_eq!(num_panes, 1);
12389 assert_eq!(num_items_in_current_pane, 3);
12390 assert_eq!(active_item.item_id(), last_item.item_id());
12391 });
12392 }
12393
12394 #[gpui::test]
12395 async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12396 init_test(cx);
12397 let fs = FakeFs::new(cx.executor());
12398
12399 let project = Project::test(fs, [], cx).await;
12400 let (multi_workspace, cx) =
12401 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12402 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12403
12404 workspace.update(cx, |workspace, _cx| {
12405 workspace.bounds.size.width = px(800.);
12406 });
12407
12408 workspace.update_in(cx, |workspace, window, cx| {
12409 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12410 workspace.add_panel(panel, window, cx);
12411 workspace.toggle_dock(DockPosition::Right, window, cx);
12412 });
12413
12414 let (panel, resized_width, ratio_basis_width) =
12415 workspace.update_in(cx, |workspace, window, cx| {
12416 let item = cx.new(|cx| {
12417 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12418 });
12419 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12420
12421 let dock = workspace.right_dock().read(cx);
12422 let workspace_width = workspace.bounds.size.width;
12423 let initial_width = workspace
12424 .dock_size(&dock, window, cx)
12425 .expect("flexible dock should have an initial width");
12426
12427 assert_eq!(initial_width, workspace_width / 2.);
12428
12429 workspace.resize_right_dock(px(300.), window, cx);
12430
12431 let dock = workspace.right_dock().read(cx);
12432 let resized_width = workspace
12433 .dock_size(&dock, window, cx)
12434 .expect("flexible dock should keep its resized width");
12435
12436 assert_eq!(resized_width, px(300.));
12437
12438 let panel = workspace
12439 .right_dock()
12440 .read(cx)
12441 .visible_panel()
12442 .expect("flexible dock should have a visible panel")
12443 .panel_id();
12444
12445 (panel, resized_width, workspace_width)
12446 });
12447
12448 workspace.update_in(cx, |workspace, window, cx| {
12449 workspace.toggle_dock(DockPosition::Right, window, cx);
12450 workspace.toggle_dock(DockPosition::Right, window, cx);
12451
12452 let dock = workspace.right_dock().read(cx);
12453 let reopened_width = workspace
12454 .dock_size(&dock, window, cx)
12455 .expect("flexible dock should restore when reopened");
12456
12457 assert_eq!(reopened_width, resized_width);
12458
12459 let right_dock = workspace.right_dock().read(cx);
12460 let flexible_panel = right_dock
12461 .visible_panel()
12462 .expect("flexible dock should still have a visible panel");
12463 assert_eq!(flexible_panel.panel_id(), panel);
12464 assert_eq!(
12465 right_dock
12466 .stored_panel_size_state(flexible_panel.as_ref())
12467 .and_then(|size_state| size_state.flex),
12468 Some(
12469 resized_width.to_f64() as f32
12470 / (workspace.bounds.size.width - resized_width).to_f64() as f32
12471 )
12472 );
12473 });
12474
12475 workspace.update_in(cx, |workspace, window, cx| {
12476 workspace.split_pane(
12477 workspace.active_pane().clone(),
12478 SplitDirection::Right,
12479 window,
12480 cx,
12481 );
12482
12483 let dock = workspace.right_dock().read(cx);
12484 let split_width = workspace
12485 .dock_size(&dock, window, cx)
12486 .expect("flexible dock should keep its user-resized proportion");
12487
12488 assert_eq!(split_width, px(300.));
12489
12490 workspace.bounds.size.width = px(1600.);
12491
12492 let dock = workspace.right_dock().read(cx);
12493 let resized_window_width = workspace
12494 .dock_size(&dock, window, cx)
12495 .expect("flexible dock should preserve proportional size on window resize");
12496
12497 assert_eq!(
12498 resized_window_width,
12499 workspace.bounds.size.width
12500 * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12501 );
12502 });
12503 }
12504
12505 #[gpui::test]
12506 async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12507 init_test(cx);
12508 let fs = FakeFs::new(cx.executor());
12509
12510 // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12511 {
12512 let project = Project::test(fs.clone(), [], cx).await;
12513 let (multi_workspace, cx) =
12514 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12515 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12516
12517 workspace.update(cx, |workspace, _cx| {
12518 workspace.set_random_database_id();
12519 workspace.bounds.size.width = px(800.);
12520 });
12521
12522 let panel = workspace.update_in(cx, |workspace, window, cx| {
12523 let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12524 workspace.add_panel(panel.clone(), window, cx);
12525 workspace.toggle_dock(DockPosition::Left, window, cx);
12526 panel
12527 });
12528
12529 workspace.update_in(cx, |workspace, window, cx| {
12530 workspace.resize_left_dock(px(350.), window, cx);
12531 });
12532
12533 cx.run_until_parked();
12534
12535 let persisted = workspace.read_with(cx, |workspace, cx| {
12536 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12537 });
12538 assert_eq!(
12539 persisted.and_then(|s| s.size),
12540 Some(px(350.)),
12541 "fixed-width panel size should be persisted to KVP"
12542 );
12543
12544 // Remove the panel and re-add a fresh instance with the same key.
12545 // The new instance should have its size state restored from KVP.
12546 workspace.update_in(cx, |workspace, window, cx| {
12547 workspace.remove_panel(&panel, window, cx);
12548 });
12549
12550 workspace.update_in(cx, |workspace, window, cx| {
12551 let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12552 workspace.add_panel(new_panel, window, cx);
12553
12554 let left_dock = workspace.left_dock().read(cx);
12555 let size_state = left_dock
12556 .panel::<TestPanel>()
12557 .and_then(|p| left_dock.stored_panel_size_state(&p));
12558 assert_eq!(
12559 size_state.and_then(|s| s.size),
12560 Some(px(350.)),
12561 "re-added fixed-width panel should restore persisted size from KVP"
12562 );
12563 });
12564 }
12565
12566 // Flexible panel: both pixel size and ratio are persisted and restored.
12567 {
12568 let project = Project::test(fs.clone(), [], cx).await;
12569 let (multi_workspace, cx) =
12570 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12571 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12572
12573 workspace.update(cx, |workspace, _cx| {
12574 workspace.set_random_database_id();
12575 workspace.bounds.size.width = px(800.);
12576 });
12577
12578 let panel = workspace.update_in(cx, |workspace, window, cx| {
12579 let item = cx.new(|cx| {
12580 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12581 });
12582 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12583
12584 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12585 workspace.add_panel(panel.clone(), window, cx);
12586 workspace.toggle_dock(DockPosition::Right, window, cx);
12587 panel
12588 });
12589
12590 workspace.update_in(cx, |workspace, window, cx| {
12591 workspace.resize_right_dock(px(300.), window, cx);
12592 });
12593
12594 cx.run_until_parked();
12595
12596 let persisted = workspace
12597 .read_with(cx, |workspace, cx| {
12598 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12599 })
12600 .expect("flexible panel state should be persisted to KVP");
12601 assert_eq!(
12602 persisted.size, None,
12603 "flexible panel should not persist a redundant pixel size"
12604 );
12605 let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12606
12607 // Remove the panel and re-add: both size and ratio should be restored.
12608 workspace.update_in(cx, |workspace, window, cx| {
12609 workspace.remove_panel(&panel, window, cx);
12610 });
12611
12612 workspace.update_in(cx, |workspace, window, cx| {
12613 let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12614 workspace.add_panel(new_panel, window, cx);
12615
12616 let right_dock = workspace.right_dock().read(cx);
12617 let size_state = right_dock
12618 .panel::<TestPanel>()
12619 .and_then(|p| right_dock.stored_panel_size_state(&p))
12620 .expect("re-added flexible panel should have restored size state from KVP");
12621 assert_eq!(
12622 size_state.size, None,
12623 "re-added flexible panel should not have a persisted pixel size"
12624 );
12625 assert_eq!(
12626 size_state.flex,
12627 Some(original_ratio),
12628 "re-added flexible panel should restore persisted flex"
12629 );
12630 });
12631 }
12632 }
12633
12634 #[gpui::test]
12635 async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12636 init_test(cx);
12637 let fs = FakeFs::new(cx.executor());
12638
12639 let project = Project::test(fs, [], cx).await;
12640 let (multi_workspace, cx) =
12641 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12642 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12643
12644 workspace.update(cx, |workspace, _cx| {
12645 workspace.bounds.size.width = px(900.);
12646 });
12647
12648 // Step 1: Add a tab to the center pane then open a flexible panel in the left
12649 // dock. With one full-width center pane the default ratio is 0.5, so the panel
12650 // and the center pane each take half the workspace width.
12651 workspace.update_in(cx, |workspace, window, cx| {
12652 let item = cx.new(|cx| {
12653 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12654 });
12655 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12656
12657 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12658 workspace.add_panel(panel, window, cx);
12659 workspace.toggle_dock(DockPosition::Left, window, cx);
12660
12661 let left_dock = workspace.left_dock().read(cx);
12662 let left_width = workspace
12663 .dock_size(&left_dock, window, cx)
12664 .expect("left dock should have an active panel");
12665
12666 assert_eq!(
12667 left_width,
12668 workspace.bounds.size.width / 2.,
12669 "flexible left panel should split evenly with the center pane"
12670 );
12671 });
12672
12673 // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12674 // change horizontal width fractions, so the flexible panel stays at the same
12675 // width as each half of the split.
12676 workspace.update_in(cx, |workspace, window, cx| {
12677 workspace.split_pane(
12678 workspace.active_pane().clone(),
12679 SplitDirection::Down,
12680 window,
12681 cx,
12682 );
12683
12684 let left_dock = workspace.left_dock().read(cx);
12685 let left_width = workspace
12686 .dock_size(&left_dock, window, cx)
12687 .expect("left dock should still have an active panel after vertical split");
12688
12689 assert_eq!(
12690 left_width,
12691 workspace.bounds.size.width / 2.,
12692 "flexible left panel width should match each vertically-split pane"
12693 );
12694 });
12695
12696 // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12697 // size reduces the available width, so the flexible left panel and the center
12698 // panes all shrink proportionally to accommodate it.
12699 workspace.update_in(cx, |workspace, window, cx| {
12700 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12701 workspace.add_panel(panel, window, cx);
12702 workspace.toggle_dock(DockPosition::Right, window, cx);
12703
12704 let right_dock = workspace.right_dock().read(cx);
12705 let right_width = workspace
12706 .dock_size(&right_dock, window, cx)
12707 .expect("right dock should have an active panel");
12708
12709 let left_dock = workspace.left_dock().read(cx);
12710 let left_width = workspace
12711 .dock_size(&left_dock, window, cx)
12712 .expect("left dock should still have an active panel");
12713
12714 let available_width = workspace.bounds.size.width - right_width;
12715 assert_eq!(
12716 left_width,
12717 available_width / 2.,
12718 "flexible left panel should shrink proportionally as the right dock takes space"
12719 );
12720 });
12721
12722 // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12723 // flex sizing and the workspace width is divided among left-flex, center
12724 // (implicit flex 1.0), and right-flex.
12725 workspace.update_in(cx, |workspace, window, cx| {
12726 let right_dock = workspace.right_dock().clone();
12727 let right_panel = right_dock
12728 .read(cx)
12729 .visible_panel()
12730 .expect("right dock should have a visible panel")
12731 .clone();
12732 workspace.toggle_dock_panel_flexible_size(
12733 &right_dock,
12734 right_panel.as_ref(),
12735 window,
12736 cx,
12737 );
12738
12739 let right_dock = right_dock.read(cx);
12740 let right_panel = right_dock
12741 .visible_panel()
12742 .expect("right dock should still have a visible panel");
12743 assert!(
12744 right_panel.has_flexible_size(window, cx),
12745 "right panel should now be flexible"
12746 );
12747
12748 let right_size_state = right_dock
12749 .stored_panel_size_state(right_panel.as_ref())
12750 .expect("right panel should have a stored size state after toggling");
12751 let right_flex = right_size_state
12752 .flex
12753 .expect("right panel should have a flex value after toggling");
12754
12755 let left_dock = workspace.left_dock().read(cx);
12756 let left_width = workspace
12757 .dock_size(&left_dock, window, cx)
12758 .expect("left dock should still have an active panel");
12759 let right_width = workspace
12760 .dock_size(&right_dock, window, cx)
12761 .expect("right dock should still have an active panel");
12762
12763 let left_flex = workspace
12764 .default_dock_flex(DockPosition::Left)
12765 .expect("left dock should have a default flex");
12766
12767 let total_flex = left_flex + 1.0 + right_flex;
12768 let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12769 let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12770 assert_eq!(
12771 left_width, expected_left,
12772 "flexible left panel should share workspace width via flex ratios"
12773 );
12774 assert_eq!(
12775 right_width, expected_right,
12776 "flexible right panel should share workspace width via flex ratios"
12777 );
12778 });
12779 }
12780
12781 struct TestModal(FocusHandle);
12782
12783 impl TestModal {
12784 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12785 Self(cx.focus_handle())
12786 }
12787 }
12788
12789 impl EventEmitter<DismissEvent> for TestModal {}
12790
12791 impl Focusable for TestModal {
12792 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12793 self.0.clone()
12794 }
12795 }
12796
12797 impl ModalView for TestModal {}
12798
12799 impl Render for TestModal {
12800 fn render(
12801 &mut self,
12802 _window: &mut Window,
12803 _cx: &mut Context<TestModal>,
12804 ) -> impl IntoElement {
12805 div().track_focus(&self.0)
12806 }
12807 }
12808
12809 #[gpui::test]
12810 async fn test_panels(cx: &mut gpui::TestAppContext) {
12811 init_test(cx);
12812 let fs = FakeFs::new(cx.executor());
12813
12814 let project = Project::test(fs, [], cx).await;
12815 let (multi_workspace, cx) =
12816 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12817 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12818
12819 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12820 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12821 workspace.add_panel(panel_1.clone(), window, cx);
12822 workspace.toggle_dock(DockPosition::Left, window, cx);
12823 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12824 workspace.add_panel(panel_2.clone(), window, cx);
12825 workspace.toggle_dock(DockPosition::Right, window, cx);
12826
12827 let left_dock = workspace.left_dock();
12828 assert_eq!(
12829 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12830 panel_1.panel_id()
12831 );
12832 assert_eq!(
12833 workspace.dock_size(&left_dock.read(cx), window, cx),
12834 Some(px(300.))
12835 );
12836
12837 workspace.resize_left_dock(px(1337.), window, cx);
12838 assert_eq!(
12839 workspace
12840 .right_dock()
12841 .read(cx)
12842 .visible_panel()
12843 .unwrap()
12844 .panel_id(),
12845 panel_2.panel_id(),
12846 );
12847
12848 (panel_1, panel_2)
12849 });
12850
12851 // Move panel_1 to the right
12852 panel_1.update_in(cx, |panel_1, window, cx| {
12853 panel_1.set_position(DockPosition::Right, window, cx)
12854 });
12855
12856 workspace.update_in(cx, |workspace, window, cx| {
12857 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12858 // Since it was the only panel on the left, the left dock should now be closed.
12859 assert!(!workspace.left_dock().read(cx).is_open());
12860 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12861 let right_dock = workspace.right_dock();
12862 assert_eq!(
12863 right_dock.read(cx).visible_panel().unwrap().panel_id(),
12864 panel_1.panel_id()
12865 );
12866 assert_eq!(
12867 right_dock
12868 .read(cx)
12869 .active_panel_size()
12870 .unwrap()
12871 .size
12872 .unwrap(),
12873 px(1337.)
12874 );
12875
12876 // Now we move panel_2 to the left
12877 panel_2.set_position(DockPosition::Left, window, cx);
12878 });
12879
12880 workspace.update(cx, |workspace, cx| {
12881 // Since panel_2 was not visible on the right, we don't open the left dock.
12882 assert!(!workspace.left_dock().read(cx).is_open());
12883 // And the right dock is unaffected in its displaying of panel_1
12884 assert!(workspace.right_dock().read(cx).is_open());
12885 assert_eq!(
12886 workspace
12887 .right_dock()
12888 .read(cx)
12889 .visible_panel()
12890 .unwrap()
12891 .panel_id(),
12892 panel_1.panel_id(),
12893 );
12894 });
12895
12896 // Move panel_1 back to the left
12897 panel_1.update_in(cx, |panel_1, window, cx| {
12898 panel_1.set_position(DockPosition::Left, window, cx)
12899 });
12900
12901 workspace.update_in(cx, |workspace, window, cx| {
12902 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12903 let left_dock = workspace.left_dock();
12904 assert!(left_dock.read(cx).is_open());
12905 assert_eq!(
12906 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12907 panel_1.panel_id()
12908 );
12909 assert_eq!(
12910 workspace.dock_size(&left_dock.read(cx), window, cx),
12911 Some(px(1337.))
12912 );
12913 // And the right dock should be closed as it no longer has any panels.
12914 assert!(!workspace.right_dock().read(cx).is_open());
12915
12916 // Now we move panel_1 to the bottom
12917 panel_1.set_position(DockPosition::Bottom, window, cx);
12918 });
12919
12920 workspace.update_in(cx, |workspace, window, cx| {
12921 // Since panel_1 was visible on the left, we close the left dock.
12922 assert!(!workspace.left_dock().read(cx).is_open());
12923 // The bottom dock is sized based on the panel's default size,
12924 // since the panel orientation changed from vertical to horizontal.
12925 let bottom_dock = workspace.bottom_dock();
12926 assert_eq!(
12927 workspace.dock_size(&bottom_dock.read(cx), window, cx),
12928 Some(px(300.))
12929 );
12930 // Close bottom dock and move panel_1 back to the left.
12931 bottom_dock.update(cx, |bottom_dock, cx| {
12932 bottom_dock.set_open(false, window, cx)
12933 });
12934 panel_1.set_position(DockPosition::Left, window, cx);
12935 });
12936
12937 // Emit activated event on panel 1
12938 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12939
12940 // Now the left dock is open and panel_1 is active and focused.
12941 workspace.update_in(cx, |workspace, window, cx| {
12942 let left_dock = workspace.left_dock();
12943 assert!(left_dock.read(cx).is_open());
12944 assert_eq!(
12945 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12946 panel_1.panel_id(),
12947 );
12948 assert!(panel_1.focus_handle(cx).is_focused(window));
12949 });
12950
12951 // Emit closed event on panel 2, which is not active
12952 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12953
12954 // Wo don't close the left dock, because panel_2 wasn't the active panel
12955 workspace.update(cx, |workspace, cx| {
12956 let left_dock = workspace.left_dock();
12957 assert!(left_dock.read(cx).is_open());
12958 assert_eq!(
12959 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12960 panel_1.panel_id(),
12961 );
12962 });
12963
12964 // Emitting a ZoomIn event shows the panel as zoomed.
12965 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12966 workspace.read_with(cx, |workspace, _| {
12967 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12968 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12969 });
12970
12971 // Move panel to another dock while it is zoomed
12972 panel_1.update_in(cx, |panel, window, cx| {
12973 panel.set_position(DockPosition::Right, window, cx)
12974 });
12975 workspace.read_with(cx, |workspace, _| {
12976 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12977
12978 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12979 });
12980
12981 // This is a helper for getting a:
12982 // - valid focus on an element,
12983 // - that isn't a part of the panes and panels system of the Workspace,
12984 // - and doesn't trigger the 'on_focus_lost' API.
12985 let focus_other_view = {
12986 let workspace = workspace.clone();
12987 move |cx: &mut VisualTestContext| {
12988 workspace.update_in(cx, |workspace, window, cx| {
12989 if workspace.active_modal::<TestModal>(cx).is_some() {
12990 workspace.toggle_modal(window, cx, TestModal::new);
12991 workspace.toggle_modal(window, cx, TestModal::new);
12992 } else {
12993 workspace.toggle_modal(window, cx, TestModal::new);
12994 }
12995 })
12996 }
12997 };
12998
12999 // If focus is transferred to another view that's not a panel or another pane, we still show
13000 // the panel as zoomed.
13001 focus_other_view(cx);
13002 workspace.read_with(cx, |workspace, _| {
13003 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13004 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13005 });
13006
13007 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13008 workspace.update_in(cx, |_workspace, window, cx| {
13009 cx.focus_self(window);
13010 });
13011 workspace.read_with(cx, |workspace, _| {
13012 assert_eq!(workspace.zoomed, None);
13013 assert_eq!(workspace.zoomed_position, None);
13014 });
13015
13016 // If focus is transferred again to another view that's not a panel or a pane, we won't
13017 // show the panel as zoomed because it wasn't zoomed before.
13018 focus_other_view(cx);
13019 workspace.read_with(cx, |workspace, _| {
13020 assert_eq!(workspace.zoomed, None);
13021 assert_eq!(workspace.zoomed_position, None);
13022 });
13023
13024 // When the panel is activated, it is zoomed again.
13025 cx.dispatch_action(ToggleRightDock);
13026 workspace.read_with(cx, |workspace, _| {
13027 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13028 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13029 });
13030
13031 // Emitting a ZoomOut event unzooms the panel.
13032 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13033 workspace.read_with(cx, |workspace, _| {
13034 assert_eq!(workspace.zoomed, None);
13035 assert_eq!(workspace.zoomed_position, None);
13036 });
13037
13038 // Emit closed event on panel 1, which is active
13039 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13040
13041 // Now the left dock is closed, because panel_1 was the active panel
13042 workspace.update(cx, |workspace, cx| {
13043 let right_dock = workspace.right_dock();
13044 assert!(!right_dock.read(cx).is_open());
13045 });
13046 }
13047
13048 #[gpui::test]
13049 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13050 init_test(cx);
13051
13052 let fs = FakeFs::new(cx.background_executor.clone());
13053 let project = Project::test(fs, [], cx).await;
13054 let (workspace, cx) =
13055 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13056 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13057
13058 let dirty_regular_buffer = cx.new(|cx| {
13059 TestItem::new(cx)
13060 .with_dirty(true)
13061 .with_label("1.txt")
13062 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13063 });
13064 let dirty_regular_buffer_2 = cx.new(|cx| {
13065 TestItem::new(cx)
13066 .with_dirty(true)
13067 .with_label("2.txt")
13068 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13069 });
13070 let dirty_multi_buffer_with_both = cx.new(|cx| {
13071 TestItem::new(cx)
13072 .with_dirty(true)
13073 .with_buffer_kind(ItemBufferKind::Multibuffer)
13074 .with_label("Fake Project Search")
13075 .with_project_items(&[
13076 dirty_regular_buffer.read(cx).project_items[0].clone(),
13077 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13078 ])
13079 });
13080 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13081 workspace.update_in(cx, |workspace, window, cx| {
13082 workspace.add_item(
13083 pane.clone(),
13084 Box::new(dirty_regular_buffer.clone()),
13085 None,
13086 false,
13087 false,
13088 window,
13089 cx,
13090 );
13091 workspace.add_item(
13092 pane.clone(),
13093 Box::new(dirty_regular_buffer_2.clone()),
13094 None,
13095 false,
13096 false,
13097 window,
13098 cx,
13099 );
13100 workspace.add_item(
13101 pane.clone(),
13102 Box::new(dirty_multi_buffer_with_both.clone()),
13103 None,
13104 false,
13105 false,
13106 window,
13107 cx,
13108 );
13109 });
13110
13111 pane.update_in(cx, |pane, window, cx| {
13112 pane.activate_item(2, true, true, window, cx);
13113 assert_eq!(
13114 pane.active_item().unwrap().item_id(),
13115 multi_buffer_with_both_files_id,
13116 "Should select the multi buffer in the pane"
13117 );
13118 });
13119 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13120 pane.close_other_items(
13121 &CloseOtherItems {
13122 save_intent: Some(SaveIntent::Save),
13123 close_pinned: true,
13124 },
13125 None,
13126 window,
13127 cx,
13128 )
13129 });
13130 cx.background_executor.run_until_parked();
13131 assert!(!cx.has_pending_prompt());
13132 close_all_but_multi_buffer_task
13133 .await
13134 .expect("Closing all buffers but the multi buffer failed");
13135 pane.update(cx, |pane, cx| {
13136 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13137 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13138 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13139 assert_eq!(pane.items_len(), 1);
13140 assert_eq!(
13141 pane.active_item().unwrap().item_id(),
13142 multi_buffer_with_both_files_id,
13143 "Should have only the multi buffer left in the pane"
13144 );
13145 assert!(
13146 dirty_multi_buffer_with_both.read(cx).is_dirty,
13147 "The multi buffer containing the unsaved buffer should still be dirty"
13148 );
13149 });
13150
13151 dirty_regular_buffer.update(cx, |buffer, cx| {
13152 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13153 });
13154
13155 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13156 pane.close_active_item(
13157 &CloseActiveItem {
13158 save_intent: Some(SaveIntent::Close),
13159 close_pinned: false,
13160 },
13161 window,
13162 cx,
13163 )
13164 });
13165 cx.background_executor.run_until_parked();
13166 assert!(
13167 cx.has_pending_prompt(),
13168 "Dirty multi buffer should prompt a save dialog"
13169 );
13170 cx.simulate_prompt_answer("Save");
13171 cx.background_executor.run_until_parked();
13172 close_multi_buffer_task
13173 .await
13174 .expect("Closing the multi buffer failed");
13175 pane.update(cx, |pane, cx| {
13176 assert_eq!(
13177 dirty_multi_buffer_with_both.read(cx).save_count,
13178 1,
13179 "Multi buffer item should get be saved"
13180 );
13181 // Test impl does not save inner items, so we do not assert them
13182 assert_eq!(
13183 pane.items_len(),
13184 0,
13185 "No more items should be left in the pane"
13186 );
13187 assert!(pane.active_item().is_none());
13188 });
13189 }
13190
13191 #[gpui::test]
13192 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13193 cx: &mut TestAppContext,
13194 ) {
13195 init_test(cx);
13196
13197 let fs = FakeFs::new(cx.background_executor.clone());
13198 let project = Project::test(fs, [], cx).await;
13199 let (workspace, cx) =
13200 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13201 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13202
13203 let dirty_regular_buffer = cx.new(|cx| {
13204 TestItem::new(cx)
13205 .with_dirty(true)
13206 .with_label("1.txt")
13207 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13208 });
13209 let dirty_regular_buffer_2 = cx.new(|cx| {
13210 TestItem::new(cx)
13211 .with_dirty(true)
13212 .with_label("2.txt")
13213 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13214 });
13215 let clear_regular_buffer = cx.new(|cx| {
13216 TestItem::new(cx)
13217 .with_label("3.txt")
13218 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13219 });
13220
13221 let dirty_multi_buffer_with_both = cx.new(|cx| {
13222 TestItem::new(cx)
13223 .with_dirty(true)
13224 .with_buffer_kind(ItemBufferKind::Multibuffer)
13225 .with_label("Fake Project Search")
13226 .with_project_items(&[
13227 dirty_regular_buffer.read(cx).project_items[0].clone(),
13228 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13229 clear_regular_buffer.read(cx).project_items[0].clone(),
13230 ])
13231 });
13232 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13233 workspace.update_in(cx, |workspace, window, cx| {
13234 workspace.add_item(
13235 pane.clone(),
13236 Box::new(dirty_regular_buffer.clone()),
13237 None,
13238 false,
13239 false,
13240 window,
13241 cx,
13242 );
13243 workspace.add_item(
13244 pane.clone(),
13245 Box::new(dirty_multi_buffer_with_both.clone()),
13246 None,
13247 false,
13248 false,
13249 window,
13250 cx,
13251 );
13252 });
13253
13254 pane.update_in(cx, |pane, window, cx| {
13255 pane.activate_item(1, true, true, window, cx);
13256 assert_eq!(
13257 pane.active_item().unwrap().item_id(),
13258 multi_buffer_with_both_files_id,
13259 "Should select the multi buffer in the pane"
13260 );
13261 });
13262 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13263 pane.close_active_item(
13264 &CloseActiveItem {
13265 save_intent: None,
13266 close_pinned: false,
13267 },
13268 window,
13269 cx,
13270 )
13271 });
13272 cx.background_executor.run_until_parked();
13273 assert!(
13274 cx.has_pending_prompt(),
13275 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13276 );
13277 }
13278
13279 /// Tests that when `close_on_file_delete` is enabled, files are automatically
13280 /// closed when they are deleted from disk.
13281 #[gpui::test]
13282 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13283 init_test(cx);
13284
13285 // Enable the close_on_disk_deletion setting
13286 cx.update_global(|store: &mut SettingsStore, cx| {
13287 store.update_user_settings(cx, |settings| {
13288 settings.workspace.close_on_file_delete = Some(true);
13289 });
13290 });
13291
13292 let fs = FakeFs::new(cx.background_executor.clone());
13293 let project = Project::test(fs, [], cx).await;
13294 let (workspace, cx) =
13295 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13296 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13297
13298 // Create a test item that simulates a file
13299 let item = cx.new(|cx| {
13300 TestItem::new(cx)
13301 .with_label("test.txt")
13302 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13303 });
13304
13305 // Add item to workspace
13306 workspace.update_in(cx, |workspace, window, cx| {
13307 workspace.add_item(
13308 pane.clone(),
13309 Box::new(item.clone()),
13310 None,
13311 false,
13312 false,
13313 window,
13314 cx,
13315 );
13316 });
13317
13318 // Verify the item is in the pane
13319 pane.read_with(cx, |pane, _| {
13320 assert_eq!(pane.items().count(), 1);
13321 });
13322
13323 // Simulate file deletion by setting the item's deleted state
13324 item.update(cx, |item, _| {
13325 item.set_has_deleted_file(true);
13326 });
13327
13328 // Emit UpdateTab event to trigger the close behavior
13329 cx.run_until_parked();
13330 item.update(cx, |_, cx| {
13331 cx.emit(ItemEvent::UpdateTab);
13332 });
13333
13334 // Allow the close operation to complete
13335 cx.run_until_parked();
13336
13337 // Verify the item was automatically closed
13338 pane.read_with(cx, |pane, _| {
13339 assert_eq!(
13340 pane.items().count(),
13341 0,
13342 "Item should be automatically closed when file is deleted"
13343 );
13344 });
13345 }
13346
13347 /// Tests that when `close_on_file_delete` is disabled (default), files remain
13348 /// open with a strikethrough when they are deleted from disk.
13349 #[gpui::test]
13350 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13351 init_test(cx);
13352
13353 // Ensure close_on_disk_deletion is disabled (default)
13354 cx.update_global(|store: &mut SettingsStore, cx| {
13355 store.update_user_settings(cx, |settings| {
13356 settings.workspace.close_on_file_delete = Some(false);
13357 });
13358 });
13359
13360 let fs = FakeFs::new(cx.background_executor.clone());
13361 let project = Project::test(fs, [], cx).await;
13362 let (workspace, cx) =
13363 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13364 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13365
13366 // Create a test item that simulates a file
13367 let item = cx.new(|cx| {
13368 TestItem::new(cx)
13369 .with_label("test.txt")
13370 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13371 });
13372
13373 // Add item to workspace
13374 workspace.update_in(cx, |workspace, window, cx| {
13375 workspace.add_item(
13376 pane.clone(),
13377 Box::new(item.clone()),
13378 None,
13379 false,
13380 false,
13381 window,
13382 cx,
13383 );
13384 });
13385
13386 // Verify the item is in the pane
13387 pane.read_with(cx, |pane, _| {
13388 assert_eq!(pane.items().count(), 1);
13389 });
13390
13391 // Simulate file deletion
13392 item.update(cx, |item, _| {
13393 item.set_has_deleted_file(true);
13394 });
13395
13396 // Emit UpdateTab event
13397 cx.run_until_parked();
13398 item.update(cx, |_, cx| {
13399 cx.emit(ItemEvent::UpdateTab);
13400 });
13401
13402 // Allow any potential close operation to complete
13403 cx.run_until_parked();
13404
13405 // Verify the item remains open (with strikethrough)
13406 pane.read_with(cx, |pane, _| {
13407 assert_eq!(
13408 pane.items().count(),
13409 1,
13410 "Item should remain open when close_on_disk_deletion is disabled"
13411 );
13412 });
13413
13414 // Verify the item shows as deleted
13415 item.read_with(cx, |item, _| {
13416 assert!(
13417 item.has_deleted_file,
13418 "Item should be marked as having deleted file"
13419 );
13420 });
13421 }
13422
13423 /// Tests that dirty files are not automatically closed when deleted from disk,
13424 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13425 /// unsaved changes without being prompted.
13426 #[gpui::test]
13427 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13428 init_test(cx);
13429
13430 // Enable the close_on_file_delete setting
13431 cx.update_global(|store: &mut SettingsStore, cx| {
13432 store.update_user_settings(cx, |settings| {
13433 settings.workspace.close_on_file_delete = Some(true);
13434 });
13435 });
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 // Create a dirty test item
13444 let item = cx.new(|cx| {
13445 TestItem::new(cx)
13446 .with_dirty(true)
13447 .with_label("test.txt")
13448 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13449 });
13450
13451 // Add item to workspace
13452 workspace.update_in(cx, |workspace, window, cx| {
13453 workspace.add_item(
13454 pane.clone(),
13455 Box::new(item.clone()),
13456 None,
13457 false,
13458 false,
13459 window,
13460 cx,
13461 );
13462 });
13463
13464 // Simulate file deletion
13465 item.update(cx, |item, _| {
13466 item.set_has_deleted_file(true);
13467 });
13468
13469 // Emit UpdateTab event to trigger the close behavior
13470 cx.run_until_parked();
13471 item.update(cx, |_, cx| {
13472 cx.emit(ItemEvent::UpdateTab);
13473 });
13474
13475 // Allow any potential close operation to complete
13476 cx.run_until_parked();
13477
13478 // Verify the item remains open (dirty files are not auto-closed)
13479 pane.read_with(cx, |pane, _| {
13480 assert_eq!(
13481 pane.items().count(),
13482 1,
13483 "Dirty items should not be automatically closed even when file is deleted"
13484 );
13485 });
13486
13487 // Verify the item is marked as deleted and still dirty
13488 item.read_with(cx, |item, _| {
13489 assert!(
13490 item.has_deleted_file,
13491 "Item should be marked as having deleted file"
13492 );
13493 assert!(item.is_dirty, "Item should still be dirty");
13494 });
13495 }
13496
13497 /// Tests that navigation history is cleaned up when files are auto-closed
13498 /// due to deletion from disk.
13499 #[gpui::test]
13500 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13501 init_test(cx);
13502
13503 // Enable the close_on_file_delete setting
13504 cx.update_global(|store: &mut SettingsStore, cx| {
13505 store.update_user_settings(cx, |settings| {
13506 settings.workspace.close_on_file_delete = Some(true);
13507 });
13508 });
13509
13510 let fs = FakeFs::new(cx.background_executor.clone());
13511 let project = Project::test(fs, [], cx).await;
13512 let (workspace, cx) =
13513 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13514 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13515
13516 // Create test items
13517 let item1 = cx.new(|cx| {
13518 TestItem::new(cx)
13519 .with_label("test1.txt")
13520 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13521 });
13522 let item1_id = item1.item_id();
13523
13524 let item2 = cx.new(|cx| {
13525 TestItem::new(cx)
13526 .with_label("test2.txt")
13527 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13528 });
13529
13530 // Add items to workspace
13531 workspace.update_in(cx, |workspace, window, cx| {
13532 workspace.add_item(
13533 pane.clone(),
13534 Box::new(item1.clone()),
13535 None,
13536 false,
13537 false,
13538 window,
13539 cx,
13540 );
13541 workspace.add_item(
13542 pane.clone(),
13543 Box::new(item2.clone()),
13544 None,
13545 false,
13546 false,
13547 window,
13548 cx,
13549 );
13550 });
13551
13552 // Activate item1 to ensure it gets navigation entries
13553 pane.update_in(cx, |pane, window, cx| {
13554 pane.activate_item(0, true, true, window, cx);
13555 });
13556
13557 // Switch to item2 and back to create navigation history
13558 pane.update_in(cx, |pane, window, cx| {
13559 pane.activate_item(1, true, true, window, cx);
13560 });
13561 cx.run_until_parked();
13562
13563 pane.update_in(cx, |pane, window, cx| {
13564 pane.activate_item(0, true, true, window, cx);
13565 });
13566 cx.run_until_parked();
13567
13568 // Simulate file deletion for item1
13569 item1.update(cx, |item, _| {
13570 item.set_has_deleted_file(true);
13571 });
13572
13573 // Emit UpdateTab event to trigger the close behavior
13574 item1.update(cx, |_, cx| {
13575 cx.emit(ItemEvent::UpdateTab);
13576 });
13577 cx.run_until_parked();
13578
13579 // Verify item1 was closed
13580 pane.read_with(cx, |pane, _| {
13581 assert_eq!(
13582 pane.items().count(),
13583 1,
13584 "Should have 1 item remaining after auto-close"
13585 );
13586 });
13587
13588 // Check navigation history after close
13589 let has_item = pane.read_with(cx, |pane, cx| {
13590 let mut has_item = false;
13591 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13592 if entry.item.id() == item1_id {
13593 has_item = true;
13594 }
13595 });
13596 has_item
13597 });
13598
13599 assert!(
13600 !has_item,
13601 "Navigation history should not contain closed item entries"
13602 );
13603 }
13604
13605 #[gpui::test]
13606 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13607 cx: &mut TestAppContext,
13608 ) {
13609 init_test(cx);
13610
13611 let fs = FakeFs::new(cx.background_executor.clone());
13612 let project = Project::test(fs, [], cx).await;
13613 let (workspace, cx) =
13614 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13615 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13616
13617 let dirty_regular_buffer = cx.new(|cx| {
13618 TestItem::new(cx)
13619 .with_dirty(true)
13620 .with_label("1.txt")
13621 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13622 });
13623 let dirty_regular_buffer_2 = cx.new(|cx| {
13624 TestItem::new(cx)
13625 .with_dirty(true)
13626 .with_label("2.txt")
13627 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13628 });
13629 let clear_regular_buffer = cx.new(|cx| {
13630 TestItem::new(cx)
13631 .with_label("3.txt")
13632 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13633 });
13634
13635 let dirty_multi_buffer = cx.new(|cx| {
13636 TestItem::new(cx)
13637 .with_dirty(true)
13638 .with_buffer_kind(ItemBufferKind::Multibuffer)
13639 .with_label("Fake Project Search")
13640 .with_project_items(&[
13641 dirty_regular_buffer.read(cx).project_items[0].clone(),
13642 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13643 clear_regular_buffer.read(cx).project_items[0].clone(),
13644 ])
13645 });
13646 workspace.update_in(cx, |workspace, window, cx| {
13647 workspace.add_item(
13648 pane.clone(),
13649 Box::new(dirty_regular_buffer.clone()),
13650 None,
13651 false,
13652 false,
13653 window,
13654 cx,
13655 );
13656 workspace.add_item(
13657 pane.clone(),
13658 Box::new(dirty_regular_buffer_2.clone()),
13659 None,
13660 false,
13661 false,
13662 window,
13663 cx,
13664 );
13665 workspace.add_item(
13666 pane.clone(),
13667 Box::new(dirty_multi_buffer.clone()),
13668 None,
13669 false,
13670 false,
13671 window,
13672 cx,
13673 );
13674 });
13675
13676 pane.update_in(cx, |pane, window, cx| {
13677 pane.activate_item(2, true, true, window, cx);
13678 assert_eq!(
13679 pane.active_item().unwrap().item_id(),
13680 dirty_multi_buffer.item_id(),
13681 "Should select the multi buffer in the pane"
13682 );
13683 });
13684 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13685 pane.close_active_item(
13686 &CloseActiveItem {
13687 save_intent: None,
13688 close_pinned: false,
13689 },
13690 window,
13691 cx,
13692 )
13693 });
13694 cx.background_executor.run_until_parked();
13695 assert!(
13696 !cx.has_pending_prompt(),
13697 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13698 );
13699 close_multi_buffer_task
13700 .await
13701 .expect("Closing multi buffer failed");
13702 pane.update(cx, |pane, cx| {
13703 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13704 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13705 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13706 assert_eq!(
13707 pane.items()
13708 .map(|item| item.item_id())
13709 .sorted()
13710 .collect::<Vec<_>>(),
13711 vec![
13712 dirty_regular_buffer.item_id(),
13713 dirty_regular_buffer_2.item_id(),
13714 ],
13715 "Should have no multi buffer left in the pane"
13716 );
13717 assert!(dirty_regular_buffer.read(cx).is_dirty);
13718 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13719 });
13720 }
13721
13722 #[gpui::test]
13723 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13724 init_test(cx);
13725 let fs = FakeFs::new(cx.executor());
13726 let project = Project::test(fs, [], cx).await;
13727 let (multi_workspace, cx) =
13728 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13729 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13730
13731 // Add a new panel to the right dock, opening the dock and setting the
13732 // focus to the new panel.
13733 let panel = workspace.update_in(cx, |workspace, window, cx| {
13734 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13735 workspace.add_panel(panel.clone(), window, cx);
13736
13737 workspace
13738 .right_dock()
13739 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13740
13741 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13742
13743 panel
13744 });
13745
13746 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13747 // panel to the next valid position which, in this case, is the left
13748 // dock.
13749 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13750 workspace.update(cx, |workspace, cx| {
13751 assert!(workspace.left_dock().read(cx).is_open());
13752 assert_eq!(panel.read(cx).position, DockPosition::Left);
13753 });
13754
13755 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13756 // panel to the next valid position which, in this case, is the bottom
13757 // dock.
13758 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13759 workspace.update(cx, |workspace, cx| {
13760 assert!(workspace.bottom_dock().read(cx).is_open());
13761 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13762 });
13763
13764 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13765 // around moving the panel to its initial position, the right dock.
13766 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13767 workspace.update(cx, |workspace, cx| {
13768 assert!(workspace.right_dock().read(cx).is_open());
13769 assert_eq!(panel.read(cx).position, DockPosition::Right);
13770 });
13771
13772 // Remove focus from the panel, ensuring that, if the panel is not
13773 // focused, the `MoveFocusedPanelToNextPosition` action does not update
13774 // the panel's position, so the panel is still in the right dock.
13775 workspace.update_in(cx, |workspace, window, cx| {
13776 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13777 });
13778
13779 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13780 workspace.update(cx, |workspace, cx| {
13781 assert!(workspace.right_dock().read(cx).is_open());
13782 assert_eq!(panel.read(cx).position, DockPosition::Right);
13783 });
13784 }
13785
13786 #[gpui::test]
13787 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13788 init_test(cx);
13789
13790 let fs = FakeFs::new(cx.executor());
13791 let project = Project::test(fs, [], cx).await;
13792 let (workspace, cx) =
13793 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13794
13795 let item_1 = cx.new(|cx| {
13796 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13797 });
13798 workspace.update_in(cx, |workspace, window, cx| {
13799 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13800 workspace.move_item_to_pane_in_direction(
13801 &MoveItemToPaneInDirection {
13802 direction: SplitDirection::Right,
13803 focus: true,
13804 clone: false,
13805 },
13806 window,
13807 cx,
13808 );
13809 workspace.move_item_to_pane_at_index(
13810 &MoveItemToPane {
13811 destination: 3,
13812 focus: true,
13813 clone: false,
13814 },
13815 window,
13816 cx,
13817 );
13818
13819 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13820 assert_eq!(
13821 pane_items_paths(&workspace.active_pane, cx),
13822 vec!["first.txt".to_string()],
13823 "Single item was not moved anywhere"
13824 );
13825 });
13826
13827 let item_2 = cx.new(|cx| {
13828 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13829 });
13830 workspace.update_in(cx, |workspace, window, cx| {
13831 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13832 assert_eq!(
13833 pane_items_paths(&workspace.panes[0], cx),
13834 vec!["first.txt".to_string(), "second.txt".to_string()],
13835 );
13836 workspace.move_item_to_pane_in_direction(
13837 &MoveItemToPaneInDirection {
13838 direction: SplitDirection::Right,
13839 focus: true,
13840 clone: false,
13841 },
13842 window,
13843 cx,
13844 );
13845
13846 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13847 assert_eq!(
13848 pane_items_paths(&workspace.panes[0], cx),
13849 vec!["first.txt".to_string()],
13850 "After moving, one item should be left in the original pane"
13851 );
13852 assert_eq!(
13853 pane_items_paths(&workspace.panes[1], cx),
13854 vec!["second.txt".to_string()],
13855 "New item should have been moved to the new pane"
13856 );
13857 });
13858
13859 let item_3 = cx.new(|cx| {
13860 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13861 });
13862 workspace.update_in(cx, |workspace, window, cx| {
13863 let original_pane = workspace.panes[0].clone();
13864 workspace.set_active_pane(&original_pane, window, cx);
13865 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13866 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13867 assert_eq!(
13868 pane_items_paths(&workspace.active_pane, cx),
13869 vec!["first.txt".to_string(), "third.txt".to_string()],
13870 "New pane should be ready to move one item out"
13871 );
13872
13873 workspace.move_item_to_pane_at_index(
13874 &MoveItemToPane {
13875 destination: 3,
13876 focus: true,
13877 clone: false,
13878 },
13879 window,
13880 cx,
13881 );
13882 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13883 assert_eq!(
13884 pane_items_paths(&workspace.active_pane, cx),
13885 vec!["first.txt".to_string()],
13886 "After moving, one item should be left in the original pane"
13887 );
13888 assert_eq!(
13889 pane_items_paths(&workspace.panes[1], cx),
13890 vec!["second.txt".to_string()],
13891 "Previously created pane should be unchanged"
13892 );
13893 assert_eq!(
13894 pane_items_paths(&workspace.panes[2], cx),
13895 vec!["third.txt".to_string()],
13896 "New item should have been moved to the new pane"
13897 );
13898 });
13899 }
13900
13901 #[gpui::test]
13902 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13903 init_test(cx);
13904
13905 let fs = FakeFs::new(cx.executor());
13906 let project = Project::test(fs, [], cx).await;
13907 let (workspace, cx) =
13908 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13909
13910 let item_1 = cx.new(|cx| {
13911 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13912 });
13913 workspace.update_in(cx, |workspace, window, cx| {
13914 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13915 workspace.move_item_to_pane_in_direction(
13916 &MoveItemToPaneInDirection {
13917 direction: SplitDirection::Right,
13918 focus: true,
13919 clone: true,
13920 },
13921 window,
13922 cx,
13923 );
13924 });
13925 cx.run_until_parked();
13926 workspace.update_in(cx, |workspace, window, cx| {
13927 workspace.move_item_to_pane_at_index(
13928 &MoveItemToPane {
13929 destination: 3,
13930 focus: true,
13931 clone: true,
13932 },
13933 window,
13934 cx,
13935 );
13936 });
13937 cx.run_until_parked();
13938
13939 workspace.update(cx, |workspace, cx| {
13940 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13941 for pane in workspace.panes() {
13942 assert_eq!(
13943 pane_items_paths(pane, cx),
13944 vec!["first.txt".to_string()],
13945 "Single item exists in all panes"
13946 );
13947 }
13948 });
13949
13950 // verify that the active pane has been updated after waiting for the
13951 // pane focus event to fire and resolve
13952 workspace.read_with(cx, |workspace, _app| {
13953 assert_eq!(
13954 workspace.active_pane(),
13955 &workspace.panes[2],
13956 "The third pane should be the active one: {:?}",
13957 workspace.panes
13958 );
13959 })
13960 }
13961
13962 #[gpui::test]
13963 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13964 init_test(cx);
13965
13966 let fs = FakeFs::new(cx.executor());
13967 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13968
13969 let project = Project::test(fs, ["root".as_ref()], cx).await;
13970 let (workspace, cx) =
13971 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13972
13973 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13974 // Add item to pane A with project path
13975 let item_a = cx.new(|cx| {
13976 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13977 });
13978 workspace.update_in(cx, |workspace, window, cx| {
13979 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13980 });
13981
13982 // Split to create pane B
13983 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13984 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13985 });
13986
13987 // Add item with SAME project path to pane B, and pin it
13988 let item_b = cx.new(|cx| {
13989 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13990 });
13991 pane_b.update_in(cx, |pane, window, cx| {
13992 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13993 pane.set_pinned_count(1);
13994 });
13995
13996 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13997 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13998
13999 // close_pinned: false should only close the unpinned copy
14000 workspace.update_in(cx, |workspace, window, cx| {
14001 workspace.close_item_in_all_panes(
14002 &CloseItemInAllPanes {
14003 save_intent: Some(SaveIntent::Close),
14004 close_pinned: false,
14005 },
14006 window,
14007 cx,
14008 )
14009 });
14010 cx.executor().run_until_parked();
14011
14012 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14013 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14014 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14015 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14016
14017 // Split again, seeing as closing the previous item also closed its
14018 // pane, so only pane remains, which does not allow us to properly test
14019 // that both items close when `close_pinned: true`.
14020 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14021 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14022 });
14023
14024 // Add an item with the same project path to pane C so that
14025 // close_item_in_all_panes can determine what to close across all panes
14026 // (it reads the active item from the active pane, and split_pane
14027 // creates an empty pane).
14028 let item_c = cx.new(|cx| {
14029 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14030 });
14031 pane_c.update_in(cx, |pane, window, cx| {
14032 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14033 });
14034
14035 // close_pinned: true should close the pinned copy too
14036 workspace.update_in(cx, |workspace, window, cx| {
14037 let panes_count = workspace.panes().len();
14038 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14039
14040 workspace.close_item_in_all_panes(
14041 &CloseItemInAllPanes {
14042 save_intent: Some(SaveIntent::Close),
14043 close_pinned: true,
14044 },
14045 window,
14046 cx,
14047 )
14048 });
14049 cx.executor().run_until_parked();
14050
14051 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14052 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14053 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14054 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14055 }
14056
14057 mod register_project_item_tests {
14058
14059 use super::*;
14060
14061 // View
14062 struct TestPngItemView {
14063 focus_handle: FocusHandle,
14064 }
14065 // Model
14066 struct TestPngItem {}
14067
14068 impl project::ProjectItem for TestPngItem {
14069 fn try_open(
14070 _project: &Entity<Project>,
14071 path: &ProjectPath,
14072 cx: &mut App,
14073 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14074 if path.path.extension().unwrap() == "png" {
14075 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14076 } else {
14077 None
14078 }
14079 }
14080
14081 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14082 None
14083 }
14084
14085 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14086 None
14087 }
14088
14089 fn is_dirty(&self) -> bool {
14090 false
14091 }
14092 }
14093
14094 impl Item for TestPngItemView {
14095 type Event = ();
14096 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14097 "".into()
14098 }
14099 }
14100 impl EventEmitter<()> for TestPngItemView {}
14101 impl Focusable for TestPngItemView {
14102 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14103 self.focus_handle.clone()
14104 }
14105 }
14106
14107 impl Render for TestPngItemView {
14108 fn render(
14109 &mut self,
14110 _window: &mut Window,
14111 _cx: &mut Context<Self>,
14112 ) -> impl IntoElement {
14113 Empty
14114 }
14115 }
14116
14117 impl ProjectItem for TestPngItemView {
14118 type Item = TestPngItem;
14119
14120 fn for_project_item(
14121 _project: Entity<Project>,
14122 _pane: Option<&Pane>,
14123 _item: Entity<Self::Item>,
14124 _: &mut Window,
14125 cx: &mut Context<Self>,
14126 ) -> Self
14127 where
14128 Self: Sized,
14129 {
14130 Self {
14131 focus_handle: cx.focus_handle(),
14132 }
14133 }
14134 }
14135
14136 // View
14137 struct TestIpynbItemView {
14138 focus_handle: FocusHandle,
14139 }
14140 // Model
14141 struct TestIpynbItem {}
14142
14143 impl project::ProjectItem for TestIpynbItem {
14144 fn try_open(
14145 _project: &Entity<Project>,
14146 path: &ProjectPath,
14147 cx: &mut App,
14148 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14149 if path.path.extension().unwrap() == "ipynb" {
14150 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14151 } else {
14152 None
14153 }
14154 }
14155
14156 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14157 None
14158 }
14159
14160 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14161 None
14162 }
14163
14164 fn is_dirty(&self) -> bool {
14165 false
14166 }
14167 }
14168
14169 impl Item for TestIpynbItemView {
14170 type Event = ();
14171 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14172 "".into()
14173 }
14174 }
14175 impl EventEmitter<()> for TestIpynbItemView {}
14176 impl Focusable for TestIpynbItemView {
14177 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14178 self.focus_handle.clone()
14179 }
14180 }
14181
14182 impl Render for TestIpynbItemView {
14183 fn render(
14184 &mut self,
14185 _window: &mut Window,
14186 _cx: &mut Context<Self>,
14187 ) -> impl IntoElement {
14188 Empty
14189 }
14190 }
14191
14192 impl ProjectItem for TestIpynbItemView {
14193 type Item = TestIpynbItem;
14194
14195 fn for_project_item(
14196 _project: Entity<Project>,
14197 _pane: Option<&Pane>,
14198 _item: Entity<Self::Item>,
14199 _: &mut Window,
14200 cx: &mut Context<Self>,
14201 ) -> Self
14202 where
14203 Self: Sized,
14204 {
14205 Self {
14206 focus_handle: cx.focus_handle(),
14207 }
14208 }
14209 }
14210
14211 struct TestAlternatePngItemView {
14212 focus_handle: FocusHandle,
14213 }
14214
14215 impl Item for TestAlternatePngItemView {
14216 type Event = ();
14217 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14218 "".into()
14219 }
14220 }
14221
14222 impl EventEmitter<()> for TestAlternatePngItemView {}
14223 impl Focusable for TestAlternatePngItemView {
14224 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14225 self.focus_handle.clone()
14226 }
14227 }
14228
14229 impl Render for TestAlternatePngItemView {
14230 fn render(
14231 &mut self,
14232 _window: &mut Window,
14233 _cx: &mut Context<Self>,
14234 ) -> impl IntoElement {
14235 Empty
14236 }
14237 }
14238
14239 impl ProjectItem for TestAlternatePngItemView {
14240 type Item = TestPngItem;
14241
14242 fn for_project_item(
14243 _project: Entity<Project>,
14244 _pane: Option<&Pane>,
14245 _item: Entity<Self::Item>,
14246 _: &mut Window,
14247 cx: &mut Context<Self>,
14248 ) -> Self
14249 where
14250 Self: Sized,
14251 {
14252 Self {
14253 focus_handle: cx.focus_handle(),
14254 }
14255 }
14256 }
14257
14258 #[gpui::test]
14259 async fn test_register_project_item(cx: &mut TestAppContext) {
14260 init_test(cx);
14261
14262 cx.update(|cx| {
14263 register_project_item::<TestPngItemView>(cx);
14264 register_project_item::<TestIpynbItemView>(cx);
14265 });
14266
14267 let fs = FakeFs::new(cx.executor());
14268 fs.insert_tree(
14269 "/root1",
14270 json!({
14271 "one.png": "BINARYDATAHERE",
14272 "two.ipynb": "{ totally a notebook }",
14273 "three.txt": "editing text, sure why not?"
14274 }),
14275 )
14276 .await;
14277
14278 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14279 let (workspace, cx) =
14280 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14281
14282 let worktree_id = project.update(cx, |project, cx| {
14283 project.worktrees(cx).next().unwrap().read(cx).id()
14284 });
14285
14286 let handle = workspace
14287 .update_in(cx, |workspace, window, cx| {
14288 let project_path = (worktree_id, rel_path("one.png"));
14289 workspace.open_path(project_path, None, true, window, cx)
14290 })
14291 .await
14292 .unwrap();
14293
14294 // Now we can check if the handle we got back errored or not
14295 assert_eq!(
14296 handle.to_any_view().entity_type(),
14297 TypeId::of::<TestPngItemView>()
14298 );
14299
14300 let handle = workspace
14301 .update_in(cx, |workspace, window, cx| {
14302 let project_path = (worktree_id, rel_path("two.ipynb"));
14303 workspace.open_path(project_path, None, true, window, cx)
14304 })
14305 .await
14306 .unwrap();
14307
14308 assert_eq!(
14309 handle.to_any_view().entity_type(),
14310 TypeId::of::<TestIpynbItemView>()
14311 );
14312
14313 let handle = workspace
14314 .update_in(cx, |workspace, window, cx| {
14315 let project_path = (worktree_id, rel_path("three.txt"));
14316 workspace.open_path(project_path, None, true, window, cx)
14317 })
14318 .await;
14319 assert!(handle.is_err());
14320 }
14321
14322 #[gpui::test]
14323 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14324 init_test(cx);
14325
14326 cx.update(|cx| {
14327 register_project_item::<TestPngItemView>(cx);
14328 register_project_item::<TestAlternatePngItemView>(cx);
14329 });
14330
14331 let fs = FakeFs::new(cx.executor());
14332 fs.insert_tree(
14333 "/root1",
14334 json!({
14335 "one.png": "BINARYDATAHERE",
14336 "two.ipynb": "{ totally a notebook }",
14337 "three.txt": "editing text, sure why not?"
14338 }),
14339 )
14340 .await;
14341 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14342 let (workspace, cx) =
14343 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14344 let worktree_id = project.update(cx, |project, cx| {
14345 project.worktrees(cx).next().unwrap().read(cx).id()
14346 });
14347
14348 let handle = workspace
14349 .update_in(cx, |workspace, window, cx| {
14350 let project_path = (worktree_id, rel_path("one.png"));
14351 workspace.open_path(project_path, None, true, window, cx)
14352 })
14353 .await
14354 .unwrap();
14355
14356 // This _must_ be the second item registered
14357 assert_eq!(
14358 handle.to_any_view().entity_type(),
14359 TypeId::of::<TestAlternatePngItemView>()
14360 );
14361
14362 let handle = workspace
14363 .update_in(cx, |workspace, window, cx| {
14364 let project_path = (worktree_id, rel_path("three.txt"));
14365 workspace.open_path(project_path, None, true, window, cx)
14366 })
14367 .await;
14368 assert!(handle.is_err());
14369 }
14370 }
14371
14372 #[gpui::test]
14373 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14374 init_test(cx);
14375
14376 let fs = FakeFs::new(cx.executor());
14377 let project = Project::test(fs, [], cx).await;
14378 let (workspace, _cx) =
14379 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14380
14381 // Test with status bar shown (default)
14382 workspace.read_with(cx, |workspace, cx| {
14383 let visible = workspace.status_bar_visible(cx);
14384 assert!(visible, "Status bar should be visible by default");
14385 });
14386
14387 // Test with status bar hidden
14388 cx.update_global(|store: &mut SettingsStore, cx| {
14389 store.update_user_settings(cx, |settings| {
14390 settings.status_bar.get_or_insert_default().show = Some(false);
14391 });
14392 });
14393
14394 workspace.read_with(cx, |workspace, cx| {
14395 let visible = workspace.status_bar_visible(cx);
14396 assert!(!visible, "Status bar should be hidden when show is false");
14397 });
14398
14399 // Test with status bar shown explicitly
14400 cx.update_global(|store: &mut SettingsStore, cx| {
14401 store.update_user_settings(cx, |settings| {
14402 settings.status_bar.get_or_insert_default().show = Some(true);
14403 });
14404 });
14405
14406 workspace.read_with(cx, |workspace, cx| {
14407 let visible = workspace.status_bar_visible(cx);
14408 assert!(visible, "Status bar should be visible when show is true");
14409 });
14410 }
14411
14412 #[gpui::test]
14413 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14414 init_test(cx);
14415
14416 let fs = FakeFs::new(cx.executor());
14417 let project = Project::test(fs, [], cx).await;
14418 let (multi_workspace, cx) =
14419 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14420 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14421 let panel = workspace.update_in(cx, |workspace, window, cx| {
14422 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14423 workspace.add_panel(panel.clone(), window, cx);
14424
14425 workspace
14426 .right_dock()
14427 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14428
14429 panel
14430 });
14431
14432 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14433 let item_a = cx.new(TestItem::new);
14434 let item_b = cx.new(TestItem::new);
14435 let item_a_id = item_a.entity_id();
14436 let item_b_id = item_b.entity_id();
14437
14438 pane.update_in(cx, |pane, window, cx| {
14439 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14440 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14441 });
14442
14443 pane.read_with(cx, |pane, _| {
14444 assert_eq!(pane.items_len(), 2);
14445 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14446 });
14447
14448 workspace.update_in(cx, |workspace, window, cx| {
14449 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14450 });
14451
14452 workspace.update_in(cx, |_, window, cx| {
14453 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14454 });
14455
14456 // Assert that the `pane::CloseActiveItem` action is handled at the
14457 // workspace level when one of the dock panels is focused and, in that
14458 // case, the center pane's active item is closed but the focus is not
14459 // moved.
14460 cx.dispatch_action(pane::CloseActiveItem::default());
14461 cx.run_until_parked();
14462
14463 pane.read_with(cx, |pane, _| {
14464 assert_eq!(pane.items_len(), 1);
14465 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14466 });
14467
14468 workspace.update_in(cx, |workspace, window, cx| {
14469 assert!(workspace.right_dock().read(cx).is_open());
14470 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14471 });
14472 }
14473
14474 #[gpui::test]
14475 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14476 init_test(cx);
14477 let fs = FakeFs::new(cx.executor());
14478
14479 let project_a = Project::test(fs.clone(), [], cx).await;
14480 let project_b = Project::test(fs, [], cx).await;
14481
14482 let multi_workspace_handle =
14483 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14484 cx.run_until_parked();
14485
14486 let workspace_a = multi_workspace_handle
14487 .read_with(cx, |mw, _| mw.workspace().clone())
14488 .unwrap();
14489
14490 let _workspace_b = multi_workspace_handle
14491 .update(cx, |mw, window, cx| {
14492 mw.test_add_workspace(project_b, window, cx)
14493 })
14494 .unwrap();
14495
14496 // Switch to workspace A
14497 multi_workspace_handle
14498 .update(cx, |mw, window, cx| {
14499 let workspace = mw.workspaces()[0].clone();
14500 mw.activate(workspace, window, cx);
14501 })
14502 .unwrap();
14503
14504 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14505
14506 // Add a panel to workspace A's right dock and open the dock
14507 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14508 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14509 workspace.add_panel(panel.clone(), window, cx);
14510 workspace
14511 .right_dock()
14512 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14513 panel
14514 });
14515
14516 // Focus the panel through the workspace (matching existing test pattern)
14517 workspace_a.update_in(cx, |workspace, window, cx| {
14518 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14519 });
14520
14521 // Zoom the panel
14522 panel.update_in(cx, |panel, window, cx| {
14523 panel.set_zoomed(true, window, cx);
14524 });
14525
14526 // Verify the panel is zoomed and the dock is open
14527 workspace_a.update_in(cx, |workspace, window, cx| {
14528 assert!(
14529 workspace.right_dock().read(cx).is_open(),
14530 "dock should be open before switch"
14531 );
14532 assert!(
14533 panel.is_zoomed(window, cx),
14534 "panel should be zoomed before switch"
14535 );
14536 assert!(
14537 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14538 "panel should be focused before switch"
14539 );
14540 });
14541
14542 // Switch to workspace B
14543 multi_workspace_handle
14544 .update(cx, |mw, window, cx| {
14545 let workspace = mw.workspaces()[1].clone();
14546 mw.activate(workspace, window, cx);
14547 })
14548 .unwrap();
14549 cx.run_until_parked();
14550
14551 // Switch back to workspace A
14552 multi_workspace_handle
14553 .update(cx, |mw, window, cx| {
14554 let workspace = mw.workspaces()[0].clone();
14555 mw.activate(workspace, window, cx);
14556 })
14557 .unwrap();
14558 cx.run_until_parked();
14559
14560 // Verify the panel is still zoomed and the dock is still open
14561 workspace_a.update_in(cx, |workspace, window, cx| {
14562 assert!(
14563 workspace.right_dock().read(cx).is_open(),
14564 "dock should still be open after switching back"
14565 );
14566 assert!(
14567 panel.is_zoomed(window, cx),
14568 "panel should still be zoomed after switching back"
14569 );
14570 });
14571 }
14572
14573 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14574 pane.read(cx)
14575 .items()
14576 .flat_map(|item| {
14577 item.project_paths(cx)
14578 .into_iter()
14579 .map(|path| path.path.display(PathStyle::local()).into_owned())
14580 })
14581 .collect()
14582 }
14583
14584 pub fn init_test(cx: &mut TestAppContext) {
14585 cx.update(|cx| {
14586 let settings_store = SettingsStore::test(cx);
14587 cx.set_global(settings_store);
14588 cx.set_global(db::AppDatabase::test_new());
14589 theme_settings::init(theme::LoadThemes::JustBase, cx);
14590 });
14591 }
14592
14593 #[gpui::test]
14594 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14595 use settings::{ThemeName, ThemeSelection};
14596 use theme::SystemAppearance;
14597 use zed_actions::theme::ToggleMode;
14598
14599 init_test(cx);
14600
14601 let fs = FakeFs::new(cx.executor());
14602 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14603
14604 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14605 .await;
14606
14607 // Build a test project and workspace view so the test can invoke
14608 // the workspace action handler the same way the UI would.
14609 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14610 let (workspace, cx) =
14611 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14612
14613 // Seed the settings file with a plain static light theme so the
14614 // first toggle always starts from a known persisted state.
14615 workspace.update_in(cx, |_workspace, _window, cx| {
14616 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14617 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14618 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14619 });
14620 });
14621 cx.executor().advance_clock(Duration::from_millis(200));
14622 cx.run_until_parked();
14623
14624 // Confirm the initial persisted settings contain the static theme
14625 // we just wrote before any toggling happens.
14626 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14627 assert!(settings_text.contains(r#""theme": "One Light""#));
14628
14629 // Toggle once. This should migrate the persisted theme settings
14630 // into light/dark slots and enable system mode.
14631 workspace.update_in(cx, |workspace, window, cx| {
14632 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14633 });
14634 cx.executor().advance_clock(Duration::from_millis(200));
14635 cx.run_until_parked();
14636
14637 // 1. Static -> Dynamic
14638 // this assertion checks theme changed from static to dynamic.
14639 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14640 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14641 assert_eq!(
14642 parsed["theme"],
14643 serde_json::json!({
14644 "mode": "system",
14645 "light": "One Light",
14646 "dark": "One Dark"
14647 })
14648 );
14649
14650 // 2. Toggle again, suppose it will change the mode to light
14651 workspace.update_in(cx, |workspace, window, cx| {
14652 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14653 });
14654 cx.executor().advance_clock(Duration::from_millis(200));
14655 cx.run_until_parked();
14656
14657 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14658 assert!(settings_text.contains(r#""mode": "light""#));
14659 }
14660
14661 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14662 let item = TestProjectItem::new(id, path, cx);
14663 item.update(cx, |item, _| {
14664 item.is_dirty = true;
14665 });
14666 item
14667 }
14668
14669 #[gpui::test]
14670 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14671 cx: &mut gpui::TestAppContext,
14672 ) {
14673 init_test(cx);
14674 let fs = FakeFs::new(cx.executor());
14675
14676 let project = Project::test(fs, [], cx).await;
14677 let (workspace, cx) =
14678 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14679
14680 let panel = workspace.update_in(cx, |workspace, window, cx| {
14681 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14682 workspace.add_panel(panel.clone(), window, cx);
14683 workspace
14684 .right_dock()
14685 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14686 panel
14687 });
14688
14689 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14690 pane.update_in(cx, |pane, window, cx| {
14691 let item = cx.new(TestItem::new);
14692 pane.add_item(Box::new(item), true, true, None, window, cx);
14693 });
14694
14695 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14696 // mirrors the real-world flow and avoids side effects from directly
14697 // focusing the panel while the center pane is active.
14698 workspace.update_in(cx, |workspace, window, cx| {
14699 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14700 });
14701
14702 panel.update_in(cx, |panel, window, cx| {
14703 panel.set_zoomed(true, window, cx);
14704 });
14705
14706 workspace.update_in(cx, |workspace, window, cx| {
14707 assert!(workspace.right_dock().read(cx).is_open());
14708 assert!(panel.is_zoomed(window, cx));
14709 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14710 });
14711
14712 // Simulate a spurious pane::Event::Focus on the center pane while the
14713 // panel still has focus. This mirrors what happens during macOS window
14714 // activation: the center pane fires a focus event even though actual
14715 // focus remains on the dock panel.
14716 pane.update_in(cx, |_, _, cx| {
14717 cx.emit(pane::Event::Focus);
14718 });
14719
14720 // The dock must remain open because the panel had focus at the time the
14721 // event was processed. Before the fix, dock_to_preserve was None for
14722 // panels that don't implement pane(), causing the dock to close.
14723 workspace.update_in(cx, |workspace, window, cx| {
14724 assert!(
14725 workspace.right_dock().read(cx).is_open(),
14726 "Dock should stay open when its zoomed panel (without pane()) still has focus"
14727 );
14728 assert!(panel.is_zoomed(window, cx));
14729 });
14730 }
14731
14732 #[gpui::test]
14733 async fn test_panels_stay_open_after_position_change_and_settings_update(
14734 cx: &mut gpui::TestAppContext,
14735 ) {
14736 init_test(cx);
14737 let fs = FakeFs::new(cx.executor());
14738 let project = Project::test(fs, [], cx).await;
14739 let (workspace, cx) =
14740 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14741
14742 // Add two panels to the left dock and open it.
14743 let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14744 let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14745 let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14746 workspace.add_panel(panel_a.clone(), window, cx);
14747 workspace.add_panel(panel_b.clone(), window, cx);
14748 workspace.left_dock().update(cx, |dock, cx| {
14749 dock.set_open(true, window, cx);
14750 dock.activate_panel(0, window, cx);
14751 });
14752 (panel_a, panel_b)
14753 });
14754
14755 workspace.update_in(cx, |workspace, _, cx| {
14756 assert!(workspace.left_dock().read(cx).is_open());
14757 });
14758
14759 // Simulate a feature flag changing default dock positions: both panels
14760 // move from Left to Right.
14761 workspace.update_in(cx, |_workspace, _window, cx| {
14762 panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14763 panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14764 cx.update_global::<SettingsStore, _>(|_, _| {});
14765 });
14766
14767 // Both panels should now be in the right dock.
14768 workspace.update_in(cx, |workspace, _, cx| {
14769 let right_dock = workspace.right_dock().read(cx);
14770 assert_eq!(right_dock.panels_len(), 2);
14771 });
14772
14773 // Open the right dock and activate panel_b (simulating the user
14774 // opening the panel after it moved).
14775 workspace.update_in(cx, |workspace, window, cx| {
14776 workspace.right_dock().update(cx, |dock, cx| {
14777 dock.set_open(true, window, cx);
14778 dock.activate_panel(1, window, cx);
14779 });
14780 });
14781
14782 // Now trigger another SettingsStore change
14783 workspace.update_in(cx, |_workspace, _window, cx| {
14784 cx.update_global::<SettingsStore, _>(|_, _| {});
14785 });
14786
14787 workspace.update_in(cx, |workspace, _, cx| {
14788 assert!(
14789 workspace.right_dock().read(cx).is_open(),
14790 "Right dock should still be open after a settings change"
14791 );
14792 assert_eq!(
14793 workspace.right_dock().read(cx).panels_len(),
14794 2,
14795 "Both panels should still be in the right dock"
14796 );
14797 });
14798 }
14799}