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;
22mod status_bar;
23pub mod tasks;
24mod theme_preview;
25mod toast_layer;
26mod toolbar;
27pub mod welcome;
28mod workspace_settings;
29
30pub use crate::notifications::NotificationFrame;
31pub use dock::Panel;
32pub use multi_workspace::{
33 CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
34 MultiWorkspaceEvent, NextWorkspace, PreviousWorkspace, Sidebar, SidebarEvent, SidebarHandle,
35 SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar, sidebar_side_context_menu,
36};
37pub use path_list::{PathList, SerializedPathList};
38pub use toast_layer::{ToastAction, ToastLayer, ToastView};
39
40use anyhow::{Context as _, Result, anyhow};
41use client::{
42 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
43 proto::{self, ErrorCode, PanelId, PeerId},
44};
45use collections::{HashMap, HashSet, hash_map};
46use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
47use fs::Fs;
48use futures::{
49 Future, FutureExt, StreamExt,
50 channel::{
51 mpsc::{self, UnboundedReceiver, UnboundedSender},
52 oneshot,
53 },
54 future::{Shared, try_join_all},
55};
56use gpui::{
57 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
58 Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
59 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
60 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
61 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
62 WindowOptions, actions, canvas, point, relative, size, transparent_black,
63};
64pub use history_manager::*;
65pub use item::{
66 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
67 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
68};
69use itertools::Itertools;
70use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
71pub use modal_layer::*;
72use node_runtime::NodeRuntime;
73use notifications::{
74 DetachAndPromptErr, Notifications, dismiss_app_notification,
75 simple_message_notification::MessageNotification,
76};
77pub use pane::*;
78pub use pane_group::{
79 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
80 SplitDirection,
81};
82use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
83pub use persistence::{
84 WorkspaceDb, delete_unloaded_items,
85 model::{
86 DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
87 SessionWorkspace,
88 },
89 read_serialized_multi_workspaces, resolve_worktree_workspaces,
90};
91use postage::stream::Stream;
92use project::{
93 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
94 WorktreeSettings,
95 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
96 project_settings::ProjectSettings,
97 toolchain_store::ToolchainStoreEvent,
98 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
99};
100use remote::{
101 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
102 remote_client::ConnectionIdentifier,
103};
104use schemars::JsonSchema;
105use serde::Deserialize;
106use session::AppSession;
107use settings::{
108 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
109};
110
111use sqlez::{
112 bindable::{Bind, Column, StaticColumnCount},
113 statement::Statement,
114};
115use status_bar::StatusBar;
116pub use status_bar::StatusItemView;
117use std::{
118 any::TypeId,
119 borrow::Cow,
120 cell::RefCell,
121 cmp,
122 collections::VecDeque,
123 env,
124 hash::Hash,
125 path::{Path, PathBuf},
126 process::ExitStatus,
127 rc::Rc,
128 sync::{
129 Arc, LazyLock,
130 atomic::{AtomicBool, AtomicUsize},
131 },
132 time::Duration,
133};
134use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
135use theme::{ActiveTheme, SystemAppearance};
136use theme_settings::ThemeSettings;
137pub use toolbar::{
138 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
139};
140pub use ui;
141use ui::{Window, prelude::*};
142use util::{
143 ResultExt, TryFutureExt,
144 paths::{PathStyle, SanitizedPath},
145 rel_path::RelPath,
146 serde::default_true,
147};
148use uuid::Uuid;
149pub use workspace_settings::{
150 AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
151 WorkspaceSettings,
152};
153use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
154
155use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::NotificationId};
156use crate::{
157 persistence::{
158 SerializedAxis,
159 model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
160 },
161 security_modal::SecurityModal,
162};
163
164pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
165
166static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
167 env::var("ZED_WINDOW_SIZE")
168 .ok()
169 .as_deref()
170 .and_then(parse_pixel_size_env_var)
171});
172
173static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
174 env::var("ZED_WINDOW_POSITION")
175 .ok()
176 .as_deref()
177 .and_then(parse_pixel_position_env_var)
178});
179
180pub trait TerminalProvider {
181 fn spawn(
182 &self,
183 task: SpawnInTerminal,
184 window: &mut Window,
185 cx: &mut App,
186 ) -> Task<Option<Result<ExitStatus>>>;
187}
188
189pub trait DebuggerProvider {
190 // `active_buffer` is used to resolve build task's name against language-specific tasks.
191 fn start_session(
192 &self,
193 definition: DebugScenario,
194 task_context: SharedTaskContext,
195 active_buffer: Option<Entity<Buffer>>,
196 worktree_id: Option<WorktreeId>,
197 window: &mut Window,
198 cx: &mut App,
199 );
200
201 fn spawn_task_or_modal(
202 &self,
203 workspace: &mut Workspace,
204 action: &Spawn,
205 window: &mut Window,
206 cx: &mut Context<Workspace>,
207 );
208
209 fn task_scheduled(&self, cx: &mut App);
210 fn debug_scenario_scheduled(&self, cx: &mut App);
211 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
212
213 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
214}
215
216/// Opens a file or directory.
217#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
218#[action(namespace = workspace)]
219pub struct Open {
220 /// When true, opens in a new window. When false, adds to the current
221 /// window as a new workspace (multi-workspace).
222 #[serde(default = "Open::default_create_new_window")]
223 pub create_new_window: bool,
224}
225
226impl Open {
227 pub const DEFAULT: Self = Self {
228 create_new_window: true,
229 };
230
231 /// Used by `#[serde(default)]` on the `create_new_window` field so that
232 /// the serde default and `Open::DEFAULT` stay in sync.
233 fn default_create_new_window() -> bool {
234 Self::DEFAULT.create_new_window
235 }
236}
237
238impl Default for Open {
239 fn default() -> Self {
240 Self::DEFAULT
241 }
242}
243
244actions!(
245 workspace,
246 [
247 /// Activates the next pane in the workspace.
248 ActivateNextPane,
249 /// Activates the previous pane in the workspace.
250 ActivatePreviousPane,
251 /// Activates the last pane in the workspace.
252 ActivateLastPane,
253 /// Switches to the next window.
254 ActivateNextWindow,
255 /// Switches to the previous window.
256 ActivatePreviousWindow,
257 /// Adds a folder to the current project.
258 AddFolderToProject,
259 /// Clears all notifications.
260 ClearAllNotifications,
261 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
262 ClearNavigationHistory,
263 /// Closes the active dock.
264 CloseActiveDock,
265 /// Closes all docks.
266 CloseAllDocks,
267 /// Toggles all docks.
268 ToggleAllDocks,
269 /// Closes the current window.
270 CloseWindow,
271 /// Closes the current project.
272 CloseProject,
273 /// Opens the feedback dialog.
274 Feedback,
275 /// Follows the next collaborator in the session.
276 FollowNextCollaborator,
277 /// Moves the focused panel to the next position.
278 MoveFocusedPanelToNextPosition,
279 /// Creates a new file.
280 NewFile,
281 /// Creates a new file in a vertical split.
282 NewFileSplitVertical,
283 /// Creates a new file in a horizontal split.
284 NewFileSplitHorizontal,
285 /// Opens a new search.
286 NewSearch,
287 /// Opens a new window.
288 NewWindow,
289 /// Opens multiple files.
290 OpenFiles,
291 /// Opens the current location in terminal.
292 OpenInTerminal,
293 /// Opens the component preview.
294 OpenComponentPreview,
295 /// Reloads the active item.
296 ReloadActiveItem,
297 /// Resets the active dock to its default size.
298 ResetActiveDockSize,
299 /// Resets all open docks to their default sizes.
300 ResetOpenDocksSize,
301 /// Reloads the application
302 Reload,
303 /// Saves the current file with a new name.
304 SaveAs,
305 /// Saves without formatting.
306 SaveWithoutFormat,
307 /// Shuts down all debug adapters.
308 ShutdownDebugAdapters,
309 /// Suppresses the current notification.
310 SuppressNotification,
311 /// Toggles the bottom dock.
312 ToggleBottomDock,
313 /// Toggles centered layout mode.
314 ToggleCenteredLayout,
315 /// Toggles edit prediction feature globally for all files.
316 ToggleEditPrediction,
317 /// Toggles the left dock.
318 ToggleLeftDock,
319 /// Toggles the right dock.
320 ToggleRightDock,
321 /// Toggles zoom on the active pane.
322 ToggleZoom,
323 /// Toggles read-only mode for the active item (if supported by that item).
324 ToggleReadOnlyFile,
325 /// Zooms in on the active pane.
326 ZoomIn,
327 /// Zooms out of the active pane.
328 ZoomOut,
329 /// If any worktrees are in restricted mode, shows a modal with possible actions.
330 /// If the modal is shown already, closes it without trusting any worktree.
331 ToggleWorktreeSecurity,
332 /// Clears all trusted worktrees, placing them in restricted mode on next open.
333 /// Requires restart to take effect on already opened projects.
334 ClearTrustedWorktrees,
335 /// Stops following a collaborator.
336 Unfollow,
337 /// Restores the banner.
338 RestoreBanner,
339 /// Toggles expansion of the selected item.
340 ToggleExpandItem,
341 ]
342);
343
344/// Activates a specific pane by its index.
345#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
346#[action(namespace = workspace)]
347pub struct ActivatePane(pub usize);
348
349/// Moves an item to a specific pane by index.
350#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
351#[action(namespace = workspace)]
352#[serde(deny_unknown_fields)]
353pub struct MoveItemToPane {
354 #[serde(default = "default_1")]
355 pub destination: usize,
356 #[serde(default = "default_true")]
357 pub focus: bool,
358 #[serde(default)]
359 pub clone: bool,
360}
361
362fn default_1() -> usize {
363 1
364}
365
366/// Moves an item to a pane in the specified direction.
367#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
368#[action(namespace = workspace)]
369#[serde(deny_unknown_fields)]
370pub struct MoveItemToPaneInDirection {
371 #[serde(default = "default_right")]
372 pub direction: SplitDirection,
373 #[serde(default = "default_true")]
374 pub focus: bool,
375 #[serde(default)]
376 pub clone: bool,
377}
378
379/// Creates a new file in a split of the desired direction.
380#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
381#[action(namespace = workspace)]
382#[serde(deny_unknown_fields)]
383pub struct NewFileSplit(pub SplitDirection);
384
385fn default_right() -> SplitDirection {
386 SplitDirection::Right
387}
388
389/// Saves all open files in the workspace.
390#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
391#[action(namespace = workspace)]
392#[serde(deny_unknown_fields)]
393pub struct SaveAll {
394 #[serde(default)]
395 pub save_intent: Option<SaveIntent>,
396}
397
398/// Saves the current file with the specified options.
399#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
400#[action(namespace = workspace)]
401#[serde(deny_unknown_fields)]
402pub struct Save {
403 #[serde(default)]
404 pub save_intent: Option<SaveIntent>,
405}
406
407/// Moves Focus to the central panes in the workspace.
408#[derive(Clone, Debug, PartialEq, Eq, Action)]
409#[action(namespace = workspace)]
410pub struct FocusCenterPane;
411
412/// Closes all items and panes in the workspace.
413#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
414#[action(namespace = workspace)]
415#[serde(deny_unknown_fields)]
416pub struct CloseAllItemsAndPanes {
417 #[serde(default)]
418 pub save_intent: Option<SaveIntent>,
419}
420
421/// Closes all inactive tabs and panes in the workspace.
422#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
423#[action(namespace = workspace)]
424#[serde(deny_unknown_fields)]
425pub struct CloseInactiveTabsAndPanes {
426 #[serde(default)]
427 pub save_intent: Option<SaveIntent>,
428}
429
430/// Closes the active item across all panes.
431#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
432#[action(namespace = workspace)]
433#[serde(deny_unknown_fields)]
434pub struct CloseItemInAllPanes {
435 #[serde(default)]
436 pub save_intent: Option<SaveIntent>,
437 #[serde(default)]
438 pub close_pinned: bool,
439}
440
441/// Sends a sequence of keystrokes to the active element.
442#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
443#[action(namespace = workspace)]
444pub struct SendKeystrokes(pub String);
445
446actions!(
447 project_symbols,
448 [
449 /// Toggles the project symbols search.
450 #[action(name = "Toggle")]
451 ToggleProjectSymbols
452 ]
453);
454
455/// Toggles the file finder interface.
456#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
457#[action(namespace = file_finder, name = "Toggle")]
458#[serde(deny_unknown_fields)]
459pub struct ToggleFileFinder {
460 #[serde(default)]
461 pub separate_history: bool,
462}
463
464/// Opens a new terminal in the center.
465#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
466#[action(namespace = workspace)]
467#[serde(deny_unknown_fields)]
468pub struct NewCenterTerminal {
469 /// If true, creates a local terminal even in remote projects.
470 #[serde(default)]
471 pub local: bool,
472}
473
474/// Opens a new terminal.
475#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
476#[action(namespace = workspace)]
477#[serde(deny_unknown_fields)]
478pub struct NewTerminal {
479 /// If true, creates a local terminal even in remote projects.
480 #[serde(default)]
481 pub local: bool,
482}
483
484/// Increases size of a currently focused dock by a given amount of pixels.
485#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
486#[action(namespace = workspace)]
487#[serde(deny_unknown_fields)]
488pub struct IncreaseActiveDockSize {
489 /// For 0px parameter, uses UI font size value.
490 #[serde(default)]
491 pub px: u32,
492}
493
494/// Decreases size of a currently focused dock by a given amount of pixels.
495#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
496#[action(namespace = workspace)]
497#[serde(deny_unknown_fields)]
498pub struct DecreaseActiveDockSize {
499 /// For 0px parameter, uses UI font size value.
500 #[serde(default)]
501 pub px: u32,
502}
503
504/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
505#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
506#[action(namespace = workspace)]
507#[serde(deny_unknown_fields)]
508pub struct IncreaseOpenDocksSize {
509 /// For 0px parameter, uses UI font size value.
510 #[serde(default)]
511 pub px: u32,
512}
513
514/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
515#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
516#[action(namespace = workspace)]
517#[serde(deny_unknown_fields)]
518pub struct DecreaseOpenDocksSize {
519 /// For 0px parameter, uses UI font size value.
520 #[serde(default)]
521 pub px: u32,
522}
523
524actions!(
525 workspace,
526 [
527 /// Activates the pane to the left.
528 ActivatePaneLeft,
529 /// Activates the pane to the right.
530 ActivatePaneRight,
531 /// Activates the pane above.
532 ActivatePaneUp,
533 /// Activates the pane below.
534 ActivatePaneDown,
535 /// Swaps the current pane with the one to the left.
536 SwapPaneLeft,
537 /// Swaps the current pane with the one to the right.
538 SwapPaneRight,
539 /// Swaps the current pane with the one above.
540 SwapPaneUp,
541 /// Swaps the current pane with the one below.
542 SwapPaneDown,
543 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
544 SwapPaneAdjacent,
545 /// Move the current pane to be at the far left.
546 MovePaneLeft,
547 /// Move the current pane to be at the far right.
548 MovePaneRight,
549 /// Move the current pane to be at the very top.
550 MovePaneUp,
551 /// Move the current pane to be at the very bottom.
552 MovePaneDown,
553 ]
554);
555
556#[derive(PartialEq, Eq, Debug)]
557pub enum CloseIntent {
558 /// Quit the program entirely.
559 Quit,
560 /// Close a window.
561 CloseWindow,
562 /// Replace the workspace in an existing window.
563 ReplaceWindow,
564}
565
566#[derive(Clone)]
567pub struct Toast {
568 id: NotificationId,
569 msg: Cow<'static, str>,
570 autohide: bool,
571 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
572}
573
574impl Toast {
575 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
576 Toast {
577 id,
578 msg: msg.into(),
579 on_click: None,
580 autohide: false,
581 }
582 }
583
584 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
585 where
586 M: Into<Cow<'static, str>>,
587 F: Fn(&mut Window, &mut App) + 'static,
588 {
589 self.on_click = Some((message.into(), Arc::new(on_click)));
590 self
591 }
592
593 pub fn autohide(mut self) -> Self {
594 self.autohide = true;
595 self
596 }
597}
598
599impl PartialEq for Toast {
600 fn eq(&self, other: &Self) -> bool {
601 self.id == other.id
602 && self.msg == other.msg
603 && self.on_click.is_some() == other.on_click.is_some()
604 }
605}
606
607/// Opens a new terminal with the specified working directory.
608#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
609#[action(namespace = workspace)]
610#[serde(deny_unknown_fields)]
611pub struct OpenTerminal {
612 pub working_directory: PathBuf,
613 /// If true, creates a local terminal even in remote projects.
614 #[serde(default)]
615 pub local: bool,
616}
617
618#[derive(
619 Clone,
620 Copy,
621 Debug,
622 Default,
623 Hash,
624 PartialEq,
625 Eq,
626 PartialOrd,
627 Ord,
628 serde::Serialize,
629 serde::Deserialize,
630)]
631pub struct WorkspaceId(i64);
632
633impl WorkspaceId {
634 pub fn from_i64(value: i64) -> Self {
635 Self(value)
636 }
637}
638
639impl StaticColumnCount for WorkspaceId {}
640impl Bind for WorkspaceId {
641 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
642 self.0.bind(statement, start_index)
643 }
644}
645impl Column for WorkspaceId {
646 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
647 i64::column(statement, start_index)
648 .map(|(i, next_index)| (Self(i), next_index))
649 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
650 }
651}
652impl From<WorkspaceId> for i64 {
653 fn from(val: WorkspaceId) -> Self {
654 val.0
655 }
656}
657
658fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
659 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
660 workspace_window
661 .update(cx, |multi_workspace, window, cx| {
662 let workspace = multi_workspace.workspace().clone();
663 workspace.update(cx, |workspace, cx| {
664 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
665 });
666 })
667 .ok();
668 } else {
669 let task = Workspace::new_local(
670 Vec::new(),
671 app_state.clone(),
672 None,
673 None,
674 None,
675 OpenMode::Replace,
676 cx,
677 );
678 cx.spawn(async move |cx| {
679 let OpenResult { window, .. } = task.await?;
680 window.update(cx, |multi_workspace, window, cx| {
681 window.activate_window();
682 let workspace = multi_workspace.workspace().clone();
683 workspace.update(cx, |workspace, cx| {
684 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
685 });
686 })?;
687 anyhow::Ok(())
688 })
689 .detach_and_log_err(cx);
690 }
691}
692
693pub fn prompt_for_open_path_and_open(
694 workspace: &mut Workspace,
695 app_state: Arc<AppState>,
696 options: PathPromptOptions,
697 create_new_window: bool,
698 window: &mut Window,
699 cx: &mut Context<Workspace>,
700) {
701 let paths = workspace.prompt_for_open_path(
702 options,
703 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
704 window,
705 cx,
706 );
707 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
708 cx.spawn_in(window, async move |this, cx| {
709 let Some(paths) = paths.await.log_err().flatten() else {
710 return;
711 };
712 if !create_new_window {
713 if let Some(handle) = multi_workspace_handle {
714 if let Some(task) = handle
715 .update(cx, |multi_workspace, window, cx| {
716 multi_workspace.open_project(paths, OpenMode::Replace, window, cx)
717 })
718 .log_err()
719 {
720 task.await.log_err();
721 }
722 return;
723 }
724 }
725 if let Some(task) = this
726 .update_in(cx, |this, window, cx| {
727 this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
728 })
729 .log_err()
730 {
731 task.await.log_err();
732 }
733 })
734 .detach();
735}
736
737pub fn init(app_state: Arc<AppState>, cx: &mut App) {
738 component::init();
739 theme_preview::init(cx);
740 toast_layer::init(cx);
741 history_manager::init(app_state.fs.clone(), cx);
742
743 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
744 .on_action(|_: &Reload, cx| reload(cx))
745 .on_action(|_: &Open, cx: &mut App| {
746 let app_state = AppState::global(cx);
747 prompt_and_open_paths(
748 app_state,
749 PathPromptOptions {
750 files: true,
751 directories: true,
752 multiple: true,
753 prompt: None,
754 },
755 cx,
756 );
757 })
758 .on_action(|_: &OpenFiles, cx: &mut App| {
759 let directories = cx.can_select_mixed_files_and_dirs();
760 let app_state = AppState::global(cx);
761 prompt_and_open_paths(
762 app_state,
763 PathPromptOptions {
764 files: true,
765 directories,
766 multiple: true,
767 prompt: None,
768 },
769 cx,
770 );
771 });
772}
773
774type BuildProjectItemFn =
775 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
776
777type BuildProjectItemForPathFn =
778 fn(
779 &Entity<Project>,
780 &ProjectPath,
781 &mut Window,
782 &mut App,
783 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
784
785#[derive(Clone, Default)]
786struct ProjectItemRegistry {
787 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
788 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
789}
790
791impl ProjectItemRegistry {
792 fn register<T: ProjectItem>(&mut self) {
793 self.build_project_item_fns_by_type.insert(
794 TypeId::of::<T::Item>(),
795 |item, project, pane, window, cx| {
796 let item = item.downcast().unwrap();
797 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
798 as Box<dyn ItemHandle>
799 },
800 );
801 self.build_project_item_for_path_fns
802 .push(|project, project_path, window, cx| {
803 let project_path = project_path.clone();
804 let is_file = project
805 .read(cx)
806 .entry_for_path(&project_path, cx)
807 .is_some_and(|entry| entry.is_file());
808 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
809 let is_local = project.read(cx).is_local();
810 let project_item =
811 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
812 let project = project.clone();
813 Some(window.spawn(cx, async move |cx| {
814 match project_item.await.with_context(|| {
815 format!(
816 "opening project path {:?}",
817 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
818 )
819 }) {
820 Ok(project_item) => {
821 let project_item = project_item;
822 let project_entry_id: Option<ProjectEntryId> =
823 project_item.read_with(cx, project::ProjectItem::entry_id);
824 let build_workspace_item = Box::new(
825 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
826 Box::new(cx.new(|cx| {
827 T::for_project_item(
828 project,
829 Some(pane),
830 project_item,
831 window,
832 cx,
833 )
834 })) as Box<dyn ItemHandle>
835 },
836 ) as Box<_>;
837 Ok((project_entry_id, build_workspace_item))
838 }
839 Err(e) => {
840 log::warn!("Failed to open a project item: {e:#}");
841 if e.error_code() == ErrorCode::Internal {
842 if let Some(abs_path) =
843 entry_abs_path.as_deref().filter(|_| is_file)
844 {
845 if let Some(broken_project_item_view) =
846 cx.update(|window, cx| {
847 T::for_broken_project_item(
848 abs_path, is_local, &e, window, cx,
849 )
850 })?
851 {
852 let build_workspace_item = Box::new(
853 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
854 cx.new(|_| broken_project_item_view).boxed_clone()
855 },
856 )
857 as Box<_>;
858 return Ok((None, build_workspace_item));
859 }
860 }
861 }
862 Err(e)
863 }
864 }
865 }))
866 });
867 }
868
869 fn open_path(
870 &self,
871 project: &Entity<Project>,
872 path: &ProjectPath,
873 window: &mut Window,
874 cx: &mut App,
875 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
876 let Some(open_project_item) = self
877 .build_project_item_for_path_fns
878 .iter()
879 .rev()
880 .find_map(|open_project_item| open_project_item(project, path, window, cx))
881 else {
882 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
883 };
884 open_project_item
885 }
886
887 fn build_item<T: project::ProjectItem>(
888 &self,
889 item: Entity<T>,
890 project: Entity<Project>,
891 pane: Option<&Pane>,
892 window: &mut Window,
893 cx: &mut App,
894 ) -> Option<Box<dyn ItemHandle>> {
895 let build = self
896 .build_project_item_fns_by_type
897 .get(&TypeId::of::<T>())?;
898 Some(build(item.into_any(), project, pane, window, cx))
899 }
900}
901
902type WorkspaceItemBuilder =
903 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
904
905impl Global for ProjectItemRegistry {}
906
907/// Registers a [ProjectItem] for the app. When opening a file, all the registered
908/// items will get a chance to open the file, starting from the project item that
909/// was added last.
910pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
911 cx.default_global::<ProjectItemRegistry>().register::<I>();
912}
913
914#[derive(Default)]
915pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
916
917struct FollowableViewDescriptor {
918 from_state_proto: fn(
919 Entity<Workspace>,
920 ViewId,
921 &mut Option<proto::view::Variant>,
922 &mut Window,
923 &mut App,
924 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
925 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
926}
927
928impl Global for FollowableViewRegistry {}
929
930impl FollowableViewRegistry {
931 pub fn register<I: FollowableItem>(cx: &mut App) {
932 cx.default_global::<Self>().0.insert(
933 TypeId::of::<I>(),
934 FollowableViewDescriptor {
935 from_state_proto: |workspace, id, state, window, cx| {
936 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
937 cx.foreground_executor()
938 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
939 })
940 },
941 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
942 },
943 );
944 }
945
946 pub fn from_state_proto(
947 workspace: Entity<Workspace>,
948 view_id: ViewId,
949 mut state: Option<proto::view::Variant>,
950 window: &mut Window,
951 cx: &mut App,
952 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
953 cx.update_default_global(|this: &mut Self, cx| {
954 this.0.values().find_map(|descriptor| {
955 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
956 })
957 })
958 }
959
960 pub fn to_followable_view(
961 view: impl Into<AnyView>,
962 cx: &App,
963 ) -> Option<Box<dyn FollowableItemHandle>> {
964 let this = cx.try_global::<Self>()?;
965 let view = view.into();
966 let descriptor = this.0.get(&view.entity_type())?;
967 Some((descriptor.to_followable_view)(&view))
968 }
969}
970
971#[derive(Copy, Clone)]
972struct SerializableItemDescriptor {
973 deserialize: fn(
974 Entity<Project>,
975 WeakEntity<Workspace>,
976 WorkspaceId,
977 ItemId,
978 &mut Window,
979 &mut Context<Pane>,
980 ) -> Task<Result<Box<dyn ItemHandle>>>,
981 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
982 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
983}
984
985#[derive(Default)]
986struct SerializableItemRegistry {
987 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
988 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
989}
990
991impl Global for SerializableItemRegistry {}
992
993impl SerializableItemRegistry {
994 fn deserialize(
995 item_kind: &str,
996 project: Entity<Project>,
997 workspace: WeakEntity<Workspace>,
998 workspace_id: WorkspaceId,
999 item_item: ItemId,
1000 window: &mut Window,
1001 cx: &mut Context<Pane>,
1002 ) -> Task<Result<Box<dyn ItemHandle>>> {
1003 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1004 return Task::ready(Err(anyhow!(
1005 "cannot deserialize {}, descriptor not found",
1006 item_kind
1007 )));
1008 };
1009
1010 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1011 }
1012
1013 fn cleanup(
1014 item_kind: &str,
1015 workspace_id: WorkspaceId,
1016 loaded_items: Vec<ItemId>,
1017 window: &mut Window,
1018 cx: &mut App,
1019 ) -> Task<Result<()>> {
1020 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1021 return Task::ready(Err(anyhow!(
1022 "cannot cleanup {}, descriptor not found",
1023 item_kind
1024 )));
1025 };
1026
1027 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1028 }
1029
1030 fn view_to_serializable_item_handle(
1031 view: AnyView,
1032 cx: &App,
1033 ) -> Option<Box<dyn SerializableItemHandle>> {
1034 let this = cx.try_global::<Self>()?;
1035 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1036 Some((descriptor.view_to_serializable_item)(view))
1037 }
1038
1039 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1040 let this = cx.try_global::<Self>()?;
1041 this.descriptors_by_kind.get(item_kind).copied()
1042 }
1043}
1044
1045pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1046 let serialized_item_kind = I::serialized_item_kind();
1047
1048 let registry = cx.default_global::<SerializableItemRegistry>();
1049 let descriptor = SerializableItemDescriptor {
1050 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1051 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1052 cx.foreground_executor()
1053 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1054 },
1055 cleanup: |workspace_id, loaded_items, window, cx| {
1056 I::cleanup(workspace_id, loaded_items, window, cx)
1057 },
1058 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1059 };
1060 registry
1061 .descriptors_by_kind
1062 .insert(Arc::from(serialized_item_kind), descriptor);
1063 registry
1064 .descriptors_by_type
1065 .insert(TypeId::of::<I>(), descriptor);
1066}
1067
1068pub struct AppState {
1069 pub languages: Arc<LanguageRegistry>,
1070 pub client: Arc<Client>,
1071 pub user_store: Entity<UserStore>,
1072 pub workspace_store: Entity<WorkspaceStore>,
1073 pub fs: Arc<dyn fs::Fs>,
1074 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1075 pub node_runtime: NodeRuntime,
1076 pub session: Entity<AppSession>,
1077}
1078
1079struct GlobalAppState(Arc<AppState>);
1080
1081impl Global for GlobalAppState {}
1082
1083pub struct WorkspaceStore {
1084 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1085 client: Arc<Client>,
1086 _subscriptions: Vec<client::Subscription>,
1087}
1088
1089#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1090pub enum CollaboratorId {
1091 PeerId(PeerId),
1092 Agent,
1093}
1094
1095impl From<PeerId> for CollaboratorId {
1096 fn from(peer_id: PeerId) -> Self {
1097 CollaboratorId::PeerId(peer_id)
1098 }
1099}
1100
1101impl From<&PeerId> for CollaboratorId {
1102 fn from(peer_id: &PeerId) -> Self {
1103 CollaboratorId::PeerId(*peer_id)
1104 }
1105}
1106
1107#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1108struct Follower {
1109 project_id: Option<u64>,
1110 peer_id: PeerId,
1111}
1112
1113impl AppState {
1114 #[track_caller]
1115 pub fn global(cx: &App) -> Arc<Self> {
1116 cx.global::<GlobalAppState>().0.clone()
1117 }
1118 pub fn try_global(cx: &App) -> Option<Arc<Self>> {
1119 cx.try_global::<GlobalAppState>()
1120 .map(|state| state.0.clone())
1121 }
1122 pub fn set_global(state: Arc<AppState>, cx: &mut App) {
1123 cx.set_global(GlobalAppState(state));
1124 }
1125
1126 #[cfg(any(test, feature = "test-support"))]
1127 pub fn test(cx: &mut App) -> Arc<Self> {
1128 use fs::Fs;
1129 use node_runtime::NodeRuntime;
1130 use session::Session;
1131 use settings::SettingsStore;
1132
1133 if !cx.has_global::<SettingsStore>() {
1134 let settings_store = SettingsStore::test(cx);
1135 cx.set_global(settings_store);
1136 }
1137
1138 let fs = fs::FakeFs::new(cx.background_executor().clone());
1139 <dyn Fs>::set_global(fs.clone(), cx);
1140 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1141 let clock = Arc::new(clock::FakeSystemClock::new());
1142 let http_client = http_client::FakeHttpClient::with_404_response();
1143 let client = Client::new(clock, http_client, cx);
1144 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1145 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1146 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1147
1148 theme_settings::init(theme::LoadThemes::JustBase, cx);
1149 client::init(&client, cx);
1150
1151 Arc::new(Self {
1152 client,
1153 fs,
1154 languages,
1155 user_store,
1156 workspace_store,
1157 node_runtime: NodeRuntime::unavailable(),
1158 build_window_options: |_, _| Default::default(),
1159 session,
1160 })
1161 }
1162}
1163
1164struct DelayedDebouncedEditAction {
1165 task: Option<Task<()>>,
1166 cancel_channel: Option<oneshot::Sender<()>>,
1167}
1168
1169impl DelayedDebouncedEditAction {
1170 fn new() -> DelayedDebouncedEditAction {
1171 DelayedDebouncedEditAction {
1172 task: None,
1173 cancel_channel: None,
1174 }
1175 }
1176
1177 fn fire_new<F>(
1178 &mut self,
1179 delay: Duration,
1180 window: &mut Window,
1181 cx: &mut Context<Workspace>,
1182 func: F,
1183 ) where
1184 F: 'static
1185 + Send
1186 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1187 {
1188 if let Some(channel) = self.cancel_channel.take() {
1189 _ = channel.send(());
1190 }
1191
1192 let (sender, mut receiver) = oneshot::channel::<()>();
1193 self.cancel_channel = Some(sender);
1194
1195 let previous_task = self.task.take();
1196 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1197 let mut timer = cx.background_executor().timer(delay).fuse();
1198 if let Some(previous_task) = previous_task {
1199 previous_task.await;
1200 }
1201
1202 futures::select_biased! {
1203 _ = receiver => return,
1204 _ = timer => {}
1205 }
1206
1207 if let Some(result) = workspace
1208 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1209 .log_err()
1210 {
1211 result.await.log_err();
1212 }
1213 }));
1214 }
1215}
1216
1217pub enum Event {
1218 PaneAdded(Entity<Pane>),
1219 PaneRemoved,
1220 ItemAdded {
1221 item: Box<dyn ItemHandle>,
1222 },
1223 ActiveItemChanged,
1224 ItemRemoved {
1225 item_id: EntityId,
1226 },
1227 UserSavedItem {
1228 pane: WeakEntity<Pane>,
1229 item: Box<dyn WeakItemHandle>,
1230 save_intent: SaveIntent,
1231 },
1232 ContactRequestedJoin(u64),
1233 WorkspaceCreated(WeakEntity<Workspace>),
1234 OpenBundledFile {
1235 text: Cow<'static, str>,
1236 title: &'static str,
1237 language: &'static str,
1238 },
1239 ZoomChanged,
1240 ModalOpened,
1241 Activate,
1242 PanelAdded(AnyView),
1243}
1244
1245#[derive(Debug, Clone)]
1246pub enum OpenVisible {
1247 All,
1248 None,
1249 OnlyFiles,
1250 OnlyDirectories,
1251}
1252
1253enum WorkspaceLocation {
1254 // Valid local paths or SSH project to serialize
1255 Location(SerializedWorkspaceLocation, PathList),
1256 // No valid location found hence clear session id
1257 DetachFromSession,
1258 // No valid location found to serialize
1259 None,
1260}
1261
1262type PromptForNewPath = Box<
1263 dyn Fn(
1264 &mut Workspace,
1265 DirectoryLister,
1266 Option<String>,
1267 &mut Window,
1268 &mut Context<Workspace>,
1269 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1270>;
1271
1272type PromptForOpenPath = Box<
1273 dyn Fn(
1274 &mut Workspace,
1275 DirectoryLister,
1276 &mut Window,
1277 &mut Context<Workspace>,
1278 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1279>;
1280
1281#[derive(Default)]
1282struct DispatchingKeystrokes {
1283 dispatched: HashSet<Vec<Keystroke>>,
1284 queue: VecDeque<Keystroke>,
1285 task: Option<Shared<Task<()>>>,
1286}
1287
1288/// Collects everything project-related for a certain window opened.
1289/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1290///
1291/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1292/// The `Workspace` owns everybody's state and serves as a default, "global context",
1293/// that can be used to register a global action to be triggered from any place in the window.
1294pub struct Workspace {
1295 weak_self: WeakEntity<Self>,
1296 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1297 zoomed: Option<AnyWeakView>,
1298 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1299 zoomed_position: Option<DockPosition>,
1300 center: PaneGroup,
1301 left_dock: Entity<Dock>,
1302 bottom_dock: Entity<Dock>,
1303 right_dock: Entity<Dock>,
1304 panes: Vec<Entity<Pane>>,
1305 active_worktree_override: Option<WorktreeId>,
1306 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1307 active_pane: Entity<Pane>,
1308 last_active_center_pane: Option<WeakEntity<Pane>>,
1309 last_active_view_id: Option<proto::ViewId>,
1310 status_bar: Entity<StatusBar>,
1311 pub(crate) modal_layer: Entity<ModalLayer>,
1312 toast_layer: Entity<ToastLayer>,
1313 titlebar_item: Option<AnyView>,
1314 notifications: Notifications,
1315 suppressed_notifications: HashSet<NotificationId>,
1316 project: Entity<Project>,
1317 follower_states: HashMap<CollaboratorId, FollowerState>,
1318 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1319 window_edited: bool,
1320 last_window_title: Option<String>,
1321 dirty_items: HashMap<EntityId, Subscription>,
1322 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1323 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1324 database_id: Option<WorkspaceId>,
1325 app_state: Arc<AppState>,
1326 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1327 _subscriptions: Vec<Subscription>,
1328 _apply_leader_updates: Task<Result<()>>,
1329 _observe_current_user: Task<Result<()>>,
1330 _schedule_serialize_workspace: Option<Task<()>>,
1331 _serialize_workspace_task: Option<Task<()>>,
1332 _schedule_serialize_ssh_paths: Option<Task<()>>,
1333 pane_history_timestamp: Arc<AtomicUsize>,
1334 bounds: Bounds<Pixels>,
1335 pub centered_layout: bool,
1336 bounds_save_task_queued: Option<Task<()>>,
1337 on_prompt_for_new_path: Option<PromptForNewPath>,
1338 on_prompt_for_open_path: Option<PromptForOpenPath>,
1339 terminal_provider: Option<Box<dyn TerminalProvider>>,
1340 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1341 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1342 _items_serializer: Task<Result<()>>,
1343 session_id: Option<String>,
1344 scheduled_tasks: Vec<Task<()>>,
1345 last_open_dock_positions: Vec<DockPosition>,
1346 removing: bool,
1347 _panels_task: Option<Task<Result<()>>>,
1348 sidebar_focus_handle: Option<FocusHandle>,
1349 multi_workspace: Option<WeakEntity<MultiWorkspace>>,
1350}
1351
1352impl EventEmitter<Event> for Workspace {}
1353
1354#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1355pub struct ViewId {
1356 pub creator: CollaboratorId,
1357 pub id: u64,
1358}
1359
1360pub struct FollowerState {
1361 center_pane: Entity<Pane>,
1362 dock_pane: Option<Entity<Pane>>,
1363 active_view_id: Option<ViewId>,
1364 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1365}
1366
1367struct FollowerView {
1368 view: Box<dyn FollowableItemHandle>,
1369 location: Option<proto::PanelId>,
1370}
1371
1372#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1373pub enum OpenMode {
1374 /// Open the workspace in a new window.
1375 NewWindow,
1376 /// Add to the window's multi workspace without activating it (used during deserialization).
1377 Add,
1378 /// Add to the window's multi workspace and activate it.
1379 #[default]
1380 Activate,
1381 /// Replace the currently active workspace, and any of it's linked workspaces
1382 Replace,
1383}
1384
1385impl Workspace {
1386 pub fn new(
1387 workspace_id: Option<WorkspaceId>,
1388 project: Entity<Project>,
1389 app_state: Arc<AppState>,
1390 window: &mut Window,
1391 cx: &mut Context<Self>,
1392 ) -> Self {
1393 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1394 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1395 if let TrustedWorktreesEvent::Trusted(..) = e {
1396 // Do not persist auto trusted worktrees
1397 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1398 worktrees_store.update(cx, |worktrees_store, cx| {
1399 worktrees_store.schedule_serialization(
1400 cx,
1401 |new_trusted_worktrees, cx| {
1402 let timeout =
1403 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1404 let db = WorkspaceDb::global(cx);
1405 cx.background_spawn(async move {
1406 timeout.await;
1407 db.save_trusted_worktrees(new_trusted_worktrees)
1408 .await
1409 .log_err();
1410 })
1411 },
1412 )
1413 });
1414 }
1415 }
1416 })
1417 .detach();
1418
1419 cx.observe_global::<SettingsStore>(|_, cx| {
1420 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1421 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1422 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1423 trusted_worktrees.auto_trust_all(cx);
1424 })
1425 }
1426 }
1427 })
1428 .detach();
1429 }
1430
1431 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1432 match event {
1433 project::Event::RemoteIdChanged(_) => {
1434 this.update_window_title(window, cx);
1435 }
1436
1437 project::Event::CollaboratorLeft(peer_id) => {
1438 this.collaborator_left(*peer_id, window, cx);
1439 }
1440
1441 &project::Event::WorktreeRemoved(_) => {
1442 this.update_window_title(window, cx);
1443 this.serialize_workspace(window, cx);
1444 this.update_history(cx);
1445 }
1446
1447 &project::Event::WorktreeAdded(id) => {
1448 this.update_window_title(window, cx);
1449 if this
1450 .project()
1451 .read(cx)
1452 .worktree_for_id(id, cx)
1453 .is_some_and(|wt| wt.read(cx).is_visible())
1454 {
1455 this.serialize_workspace(window, cx);
1456 this.update_history(cx);
1457 }
1458 }
1459 project::Event::WorktreeUpdatedEntries(..) => {
1460 this.update_window_title(window, cx);
1461 this.serialize_workspace(window, cx);
1462 }
1463
1464 project::Event::DisconnectedFromHost => {
1465 this.update_window_edited(window, cx);
1466 let leaders_to_unfollow =
1467 this.follower_states.keys().copied().collect::<Vec<_>>();
1468 for leader_id in leaders_to_unfollow {
1469 this.unfollow(leader_id, window, cx);
1470 }
1471 }
1472
1473 project::Event::DisconnectedFromRemote {
1474 server_not_running: _,
1475 } => {
1476 this.update_window_edited(window, cx);
1477 }
1478
1479 project::Event::Closed => {
1480 window.remove_window();
1481 }
1482
1483 project::Event::DeletedEntry(_, entry_id) => {
1484 for pane in this.panes.iter() {
1485 pane.update(cx, |pane, cx| {
1486 pane.handle_deleted_project_item(*entry_id, window, cx)
1487 });
1488 }
1489 }
1490
1491 project::Event::Toast {
1492 notification_id,
1493 message,
1494 link,
1495 } => this.show_notification(
1496 NotificationId::named(notification_id.clone()),
1497 cx,
1498 |cx| {
1499 let mut notification = MessageNotification::new(message.clone(), cx);
1500 if let Some(link) = link {
1501 notification = notification
1502 .more_info_message(link.label)
1503 .more_info_url(link.url);
1504 }
1505
1506 cx.new(|_| notification)
1507 },
1508 ),
1509
1510 project::Event::HideToast { notification_id } => {
1511 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1512 }
1513
1514 project::Event::LanguageServerPrompt(request) => {
1515 struct LanguageServerPrompt;
1516
1517 this.show_notification(
1518 NotificationId::composite::<LanguageServerPrompt>(request.id),
1519 cx,
1520 |cx| {
1521 cx.new(|cx| {
1522 notifications::LanguageServerPrompt::new(request.clone(), cx)
1523 })
1524 },
1525 );
1526 }
1527
1528 project::Event::AgentLocationChanged => {
1529 this.handle_agent_location_changed(window, cx)
1530 }
1531
1532 _ => {}
1533 }
1534 cx.notify()
1535 })
1536 .detach();
1537
1538 cx.subscribe_in(
1539 &project.read(cx).breakpoint_store(),
1540 window,
1541 |workspace, _, event, window, cx| match event {
1542 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1543 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1544 workspace.serialize_workspace(window, cx);
1545 }
1546 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1547 },
1548 )
1549 .detach();
1550 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1551 cx.subscribe_in(
1552 &toolchain_store,
1553 window,
1554 |workspace, _, event, window, cx| match event {
1555 ToolchainStoreEvent::CustomToolchainsModified => {
1556 workspace.serialize_workspace(window, cx);
1557 }
1558 _ => {}
1559 },
1560 )
1561 .detach();
1562 }
1563
1564 cx.on_focus_lost(window, |this, window, cx| {
1565 let focus_handle = this.focus_handle(cx);
1566 window.focus(&focus_handle, cx);
1567 })
1568 .detach();
1569
1570 let weak_handle = cx.entity().downgrade();
1571 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1572
1573 let center_pane = cx.new(|cx| {
1574 let mut center_pane = Pane::new(
1575 weak_handle.clone(),
1576 project.clone(),
1577 pane_history_timestamp.clone(),
1578 None,
1579 NewFile.boxed_clone(),
1580 true,
1581 window,
1582 cx,
1583 );
1584 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1585 center_pane.set_should_display_welcome_page(true);
1586 center_pane
1587 });
1588 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1589 .detach();
1590
1591 window.focus(¢er_pane.focus_handle(cx), cx);
1592
1593 cx.emit(Event::PaneAdded(center_pane.clone()));
1594
1595 let any_window_handle = window.window_handle();
1596 app_state.workspace_store.update(cx, |store, _| {
1597 store
1598 .workspaces
1599 .insert((any_window_handle, weak_handle.clone()));
1600 });
1601
1602 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1603 let mut connection_status = app_state.client.status();
1604 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1605 current_user.next().await;
1606 connection_status.next().await;
1607 let mut stream =
1608 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1609
1610 while stream.recv().await.is_some() {
1611 this.update(cx, |_, cx| cx.notify())?;
1612 }
1613 anyhow::Ok(())
1614 });
1615
1616 // All leader updates are enqueued and then processed in a single task, so
1617 // that each asynchronous operation can be run in order.
1618 let (leader_updates_tx, mut leader_updates_rx) =
1619 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1620 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1621 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1622 Self::process_leader_update(&this, leader_id, update, cx)
1623 .await
1624 .log_err();
1625 }
1626
1627 Ok(())
1628 });
1629
1630 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1631 let modal_layer = cx.new(|_| ModalLayer::new());
1632 let toast_layer = cx.new(|_| ToastLayer::new());
1633 cx.subscribe(
1634 &modal_layer,
1635 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1636 cx.emit(Event::ModalOpened);
1637 },
1638 )
1639 .detach();
1640
1641 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1642 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1643 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1644 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1645 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1646 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1647 let multi_workspace = window
1648 .root::<MultiWorkspace>()
1649 .flatten()
1650 .map(|mw| mw.downgrade());
1651 let status_bar = cx.new(|cx| {
1652 let mut status_bar =
1653 StatusBar::new(¢er_pane.clone(), multi_workspace.clone(), window, cx);
1654 status_bar.add_left_item(left_dock_buttons, window, cx);
1655 status_bar.add_right_item(right_dock_buttons, window, cx);
1656 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1657 status_bar
1658 });
1659
1660 let session_id = app_state.session.read(cx).id().to_owned();
1661
1662 let mut active_call = None;
1663 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1664 let subscriptions =
1665 vec![
1666 call.0
1667 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1668 ];
1669 active_call = Some((call, subscriptions));
1670 }
1671
1672 let (serializable_items_tx, serializable_items_rx) =
1673 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1674 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1675 Self::serialize_items(&this, serializable_items_rx, cx).await
1676 });
1677
1678 let subscriptions = vec![
1679 cx.observe_window_activation(window, Self::on_window_activation_changed),
1680 cx.observe_window_bounds(window, move |this, window, cx| {
1681 if this.bounds_save_task_queued.is_some() {
1682 return;
1683 }
1684 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1685 cx.background_executor()
1686 .timer(Duration::from_millis(100))
1687 .await;
1688 this.update_in(cx, |this, window, cx| {
1689 this.save_window_bounds(window, cx).detach();
1690 this.bounds_save_task_queued.take();
1691 })
1692 .ok();
1693 }));
1694 cx.notify();
1695 }),
1696 cx.observe_window_appearance(window, |_, window, cx| {
1697 let window_appearance = window.appearance();
1698
1699 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1700
1701 theme_settings::reload_theme(cx);
1702 theme_settings::reload_icon_theme(cx);
1703 }),
1704 cx.on_release({
1705 let weak_handle = weak_handle.clone();
1706 move |this, cx| {
1707 this.app_state.workspace_store.update(cx, move |store, _| {
1708 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1709 })
1710 }
1711 }),
1712 ];
1713
1714 cx.defer_in(window, move |this, window, cx| {
1715 this.update_window_title(window, cx);
1716 this.show_initial_notifications(cx);
1717 });
1718
1719 let mut center = PaneGroup::new(center_pane.clone());
1720 center.set_is_center(true);
1721 center.mark_positions(cx);
1722
1723 Workspace {
1724 weak_self: weak_handle.clone(),
1725 zoomed: None,
1726 zoomed_position: None,
1727 previous_dock_drag_coordinates: None,
1728 center,
1729 panes: vec![center_pane.clone()],
1730 panes_by_item: Default::default(),
1731 active_pane: center_pane.clone(),
1732 last_active_center_pane: Some(center_pane.downgrade()),
1733 last_active_view_id: None,
1734 status_bar,
1735 modal_layer,
1736 toast_layer,
1737 titlebar_item: None,
1738 active_worktree_override: None,
1739 notifications: Notifications::default(),
1740 suppressed_notifications: HashSet::default(),
1741 left_dock,
1742 bottom_dock,
1743 right_dock,
1744 _panels_task: None,
1745 project: project.clone(),
1746 follower_states: Default::default(),
1747 last_leaders_by_pane: Default::default(),
1748 dispatching_keystrokes: Default::default(),
1749 window_edited: false,
1750 last_window_title: None,
1751 dirty_items: Default::default(),
1752 active_call,
1753 database_id: workspace_id,
1754 app_state,
1755 _observe_current_user,
1756 _apply_leader_updates,
1757 _schedule_serialize_workspace: None,
1758 _serialize_workspace_task: None,
1759 _schedule_serialize_ssh_paths: None,
1760 leader_updates_tx,
1761 _subscriptions: subscriptions,
1762 pane_history_timestamp,
1763 workspace_actions: Default::default(),
1764 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1765 bounds: Default::default(),
1766 centered_layout: false,
1767 bounds_save_task_queued: None,
1768 on_prompt_for_new_path: None,
1769 on_prompt_for_open_path: None,
1770 terminal_provider: None,
1771 debugger_provider: None,
1772 serializable_items_tx,
1773 _items_serializer,
1774 session_id: Some(session_id),
1775
1776 scheduled_tasks: Vec::new(),
1777 last_open_dock_positions: Vec::new(),
1778 removing: false,
1779 sidebar_focus_handle: None,
1780 multi_workspace,
1781 }
1782 }
1783
1784 pub fn new_local(
1785 abs_paths: Vec<PathBuf>,
1786 app_state: Arc<AppState>,
1787 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1788 env: Option<HashMap<String, String>>,
1789 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1790 open_mode: OpenMode,
1791 cx: &mut App,
1792 ) -> Task<anyhow::Result<OpenResult>> {
1793 let project_handle = Project::local(
1794 app_state.client.clone(),
1795 app_state.node_runtime.clone(),
1796 app_state.user_store.clone(),
1797 app_state.languages.clone(),
1798 app_state.fs.clone(),
1799 env,
1800 Default::default(),
1801 cx,
1802 );
1803
1804 let db = WorkspaceDb::global(cx);
1805 let kvp = db::kvp::KeyValueStore::global(cx);
1806 cx.spawn(async move |cx| {
1807 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1808 for path in abs_paths.into_iter() {
1809 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1810 paths_to_open.push(canonical)
1811 } else {
1812 paths_to_open.push(path)
1813 }
1814 }
1815
1816 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1817
1818 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1819 paths_to_open = paths.ordered_paths().cloned().collect();
1820 if !paths.is_lexicographically_ordered() {
1821 project_handle.update(cx, |project, cx| {
1822 project.set_worktrees_reordered(true, cx);
1823 });
1824 }
1825 }
1826
1827 // Get project paths for all of the abs_paths
1828 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1829 Vec::with_capacity(paths_to_open.len());
1830
1831 for path in paths_to_open.into_iter() {
1832 if let Some((_, project_entry)) = cx
1833 .update(|cx| {
1834 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1835 })
1836 .await
1837 .log_err()
1838 {
1839 project_paths.push((path, Some(project_entry)));
1840 } else {
1841 project_paths.push((path, None));
1842 }
1843 }
1844
1845 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1846 serialized_workspace.id
1847 } else {
1848 db.next_id().await.unwrap_or_else(|_| Default::default())
1849 };
1850
1851 let toolchains = db.toolchains(workspace_id).await?;
1852
1853 for (toolchain, worktree_path, path) in toolchains {
1854 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1855 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1856 this.find_worktree(&worktree_path, cx)
1857 .and_then(|(worktree, rel_path)| {
1858 if rel_path.is_empty() {
1859 Some(worktree.read(cx).id())
1860 } else {
1861 None
1862 }
1863 })
1864 }) else {
1865 // We did not find a worktree with a given path, but that's whatever.
1866 continue;
1867 };
1868 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1869 continue;
1870 }
1871
1872 project_handle
1873 .update(cx, |this, cx| {
1874 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1875 })
1876 .await;
1877 }
1878 if let Some(workspace) = serialized_workspace.as_ref() {
1879 project_handle.update(cx, |this, cx| {
1880 for (scope, toolchains) in &workspace.user_toolchains {
1881 for toolchain in toolchains {
1882 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1883 }
1884 }
1885 });
1886 }
1887
1888 let window_to_replace = match open_mode {
1889 OpenMode::NewWindow => None,
1890 _ => requesting_window,
1891 };
1892
1893 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1894 if let Some(window) = window_to_replace {
1895 let centered_layout = serialized_workspace
1896 .as_ref()
1897 .map(|w| w.centered_layout)
1898 .unwrap_or(false);
1899
1900 let workspace = window.update(cx, |multi_workspace, window, cx| {
1901 let workspace = cx.new(|cx| {
1902 let mut workspace = Workspace::new(
1903 Some(workspace_id),
1904 project_handle.clone(),
1905 app_state.clone(),
1906 window,
1907 cx,
1908 );
1909
1910 workspace.centered_layout = centered_layout;
1911
1912 // Call init callback to add items before window renders
1913 if let Some(init) = init {
1914 init(&mut workspace, window, cx);
1915 }
1916
1917 workspace
1918 });
1919 match open_mode {
1920 OpenMode::Replace => {
1921 multi_workspace.replace(workspace.clone(), &*window, cx);
1922 }
1923 OpenMode::Activate => {
1924 multi_workspace.activate(workspace.clone(), window, cx);
1925 }
1926 OpenMode::Add => {
1927 multi_workspace.add(workspace.clone(), &*window, cx);
1928 }
1929 OpenMode::NewWindow => {
1930 unreachable!()
1931 }
1932 }
1933 workspace
1934 })?;
1935 (window, workspace)
1936 } else {
1937 let window_bounds_override = window_bounds_env_override();
1938
1939 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1940 (Some(WindowBounds::Windowed(bounds)), None)
1941 } else if let Some(workspace) = serialized_workspace.as_ref()
1942 && let Some(display) = workspace.display
1943 && let Some(bounds) = workspace.window_bounds.as_ref()
1944 {
1945 // Reopening an existing workspace - restore its saved bounds
1946 (Some(bounds.0), Some(display))
1947 } else if let Some((display, bounds)) =
1948 persistence::read_default_window_bounds(&kvp)
1949 {
1950 // New or empty workspace - use the last known window bounds
1951 (Some(bounds), Some(display))
1952 } else {
1953 // New window - let GPUI's default_bounds() handle cascading
1954 (None, None)
1955 };
1956
1957 // Use the serialized workspace to construct the new window
1958 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1959 options.window_bounds = window_bounds;
1960 let centered_layout = serialized_workspace
1961 .as_ref()
1962 .map(|w| w.centered_layout)
1963 .unwrap_or(false);
1964 let window = cx.open_window(options, {
1965 let app_state = app_state.clone();
1966 let project_handle = project_handle.clone();
1967 move |window, cx| {
1968 let workspace = cx.new(|cx| {
1969 let mut workspace = Workspace::new(
1970 Some(workspace_id),
1971 project_handle,
1972 app_state,
1973 window,
1974 cx,
1975 );
1976 workspace.centered_layout = centered_layout;
1977
1978 // Call init callback to add items before window renders
1979 if let Some(init) = init {
1980 init(&mut workspace, window, cx);
1981 }
1982
1983 workspace
1984 });
1985 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1986 }
1987 })?;
1988 let workspace =
1989 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1990 multi_workspace.workspace().clone()
1991 })?;
1992 (window, workspace)
1993 };
1994
1995 notify_if_database_failed(window, cx);
1996 // Check if this is an empty workspace (no paths to open)
1997 // An empty workspace is one where project_paths is empty
1998 let is_empty_workspace = project_paths.is_empty();
1999 // Check if serialized workspace has paths before it's moved
2000 let serialized_workspace_has_paths = serialized_workspace
2001 .as_ref()
2002 .map(|ws| !ws.paths.is_empty())
2003 .unwrap_or(false);
2004
2005 let opened_items = window
2006 .update(cx, |_, window, cx| {
2007 workspace.update(cx, |_workspace: &mut Workspace, cx| {
2008 open_items(serialized_workspace, project_paths, window, cx)
2009 })
2010 })?
2011 .await
2012 .unwrap_or_default();
2013
2014 // Restore default dock state for empty workspaces
2015 // Only restore if:
2016 // 1. This is an empty workspace (no paths), AND
2017 // 2. The serialized workspace either doesn't exist or has no paths
2018 if is_empty_workspace && !serialized_workspace_has_paths {
2019 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
2020 window
2021 .update(cx, |_, window, cx| {
2022 workspace.update(cx, |workspace, cx| {
2023 for (dock, serialized_dock) in [
2024 (&workspace.right_dock, &default_docks.right),
2025 (&workspace.left_dock, &default_docks.left),
2026 (&workspace.bottom_dock, &default_docks.bottom),
2027 ] {
2028 dock.update(cx, |dock, cx| {
2029 dock.serialized_dock = Some(serialized_dock.clone());
2030 dock.restore_state(window, cx);
2031 });
2032 }
2033 cx.notify();
2034 });
2035 })
2036 .log_err();
2037 }
2038 }
2039
2040 window
2041 .update(cx, |_, _window, cx| {
2042 workspace.update(cx, |this: &mut Workspace, cx| {
2043 this.update_history(cx);
2044 });
2045 })
2046 .log_err();
2047 Ok(OpenResult {
2048 window,
2049 workspace,
2050 opened_items,
2051 })
2052 })
2053 }
2054
2055 pub fn weak_handle(&self) -> WeakEntity<Self> {
2056 self.weak_self.clone()
2057 }
2058
2059 pub fn left_dock(&self) -> &Entity<Dock> {
2060 &self.left_dock
2061 }
2062
2063 pub fn bottom_dock(&self) -> &Entity<Dock> {
2064 &self.bottom_dock
2065 }
2066
2067 pub fn set_bottom_dock_layout(
2068 &mut self,
2069 layout: BottomDockLayout,
2070 window: &mut Window,
2071 cx: &mut Context<Self>,
2072 ) {
2073 let fs = self.project().read(cx).fs();
2074 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2075 content.workspace.bottom_dock_layout = Some(layout);
2076 });
2077
2078 cx.notify();
2079 self.serialize_workspace(window, cx);
2080 }
2081
2082 pub fn right_dock(&self) -> &Entity<Dock> {
2083 &self.right_dock
2084 }
2085
2086 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2087 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2088 }
2089
2090 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2091 let left_dock = self.left_dock.read(cx);
2092 let left_visible = left_dock.is_open();
2093 let left_active_panel = left_dock
2094 .active_panel()
2095 .map(|panel| panel.persistent_name().to_string());
2096 // `zoomed_position` is kept in sync with individual panel zoom state
2097 // by the dock code in `Dock::new` and `Dock::add_panel`.
2098 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2099
2100 let right_dock = self.right_dock.read(cx);
2101 let right_visible = right_dock.is_open();
2102 let right_active_panel = right_dock
2103 .active_panel()
2104 .map(|panel| panel.persistent_name().to_string());
2105 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2106
2107 let bottom_dock = self.bottom_dock.read(cx);
2108 let bottom_visible = bottom_dock.is_open();
2109 let bottom_active_panel = bottom_dock
2110 .active_panel()
2111 .map(|panel| panel.persistent_name().to_string());
2112 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2113
2114 DockStructure {
2115 left: DockData {
2116 visible: left_visible,
2117 active_panel: left_active_panel,
2118 zoom: left_dock_zoom,
2119 },
2120 right: DockData {
2121 visible: right_visible,
2122 active_panel: right_active_panel,
2123 zoom: right_dock_zoom,
2124 },
2125 bottom: DockData {
2126 visible: bottom_visible,
2127 active_panel: bottom_active_panel,
2128 zoom: bottom_dock_zoom,
2129 },
2130 }
2131 }
2132
2133 pub fn set_dock_structure(
2134 &self,
2135 docks: DockStructure,
2136 window: &mut Window,
2137 cx: &mut Context<Self>,
2138 ) {
2139 for (dock, data) in [
2140 (&self.left_dock, docks.left),
2141 (&self.bottom_dock, docks.bottom),
2142 (&self.right_dock, docks.right),
2143 ] {
2144 dock.update(cx, |dock, cx| {
2145 dock.serialized_dock = Some(data);
2146 dock.restore_state(window, cx);
2147 });
2148 }
2149 }
2150
2151 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2152 self.items(cx)
2153 .filter_map(|item| {
2154 let project_path = item.project_path(cx)?;
2155 self.project.read(cx).absolute_path(&project_path, cx)
2156 })
2157 .collect()
2158 }
2159
2160 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2161 match position {
2162 DockPosition::Left => &self.left_dock,
2163 DockPosition::Bottom => &self.bottom_dock,
2164 DockPosition::Right => &self.right_dock,
2165 }
2166 }
2167
2168 pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
2169 self.all_docks().into_iter().find_map(|dock| {
2170 let dock = dock.read(cx);
2171 dock.has_agent_panel(cx).then_some(dock.position())
2172 })
2173 }
2174
2175 pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
2176 self.all_docks().into_iter().find_map(|dock| {
2177 let dock = dock.read(cx);
2178 let panel = dock.panel::<T>()?;
2179 dock.stored_panel_size_state(&panel)
2180 })
2181 }
2182
2183 pub fn persisted_panel_size_state(
2184 &self,
2185 panel_key: &'static str,
2186 cx: &App,
2187 ) -> Option<dock::PanelSizeState> {
2188 dock::Dock::load_persisted_size_state(self, panel_key, cx)
2189 }
2190
2191 pub fn persist_panel_size_state(
2192 &self,
2193 panel_key: &str,
2194 size_state: dock::PanelSizeState,
2195 cx: &mut App,
2196 ) {
2197 let Some(workspace_id) = self
2198 .database_id()
2199 .map(|id| i64::from(id).to_string())
2200 .or(self.session_id())
2201 else {
2202 return;
2203 };
2204
2205 let kvp = db::kvp::KeyValueStore::global(cx);
2206 let panel_key = panel_key.to_string();
2207 cx.background_spawn(async move {
2208 let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
2209 scope
2210 .write(
2211 format!("{workspace_id}:{panel_key}"),
2212 serde_json::to_string(&size_state)?,
2213 )
2214 .await
2215 })
2216 .detach_and_log_err(cx);
2217 }
2218
2219 pub fn set_panel_size_state<T: Panel>(
2220 &mut self,
2221 size_state: dock::PanelSizeState,
2222 window: &mut Window,
2223 cx: &mut Context<Self>,
2224 ) -> bool {
2225 let Some(panel) = self.panel::<T>(cx) else {
2226 return false;
2227 };
2228
2229 let dock = self.dock_at_position(panel.position(window, cx));
2230 let did_set = dock.update(cx, |dock, cx| {
2231 dock.set_panel_size_state(&panel, size_state, cx)
2232 });
2233
2234 if did_set {
2235 self.persist_panel_size_state(T::panel_key(), size_state, cx);
2236 }
2237
2238 did_set
2239 }
2240
2241 pub fn toggle_dock_panel_flexible_size(
2242 &self,
2243 dock: &Entity<Dock>,
2244 panel: &dyn PanelHandle,
2245 window: &mut Window,
2246 cx: &mut App,
2247 ) {
2248 let position = dock.read(cx).position();
2249 let current_size = self.dock_size(&dock.read(cx), window, cx);
2250 let current_flex =
2251 current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
2252 dock.update(cx, |dock, cx| {
2253 dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
2254 });
2255 }
2256
2257 fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
2258 let panel = dock.active_panel()?;
2259 let size_state = dock
2260 .stored_panel_size_state(panel.as_ref())
2261 .unwrap_or_default();
2262 let position = dock.position();
2263
2264 let use_flex = panel.has_flexible_size(window, cx);
2265
2266 if position.axis() == Axis::Horizontal
2267 && use_flex
2268 && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
2269 {
2270 let workspace_width = self.bounds.size.width;
2271 if workspace_width <= Pixels::ZERO {
2272 return None;
2273 }
2274 let flex = flex.max(0.001);
2275 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2276 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2277 // Both docks are flex items sharing the full workspace width.
2278 let total_flex = flex + 1.0 + opposite_flex;
2279 return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
2280 } else {
2281 // Opposite dock is fixed-width; flex items share (W - fixed).
2282 let opposite_fixed = opposite
2283 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2284 .unwrap_or_default();
2285 let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
2286 return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
2287 }
2288 }
2289
2290 Some(
2291 size_state
2292 .size
2293 .unwrap_or_else(|| panel.default_size(window, cx)),
2294 )
2295 }
2296
2297 pub fn dock_flex_for_size(
2298 &self,
2299 position: DockPosition,
2300 size: Pixels,
2301 window: &Window,
2302 cx: &App,
2303 ) -> Option<f32> {
2304 if position.axis() != Axis::Horizontal {
2305 return None;
2306 }
2307
2308 let workspace_width = self.bounds.size.width;
2309 if workspace_width <= Pixels::ZERO {
2310 return None;
2311 }
2312
2313 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2314 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2315 let size = size.clamp(px(0.), workspace_width - px(1.));
2316 Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
2317 } else {
2318 let opposite_width = opposite
2319 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2320 .unwrap_or_default();
2321 let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
2322 let remaining = (available - size).max(px(1.));
2323 Some((size / remaining).max(0.0))
2324 }
2325 }
2326
2327 fn opposite_dock_panel_and_size_state(
2328 &self,
2329 position: DockPosition,
2330 window: &Window,
2331 cx: &App,
2332 ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
2333 let opposite_position = match position {
2334 DockPosition::Left => DockPosition::Right,
2335 DockPosition::Right => DockPosition::Left,
2336 DockPosition::Bottom => return None,
2337 };
2338
2339 let opposite_dock = self.dock_at_position(opposite_position).read(cx);
2340 let panel = opposite_dock.visible_panel()?;
2341 let mut size_state = opposite_dock
2342 .stored_panel_size_state(panel.as_ref())
2343 .unwrap_or_default();
2344 if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
2345 size_state.flex = self.default_dock_flex(opposite_position);
2346 }
2347 Some((panel.clone(), size_state))
2348 }
2349
2350 pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
2351 if position.axis() != Axis::Horizontal {
2352 return None;
2353 }
2354
2355 let pane = self.last_active_center_pane.clone()?.upgrade()?;
2356 Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
2357 }
2358
2359 pub fn is_edited(&self) -> bool {
2360 self.window_edited
2361 }
2362
2363 pub fn add_panel<T: Panel>(
2364 &mut self,
2365 panel: Entity<T>,
2366 window: &mut Window,
2367 cx: &mut Context<Self>,
2368 ) {
2369 let focus_handle = panel.panel_focus_handle(cx);
2370 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2371 .detach();
2372
2373 let dock_position = panel.position(window, cx);
2374 let dock = self.dock_at_position(dock_position);
2375 let any_panel = panel.to_any();
2376 let persisted_size_state =
2377 self.persisted_panel_size_state(T::panel_key(), cx)
2378 .or_else(|| {
2379 load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
2380 let state = dock::PanelSizeState {
2381 size: Some(size),
2382 flex: None,
2383 };
2384 self.persist_panel_size_state(T::panel_key(), state, cx);
2385 state
2386 })
2387 });
2388
2389 dock.update(cx, |dock, cx| {
2390 let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
2391 if let Some(size_state) = persisted_size_state {
2392 dock.set_panel_size_state(&panel, size_state, cx);
2393 }
2394 index
2395 });
2396
2397 cx.emit(Event::PanelAdded(any_panel));
2398 }
2399
2400 pub fn remove_panel<T: Panel>(
2401 &mut self,
2402 panel: &Entity<T>,
2403 window: &mut Window,
2404 cx: &mut Context<Self>,
2405 ) {
2406 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2407 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2408 }
2409 }
2410
2411 pub fn status_bar(&self) -> &Entity<StatusBar> {
2412 &self.status_bar
2413 }
2414
2415 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2416 self.sidebar_focus_handle = handle;
2417 }
2418
2419 pub fn status_bar_visible(&self, cx: &App) -> bool {
2420 StatusBarSettings::get_global(cx).show
2421 }
2422
2423 pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
2424 self.multi_workspace.as_ref()
2425 }
2426
2427 pub fn set_multi_workspace(
2428 &mut self,
2429 multi_workspace: WeakEntity<MultiWorkspace>,
2430 cx: &mut App,
2431 ) {
2432 self.status_bar.update(cx, |status_bar, cx| {
2433 status_bar.set_multi_workspace(multi_workspace.clone(), cx);
2434 });
2435 self.multi_workspace = Some(multi_workspace);
2436 }
2437
2438 pub fn app_state(&self) -> &Arc<AppState> {
2439 &self.app_state
2440 }
2441
2442 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2443 self._panels_task = Some(task);
2444 }
2445
2446 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2447 self._panels_task.take()
2448 }
2449
2450 pub fn user_store(&self) -> &Entity<UserStore> {
2451 &self.app_state.user_store
2452 }
2453
2454 pub fn project(&self) -> &Entity<Project> {
2455 &self.project
2456 }
2457
2458 pub fn path_style(&self, cx: &App) -> PathStyle {
2459 self.project.read(cx).path_style(cx)
2460 }
2461
2462 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2463 let mut history: HashMap<EntityId, usize> = HashMap::default();
2464
2465 for pane_handle in &self.panes {
2466 let pane = pane_handle.read(cx);
2467
2468 for entry in pane.activation_history() {
2469 history.insert(
2470 entry.entity_id,
2471 history
2472 .get(&entry.entity_id)
2473 .cloned()
2474 .unwrap_or(0)
2475 .max(entry.timestamp),
2476 );
2477 }
2478 }
2479
2480 history
2481 }
2482
2483 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2484 let mut recent_item: Option<Entity<T>> = None;
2485 let mut recent_timestamp = 0;
2486 for pane_handle in &self.panes {
2487 let pane = pane_handle.read(cx);
2488 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2489 pane.items().map(|item| (item.item_id(), item)).collect();
2490 for entry in pane.activation_history() {
2491 if entry.timestamp > recent_timestamp
2492 && let Some(&item) = item_map.get(&entry.entity_id)
2493 && let Some(typed_item) = item.act_as::<T>(cx)
2494 {
2495 recent_timestamp = entry.timestamp;
2496 recent_item = Some(typed_item);
2497 }
2498 }
2499 }
2500 recent_item
2501 }
2502
2503 pub fn recent_navigation_history_iter(
2504 &self,
2505 cx: &App,
2506 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2507 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2508 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2509
2510 for pane in &self.panes {
2511 let pane = pane.read(cx);
2512
2513 pane.nav_history()
2514 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2515 if let Some(fs_path) = &fs_path {
2516 abs_paths_opened
2517 .entry(fs_path.clone())
2518 .or_default()
2519 .insert(project_path.clone());
2520 }
2521 let timestamp = entry.timestamp;
2522 match history.entry(project_path) {
2523 hash_map::Entry::Occupied(mut entry) => {
2524 let (_, old_timestamp) = entry.get();
2525 if ×tamp > old_timestamp {
2526 entry.insert((fs_path, timestamp));
2527 }
2528 }
2529 hash_map::Entry::Vacant(entry) => {
2530 entry.insert((fs_path, timestamp));
2531 }
2532 }
2533 });
2534
2535 if let Some(item) = pane.active_item()
2536 && let Some(project_path) = item.project_path(cx)
2537 {
2538 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2539
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
2547 history.insert(project_path, (fs_path, std::usize::MAX));
2548 }
2549 }
2550
2551 history
2552 .into_iter()
2553 .sorted_by_key(|(_, (_, order))| *order)
2554 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2555 .rev()
2556 .filter(move |(history_path, abs_path)| {
2557 let latest_project_path_opened = abs_path
2558 .as_ref()
2559 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2560 .and_then(|project_paths| {
2561 project_paths
2562 .iter()
2563 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2564 });
2565
2566 latest_project_path_opened.is_none_or(|path| path == history_path)
2567 })
2568 }
2569
2570 pub fn recent_navigation_history(
2571 &self,
2572 limit: Option<usize>,
2573 cx: &App,
2574 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2575 self.recent_navigation_history_iter(cx)
2576 .take(limit.unwrap_or(usize::MAX))
2577 .collect()
2578 }
2579
2580 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2581 for pane in &self.panes {
2582 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2583 }
2584 }
2585
2586 fn navigate_history(
2587 &mut self,
2588 pane: WeakEntity<Pane>,
2589 mode: NavigationMode,
2590 window: &mut Window,
2591 cx: &mut Context<Workspace>,
2592 ) -> Task<Result<()>> {
2593 self.navigate_history_impl(
2594 pane,
2595 mode,
2596 window,
2597 &mut |history, cx| history.pop(mode, cx),
2598 cx,
2599 )
2600 }
2601
2602 fn navigate_tag_history(
2603 &mut self,
2604 pane: WeakEntity<Pane>,
2605 mode: TagNavigationMode,
2606 window: &mut Window,
2607 cx: &mut Context<Workspace>,
2608 ) -> Task<Result<()>> {
2609 self.navigate_history_impl(
2610 pane,
2611 NavigationMode::Normal,
2612 window,
2613 &mut |history, _cx| history.pop_tag(mode),
2614 cx,
2615 )
2616 }
2617
2618 fn navigate_history_impl(
2619 &mut self,
2620 pane: WeakEntity<Pane>,
2621 mode: NavigationMode,
2622 window: &mut Window,
2623 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2624 cx: &mut Context<Workspace>,
2625 ) -> Task<Result<()>> {
2626 let to_load = if let Some(pane) = pane.upgrade() {
2627 pane.update(cx, |pane, cx| {
2628 window.focus(&pane.focus_handle(cx), cx);
2629 loop {
2630 // Retrieve the weak item handle from the history.
2631 let entry = cb(pane.nav_history_mut(), cx)?;
2632
2633 // If the item is still present in this pane, then activate it.
2634 if let Some(index) = entry
2635 .item
2636 .upgrade()
2637 .and_then(|v| pane.index_for_item(v.as_ref()))
2638 {
2639 let prev_active_item_index = pane.active_item_index();
2640 pane.nav_history_mut().set_mode(mode);
2641 pane.activate_item(index, true, true, window, cx);
2642 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2643
2644 let mut navigated = prev_active_item_index != pane.active_item_index();
2645 if let Some(data) = entry.data {
2646 navigated |= pane.active_item()?.navigate(data, window, cx);
2647 }
2648
2649 if navigated {
2650 break None;
2651 }
2652 } else {
2653 // If the item is no longer present in this pane, then retrieve its
2654 // path info in order to reopen it.
2655 break pane
2656 .nav_history()
2657 .path_for_item(entry.item.id())
2658 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2659 }
2660 }
2661 })
2662 } else {
2663 None
2664 };
2665
2666 if let Some((project_path, abs_path, entry)) = to_load {
2667 // If the item was no longer present, then load it again from its previous path, first try the local path
2668 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2669
2670 cx.spawn_in(window, async move |workspace, cx| {
2671 let open_by_project_path = open_by_project_path.await;
2672 let mut navigated = false;
2673 match open_by_project_path
2674 .with_context(|| format!("Navigating to {project_path:?}"))
2675 {
2676 Ok((project_entry_id, build_item)) => {
2677 let prev_active_item_id = pane.update(cx, |pane, _| {
2678 pane.nav_history_mut().set_mode(mode);
2679 pane.active_item().map(|p| p.item_id())
2680 })?;
2681
2682 pane.update_in(cx, |pane, window, cx| {
2683 let item = pane.open_item(
2684 project_entry_id,
2685 project_path,
2686 true,
2687 entry.is_preview,
2688 true,
2689 None,
2690 window, cx,
2691 build_item,
2692 );
2693 navigated |= Some(item.item_id()) != prev_active_item_id;
2694 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2695 if let Some(data) = entry.data {
2696 navigated |= item.navigate(data, window, cx);
2697 }
2698 })?;
2699 }
2700 Err(open_by_project_path_e) => {
2701 // Fall back to opening by abs path, in case an external file was opened and closed,
2702 // and its worktree is now dropped
2703 if let Some(abs_path) = abs_path {
2704 let prev_active_item_id = pane.update(cx, |pane, _| {
2705 pane.nav_history_mut().set_mode(mode);
2706 pane.active_item().map(|p| p.item_id())
2707 })?;
2708 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2709 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2710 })?;
2711 match open_by_abs_path
2712 .await
2713 .with_context(|| format!("Navigating to {abs_path:?}"))
2714 {
2715 Ok(item) => {
2716 pane.update_in(cx, |pane, window, cx| {
2717 navigated |= Some(item.item_id()) != prev_active_item_id;
2718 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2719 if let Some(data) = entry.data {
2720 navigated |= item.navigate(data, window, cx);
2721 }
2722 })?;
2723 }
2724 Err(open_by_abs_path_e) => {
2725 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2726 }
2727 }
2728 }
2729 }
2730 }
2731
2732 if !navigated {
2733 workspace
2734 .update_in(cx, |workspace, window, cx| {
2735 Self::navigate_history(workspace, pane, mode, window, cx)
2736 })?
2737 .await?;
2738 }
2739
2740 Ok(())
2741 })
2742 } else {
2743 Task::ready(Ok(()))
2744 }
2745 }
2746
2747 pub fn go_back(
2748 &mut self,
2749 pane: WeakEntity<Pane>,
2750 window: &mut Window,
2751 cx: &mut Context<Workspace>,
2752 ) -> Task<Result<()>> {
2753 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2754 }
2755
2756 pub fn go_forward(
2757 &mut self,
2758 pane: WeakEntity<Pane>,
2759 window: &mut Window,
2760 cx: &mut Context<Workspace>,
2761 ) -> Task<Result<()>> {
2762 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2763 }
2764
2765 pub fn reopen_closed_item(
2766 &mut self,
2767 window: &mut Window,
2768 cx: &mut Context<Workspace>,
2769 ) -> Task<Result<()>> {
2770 self.navigate_history(
2771 self.active_pane().downgrade(),
2772 NavigationMode::ReopeningClosedItem,
2773 window,
2774 cx,
2775 )
2776 }
2777
2778 pub fn client(&self) -> &Arc<Client> {
2779 &self.app_state.client
2780 }
2781
2782 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2783 self.titlebar_item = Some(item);
2784 cx.notify();
2785 }
2786
2787 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2788 self.on_prompt_for_new_path = Some(prompt)
2789 }
2790
2791 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2792 self.on_prompt_for_open_path = Some(prompt)
2793 }
2794
2795 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2796 self.terminal_provider = Some(Box::new(provider));
2797 }
2798
2799 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2800 self.debugger_provider = Some(Arc::new(provider));
2801 }
2802
2803 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2804 self.debugger_provider.clone()
2805 }
2806
2807 pub fn prompt_for_open_path(
2808 &mut self,
2809 path_prompt_options: PathPromptOptions,
2810 lister: DirectoryLister,
2811 window: &mut Window,
2812 cx: &mut Context<Self>,
2813 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2814 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2815 let prompt = self.on_prompt_for_open_path.take().unwrap();
2816 let rx = prompt(self, lister, window, cx);
2817 self.on_prompt_for_open_path = Some(prompt);
2818 rx
2819 } else {
2820 let (tx, rx) = oneshot::channel();
2821 let abs_path = cx.prompt_for_paths(path_prompt_options);
2822
2823 cx.spawn_in(window, async move |workspace, cx| {
2824 let Ok(result) = abs_path.await else {
2825 return Ok(());
2826 };
2827
2828 match result {
2829 Ok(result) => {
2830 tx.send(result).ok();
2831 }
2832 Err(err) => {
2833 let rx = workspace.update_in(cx, |workspace, window, cx| {
2834 workspace.show_portal_error(err.to_string(), cx);
2835 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2836 let rx = prompt(workspace, lister, window, cx);
2837 workspace.on_prompt_for_open_path = Some(prompt);
2838 rx
2839 })?;
2840 if let Ok(path) = rx.await {
2841 tx.send(path).ok();
2842 }
2843 }
2844 };
2845 anyhow::Ok(())
2846 })
2847 .detach();
2848
2849 rx
2850 }
2851 }
2852
2853 pub fn prompt_for_new_path(
2854 &mut self,
2855 lister: DirectoryLister,
2856 suggested_name: Option<String>,
2857 window: &mut Window,
2858 cx: &mut Context<Self>,
2859 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2860 if self.project.read(cx).is_via_collab()
2861 || self.project.read(cx).is_via_remote_server()
2862 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2863 {
2864 let prompt = self.on_prompt_for_new_path.take().unwrap();
2865 let rx = prompt(self, lister, suggested_name, window, cx);
2866 self.on_prompt_for_new_path = Some(prompt);
2867 return rx;
2868 }
2869
2870 let (tx, rx) = oneshot::channel();
2871 cx.spawn_in(window, async move |workspace, cx| {
2872 let abs_path = workspace.update(cx, |workspace, cx| {
2873 let relative_to = workspace
2874 .most_recent_active_path(cx)
2875 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2876 .or_else(|| {
2877 let project = workspace.project.read(cx);
2878 project.visible_worktrees(cx).find_map(|worktree| {
2879 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2880 })
2881 })
2882 .or_else(std::env::home_dir)
2883 .unwrap_or_else(|| PathBuf::from(""));
2884 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2885 })?;
2886 let abs_path = match abs_path.await? {
2887 Ok(path) => path,
2888 Err(err) => {
2889 let rx = workspace.update_in(cx, |workspace, window, cx| {
2890 workspace.show_portal_error(err.to_string(), cx);
2891
2892 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2893 let rx = prompt(workspace, lister, suggested_name, window, cx);
2894 workspace.on_prompt_for_new_path = Some(prompt);
2895 rx
2896 })?;
2897 if let Ok(path) = rx.await {
2898 tx.send(path).ok();
2899 }
2900 return anyhow::Ok(());
2901 }
2902 };
2903
2904 tx.send(abs_path.map(|path| vec![path])).ok();
2905 anyhow::Ok(())
2906 })
2907 .detach();
2908
2909 rx
2910 }
2911
2912 pub fn titlebar_item(&self) -> Option<AnyView> {
2913 self.titlebar_item.clone()
2914 }
2915
2916 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2917 /// When set, git-related operations should use this worktree instead of deriving
2918 /// the active worktree from the focused file.
2919 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2920 self.active_worktree_override
2921 }
2922
2923 pub fn set_active_worktree_override(
2924 &mut self,
2925 worktree_id: Option<WorktreeId>,
2926 cx: &mut Context<Self>,
2927 ) {
2928 self.active_worktree_override = worktree_id;
2929 cx.notify();
2930 }
2931
2932 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2933 self.active_worktree_override = None;
2934 cx.notify();
2935 }
2936
2937 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2938 ///
2939 /// If the given workspace has a local project, then it will be passed
2940 /// to the callback. Otherwise, a new empty window will be created.
2941 pub fn with_local_workspace<T, F>(
2942 &mut self,
2943 window: &mut Window,
2944 cx: &mut Context<Self>,
2945 callback: F,
2946 ) -> Task<Result<T>>
2947 where
2948 T: 'static,
2949 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2950 {
2951 if self.project.read(cx).is_local() {
2952 Task::ready(Ok(callback(self, window, cx)))
2953 } else {
2954 let env = self.project.read(cx).cli_environment(cx);
2955 let task = Self::new_local(
2956 Vec::new(),
2957 self.app_state.clone(),
2958 None,
2959 env,
2960 None,
2961 OpenMode::Activate,
2962 cx,
2963 );
2964 cx.spawn_in(window, async move |_vh, cx| {
2965 let OpenResult {
2966 window: multi_workspace_window,
2967 ..
2968 } = task.await?;
2969 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2970 let workspace = multi_workspace.workspace().clone();
2971 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2972 })
2973 })
2974 }
2975 }
2976
2977 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2978 ///
2979 /// If the given workspace has a local project, then it will be passed
2980 /// to the callback. Otherwise, a new empty window will be created.
2981 pub fn with_local_or_wsl_workspace<T, F>(
2982 &mut self,
2983 window: &mut Window,
2984 cx: &mut Context<Self>,
2985 callback: F,
2986 ) -> Task<Result<T>>
2987 where
2988 T: 'static,
2989 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2990 {
2991 let project = self.project.read(cx);
2992 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2993 Task::ready(Ok(callback(self, window, cx)))
2994 } else {
2995 let env = self.project.read(cx).cli_environment(cx);
2996 let task = Self::new_local(
2997 Vec::new(),
2998 self.app_state.clone(),
2999 None,
3000 env,
3001 None,
3002 OpenMode::Activate,
3003 cx,
3004 );
3005 cx.spawn_in(window, async move |_vh, cx| {
3006 let OpenResult {
3007 window: multi_workspace_window,
3008 ..
3009 } = task.await?;
3010 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
3011 let workspace = multi_workspace.workspace().clone();
3012 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3013 })
3014 })
3015 }
3016 }
3017
3018 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3019 self.project.read(cx).worktrees(cx)
3020 }
3021
3022 pub fn visible_worktrees<'a>(
3023 &self,
3024 cx: &'a App,
3025 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3026 self.project.read(cx).visible_worktrees(cx)
3027 }
3028
3029 #[cfg(any(test, feature = "test-support"))]
3030 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
3031 let futures = self
3032 .worktrees(cx)
3033 .filter_map(|worktree| worktree.read(cx).as_local())
3034 .map(|worktree| worktree.scan_complete())
3035 .collect::<Vec<_>>();
3036 async move {
3037 for future in futures {
3038 future.await;
3039 }
3040 }
3041 }
3042
3043 pub fn close_global(cx: &mut App) {
3044 cx.defer(|cx| {
3045 cx.windows().iter().find(|window| {
3046 window
3047 .update(cx, |_, window, _| {
3048 if window.is_window_active() {
3049 //This can only get called when the window's project connection has been lost
3050 //so we don't need to prompt the user for anything and instead just close the window
3051 window.remove_window();
3052 true
3053 } else {
3054 false
3055 }
3056 })
3057 .unwrap_or(false)
3058 });
3059 });
3060 }
3061
3062 pub fn move_focused_panel_to_next_position(
3063 &mut self,
3064 _: &MoveFocusedPanelToNextPosition,
3065 window: &mut Window,
3066 cx: &mut Context<Self>,
3067 ) {
3068 let docks = self.all_docks();
3069 let active_dock = docks
3070 .into_iter()
3071 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
3072
3073 if let Some(dock) = active_dock {
3074 dock.update(cx, |dock, cx| {
3075 let active_panel = dock
3076 .active_panel()
3077 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
3078
3079 if let Some(panel) = active_panel {
3080 panel.move_to_next_position(window, cx);
3081 }
3082 })
3083 }
3084 }
3085
3086 pub fn prepare_to_close(
3087 &mut self,
3088 close_intent: CloseIntent,
3089 window: &mut Window,
3090 cx: &mut Context<Self>,
3091 ) -> Task<Result<bool>> {
3092 let active_call = self.active_global_call();
3093
3094 cx.spawn_in(window, async move |this, cx| {
3095 this.update(cx, |this, _| {
3096 if close_intent == CloseIntent::CloseWindow {
3097 this.removing = true;
3098 }
3099 })?;
3100
3101 let workspace_count = cx.update(|_window, cx| {
3102 cx.windows()
3103 .iter()
3104 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
3105 .count()
3106 })?;
3107
3108 #[cfg(target_os = "macos")]
3109 let save_last_workspace = false;
3110
3111 // On Linux and Windows, closing the last window should restore the last workspace.
3112 #[cfg(not(target_os = "macos"))]
3113 let save_last_workspace = {
3114 let remaining_workspaces = cx.update(|_window, cx| {
3115 cx.windows()
3116 .iter()
3117 .filter_map(|window| window.downcast::<MultiWorkspace>())
3118 .filter_map(|multi_workspace| {
3119 multi_workspace
3120 .update(cx, |multi_workspace, _, cx| {
3121 multi_workspace.workspace().read(cx).removing
3122 })
3123 .ok()
3124 })
3125 .filter(|removing| !removing)
3126 .count()
3127 })?;
3128
3129 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
3130 };
3131
3132 if let Some(active_call) = active_call
3133 && workspace_count == 1
3134 && cx
3135 .update(|_window, cx| active_call.0.is_in_room(cx))
3136 .unwrap_or(false)
3137 {
3138 if close_intent == CloseIntent::CloseWindow {
3139 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
3140 let answer = cx.update(|window, cx| {
3141 window.prompt(
3142 PromptLevel::Warning,
3143 "Do you want to leave the current call?",
3144 None,
3145 &["Close window and hang up", "Cancel"],
3146 cx,
3147 )
3148 })?;
3149
3150 if answer.await.log_err() == Some(1) {
3151 return anyhow::Ok(false);
3152 } else {
3153 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
3154 task.await.log_err();
3155 }
3156 }
3157 }
3158 if close_intent == CloseIntent::ReplaceWindow {
3159 _ = cx.update(|_window, cx| {
3160 let multi_workspace = cx
3161 .windows()
3162 .iter()
3163 .filter_map(|window| window.downcast::<MultiWorkspace>())
3164 .next()
3165 .unwrap();
3166 let project = multi_workspace
3167 .read(cx)?
3168 .workspace()
3169 .read(cx)
3170 .project
3171 .clone();
3172 if project.read(cx).is_shared() {
3173 active_call.0.unshare_project(project, cx)?;
3174 }
3175 Ok::<_, anyhow::Error>(())
3176 });
3177 }
3178 }
3179
3180 let save_result = this
3181 .update_in(cx, |this, window, cx| {
3182 this.save_all_internal(SaveIntent::Close, window, cx)
3183 })?
3184 .await;
3185
3186 // If we're not quitting, but closing, we remove the workspace from
3187 // the current session.
3188 if close_intent != CloseIntent::Quit
3189 && !save_last_workspace
3190 && save_result.as_ref().is_ok_and(|&res| res)
3191 {
3192 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
3193 .await;
3194 }
3195
3196 save_result
3197 })
3198 }
3199
3200 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
3201 self.save_all_internal(
3202 action.save_intent.unwrap_or(SaveIntent::SaveAll),
3203 window,
3204 cx,
3205 )
3206 .detach_and_log_err(cx);
3207 }
3208
3209 fn send_keystrokes(
3210 &mut self,
3211 action: &SendKeystrokes,
3212 window: &mut Window,
3213 cx: &mut Context<Self>,
3214 ) {
3215 let keystrokes: Vec<Keystroke> = action
3216 .0
3217 .split(' ')
3218 .flat_map(|k| Keystroke::parse(k).log_err())
3219 .map(|k| {
3220 cx.keyboard_mapper()
3221 .map_key_equivalent(k, false)
3222 .inner()
3223 .clone()
3224 })
3225 .collect();
3226 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
3227 }
3228
3229 pub fn send_keystrokes_impl(
3230 &mut self,
3231 keystrokes: Vec<Keystroke>,
3232 window: &mut Window,
3233 cx: &mut Context<Self>,
3234 ) -> Shared<Task<()>> {
3235 let mut state = self.dispatching_keystrokes.borrow_mut();
3236 if !state.dispatched.insert(keystrokes.clone()) {
3237 cx.propagate();
3238 return state.task.clone().unwrap();
3239 }
3240
3241 state.queue.extend(keystrokes);
3242
3243 let keystrokes = self.dispatching_keystrokes.clone();
3244 if state.task.is_none() {
3245 state.task = Some(
3246 window
3247 .spawn(cx, async move |cx| {
3248 // limit to 100 keystrokes to avoid infinite recursion.
3249 for _ in 0..100 {
3250 let keystroke = {
3251 let mut state = keystrokes.borrow_mut();
3252 let Some(keystroke) = state.queue.pop_front() else {
3253 state.dispatched.clear();
3254 state.task.take();
3255 return;
3256 };
3257 keystroke
3258 };
3259 cx.update(|window, cx| {
3260 let focused = window.focused(cx);
3261 window.dispatch_keystroke(keystroke.clone(), cx);
3262 if window.focused(cx) != focused {
3263 // dispatch_keystroke may cause the focus to change.
3264 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3265 // And we need that to happen before the next keystroke to keep vim mode happy...
3266 // (Note that the tests always do this implicitly, so you must manually test with something like:
3267 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3268 // )
3269 window.draw(cx).clear();
3270 }
3271 })
3272 .ok();
3273
3274 // Yield between synthetic keystrokes so deferred focus and
3275 // other effects can settle before dispatching the next key.
3276 yield_now().await;
3277 }
3278
3279 *keystrokes.borrow_mut() = Default::default();
3280 log::error!("over 100 keystrokes passed to send_keystrokes");
3281 })
3282 .shared(),
3283 );
3284 }
3285 state.task.clone().unwrap()
3286 }
3287
3288 fn save_all_internal(
3289 &mut self,
3290 mut save_intent: SaveIntent,
3291 window: &mut Window,
3292 cx: &mut Context<Self>,
3293 ) -> Task<Result<bool>> {
3294 if self.project.read(cx).is_disconnected(cx) {
3295 return Task::ready(Ok(true));
3296 }
3297 let dirty_items = self
3298 .panes
3299 .iter()
3300 .flat_map(|pane| {
3301 pane.read(cx).items().filter_map(|item| {
3302 if item.is_dirty(cx) {
3303 item.tab_content_text(0, cx);
3304 Some((pane.downgrade(), item.boxed_clone()))
3305 } else {
3306 None
3307 }
3308 })
3309 })
3310 .collect::<Vec<_>>();
3311
3312 let project = self.project.clone();
3313 cx.spawn_in(window, async move |workspace, cx| {
3314 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3315 let (serialize_tasks, remaining_dirty_items) =
3316 workspace.update_in(cx, |workspace, window, cx| {
3317 let mut remaining_dirty_items = Vec::new();
3318 let mut serialize_tasks = Vec::new();
3319 for (pane, item) in dirty_items {
3320 if let Some(task) = item
3321 .to_serializable_item_handle(cx)
3322 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3323 {
3324 serialize_tasks.push(task);
3325 } else {
3326 remaining_dirty_items.push((pane, item));
3327 }
3328 }
3329 (serialize_tasks, remaining_dirty_items)
3330 })?;
3331
3332 futures::future::try_join_all(serialize_tasks).await?;
3333
3334 if !remaining_dirty_items.is_empty() {
3335 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3336 }
3337
3338 if remaining_dirty_items.len() > 1 {
3339 let answer = workspace.update_in(cx, |_, window, cx| {
3340 let detail = Pane::file_names_for_prompt(
3341 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3342 cx,
3343 );
3344 window.prompt(
3345 PromptLevel::Warning,
3346 "Do you want to save all changes in the following files?",
3347 Some(&detail),
3348 &["Save all", "Discard all", "Cancel"],
3349 cx,
3350 )
3351 })?;
3352 match answer.await.log_err() {
3353 Some(0) => save_intent = SaveIntent::SaveAll,
3354 Some(1) => save_intent = SaveIntent::Skip,
3355 Some(2) => return Ok(false),
3356 _ => {}
3357 }
3358 }
3359
3360 remaining_dirty_items
3361 } else {
3362 dirty_items
3363 };
3364
3365 for (pane, item) in dirty_items {
3366 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3367 (
3368 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3369 item.project_entry_ids(cx),
3370 )
3371 })?;
3372 if (singleton || !project_entry_ids.is_empty())
3373 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3374 {
3375 return Ok(false);
3376 }
3377 }
3378 Ok(true)
3379 })
3380 }
3381
3382 pub fn open_workspace_for_paths(
3383 &mut self,
3384 // replace_current_window: bool,
3385 mut open_mode: OpenMode,
3386 paths: Vec<PathBuf>,
3387 window: &mut Window,
3388 cx: &mut Context<Self>,
3389 ) -> Task<Result<Entity<Workspace>>> {
3390 let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
3391 let is_remote = self.project.read(cx).is_via_collab();
3392 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3393 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3394
3395 let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
3396 if workspace_is_empty {
3397 open_mode = OpenMode::Replace;
3398 }
3399
3400 let app_state = self.app_state.clone();
3401
3402 cx.spawn(async move |_, cx| {
3403 let OpenResult { workspace, .. } = cx
3404 .update(|cx| {
3405 open_paths(
3406 &paths,
3407 app_state,
3408 OpenOptions {
3409 requesting_window,
3410 open_mode,
3411 ..Default::default()
3412 },
3413 cx,
3414 )
3415 })
3416 .await?;
3417 Ok(workspace)
3418 })
3419 }
3420
3421 #[allow(clippy::type_complexity)]
3422 pub fn open_paths(
3423 &mut self,
3424 mut abs_paths: Vec<PathBuf>,
3425 options: OpenOptions,
3426 pane: Option<WeakEntity<Pane>>,
3427 window: &mut Window,
3428 cx: &mut Context<Self>,
3429 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3430 let fs = self.app_state.fs.clone();
3431
3432 let caller_ordered_abs_paths = abs_paths.clone();
3433
3434 // Sort the paths to ensure we add worktrees for parents before their children.
3435 abs_paths.sort_unstable();
3436 cx.spawn_in(window, async move |this, cx| {
3437 let mut tasks = Vec::with_capacity(abs_paths.len());
3438
3439 for abs_path in &abs_paths {
3440 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3441 OpenVisible::All => Some(true),
3442 OpenVisible::None => Some(false),
3443 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3444 Some(Some(metadata)) => Some(!metadata.is_dir),
3445 Some(None) => Some(true),
3446 None => None,
3447 },
3448 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3449 Some(Some(metadata)) => Some(metadata.is_dir),
3450 Some(None) => Some(false),
3451 None => None,
3452 },
3453 };
3454 let project_path = match visible {
3455 Some(visible) => match this
3456 .update(cx, |this, cx| {
3457 Workspace::project_path_for_path(
3458 this.project.clone(),
3459 abs_path,
3460 visible,
3461 cx,
3462 )
3463 })
3464 .log_err()
3465 {
3466 Some(project_path) => project_path.await.log_err(),
3467 None => None,
3468 },
3469 None => None,
3470 };
3471
3472 let this = this.clone();
3473 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3474 let fs = fs.clone();
3475 let pane = pane.clone();
3476 let task = cx.spawn(async move |cx| {
3477 let (_worktree, project_path) = project_path?;
3478 if fs.is_dir(&abs_path).await {
3479 // Opening a directory should not race to update the active entry.
3480 // We'll select/reveal a deterministic final entry after all paths finish opening.
3481 None
3482 } else {
3483 Some(
3484 this.update_in(cx, |this, window, cx| {
3485 this.open_path(
3486 project_path,
3487 pane,
3488 options.focus.unwrap_or(true),
3489 window,
3490 cx,
3491 )
3492 })
3493 .ok()?
3494 .await,
3495 )
3496 }
3497 });
3498 tasks.push(task);
3499 }
3500
3501 let results = futures::future::join_all(tasks).await;
3502
3503 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3504 let mut winner: Option<(PathBuf, bool)> = None;
3505 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3506 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3507 if !metadata.is_dir {
3508 winner = Some((abs_path, false));
3509 break;
3510 }
3511 if winner.is_none() {
3512 winner = Some((abs_path, true));
3513 }
3514 } else if winner.is_none() {
3515 winner = Some((abs_path, false));
3516 }
3517 }
3518
3519 // Compute the winner entry id on the foreground thread and emit once, after all
3520 // paths finish opening. This avoids races between concurrently-opening paths
3521 // (directories in particular) and makes the resulting project panel selection
3522 // deterministic.
3523 if let Some((winner_abs_path, winner_is_dir)) = winner {
3524 'emit_winner: {
3525 let winner_abs_path: Arc<Path> =
3526 SanitizedPath::new(&winner_abs_path).as_path().into();
3527
3528 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3529 OpenVisible::All => true,
3530 OpenVisible::None => false,
3531 OpenVisible::OnlyFiles => !winner_is_dir,
3532 OpenVisible::OnlyDirectories => winner_is_dir,
3533 };
3534
3535 let Some(worktree_task) = this
3536 .update(cx, |workspace, cx| {
3537 workspace.project.update(cx, |project, cx| {
3538 project.find_or_create_worktree(
3539 winner_abs_path.as_ref(),
3540 visible,
3541 cx,
3542 )
3543 })
3544 })
3545 .ok()
3546 else {
3547 break 'emit_winner;
3548 };
3549
3550 let Ok((worktree, _)) = worktree_task.await else {
3551 break 'emit_winner;
3552 };
3553
3554 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3555 let worktree = worktree.read(cx);
3556 let worktree_abs_path = worktree.abs_path();
3557 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3558 worktree.root_entry()
3559 } else {
3560 winner_abs_path
3561 .strip_prefix(worktree_abs_path.as_ref())
3562 .ok()
3563 .and_then(|relative_path| {
3564 let relative_path =
3565 RelPath::new(relative_path, PathStyle::local())
3566 .log_err()?;
3567 worktree.entry_for_path(&relative_path)
3568 })
3569 }?;
3570 Some(entry.id)
3571 }) else {
3572 break 'emit_winner;
3573 };
3574
3575 this.update(cx, |workspace, cx| {
3576 workspace.project.update(cx, |_, cx| {
3577 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3578 });
3579 })
3580 .ok();
3581 }
3582 }
3583
3584 results
3585 })
3586 }
3587
3588 pub fn open_resolved_path(
3589 &mut self,
3590 path: ResolvedPath,
3591 window: &mut Window,
3592 cx: &mut Context<Self>,
3593 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3594 match path {
3595 ResolvedPath::ProjectPath { project_path, .. } => {
3596 self.open_path(project_path, None, true, window, cx)
3597 }
3598 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3599 PathBuf::from(path),
3600 OpenOptions {
3601 visible: Some(OpenVisible::None),
3602 ..Default::default()
3603 },
3604 window,
3605 cx,
3606 ),
3607 }
3608 }
3609
3610 pub fn absolute_path_of_worktree(
3611 &self,
3612 worktree_id: WorktreeId,
3613 cx: &mut Context<Self>,
3614 ) -> Option<PathBuf> {
3615 self.project
3616 .read(cx)
3617 .worktree_for_id(worktree_id, cx)
3618 // TODO: use `abs_path` or `root_dir`
3619 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3620 }
3621
3622 pub fn add_folder_to_project(
3623 &mut self,
3624 _: &AddFolderToProject,
3625 window: &mut Window,
3626 cx: &mut Context<Self>,
3627 ) {
3628 let project = self.project.read(cx);
3629 if project.is_via_collab() {
3630 self.show_error(
3631 &anyhow!("You cannot add folders to someone else's project"),
3632 cx,
3633 );
3634 return;
3635 }
3636 let paths = self.prompt_for_open_path(
3637 PathPromptOptions {
3638 files: false,
3639 directories: true,
3640 multiple: true,
3641 prompt: None,
3642 },
3643 DirectoryLister::Project(self.project.clone()),
3644 window,
3645 cx,
3646 );
3647 cx.spawn_in(window, async move |this, cx| {
3648 if let Some(paths) = paths.await.log_err().flatten() {
3649 let results = this
3650 .update_in(cx, |this, window, cx| {
3651 this.open_paths(
3652 paths,
3653 OpenOptions {
3654 visible: Some(OpenVisible::All),
3655 ..Default::default()
3656 },
3657 None,
3658 window,
3659 cx,
3660 )
3661 })?
3662 .await;
3663 for result in results.into_iter().flatten() {
3664 result.log_err();
3665 }
3666 }
3667 anyhow::Ok(())
3668 })
3669 .detach_and_log_err(cx);
3670 }
3671
3672 pub fn project_path_for_path(
3673 project: Entity<Project>,
3674 abs_path: &Path,
3675 visible: bool,
3676 cx: &mut App,
3677 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3678 let entry = project.update(cx, |project, cx| {
3679 project.find_or_create_worktree(abs_path, visible, cx)
3680 });
3681 cx.spawn(async move |cx| {
3682 let (worktree, path) = entry.await?;
3683 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3684 Ok((worktree, ProjectPath { worktree_id, path }))
3685 })
3686 }
3687
3688 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3689 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3690 }
3691
3692 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3693 self.items_of_type(cx).max_by_key(|item| item.item_id())
3694 }
3695
3696 pub fn items_of_type<'a, T: Item>(
3697 &'a self,
3698 cx: &'a App,
3699 ) -> impl 'a + Iterator<Item = Entity<T>> {
3700 self.panes
3701 .iter()
3702 .flat_map(|pane| pane.read(cx).items_of_type())
3703 }
3704
3705 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3706 self.active_pane().read(cx).active_item()
3707 }
3708
3709 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3710 let item = self.active_item(cx)?;
3711 item.to_any_view().downcast::<I>().ok()
3712 }
3713
3714 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3715 self.active_item(cx).and_then(|item| item.project_path(cx))
3716 }
3717
3718 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3719 self.recent_navigation_history_iter(cx)
3720 .filter_map(|(path, abs_path)| {
3721 let worktree = self
3722 .project
3723 .read(cx)
3724 .worktree_for_id(path.worktree_id, cx)?;
3725 if worktree.read(cx).is_visible() {
3726 abs_path
3727 } else {
3728 None
3729 }
3730 })
3731 .next()
3732 }
3733
3734 pub fn save_active_item(
3735 &mut self,
3736 save_intent: SaveIntent,
3737 window: &mut Window,
3738 cx: &mut App,
3739 ) -> Task<Result<()>> {
3740 let project = self.project.clone();
3741 let pane = self.active_pane();
3742 let item = pane.read(cx).active_item();
3743 let pane = pane.downgrade();
3744
3745 window.spawn(cx, async move |cx| {
3746 if let Some(item) = item {
3747 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3748 .await
3749 .map(|_| ())
3750 } else {
3751 Ok(())
3752 }
3753 })
3754 }
3755
3756 pub fn close_inactive_items_and_panes(
3757 &mut self,
3758 action: &CloseInactiveTabsAndPanes,
3759 window: &mut Window,
3760 cx: &mut Context<Self>,
3761 ) {
3762 if let Some(task) = self.close_all_internal(
3763 true,
3764 action.save_intent.unwrap_or(SaveIntent::Close),
3765 window,
3766 cx,
3767 ) {
3768 task.detach_and_log_err(cx)
3769 }
3770 }
3771
3772 pub fn close_all_items_and_panes(
3773 &mut self,
3774 action: &CloseAllItemsAndPanes,
3775 window: &mut Window,
3776 cx: &mut Context<Self>,
3777 ) {
3778 if let Some(task) = self.close_all_internal(
3779 false,
3780 action.save_intent.unwrap_or(SaveIntent::Close),
3781 window,
3782 cx,
3783 ) {
3784 task.detach_and_log_err(cx)
3785 }
3786 }
3787
3788 /// Closes the active item across all panes.
3789 pub fn close_item_in_all_panes(
3790 &mut self,
3791 action: &CloseItemInAllPanes,
3792 window: &mut Window,
3793 cx: &mut Context<Self>,
3794 ) {
3795 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3796 return;
3797 };
3798
3799 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3800 let close_pinned = action.close_pinned;
3801
3802 if let Some(project_path) = active_item.project_path(cx) {
3803 self.close_items_with_project_path(
3804 &project_path,
3805 save_intent,
3806 close_pinned,
3807 window,
3808 cx,
3809 );
3810 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3811 let item_id = active_item.item_id();
3812 self.active_pane().update(cx, |pane, cx| {
3813 pane.close_item_by_id(item_id, save_intent, window, cx)
3814 .detach_and_log_err(cx);
3815 });
3816 }
3817 }
3818
3819 /// Closes all items with the given project path across all panes.
3820 pub fn close_items_with_project_path(
3821 &mut self,
3822 project_path: &ProjectPath,
3823 save_intent: SaveIntent,
3824 close_pinned: bool,
3825 window: &mut Window,
3826 cx: &mut Context<Self>,
3827 ) {
3828 let panes = self.panes().to_vec();
3829 for pane in panes {
3830 pane.update(cx, |pane, cx| {
3831 pane.close_items_for_project_path(
3832 project_path,
3833 save_intent,
3834 close_pinned,
3835 window,
3836 cx,
3837 )
3838 .detach_and_log_err(cx);
3839 });
3840 }
3841 }
3842
3843 fn close_all_internal(
3844 &mut self,
3845 retain_active_pane: bool,
3846 save_intent: SaveIntent,
3847 window: &mut Window,
3848 cx: &mut Context<Self>,
3849 ) -> Option<Task<Result<()>>> {
3850 let current_pane = self.active_pane();
3851
3852 let mut tasks = Vec::new();
3853
3854 if retain_active_pane {
3855 let current_pane_close = current_pane.update(cx, |pane, cx| {
3856 pane.close_other_items(
3857 &CloseOtherItems {
3858 save_intent: None,
3859 close_pinned: false,
3860 },
3861 None,
3862 window,
3863 cx,
3864 )
3865 });
3866
3867 tasks.push(current_pane_close);
3868 }
3869
3870 for pane in self.panes() {
3871 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3872 continue;
3873 }
3874
3875 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3876 pane.close_all_items(
3877 &CloseAllItems {
3878 save_intent: Some(save_intent),
3879 close_pinned: false,
3880 },
3881 window,
3882 cx,
3883 )
3884 });
3885
3886 tasks.push(close_pane_items)
3887 }
3888
3889 if tasks.is_empty() {
3890 None
3891 } else {
3892 Some(cx.spawn_in(window, async move |_, _| {
3893 for task in tasks {
3894 task.await?
3895 }
3896 Ok(())
3897 }))
3898 }
3899 }
3900
3901 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3902 self.dock_at_position(position).read(cx).is_open()
3903 }
3904
3905 pub fn toggle_dock(
3906 &mut self,
3907 dock_side: DockPosition,
3908 window: &mut Window,
3909 cx: &mut Context<Self>,
3910 ) {
3911 let mut focus_center = false;
3912 let mut reveal_dock = false;
3913
3914 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3915 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3916
3917 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3918 telemetry::event!(
3919 "Panel Button Clicked",
3920 name = panel.persistent_name(),
3921 toggle_state = !was_visible
3922 );
3923 }
3924 if was_visible {
3925 self.save_open_dock_positions(cx);
3926 }
3927
3928 let dock = self.dock_at_position(dock_side);
3929 dock.update(cx, |dock, cx| {
3930 dock.set_open(!was_visible, window, cx);
3931
3932 if dock.active_panel().is_none() {
3933 let Some(panel_ix) = dock
3934 .first_enabled_panel_idx(cx)
3935 .log_with_level(log::Level::Info)
3936 else {
3937 return;
3938 };
3939 dock.activate_panel(panel_ix, window, cx);
3940 }
3941
3942 if let Some(active_panel) = dock.active_panel() {
3943 if was_visible {
3944 if active_panel
3945 .panel_focus_handle(cx)
3946 .contains_focused(window, cx)
3947 {
3948 focus_center = true;
3949 }
3950 } else {
3951 let focus_handle = &active_panel.panel_focus_handle(cx);
3952 window.focus(focus_handle, cx);
3953 reveal_dock = true;
3954 }
3955 }
3956 });
3957
3958 if reveal_dock {
3959 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3960 }
3961
3962 if focus_center {
3963 self.active_pane
3964 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3965 }
3966
3967 cx.notify();
3968 self.serialize_workspace(window, cx);
3969 }
3970
3971 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3972 self.all_docks().into_iter().find(|&dock| {
3973 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3974 })
3975 }
3976
3977 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3978 if let Some(dock) = self.active_dock(window, cx).cloned() {
3979 self.save_open_dock_positions(cx);
3980 dock.update(cx, |dock, cx| {
3981 dock.set_open(false, window, cx);
3982 });
3983 return true;
3984 }
3985 false
3986 }
3987
3988 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3989 self.save_open_dock_positions(cx);
3990 for dock in self.all_docks() {
3991 dock.update(cx, |dock, cx| {
3992 dock.set_open(false, window, cx);
3993 });
3994 }
3995
3996 cx.focus_self(window);
3997 cx.notify();
3998 self.serialize_workspace(window, cx);
3999 }
4000
4001 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
4002 self.all_docks()
4003 .into_iter()
4004 .filter_map(|dock| {
4005 let dock_ref = dock.read(cx);
4006 if dock_ref.is_open() {
4007 Some(dock_ref.position())
4008 } else {
4009 None
4010 }
4011 })
4012 .collect()
4013 }
4014
4015 /// Saves the positions of currently open docks.
4016 ///
4017 /// Updates `last_open_dock_positions` with positions of all currently open
4018 /// docks, to later be restored by the 'Toggle All Docks' action.
4019 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
4020 let open_dock_positions = self.get_open_dock_positions(cx);
4021 if !open_dock_positions.is_empty() {
4022 self.last_open_dock_positions = open_dock_positions;
4023 }
4024 }
4025
4026 /// Toggles all docks between open and closed states.
4027 ///
4028 /// If any docks are open, closes all and remembers their positions. If all
4029 /// docks are closed, restores the last remembered dock configuration.
4030 fn toggle_all_docks(
4031 &mut self,
4032 _: &ToggleAllDocks,
4033 window: &mut Window,
4034 cx: &mut Context<Self>,
4035 ) {
4036 let open_dock_positions = self.get_open_dock_positions(cx);
4037
4038 if !open_dock_positions.is_empty() {
4039 self.close_all_docks(window, cx);
4040 } else if !self.last_open_dock_positions.is_empty() {
4041 self.restore_last_open_docks(window, cx);
4042 }
4043 }
4044
4045 /// Reopens docks from the most recently remembered configuration.
4046 ///
4047 /// Opens all docks whose positions are stored in `last_open_dock_positions`
4048 /// and clears the stored positions.
4049 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4050 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
4051
4052 for position in positions_to_open {
4053 let dock = self.dock_at_position(position);
4054 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
4055 }
4056
4057 cx.focus_self(window);
4058 cx.notify();
4059 self.serialize_workspace(window, cx);
4060 }
4061
4062 /// Transfer focus to the panel of the given type.
4063 pub fn focus_panel<T: Panel>(
4064 &mut self,
4065 window: &mut Window,
4066 cx: &mut Context<Self>,
4067 ) -> Option<Entity<T>> {
4068 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
4069 panel.to_any().downcast().ok()
4070 }
4071
4072 /// Focus the panel of the given type if it isn't already focused. If it is
4073 /// already focused, then transfer focus back to the workspace center.
4074 /// When the `close_panel_on_toggle` setting is enabled, also closes the
4075 /// panel when transferring focus back to the center.
4076 pub fn toggle_panel_focus<T: Panel>(
4077 &mut self,
4078 window: &mut Window,
4079 cx: &mut Context<Self>,
4080 ) -> bool {
4081 let mut did_focus_panel = false;
4082 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
4083 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
4084 did_focus_panel
4085 });
4086
4087 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
4088 self.close_panel::<T>(window, cx);
4089 }
4090
4091 telemetry::event!(
4092 "Panel Button Clicked",
4093 name = T::persistent_name(),
4094 toggle_state = did_focus_panel
4095 );
4096
4097 did_focus_panel
4098 }
4099
4100 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4101 if let Some(item) = self.active_item(cx) {
4102 item.item_focus_handle(cx).focus(window, cx);
4103 } else {
4104 log::error!("Could not find a focus target when switching focus to the center panes",);
4105 }
4106 }
4107
4108 pub fn activate_panel_for_proto_id(
4109 &mut self,
4110 panel_id: PanelId,
4111 window: &mut Window,
4112 cx: &mut Context<Self>,
4113 ) -> Option<Arc<dyn PanelHandle>> {
4114 let mut panel = None;
4115 for dock in self.all_docks() {
4116 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
4117 panel = dock.update(cx, |dock, cx| {
4118 dock.activate_panel(panel_index, window, cx);
4119 dock.set_open(true, window, cx);
4120 dock.active_panel().cloned()
4121 });
4122 break;
4123 }
4124 }
4125
4126 if panel.is_some() {
4127 cx.notify();
4128 self.serialize_workspace(window, cx);
4129 }
4130
4131 panel
4132 }
4133
4134 /// Focus or unfocus the given panel type, depending on the given callback.
4135 fn focus_or_unfocus_panel<T: Panel>(
4136 &mut self,
4137 window: &mut Window,
4138 cx: &mut Context<Self>,
4139 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
4140 ) -> Option<Arc<dyn PanelHandle>> {
4141 let mut result_panel = None;
4142 let mut serialize = false;
4143 for dock in self.all_docks() {
4144 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4145 let mut focus_center = false;
4146 let panel = dock.update(cx, |dock, cx| {
4147 dock.activate_panel(panel_index, window, cx);
4148
4149 let panel = dock.active_panel().cloned();
4150 if let Some(panel) = panel.as_ref() {
4151 if should_focus(&**panel, window, cx) {
4152 dock.set_open(true, window, cx);
4153 panel.panel_focus_handle(cx).focus(window, cx);
4154 } else {
4155 focus_center = true;
4156 }
4157 }
4158 panel
4159 });
4160
4161 if focus_center {
4162 self.active_pane
4163 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4164 }
4165
4166 result_panel = panel;
4167 serialize = true;
4168 break;
4169 }
4170 }
4171
4172 if serialize {
4173 self.serialize_workspace(window, cx);
4174 }
4175
4176 cx.notify();
4177 result_panel
4178 }
4179
4180 /// Open the panel of the given type
4181 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4182 for dock in self.all_docks() {
4183 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4184 dock.update(cx, |dock, cx| {
4185 dock.activate_panel(panel_index, window, cx);
4186 dock.set_open(true, window, cx);
4187 });
4188 }
4189 }
4190 }
4191
4192 /// Open the panel of the given type, dismissing any zoomed items that
4193 /// would obscure it (e.g. a zoomed terminal).
4194 pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4195 let dock_position = self.all_docks().iter().find_map(|dock| {
4196 let dock = dock.read(cx);
4197 dock.panel_index_for_type::<T>().map(|_| dock.position())
4198 });
4199 self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
4200 self.open_panel::<T>(window, cx);
4201 }
4202
4203 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
4204 for dock in self.all_docks().iter() {
4205 dock.update(cx, |dock, cx| {
4206 if dock.panel::<T>().is_some() {
4207 dock.set_open(false, window, cx)
4208 }
4209 })
4210 }
4211 }
4212
4213 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
4214 self.all_docks()
4215 .iter()
4216 .find_map(|dock| dock.read(cx).panel::<T>())
4217 }
4218
4219 fn dismiss_zoomed_items_to_reveal(
4220 &mut self,
4221 dock_to_reveal: Option<DockPosition>,
4222 window: &mut Window,
4223 cx: &mut Context<Self>,
4224 ) {
4225 // If a center pane is zoomed, unzoom it.
4226 for pane in &self.panes {
4227 if pane != &self.active_pane || dock_to_reveal.is_some() {
4228 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4229 }
4230 }
4231
4232 // If another dock is zoomed, hide it.
4233 let mut focus_center = false;
4234 for dock in self.all_docks() {
4235 dock.update(cx, |dock, cx| {
4236 if Some(dock.position()) != dock_to_reveal
4237 && let Some(panel) = dock.active_panel()
4238 && panel.is_zoomed(window, cx)
4239 {
4240 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
4241 dock.set_open(false, window, cx);
4242 }
4243 });
4244 }
4245
4246 if focus_center {
4247 self.active_pane
4248 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4249 }
4250
4251 if self.zoomed_position != dock_to_reveal {
4252 self.zoomed = None;
4253 self.zoomed_position = None;
4254 cx.emit(Event::ZoomChanged);
4255 }
4256
4257 cx.notify();
4258 }
4259
4260 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4261 let pane = cx.new(|cx| {
4262 let mut pane = Pane::new(
4263 self.weak_handle(),
4264 self.project.clone(),
4265 self.pane_history_timestamp.clone(),
4266 None,
4267 NewFile.boxed_clone(),
4268 true,
4269 window,
4270 cx,
4271 );
4272 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4273 pane
4274 });
4275 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4276 .detach();
4277 self.panes.push(pane.clone());
4278
4279 window.focus(&pane.focus_handle(cx), cx);
4280
4281 cx.emit(Event::PaneAdded(pane.clone()));
4282 pane
4283 }
4284
4285 pub fn add_item_to_center(
4286 &mut self,
4287 item: Box<dyn ItemHandle>,
4288 window: &mut Window,
4289 cx: &mut Context<Self>,
4290 ) -> bool {
4291 if let Some(center_pane) = self.last_active_center_pane.clone() {
4292 if let Some(center_pane) = center_pane.upgrade() {
4293 center_pane.update(cx, |pane, cx| {
4294 pane.add_item(item, true, true, None, window, cx)
4295 });
4296 true
4297 } else {
4298 false
4299 }
4300 } else {
4301 false
4302 }
4303 }
4304
4305 pub fn add_item_to_active_pane(
4306 &mut self,
4307 item: Box<dyn ItemHandle>,
4308 destination_index: Option<usize>,
4309 focus_item: bool,
4310 window: &mut Window,
4311 cx: &mut App,
4312 ) {
4313 self.add_item(
4314 self.active_pane.clone(),
4315 item,
4316 destination_index,
4317 false,
4318 focus_item,
4319 window,
4320 cx,
4321 )
4322 }
4323
4324 pub fn add_item(
4325 &mut self,
4326 pane: Entity<Pane>,
4327 item: Box<dyn ItemHandle>,
4328 destination_index: Option<usize>,
4329 activate_pane: bool,
4330 focus_item: bool,
4331 window: &mut Window,
4332 cx: &mut App,
4333 ) {
4334 pane.update(cx, |pane, cx| {
4335 pane.add_item(
4336 item,
4337 activate_pane,
4338 focus_item,
4339 destination_index,
4340 window,
4341 cx,
4342 )
4343 });
4344 }
4345
4346 pub fn split_item(
4347 &mut self,
4348 split_direction: SplitDirection,
4349 item: Box<dyn ItemHandle>,
4350 window: &mut Window,
4351 cx: &mut Context<Self>,
4352 ) {
4353 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4354 self.add_item(new_pane, item, None, true, true, window, cx);
4355 }
4356
4357 pub fn open_abs_path(
4358 &mut self,
4359 abs_path: PathBuf,
4360 options: OpenOptions,
4361 window: &mut Window,
4362 cx: &mut Context<Self>,
4363 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4364 cx.spawn_in(window, async move |workspace, cx| {
4365 let open_paths_task_result = workspace
4366 .update_in(cx, |workspace, window, cx| {
4367 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4368 })
4369 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4370 .await;
4371 anyhow::ensure!(
4372 open_paths_task_result.len() == 1,
4373 "open abs path {abs_path:?} task returned incorrect number of results"
4374 );
4375 match open_paths_task_result
4376 .into_iter()
4377 .next()
4378 .expect("ensured single task result")
4379 {
4380 Some(open_result) => {
4381 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4382 }
4383 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4384 }
4385 })
4386 }
4387
4388 pub fn split_abs_path(
4389 &mut self,
4390 abs_path: PathBuf,
4391 visible: bool,
4392 window: &mut Window,
4393 cx: &mut Context<Self>,
4394 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4395 let project_path_task =
4396 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4397 cx.spawn_in(window, async move |this, cx| {
4398 let (_, path) = project_path_task.await?;
4399 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4400 .await
4401 })
4402 }
4403
4404 pub fn open_path(
4405 &mut self,
4406 path: impl Into<ProjectPath>,
4407 pane: Option<WeakEntity<Pane>>,
4408 focus_item: bool,
4409 window: &mut Window,
4410 cx: &mut App,
4411 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4412 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4413 }
4414
4415 pub fn open_path_preview(
4416 &mut self,
4417 path: impl Into<ProjectPath>,
4418 pane: Option<WeakEntity<Pane>>,
4419 focus_item: bool,
4420 allow_preview: bool,
4421 activate: bool,
4422 window: &mut Window,
4423 cx: &mut App,
4424 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4425 let pane = pane.unwrap_or_else(|| {
4426 self.last_active_center_pane.clone().unwrap_or_else(|| {
4427 self.panes
4428 .first()
4429 .expect("There must be an active pane")
4430 .downgrade()
4431 })
4432 });
4433
4434 let project_path = path.into();
4435 let task = self.load_path(project_path.clone(), window, cx);
4436 window.spawn(cx, async move |cx| {
4437 let (project_entry_id, build_item) = task.await?;
4438
4439 pane.update_in(cx, |pane, window, cx| {
4440 pane.open_item(
4441 project_entry_id,
4442 project_path,
4443 focus_item,
4444 allow_preview,
4445 activate,
4446 None,
4447 window,
4448 cx,
4449 build_item,
4450 )
4451 })
4452 })
4453 }
4454
4455 pub fn split_path(
4456 &mut self,
4457 path: impl Into<ProjectPath>,
4458 window: &mut Window,
4459 cx: &mut Context<Self>,
4460 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4461 self.split_path_preview(path, false, None, window, cx)
4462 }
4463
4464 pub fn split_path_preview(
4465 &mut self,
4466 path: impl Into<ProjectPath>,
4467 allow_preview: bool,
4468 split_direction: Option<SplitDirection>,
4469 window: &mut Window,
4470 cx: &mut Context<Self>,
4471 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4472 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4473 self.panes
4474 .first()
4475 .expect("There must be an active pane")
4476 .downgrade()
4477 });
4478
4479 if let Member::Pane(center_pane) = &self.center.root
4480 && center_pane.read(cx).items_len() == 0
4481 {
4482 return self.open_path(path, Some(pane), true, window, cx);
4483 }
4484
4485 let project_path = path.into();
4486 let task = self.load_path(project_path.clone(), window, cx);
4487 cx.spawn_in(window, async move |this, cx| {
4488 let (project_entry_id, build_item) = task.await?;
4489 this.update_in(cx, move |this, window, cx| -> Option<_> {
4490 let pane = pane.upgrade()?;
4491 let new_pane = this.split_pane(
4492 pane,
4493 split_direction.unwrap_or(SplitDirection::Right),
4494 window,
4495 cx,
4496 );
4497 new_pane.update(cx, |new_pane, cx| {
4498 Some(new_pane.open_item(
4499 project_entry_id,
4500 project_path,
4501 true,
4502 allow_preview,
4503 true,
4504 None,
4505 window,
4506 cx,
4507 build_item,
4508 ))
4509 })
4510 })
4511 .map(|option| option.context("pane was dropped"))?
4512 })
4513 }
4514
4515 fn load_path(
4516 &mut self,
4517 path: ProjectPath,
4518 window: &mut Window,
4519 cx: &mut App,
4520 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4521 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4522 registry.open_path(self.project(), &path, window, cx)
4523 }
4524
4525 pub fn find_project_item<T>(
4526 &self,
4527 pane: &Entity<Pane>,
4528 project_item: &Entity<T::Item>,
4529 cx: &App,
4530 ) -> Option<Entity<T>>
4531 where
4532 T: ProjectItem,
4533 {
4534 use project::ProjectItem as _;
4535 let project_item = project_item.read(cx);
4536 let entry_id = project_item.entry_id(cx);
4537 let project_path = project_item.project_path(cx);
4538
4539 let mut item = None;
4540 if let Some(entry_id) = entry_id {
4541 item = pane.read(cx).item_for_entry(entry_id, cx);
4542 }
4543 if item.is_none()
4544 && let Some(project_path) = project_path
4545 {
4546 item = pane.read(cx).item_for_path(project_path, cx);
4547 }
4548
4549 item.and_then(|item| item.downcast::<T>())
4550 }
4551
4552 pub fn is_project_item_open<T>(
4553 &self,
4554 pane: &Entity<Pane>,
4555 project_item: &Entity<T::Item>,
4556 cx: &App,
4557 ) -> bool
4558 where
4559 T: ProjectItem,
4560 {
4561 self.find_project_item::<T>(pane, project_item, cx)
4562 .is_some()
4563 }
4564
4565 pub fn open_project_item<T>(
4566 &mut self,
4567 pane: Entity<Pane>,
4568 project_item: Entity<T::Item>,
4569 activate_pane: bool,
4570 focus_item: bool,
4571 keep_old_preview: bool,
4572 allow_new_preview: bool,
4573 window: &mut Window,
4574 cx: &mut Context<Self>,
4575 ) -> Entity<T>
4576 where
4577 T: ProjectItem,
4578 {
4579 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4580
4581 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4582 if !keep_old_preview
4583 && let Some(old_id) = old_item_id
4584 && old_id != item.item_id()
4585 {
4586 // switching to a different item, so unpreview old active item
4587 pane.update(cx, |pane, _| {
4588 pane.unpreview_item_if_preview(old_id);
4589 });
4590 }
4591
4592 self.activate_item(&item, activate_pane, focus_item, window, cx);
4593 if !allow_new_preview {
4594 pane.update(cx, |pane, _| {
4595 pane.unpreview_item_if_preview(item.item_id());
4596 });
4597 }
4598 return item;
4599 }
4600
4601 let item = pane.update(cx, |pane, cx| {
4602 cx.new(|cx| {
4603 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4604 })
4605 });
4606 let mut destination_index = None;
4607 pane.update(cx, |pane, cx| {
4608 if !keep_old_preview && let Some(old_id) = old_item_id {
4609 pane.unpreview_item_if_preview(old_id);
4610 }
4611 if allow_new_preview {
4612 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4613 }
4614 });
4615
4616 self.add_item(
4617 pane,
4618 Box::new(item.clone()),
4619 destination_index,
4620 activate_pane,
4621 focus_item,
4622 window,
4623 cx,
4624 );
4625 item
4626 }
4627
4628 pub fn open_shared_screen(
4629 &mut self,
4630 peer_id: PeerId,
4631 window: &mut Window,
4632 cx: &mut Context<Self>,
4633 ) {
4634 if let Some(shared_screen) =
4635 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4636 {
4637 self.active_pane.update(cx, |pane, cx| {
4638 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4639 });
4640 }
4641 }
4642
4643 pub fn activate_item(
4644 &mut self,
4645 item: &dyn ItemHandle,
4646 activate_pane: bool,
4647 focus_item: bool,
4648 window: &mut Window,
4649 cx: &mut App,
4650 ) -> bool {
4651 let result = self.panes.iter().find_map(|pane| {
4652 pane.read(cx)
4653 .index_for_item(item)
4654 .map(|ix| (pane.clone(), ix))
4655 });
4656 if let Some((pane, ix)) = result {
4657 pane.update(cx, |pane, cx| {
4658 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4659 });
4660 true
4661 } else {
4662 false
4663 }
4664 }
4665
4666 fn activate_pane_at_index(
4667 &mut self,
4668 action: &ActivatePane,
4669 window: &mut Window,
4670 cx: &mut Context<Self>,
4671 ) {
4672 let panes = self.center.panes();
4673 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4674 window.focus(&pane.focus_handle(cx), cx);
4675 } else {
4676 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4677 .detach();
4678 }
4679 }
4680
4681 fn move_item_to_pane_at_index(
4682 &mut self,
4683 action: &MoveItemToPane,
4684 window: &mut Window,
4685 cx: &mut Context<Self>,
4686 ) {
4687 let panes = self.center.panes();
4688 let destination = match panes.get(action.destination) {
4689 Some(&destination) => destination.clone(),
4690 None => {
4691 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4692 return;
4693 }
4694 let direction = SplitDirection::Right;
4695 let split_off_pane = self
4696 .find_pane_in_direction(direction, cx)
4697 .unwrap_or_else(|| self.active_pane.clone());
4698 let new_pane = self.add_pane(window, cx);
4699 self.center.split(&split_off_pane, &new_pane, direction, cx);
4700 new_pane
4701 }
4702 };
4703
4704 if action.clone {
4705 if self
4706 .active_pane
4707 .read(cx)
4708 .active_item()
4709 .is_some_and(|item| item.can_split(cx))
4710 {
4711 clone_active_item(
4712 self.database_id(),
4713 &self.active_pane,
4714 &destination,
4715 action.focus,
4716 window,
4717 cx,
4718 );
4719 return;
4720 }
4721 }
4722 move_active_item(
4723 &self.active_pane,
4724 &destination,
4725 action.focus,
4726 true,
4727 window,
4728 cx,
4729 )
4730 }
4731
4732 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4733 let panes = self.center.panes();
4734 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4735 let next_ix = (ix + 1) % panes.len();
4736 let next_pane = panes[next_ix].clone();
4737 window.focus(&next_pane.focus_handle(cx), cx);
4738 }
4739 }
4740
4741 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4742 let panes = self.center.panes();
4743 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4744 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4745 let prev_pane = panes[prev_ix].clone();
4746 window.focus(&prev_pane.focus_handle(cx), cx);
4747 }
4748 }
4749
4750 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4751 let last_pane = self.center.last_pane();
4752 window.focus(&last_pane.focus_handle(cx), cx);
4753 }
4754
4755 pub fn activate_pane_in_direction(
4756 &mut self,
4757 direction: SplitDirection,
4758 window: &mut Window,
4759 cx: &mut App,
4760 ) {
4761 use ActivateInDirectionTarget as Target;
4762 enum Origin {
4763 Sidebar,
4764 LeftDock,
4765 RightDock,
4766 BottomDock,
4767 Center,
4768 }
4769
4770 let origin: Origin = if self
4771 .sidebar_focus_handle
4772 .as_ref()
4773 .is_some_and(|h| h.contains_focused(window, cx))
4774 {
4775 Origin::Sidebar
4776 } else {
4777 [
4778 (&self.left_dock, Origin::LeftDock),
4779 (&self.right_dock, Origin::RightDock),
4780 (&self.bottom_dock, Origin::BottomDock),
4781 ]
4782 .into_iter()
4783 .find_map(|(dock, origin)| {
4784 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4785 Some(origin)
4786 } else {
4787 None
4788 }
4789 })
4790 .unwrap_or(Origin::Center)
4791 };
4792
4793 let get_last_active_pane = || {
4794 let pane = self
4795 .last_active_center_pane
4796 .clone()
4797 .unwrap_or_else(|| {
4798 self.panes
4799 .first()
4800 .expect("There must be an active pane")
4801 .downgrade()
4802 })
4803 .upgrade()?;
4804 (pane.read(cx).items_len() != 0).then_some(pane)
4805 };
4806
4807 let try_dock =
4808 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4809
4810 let sidebar_target = self
4811 .sidebar_focus_handle
4812 .as_ref()
4813 .map(|h| Target::Sidebar(h.clone()));
4814
4815 let target = match (origin, direction) {
4816 // From the sidebar, only Right navigates into the workspace.
4817 (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
4818 .or_else(|| get_last_active_pane().map(Target::Pane))
4819 .or_else(|| try_dock(&self.bottom_dock))
4820 .or_else(|| try_dock(&self.right_dock)),
4821
4822 (Origin::Sidebar, _) => None,
4823
4824 // We're in the center, so we first try to go to a different pane,
4825 // otherwise try to go to a dock.
4826 (Origin::Center, direction) => {
4827 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4828 Some(Target::Pane(pane))
4829 } else {
4830 match direction {
4831 SplitDirection::Up => None,
4832 SplitDirection::Down => try_dock(&self.bottom_dock),
4833 SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
4834 SplitDirection::Right => try_dock(&self.right_dock),
4835 }
4836 }
4837 }
4838
4839 (Origin::LeftDock, SplitDirection::Right) => {
4840 if let Some(last_active_pane) = get_last_active_pane() {
4841 Some(Target::Pane(last_active_pane))
4842 } else {
4843 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4844 }
4845 }
4846
4847 (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
4848
4849 (Origin::LeftDock, SplitDirection::Down)
4850 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4851
4852 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4853 (Origin::BottomDock, SplitDirection::Left) => {
4854 try_dock(&self.left_dock).or(sidebar_target)
4855 }
4856 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4857
4858 (Origin::RightDock, SplitDirection::Left) => {
4859 if let Some(last_active_pane) = get_last_active_pane() {
4860 Some(Target::Pane(last_active_pane))
4861 } else {
4862 try_dock(&self.bottom_dock)
4863 .or_else(|| try_dock(&self.left_dock))
4864 .or(sidebar_target)
4865 }
4866 }
4867
4868 _ => None,
4869 };
4870
4871 match target {
4872 Some(ActivateInDirectionTarget::Pane(pane)) => {
4873 let pane = pane.read(cx);
4874 if let Some(item) = pane.active_item() {
4875 item.item_focus_handle(cx).focus(window, cx);
4876 } else {
4877 log::error!(
4878 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4879 );
4880 }
4881 }
4882 Some(ActivateInDirectionTarget::Dock(dock)) => {
4883 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4884 window.defer(cx, move |window, cx| {
4885 let dock = dock.read(cx);
4886 if let Some(panel) = dock.active_panel() {
4887 panel.panel_focus_handle(cx).focus(window, cx);
4888 } else {
4889 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4890 }
4891 })
4892 }
4893 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4894 focus_handle.focus(window, cx);
4895 }
4896 None => {}
4897 }
4898 }
4899
4900 pub fn move_item_to_pane_in_direction(
4901 &mut self,
4902 action: &MoveItemToPaneInDirection,
4903 window: &mut Window,
4904 cx: &mut Context<Self>,
4905 ) {
4906 let destination = match self.find_pane_in_direction(action.direction, cx) {
4907 Some(destination) => destination,
4908 None => {
4909 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4910 return;
4911 }
4912 let new_pane = self.add_pane(window, cx);
4913 self.center
4914 .split(&self.active_pane, &new_pane, action.direction, cx);
4915 new_pane
4916 }
4917 };
4918
4919 if action.clone {
4920 if self
4921 .active_pane
4922 .read(cx)
4923 .active_item()
4924 .is_some_and(|item| item.can_split(cx))
4925 {
4926 clone_active_item(
4927 self.database_id(),
4928 &self.active_pane,
4929 &destination,
4930 action.focus,
4931 window,
4932 cx,
4933 );
4934 return;
4935 }
4936 }
4937 move_active_item(
4938 &self.active_pane,
4939 &destination,
4940 action.focus,
4941 true,
4942 window,
4943 cx,
4944 );
4945 }
4946
4947 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4948 self.center.bounding_box_for_pane(pane)
4949 }
4950
4951 pub fn find_pane_in_direction(
4952 &mut self,
4953 direction: SplitDirection,
4954 cx: &App,
4955 ) -> Option<Entity<Pane>> {
4956 self.center
4957 .find_pane_in_direction(&self.active_pane, direction, cx)
4958 .cloned()
4959 }
4960
4961 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4962 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4963 self.center.swap(&self.active_pane, &to, cx);
4964 cx.notify();
4965 }
4966 }
4967
4968 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4969 if self
4970 .center
4971 .move_to_border(&self.active_pane, direction, cx)
4972 .unwrap()
4973 {
4974 cx.notify();
4975 }
4976 }
4977
4978 pub fn resize_pane(
4979 &mut self,
4980 axis: gpui::Axis,
4981 amount: Pixels,
4982 window: &mut Window,
4983 cx: &mut Context<Self>,
4984 ) {
4985 let docks = self.all_docks();
4986 let active_dock = docks
4987 .into_iter()
4988 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4989
4990 if let Some(dock_entity) = active_dock {
4991 let dock = dock_entity.read(cx);
4992 let Some(panel_size) = self.dock_size(&dock, window, cx) else {
4993 return;
4994 };
4995 match dock.position() {
4996 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4997 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4998 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4999 }
5000 } else {
5001 self.center
5002 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
5003 }
5004 cx.notify();
5005 }
5006
5007 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
5008 self.center.reset_pane_sizes(cx);
5009 cx.notify();
5010 }
5011
5012 fn handle_pane_focused(
5013 &mut self,
5014 pane: Entity<Pane>,
5015 window: &mut Window,
5016 cx: &mut Context<Self>,
5017 ) {
5018 // This is explicitly hoisted out of the following check for pane identity as
5019 // terminal panel panes are not registered as a center panes.
5020 self.status_bar.update(cx, |status_bar, cx| {
5021 status_bar.set_active_pane(&pane, window, cx);
5022 });
5023 if self.active_pane != pane {
5024 self.set_active_pane(&pane, window, cx);
5025 }
5026
5027 if self.last_active_center_pane.is_none() {
5028 self.last_active_center_pane = Some(pane.downgrade());
5029 }
5030
5031 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
5032 // This prevents the dock from closing when focus events fire during window activation.
5033 // We also preserve any dock whose active panel itself has focus — this covers
5034 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
5035 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
5036 let dock_read = dock.read(cx);
5037 if let Some(panel) = dock_read.active_panel() {
5038 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
5039 || panel.panel_focus_handle(cx).contains_focused(window, cx)
5040 {
5041 return Some(dock_read.position());
5042 }
5043 }
5044 None
5045 });
5046
5047 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
5048 if pane.read(cx).is_zoomed() {
5049 self.zoomed = Some(pane.downgrade().into());
5050 } else {
5051 self.zoomed = None;
5052 }
5053 self.zoomed_position = None;
5054 cx.emit(Event::ZoomChanged);
5055 self.update_active_view_for_followers(window, cx);
5056 pane.update(cx, |pane, _| {
5057 pane.track_alternate_file_items();
5058 });
5059
5060 cx.notify();
5061 }
5062
5063 fn set_active_pane(
5064 &mut self,
5065 pane: &Entity<Pane>,
5066 window: &mut Window,
5067 cx: &mut Context<Self>,
5068 ) {
5069 self.active_pane = pane.clone();
5070 self.active_item_path_changed(true, window, cx);
5071 self.last_active_center_pane = Some(pane.downgrade());
5072 }
5073
5074 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5075 self.update_active_view_for_followers(window, cx);
5076 }
5077
5078 fn handle_pane_event(
5079 &mut self,
5080 pane: &Entity<Pane>,
5081 event: &pane::Event,
5082 window: &mut Window,
5083 cx: &mut Context<Self>,
5084 ) {
5085 let mut serialize_workspace = true;
5086 match event {
5087 pane::Event::AddItem { item } => {
5088 item.added_to_pane(self, pane.clone(), window, cx);
5089 cx.emit(Event::ItemAdded {
5090 item: item.boxed_clone(),
5091 });
5092 }
5093 pane::Event::Split { direction, mode } => {
5094 match mode {
5095 SplitMode::ClonePane => {
5096 self.split_and_clone(pane.clone(), *direction, window, cx)
5097 .detach();
5098 }
5099 SplitMode::EmptyPane => {
5100 self.split_pane(pane.clone(), *direction, window, cx);
5101 }
5102 SplitMode::MovePane => {
5103 self.split_and_move(pane.clone(), *direction, window, cx);
5104 }
5105 };
5106 }
5107 pane::Event::JoinIntoNext => {
5108 self.join_pane_into_next(pane.clone(), window, cx);
5109 }
5110 pane::Event::JoinAll => {
5111 self.join_all_panes(window, cx);
5112 }
5113 pane::Event::Remove { focus_on_pane } => {
5114 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
5115 }
5116 pane::Event::ActivateItem {
5117 local,
5118 focus_changed,
5119 } => {
5120 window.invalidate_character_coordinates();
5121
5122 pane.update(cx, |pane, _| {
5123 pane.track_alternate_file_items();
5124 });
5125 if *local {
5126 self.unfollow_in_pane(pane, window, cx);
5127 }
5128 serialize_workspace = *focus_changed || pane != self.active_pane();
5129 if pane == self.active_pane() {
5130 self.active_item_path_changed(*focus_changed, window, cx);
5131 self.update_active_view_for_followers(window, cx);
5132 } else if *local {
5133 self.set_active_pane(pane, window, cx);
5134 }
5135 }
5136 pane::Event::UserSavedItem { item, save_intent } => {
5137 cx.emit(Event::UserSavedItem {
5138 pane: pane.downgrade(),
5139 item: item.boxed_clone(),
5140 save_intent: *save_intent,
5141 });
5142 serialize_workspace = false;
5143 }
5144 pane::Event::ChangeItemTitle => {
5145 if *pane == self.active_pane {
5146 self.active_item_path_changed(false, window, cx);
5147 }
5148 serialize_workspace = false;
5149 }
5150 pane::Event::RemovedItem { item } => {
5151 cx.emit(Event::ActiveItemChanged);
5152 self.update_window_edited(window, cx);
5153 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
5154 && entry.get().entity_id() == pane.entity_id()
5155 {
5156 entry.remove();
5157 }
5158 cx.emit(Event::ItemRemoved {
5159 item_id: item.item_id(),
5160 });
5161 }
5162 pane::Event::Focus => {
5163 window.invalidate_character_coordinates();
5164 self.handle_pane_focused(pane.clone(), window, cx);
5165 }
5166 pane::Event::ZoomIn => {
5167 if *pane == self.active_pane {
5168 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
5169 if pane.read(cx).has_focus(window, cx) {
5170 self.zoomed = Some(pane.downgrade().into());
5171 self.zoomed_position = None;
5172 cx.emit(Event::ZoomChanged);
5173 }
5174 cx.notify();
5175 }
5176 }
5177 pane::Event::ZoomOut => {
5178 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
5179 if self.zoomed_position.is_none() {
5180 self.zoomed = None;
5181 cx.emit(Event::ZoomChanged);
5182 }
5183 cx.notify();
5184 }
5185 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
5186 }
5187
5188 if serialize_workspace {
5189 self.serialize_workspace(window, cx);
5190 }
5191 }
5192
5193 pub fn unfollow_in_pane(
5194 &mut self,
5195 pane: &Entity<Pane>,
5196 window: &mut Window,
5197 cx: &mut Context<Workspace>,
5198 ) -> Option<CollaboratorId> {
5199 let leader_id = self.leader_for_pane(pane)?;
5200 self.unfollow(leader_id, window, cx);
5201 Some(leader_id)
5202 }
5203
5204 pub fn split_pane(
5205 &mut self,
5206 pane_to_split: Entity<Pane>,
5207 split_direction: SplitDirection,
5208 window: &mut Window,
5209 cx: &mut Context<Self>,
5210 ) -> Entity<Pane> {
5211 let new_pane = self.add_pane(window, cx);
5212 self.center
5213 .split(&pane_to_split, &new_pane, split_direction, cx);
5214 cx.notify();
5215 new_pane
5216 }
5217
5218 pub fn split_and_move(
5219 &mut self,
5220 pane: Entity<Pane>,
5221 direction: SplitDirection,
5222 window: &mut Window,
5223 cx: &mut Context<Self>,
5224 ) {
5225 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
5226 return;
5227 };
5228 let new_pane = self.add_pane(window, cx);
5229 new_pane.update(cx, |pane, cx| {
5230 pane.add_item(item, true, true, None, window, cx)
5231 });
5232 self.center.split(&pane, &new_pane, direction, cx);
5233 cx.notify();
5234 }
5235
5236 pub fn split_and_clone(
5237 &mut self,
5238 pane: Entity<Pane>,
5239 direction: SplitDirection,
5240 window: &mut Window,
5241 cx: &mut Context<Self>,
5242 ) -> Task<Option<Entity<Pane>>> {
5243 let Some(item) = pane.read(cx).active_item() else {
5244 return Task::ready(None);
5245 };
5246 if !item.can_split(cx) {
5247 return Task::ready(None);
5248 }
5249 let task = item.clone_on_split(self.database_id(), window, cx);
5250 cx.spawn_in(window, async move |this, cx| {
5251 if let Some(clone) = task.await {
5252 this.update_in(cx, |this, window, cx| {
5253 let new_pane = this.add_pane(window, cx);
5254 let nav_history = pane.read(cx).fork_nav_history();
5255 new_pane.update(cx, |pane, cx| {
5256 pane.set_nav_history(nav_history, cx);
5257 pane.add_item(clone, true, true, None, window, cx)
5258 });
5259 this.center.split(&pane, &new_pane, direction, cx);
5260 cx.notify();
5261 new_pane
5262 })
5263 .ok()
5264 } else {
5265 None
5266 }
5267 })
5268 }
5269
5270 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5271 let active_item = self.active_pane.read(cx).active_item();
5272 for pane in &self.panes {
5273 join_pane_into_active(&self.active_pane, pane, window, cx);
5274 }
5275 if let Some(active_item) = active_item {
5276 self.activate_item(active_item.as_ref(), true, true, window, cx);
5277 }
5278 cx.notify();
5279 }
5280
5281 pub fn join_pane_into_next(
5282 &mut self,
5283 pane: Entity<Pane>,
5284 window: &mut Window,
5285 cx: &mut Context<Self>,
5286 ) {
5287 let next_pane = self
5288 .find_pane_in_direction(SplitDirection::Right, cx)
5289 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5290 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5291 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5292 let Some(next_pane) = next_pane else {
5293 return;
5294 };
5295 move_all_items(&pane, &next_pane, window, cx);
5296 cx.notify();
5297 }
5298
5299 fn remove_pane(
5300 &mut self,
5301 pane: Entity<Pane>,
5302 focus_on: Option<Entity<Pane>>,
5303 window: &mut Window,
5304 cx: &mut Context<Self>,
5305 ) {
5306 if self.center.remove(&pane, cx).unwrap() {
5307 self.force_remove_pane(&pane, &focus_on, window, cx);
5308 self.unfollow_in_pane(&pane, window, cx);
5309 self.last_leaders_by_pane.remove(&pane.downgrade());
5310 for removed_item in pane.read(cx).items() {
5311 self.panes_by_item.remove(&removed_item.item_id());
5312 }
5313
5314 cx.notify();
5315 } else {
5316 self.active_item_path_changed(true, window, cx);
5317 }
5318 cx.emit(Event::PaneRemoved);
5319 }
5320
5321 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5322 &mut self.panes
5323 }
5324
5325 pub fn panes(&self) -> &[Entity<Pane>] {
5326 &self.panes
5327 }
5328
5329 pub fn active_pane(&self) -> &Entity<Pane> {
5330 &self.active_pane
5331 }
5332
5333 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5334 for dock in self.all_docks() {
5335 if dock.focus_handle(cx).contains_focused(window, cx)
5336 && let Some(pane) = dock
5337 .read(cx)
5338 .active_panel()
5339 .and_then(|panel| panel.pane(cx))
5340 {
5341 return pane;
5342 }
5343 }
5344 self.active_pane().clone()
5345 }
5346
5347 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5348 self.find_pane_in_direction(SplitDirection::Right, cx)
5349 .unwrap_or_else(|| {
5350 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5351 })
5352 }
5353
5354 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5355 self.pane_for_item_id(handle.item_id())
5356 }
5357
5358 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5359 let weak_pane = self.panes_by_item.get(&item_id)?;
5360 weak_pane.upgrade()
5361 }
5362
5363 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5364 self.panes
5365 .iter()
5366 .find(|pane| pane.entity_id() == entity_id)
5367 .cloned()
5368 }
5369
5370 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5371 self.follower_states.retain(|leader_id, state| {
5372 if *leader_id == CollaboratorId::PeerId(peer_id) {
5373 for item in state.items_by_leader_view_id.values() {
5374 item.view.set_leader_id(None, window, cx);
5375 }
5376 false
5377 } else {
5378 true
5379 }
5380 });
5381 cx.notify();
5382 }
5383
5384 pub fn start_following(
5385 &mut self,
5386 leader_id: impl Into<CollaboratorId>,
5387 window: &mut Window,
5388 cx: &mut Context<Self>,
5389 ) -> Option<Task<Result<()>>> {
5390 let leader_id = leader_id.into();
5391 let pane = self.active_pane().clone();
5392
5393 self.last_leaders_by_pane
5394 .insert(pane.downgrade(), leader_id);
5395 self.unfollow(leader_id, window, cx);
5396 self.unfollow_in_pane(&pane, window, cx);
5397 self.follower_states.insert(
5398 leader_id,
5399 FollowerState {
5400 center_pane: pane.clone(),
5401 dock_pane: None,
5402 active_view_id: None,
5403 items_by_leader_view_id: Default::default(),
5404 },
5405 );
5406 cx.notify();
5407
5408 match leader_id {
5409 CollaboratorId::PeerId(leader_peer_id) => {
5410 let room_id = self.active_call()?.room_id(cx)?;
5411 let project_id = self.project.read(cx).remote_id();
5412 let request = self.app_state.client.request(proto::Follow {
5413 room_id,
5414 project_id,
5415 leader_id: Some(leader_peer_id),
5416 });
5417
5418 Some(cx.spawn_in(window, async move |this, cx| {
5419 let response = request.await?;
5420 this.update(cx, |this, _| {
5421 let state = this
5422 .follower_states
5423 .get_mut(&leader_id)
5424 .context("following interrupted")?;
5425 state.active_view_id = response
5426 .active_view
5427 .as_ref()
5428 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5429 anyhow::Ok(())
5430 })??;
5431 if let Some(view) = response.active_view {
5432 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5433 }
5434 this.update_in(cx, |this, window, cx| {
5435 this.leader_updated(leader_id, window, cx)
5436 })?;
5437 Ok(())
5438 }))
5439 }
5440 CollaboratorId::Agent => {
5441 self.leader_updated(leader_id, window, cx)?;
5442 Some(Task::ready(Ok(())))
5443 }
5444 }
5445 }
5446
5447 pub fn follow_next_collaborator(
5448 &mut self,
5449 _: &FollowNextCollaborator,
5450 window: &mut Window,
5451 cx: &mut Context<Self>,
5452 ) {
5453 let collaborators = self.project.read(cx).collaborators();
5454 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5455 let mut collaborators = collaborators.keys().copied();
5456 for peer_id in collaborators.by_ref() {
5457 if CollaboratorId::PeerId(peer_id) == leader_id {
5458 break;
5459 }
5460 }
5461 collaborators.next().map(CollaboratorId::PeerId)
5462 } else if let Some(last_leader_id) =
5463 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5464 {
5465 match last_leader_id {
5466 CollaboratorId::PeerId(peer_id) => {
5467 if collaborators.contains_key(peer_id) {
5468 Some(*last_leader_id)
5469 } else {
5470 None
5471 }
5472 }
5473 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5474 }
5475 } else {
5476 None
5477 };
5478
5479 let pane = self.active_pane.clone();
5480 let Some(leader_id) = next_leader_id.or_else(|| {
5481 Some(CollaboratorId::PeerId(
5482 collaborators.keys().copied().next()?,
5483 ))
5484 }) else {
5485 return;
5486 };
5487 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5488 return;
5489 }
5490 if let Some(task) = self.start_following(leader_id, window, cx) {
5491 task.detach_and_log_err(cx)
5492 }
5493 }
5494
5495 pub fn follow(
5496 &mut self,
5497 leader_id: impl Into<CollaboratorId>,
5498 window: &mut Window,
5499 cx: &mut Context<Self>,
5500 ) {
5501 let leader_id = leader_id.into();
5502
5503 if let CollaboratorId::PeerId(peer_id) = leader_id {
5504 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5505 return;
5506 };
5507 let Some(remote_participant) =
5508 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5509 else {
5510 return;
5511 };
5512
5513 let project = self.project.read(cx);
5514
5515 let other_project_id = match remote_participant.location {
5516 ParticipantLocation::External => None,
5517 ParticipantLocation::UnsharedProject => None,
5518 ParticipantLocation::SharedProject { project_id } => {
5519 if Some(project_id) == project.remote_id() {
5520 None
5521 } else {
5522 Some(project_id)
5523 }
5524 }
5525 };
5526
5527 // if they are active in another project, follow there.
5528 if let Some(project_id) = other_project_id {
5529 let app_state = self.app_state.clone();
5530 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5531 .detach_and_log_err(cx);
5532 }
5533 }
5534
5535 // if you're already following, find the right pane and focus it.
5536 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5537 window.focus(&follower_state.pane().focus_handle(cx), cx);
5538
5539 return;
5540 }
5541
5542 // Otherwise, follow.
5543 if let Some(task) = self.start_following(leader_id, window, cx) {
5544 task.detach_and_log_err(cx)
5545 }
5546 }
5547
5548 pub fn unfollow(
5549 &mut self,
5550 leader_id: impl Into<CollaboratorId>,
5551 window: &mut Window,
5552 cx: &mut Context<Self>,
5553 ) -> Option<()> {
5554 cx.notify();
5555
5556 let leader_id = leader_id.into();
5557 let state = self.follower_states.remove(&leader_id)?;
5558 for (_, item) in state.items_by_leader_view_id {
5559 item.view.set_leader_id(None, window, cx);
5560 }
5561
5562 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5563 let project_id = self.project.read(cx).remote_id();
5564 let room_id = self.active_call()?.room_id(cx)?;
5565 self.app_state
5566 .client
5567 .send(proto::Unfollow {
5568 room_id,
5569 project_id,
5570 leader_id: Some(leader_peer_id),
5571 })
5572 .log_err();
5573 }
5574
5575 Some(())
5576 }
5577
5578 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5579 self.follower_states.contains_key(&id.into())
5580 }
5581
5582 fn active_item_path_changed(
5583 &mut self,
5584 focus_changed: bool,
5585 window: &mut Window,
5586 cx: &mut Context<Self>,
5587 ) {
5588 cx.emit(Event::ActiveItemChanged);
5589 let active_entry = self.active_project_path(cx);
5590 self.project.update(cx, |project, cx| {
5591 project.set_active_path(active_entry.clone(), cx)
5592 });
5593
5594 if focus_changed && let Some(project_path) = &active_entry {
5595 let git_store_entity = self.project.read(cx).git_store().clone();
5596 git_store_entity.update(cx, |git_store, cx| {
5597 git_store.set_active_repo_for_path(project_path, cx);
5598 });
5599 }
5600
5601 self.update_window_title(window, cx);
5602 }
5603
5604 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5605 let project = self.project().read(cx);
5606 let mut title = String::new();
5607
5608 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5609 let name = {
5610 let settings_location = SettingsLocation {
5611 worktree_id: worktree.read(cx).id(),
5612 path: RelPath::empty(),
5613 };
5614
5615 let settings = WorktreeSettings::get(Some(settings_location), cx);
5616 match &settings.project_name {
5617 Some(name) => name.as_str(),
5618 None => worktree.read(cx).root_name_str(),
5619 }
5620 };
5621 if i > 0 {
5622 title.push_str(", ");
5623 }
5624 title.push_str(name);
5625 }
5626
5627 if title.is_empty() {
5628 title = "empty project".to_string();
5629 }
5630
5631 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5632 let filename = path.path.file_name().or_else(|| {
5633 Some(
5634 project
5635 .worktree_for_id(path.worktree_id, cx)?
5636 .read(cx)
5637 .root_name_str(),
5638 )
5639 });
5640
5641 if let Some(filename) = filename {
5642 title.push_str(" — ");
5643 title.push_str(filename.as_ref());
5644 }
5645 }
5646
5647 if project.is_via_collab() {
5648 title.push_str(" ↙");
5649 } else if project.is_shared() {
5650 title.push_str(" ↗");
5651 }
5652
5653 if let Some(last_title) = self.last_window_title.as_ref()
5654 && &title == last_title
5655 {
5656 return;
5657 }
5658 window.set_window_title(&title);
5659 SystemWindowTabController::update_tab_title(
5660 cx,
5661 window.window_handle().window_id(),
5662 SharedString::from(&title),
5663 );
5664 self.last_window_title = Some(title);
5665 }
5666
5667 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5668 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5669 if is_edited != self.window_edited {
5670 self.window_edited = is_edited;
5671 window.set_window_edited(self.window_edited)
5672 }
5673 }
5674
5675 fn update_item_dirty_state(
5676 &mut self,
5677 item: &dyn ItemHandle,
5678 window: &mut Window,
5679 cx: &mut App,
5680 ) {
5681 let is_dirty = item.is_dirty(cx);
5682 let item_id = item.item_id();
5683 let was_dirty = self.dirty_items.contains_key(&item_id);
5684 if is_dirty == was_dirty {
5685 return;
5686 }
5687 if was_dirty {
5688 self.dirty_items.remove(&item_id);
5689 self.update_window_edited(window, cx);
5690 return;
5691 }
5692
5693 let workspace = self.weak_handle();
5694 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5695 return;
5696 };
5697 let on_release_callback = Box::new(move |cx: &mut App| {
5698 window_handle
5699 .update(cx, |_, window, cx| {
5700 workspace
5701 .update(cx, |workspace, cx| {
5702 workspace.dirty_items.remove(&item_id);
5703 workspace.update_window_edited(window, cx)
5704 })
5705 .ok();
5706 })
5707 .ok();
5708 });
5709
5710 let s = item.on_release(cx, on_release_callback);
5711 self.dirty_items.insert(item_id, s);
5712 self.update_window_edited(window, cx);
5713 }
5714
5715 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5716 if self.notifications.is_empty() {
5717 None
5718 } else {
5719 Some(
5720 div()
5721 .absolute()
5722 .right_3()
5723 .bottom_3()
5724 .w_112()
5725 .h_full()
5726 .flex()
5727 .flex_col()
5728 .justify_end()
5729 .gap_2()
5730 .children(
5731 self.notifications
5732 .iter()
5733 .map(|(_, notification)| notification.clone().into_any()),
5734 ),
5735 )
5736 }
5737 }
5738
5739 // RPC handlers
5740
5741 fn active_view_for_follower(
5742 &self,
5743 follower_project_id: Option<u64>,
5744 window: &mut Window,
5745 cx: &mut Context<Self>,
5746 ) -> Option<proto::View> {
5747 let (item, panel_id) = self.active_item_for_followers(window, cx);
5748 let item = item?;
5749 let leader_id = self
5750 .pane_for(&*item)
5751 .and_then(|pane| self.leader_for_pane(&pane));
5752 let leader_peer_id = match leader_id {
5753 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5754 Some(CollaboratorId::Agent) | None => None,
5755 };
5756
5757 let item_handle = item.to_followable_item_handle(cx)?;
5758 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5759 let variant = item_handle.to_state_proto(window, cx)?;
5760
5761 if item_handle.is_project_item(window, cx)
5762 && (follower_project_id.is_none()
5763 || follower_project_id != self.project.read(cx).remote_id())
5764 {
5765 return None;
5766 }
5767
5768 Some(proto::View {
5769 id: id.to_proto(),
5770 leader_id: leader_peer_id,
5771 variant: Some(variant),
5772 panel_id: panel_id.map(|id| id as i32),
5773 })
5774 }
5775
5776 fn handle_follow(
5777 &mut self,
5778 follower_project_id: Option<u64>,
5779 window: &mut Window,
5780 cx: &mut Context<Self>,
5781 ) -> proto::FollowResponse {
5782 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5783
5784 cx.notify();
5785 proto::FollowResponse {
5786 views: active_view.iter().cloned().collect(),
5787 active_view,
5788 }
5789 }
5790
5791 fn handle_update_followers(
5792 &mut self,
5793 leader_id: PeerId,
5794 message: proto::UpdateFollowers,
5795 _window: &mut Window,
5796 _cx: &mut Context<Self>,
5797 ) {
5798 self.leader_updates_tx
5799 .unbounded_send((leader_id, message))
5800 .ok();
5801 }
5802
5803 async fn process_leader_update(
5804 this: &WeakEntity<Self>,
5805 leader_id: PeerId,
5806 update: proto::UpdateFollowers,
5807 cx: &mut AsyncWindowContext,
5808 ) -> Result<()> {
5809 match update.variant.context("invalid update")? {
5810 proto::update_followers::Variant::CreateView(view) => {
5811 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5812 let should_add_view = this.update(cx, |this, _| {
5813 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5814 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5815 } else {
5816 anyhow::Ok(false)
5817 }
5818 })??;
5819
5820 if should_add_view {
5821 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5822 }
5823 }
5824 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5825 let should_add_view = this.update(cx, |this, _| {
5826 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5827 state.active_view_id = update_active_view
5828 .view
5829 .as_ref()
5830 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5831
5832 if state.active_view_id.is_some_and(|view_id| {
5833 !state.items_by_leader_view_id.contains_key(&view_id)
5834 }) {
5835 anyhow::Ok(true)
5836 } else {
5837 anyhow::Ok(false)
5838 }
5839 } else {
5840 anyhow::Ok(false)
5841 }
5842 })??;
5843
5844 if should_add_view && let Some(view) = update_active_view.view {
5845 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5846 }
5847 }
5848 proto::update_followers::Variant::UpdateView(update_view) => {
5849 let variant = update_view.variant.context("missing update view variant")?;
5850 let id = update_view.id.context("missing update view id")?;
5851 let mut tasks = Vec::new();
5852 this.update_in(cx, |this, window, cx| {
5853 let project = this.project.clone();
5854 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5855 let view_id = ViewId::from_proto(id.clone())?;
5856 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5857 tasks.push(item.view.apply_update_proto(
5858 &project,
5859 variant.clone(),
5860 window,
5861 cx,
5862 ));
5863 }
5864 }
5865 anyhow::Ok(())
5866 })??;
5867 try_join_all(tasks).await.log_err();
5868 }
5869 }
5870 this.update_in(cx, |this, window, cx| {
5871 this.leader_updated(leader_id, window, cx)
5872 })?;
5873 Ok(())
5874 }
5875
5876 async fn add_view_from_leader(
5877 this: WeakEntity<Self>,
5878 leader_id: PeerId,
5879 view: &proto::View,
5880 cx: &mut AsyncWindowContext,
5881 ) -> Result<()> {
5882 let this = this.upgrade().context("workspace dropped")?;
5883
5884 let Some(id) = view.id.clone() else {
5885 anyhow::bail!("no id for view");
5886 };
5887 let id = ViewId::from_proto(id)?;
5888 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5889
5890 let pane = this.update(cx, |this, _cx| {
5891 let state = this
5892 .follower_states
5893 .get(&leader_id.into())
5894 .context("stopped following")?;
5895 anyhow::Ok(state.pane().clone())
5896 })?;
5897 let existing_item = pane.update_in(cx, |pane, window, cx| {
5898 let client = this.read(cx).client().clone();
5899 pane.items().find_map(|item| {
5900 let item = item.to_followable_item_handle(cx)?;
5901 if item.remote_id(&client, window, cx) == Some(id) {
5902 Some(item)
5903 } else {
5904 None
5905 }
5906 })
5907 })?;
5908 let item = if let Some(existing_item) = existing_item {
5909 existing_item
5910 } else {
5911 let variant = view.variant.clone();
5912 anyhow::ensure!(variant.is_some(), "missing view variant");
5913
5914 let task = cx.update(|window, cx| {
5915 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5916 })?;
5917
5918 let Some(task) = task else {
5919 anyhow::bail!(
5920 "failed to construct view from leader (maybe from a different version of zed?)"
5921 );
5922 };
5923
5924 let mut new_item = task.await?;
5925 pane.update_in(cx, |pane, window, cx| {
5926 let mut item_to_remove = None;
5927 for (ix, item) in pane.items().enumerate() {
5928 if let Some(item) = item.to_followable_item_handle(cx) {
5929 match new_item.dedup(item.as_ref(), window, cx) {
5930 Some(item::Dedup::KeepExisting) => {
5931 new_item =
5932 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5933 break;
5934 }
5935 Some(item::Dedup::ReplaceExisting) => {
5936 item_to_remove = Some((ix, item.item_id()));
5937 break;
5938 }
5939 None => {}
5940 }
5941 }
5942 }
5943
5944 if let Some((ix, id)) = item_to_remove {
5945 pane.remove_item(id, false, false, window, cx);
5946 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5947 }
5948 })?;
5949
5950 new_item
5951 };
5952
5953 this.update_in(cx, |this, window, cx| {
5954 let state = this.follower_states.get_mut(&leader_id.into())?;
5955 item.set_leader_id(Some(leader_id.into()), window, cx);
5956 state.items_by_leader_view_id.insert(
5957 id,
5958 FollowerView {
5959 view: item,
5960 location: panel_id,
5961 },
5962 );
5963
5964 Some(())
5965 })
5966 .context("no follower state")?;
5967
5968 Ok(())
5969 }
5970
5971 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5972 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5973 return;
5974 };
5975
5976 if let Some(agent_location) = self.project.read(cx).agent_location() {
5977 let buffer_entity_id = agent_location.buffer.entity_id();
5978 let view_id = ViewId {
5979 creator: CollaboratorId::Agent,
5980 id: buffer_entity_id.as_u64(),
5981 };
5982 follower_state.active_view_id = Some(view_id);
5983
5984 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5985 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5986 hash_map::Entry::Vacant(entry) => {
5987 let existing_view =
5988 follower_state
5989 .center_pane
5990 .read(cx)
5991 .items()
5992 .find_map(|item| {
5993 let item = item.to_followable_item_handle(cx)?;
5994 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5995 && item.project_item_model_ids(cx).as_slice()
5996 == [buffer_entity_id]
5997 {
5998 Some(item)
5999 } else {
6000 None
6001 }
6002 });
6003 let view = existing_view.or_else(|| {
6004 agent_location.buffer.upgrade().and_then(|buffer| {
6005 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
6006 registry.build_item(buffer, self.project.clone(), None, window, cx)
6007 })?
6008 .to_followable_item_handle(cx)
6009 })
6010 });
6011
6012 view.map(|view| {
6013 entry.insert(FollowerView {
6014 view,
6015 location: None,
6016 })
6017 })
6018 }
6019 };
6020
6021 if let Some(item) = item {
6022 item.view
6023 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
6024 item.view
6025 .update_agent_location(agent_location.position, window, cx);
6026 }
6027 } else {
6028 follower_state.active_view_id = None;
6029 }
6030
6031 self.leader_updated(CollaboratorId::Agent, window, cx);
6032 }
6033
6034 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
6035 let mut is_project_item = true;
6036 let mut update = proto::UpdateActiveView::default();
6037 if window.is_window_active() {
6038 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
6039
6040 if let Some(item) = active_item
6041 && item.item_focus_handle(cx).contains_focused(window, cx)
6042 {
6043 let leader_id = self
6044 .pane_for(&*item)
6045 .and_then(|pane| self.leader_for_pane(&pane));
6046 let leader_peer_id = match leader_id {
6047 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
6048 Some(CollaboratorId::Agent) | None => None,
6049 };
6050
6051 if let Some(item) = item.to_followable_item_handle(cx) {
6052 let id = item
6053 .remote_id(&self.app_state.client, window, cx)
6054 .map(|id| id.to_proto());
6055
6056 if let Some(id) = id
6057 && let Some(variant) = item.to_state_proto(window, cx)
6058 {
6059 let view = Some(proto::View {
6060 id,
6061 leader_id: leader_peer_id,
6062 variant: Some(variant),
6063 panel_id: panel_id.map(|id| id as i32),
6064 });
6065
6066 is_project_item = item.is_project_item(window, cx);
6067 update = proto::UpdateActiveView { view };
6068 };
6069 }
6070 }
6071 }
6072
6073 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
6074 if active_view_id != self.last_active_view_id.as_ref() {
6075 self.last_active_view_id = active_view_id.cloned();
6076 self.update_followers(
6077 is_project_item,
6078 proto::update_followers::Variant::UpdateActiveView(update),
6079 window,
6080 cx,
6081 );
6082 }
6083 }
6084
6085 fn active_item_for_followers(
6086 &self,
6087 window: &mut Window,
6088 cx: &mut App,
6089 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
6090 let mut active_item = None;
6091 let mut panel_id = None;
6092 for dock in self.all_docks() {
6093 if dock.focus_handle(cx).contains_focused(window, cx)
6094 && let Some(panel) = dock.read(cx).active_panel()
6095 && let Some(pane) = panel.pane(cx)
6096 && let Some(item) = pane.read(cx).active_item()
6097 {
6098 active_item = Some(item);
6099 panel_id = panel.remote_id();
6100 break;
6101 }
6102 }
6103
6104 if active_item.is_none() {
6105 active_item = self.active_pane().read(cx).active_item();
6106 }
6107 (active_item, panel_id)
6108 }
6109
6110 fn update_followers(
6111 &self,
6112 project_only: bool,
6113 update: proto::update_followers::Variant,
6114 _: &mut Window,
6115 cx: &mut App,
6116 ) -> Option<()> {
6117 // If this update only applies to for followers in the current project,
6118 // then skip it unless this project is shared. If it applies to all
6119 // followers, regardless of project, then set `project_id` to none,
6120 // indicating that it goes to all followers.
6121 let project_id = if project_only {
6122 Some(self.project.read(cx).remote_id()?)
6123 } else {
6124 None
6125 };
6126 self.app_state().workspace_store.update(cx, |store, cx| {
6127 store.update_followers(project_id, update, cx)
6128 })
6129 }
6130
6131 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
6132 self.follower_states.iter().find_map(|(leader_id, state)| {
6133 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
6134 Some(*leader_id)
6135 } else {
6136 None
6137 }
6138 })
6139 }
6140
6141 fn leader_updated(
6142 &mut self,
6143 leader_id: impl Into<CollaboratorId>,
6144 window: &mut Window,
6145 cx: &mut Context<Self>,
6146 ) -> Option<Box<dyn ItemHandle>> {
6147 cx.notify();
6148
6149 let leader_id = leader_id.into();
6150 let (panel_id, item) = match leader_id {
6151 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
6152 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
6153 };
6154
6155 let state = self.follower_states.get(&leader_id)?;
6156 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
6157 let pane;
6158 if let Some(panel_id) = panel_id {
6159 pane = self
6160 .activate_panel_for_proto_id(panel_id, window, cx)?
6161 .pane(cx)?;
6162 let state = self.follower_states.get_mut(&leader_id)?;
6163 state.dock_pane = Some(pane.clone());
6164 } else {
6165 pane = state.center_pane.clone();
6166 let state = self.follower_states.get_mut(&leader_id)?;
6167 if let Some(dock_pane) = state.dock_pane.take() {
6168 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
6169 }
6170 }
6171
6172 pane.update(cx, |pane, cx| {
6173 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
6174 if let Some(index) = pane.index_for_item(item.as_ref()) {
6175 pane.activate_item(index, false, false, window, cx);
6176 } else {
6177 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
6178 }
6179
6180 if focus_active_item {
6181 pane.focus_active_item(window, cx)
6182 }
6183 });
6184
6185 Some(item)
6186 }
6187
6188 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
6189 let state = self.follower_states.get(&CollaboratorId::Agent)?;
6190 let active_view_id = state.active_view_id?;
6191 Some(
6192 state
6193 .items_by_leader_view_id
6194 .get(&active_view_id)?
6195 .view
6196 .boxed_clone(),
6197 )
6198 }
6199
6200 fn active_item_for_peer(
6201 &self,
6202 peer_id: PeerId,
6203 window: &mut Window,
6204 cx: &mut Context<Self>,
6205 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
6206 let call = self.active_call()?;
6207 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
6208 let leader_in_this_app;
6209 let leader_in_this_project;
6210 match participant.location {
6211 ParticipantLocation::SharedProject { project_id } => {
6212 leader_in_this_app = true;
6213 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
6214 }
6215 ParticipantLocation::UnsharedProject => {
6216 leader_in_this_app = true;
6217 leader_in_this_project = false;
6218 }
6219 ParticipantLocation::External => {
6220 leader_in_this_app = false;
6221 leader_in_this_project = false;
6222 }
6223 };
6224 let state = self.follower_states.get(&peer_id.into())?;
6225 let mut item_to_activate = None;
6226 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
6227 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
6228 && (leader_in_this_project || !item.view.is_project_item(window, cx))
6229 {
6230 item_to_activate = Some((item.location, item.view.boxed_clone()));
6231 }
6232 } else if let Some(shared_screen) =
6233 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
6234 {
6235 item_to_activate = Some((None, Box::new(shared_screen)));
6236 }
6237 item_to_activate
6238 }
6239
6240 fn shared_screen_for_peer(
6241 &self,
6242 peer_id: PeerId,
6243 pane: &Entity<Pane>,
6244 window: &mut Window,
6245 cx: &mut App,
6246 ) -> Option<Entity<SharedScreen>> {
6247 self.active_call()?
6248 .create_shared_screen(peer_id, pane, window, cx)
6249 }
6250
6251 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6252 if window.is_window_active() {
6253 self.update_active_view_for_followers(window, cx);
6254
6255 if let Some(database_id) = self.database_id {
6256 let db = WorkspaceDb::global(cx);
6257 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6258 .detach();
6259 }
6260 } else {
6261 for pane in &self.panes {
6262 pane.update(cx, |pane, cx| {
6263 if let Some(item) = pane.active_item() {
6264 item.workspace_deactivated(window, cx);
6265 }
6266 for item in pane.items() {
6267 if matches!(
6268 item.workspace_settings(cx).autosave,
6269 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6270 ) {
6271 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6272 .detach_and_log_err(cx);
6273 }
6274 }
6275 });
6276 }
6277 }
6278 }
6279
6280 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6281 self.active_call.as_ref().map(|(call, _)| &*call.0)
6282 }
6283
6284 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6285 self.active_call.as_ref().map(|(call, _)| call.clone())
6286 }
6287
6288 fn on_active_call_event(
6289 &mut self,
6290 event: &ActiveCallEvent,
6291 window: &mut Window,
6292 cx: &mut Context<Self>,
6293 ) {
6294 match event {
6295 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6296 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6297 self.leader_updated(participant_id, window, cx);
6298 }
6299 }
6300 }
6301
6302 pub fn database_id(&self) -> Option<WorkspaceId> {
6303 self.database_id
6304 }
6305
6306 #[cfg(any(test, feature = "test-support"))]
6307 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6308 self.database_id = Some(id);
6309 }
6310
6311 pub fn session_id(&self) -> Option<String> {
6312 self.session_id.clone()
6313 }
6314
6315 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6316 let Some(display) = window.display(cx) else {
6317 return Task::ready(());
6318 };
6319 let Ok(display_uuid) = display.uuid() else {
6320 return Task::ready(());
6321 };
6322
6323 let window_bounds = window.inner_window_bounds();
6324 let database_id = self.database_id;
6325 let has_paths = !self.root_paths(cx).is_empty();
6326 let db = WorkspaceDb::global(cx);
6327 let kvp = db::kvp::KeyValueStore::global(cx);
6328
6329 cx.background_executor().spawn(async move {
6330 if !has_paths {
6331 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6332 .await
6333 .log_err();
6334 }
6335 if let Some(database_id) = database_id {
6336 db.set_window_open_status(
6337 database_id,
6338 SerializedWindowBounds(window_bounds),
6339 display_uuid,
6340 )
6341 .await
6342 .log_err();
6343 } else {
6344 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6345 .await
6346 .log_err();
6347 }
6348 })
6349 }
6350
6351 /// Bypass the 200ms serialization throttle and write workspace state to
6352 /// the DB immediately. Returns a task the caller can await to ensure the
6353 /// write completes. Used by the quit handler so the most recent state
6354 /// isn't lost to a pending throttle timer when the process exits.
6355 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6356 self._schedule_serialize_workspace.take();
6357 self._serialize_workspace_task.take();
6358 self.bounds_save_task_queued.take();
6359
6360 let bounds_task = self.save_window_bounds(window, cx);
6361 let serialize_task = self.serialize_workspace_internal(window, cx);
6362 cx.spawn(async move |_| {
6363 bounds_task.await;
6364 serialize_task.await;
6365 })
6366 }
6367
6368 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6369 let project = self.project().read(cx);
6370 project
6371 .visible_worktrees(cx)
6372 .map(|worktree| worktree.read(cx).abs_path())
6373 .collect::<Vec<_>>()
6374 }
6375
6376 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6377 match member {
6378 Member::Axis(PaneAxis { members, .. }) => {
6379 for child in members.iter() {
6380 self.remove_panes(child.clone(), window, cx)
6381 }
6382 }
6383 Member::Pane(pane) => {
6384 self.force_remove_pane(&pane, &None, window, cx);
6385 }
6386 }
6387 }
6388
6389 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6390 self.session_id.take();
6391 self.serialize_workspace_internal(window, cx)
6392 }
6393
6394 fn force_remove_pane(
6395 &mut self,
6396 pane: &Entity<Pane>,
6397 focus_on: &Option<Entity<Pane>>,
6398 window: &mut Window,
6399 cx: &mut Context<Workspace>,
6400 ) {
6401 self.panes.retain(|p| p != pane);
6402 if let Some(focus_on) = focus_on {
6403 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6404 } else if self.active_pane() == pane {
6405 self.panes
6406 .last()
6407 .unwrap()
6408 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6409 }
6410 if self.last_active_center_pane == Some(pane.downgrade()) {
6411 self.last_active_center_pane = None;
6412 }
6413 cx.notify();
6414 }
6415
6416 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6417 if self._schedule_serialize_workspace.is_none() {
6418 self._schedule_serialize_workspace =
6419 Some(cx.spawn_in(window, async move |this, cx| {
6420 cx.background_executor()
6421 .timer(SERIALIZATION_THROTTLE_TIME)
6422 .await;
6423 this.update_in(cx, |this, window, cx| {
6424 this._serialize_workspace_task =
6425 Some(this.serialize_workspace_internal(window, cx));
6426 this._schedule_serialize_workspace.take();
6427 })
6428 .log_err();
6429 }));
6430 }
6431 }
6432
6433 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6434 let Some(database_id) = self.database_id() else {
6435 return Task::ready(());
6436 };
6437
6438 fn serialize_pane_handle(
6439 pane_handle: &Entity<Pane>,
6440 window: &mut Window,
6441 cx: &mut App,
6442 ) -> SerializedPane {
6443 let (items, active, pinned_count) = {
6444 let pane = pane_handle.read(cx);
6445 let active_item_id = pane.active_item().map(|item| item.item_id());
6446 (
6447 pane.items()
6448 .filter_map(|handle| {
6449 let handle = handle.to_serializable_item_handle(cx)?;
6450
6451 Some(SerializedItem {
6452 kind: Arc::from(handle.serialized_item_kind()),
6453 item_id: handle.item_id().as_u64(),
6454 active: Some(handle.item_id()) == active_item_id,
6455 preview: pane.is_active_preview_item(handle.item_id()),
6456 })
6457 })
6458 .collect::<Vec<_>>(),
6459 pane.has_focus(window, cx),
6460 pane.pinned_count(),
6461 )
6462 };
6463
6464 SerializedPane::new(items, active, pinned_count)
6465 }
6466
6467 fn build_serialized_pane_group(
6468 pane_group: &Member,
6469 window: &mut Window,
6470 cx: &mut App,
6471 ) -> SerializedPaneGroup {
6472 match pane_group {
6473 Member::Axis(PaneAxis {
6474 axis,
6475 members,
6476 flexes,
6477 bounding_boxes: _,
6478 }) => SerializedPaneGroup::Group {
6479 axis: SerializedAxis(*axis),
6480 children: members
6481 .iter()
6482 .map(|member| build_serialized_pane_group(member, window, cx))
6483 .collect::<Vec<_>>(),
6484 flexes: Some(flexes.lock().clone()),
6485 },
6486 Member::Pane(pane_handle) => {
6487 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6488 }
6489 }
6490 }
6491
6492 fn build_serialized_docks(
6493 this: &Workspace,
6494 window: &mut Window,
6495 cx: &mut App,
6496 ) -> DockStructure {
6497 this.capture_dock_state(window, cx)
6498 }
6499
6500 match self.workspace_location(cx) {
6501 WorkspaceLocation::Location(location, paths) => {
6502 let breakpoints = self.project.update(cx, |project, cx| {
6503 project
6504 .breakpoint_store()
6505 .read(cx)
6506 .all_source_breakpoints(cx)
6507 });
6508 let user_toolchains = self
6509 .project
6510 .read(cx)
6511 .user_toolchains(cx)
6512 .unwrap_or_default();
6513
6514 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6515 let docks = build_serialized_docks(self, window, cx);
6516 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6517
6518 let serialized_workspace = SerializedWorkspace {
6519 id: database_id,
6520 location,
6521 paths,
6522 center_group,
6523 window_bounds,
6524 display: Default::default(),
6525 docks,
6526 centered_layout: self.centered_layout,
6527 session_id: self.session_id.clone(),
6528 breakpoints,
6529 window_id: Some(window.window_handle().window_id().as_u64()),
6530 user_toolchains,
6531 };
6532
6533 let db = WorkspaceDb::global(cx);
6534 window.spawn(cx, async move |_| {
6535 db.save_workspace(serialized_workspace).await;
6536 })
6537 }
6538 WorkspaceLocation::DetachFromSession => {
6539 let window_bounds = SerializedWindowBounds(window.window_bounds());
6540 let display = window.display(cx).and_then(|d| d.uuid().ok());
6541 // Save dock state for empty local workspaces
6542 let docks = build_serialized_docks(self, window, cx);
6543 let db = WorkspaceDb::global(cx);
6544 let kvp = db::kvp::KeyValueStore::global(cx);
6545 window.spawn(cx, async move |_| {
6546 db.set_window_open_status(
6547 database_id,
6548 window_bounds,
6549 display.unwrap_or_default(),
6550 )
6551 .await
6552 .log_err();
6553 db.set_session_id(database_id, None).await.log_err();
6554 persistence::write_default_dock_state(&kvp, docks)
6555 .await
6556 .log_err();
6557 })
6558 }
6559 WorkspaceLocation::None => {
6560 // Save dock state for empty non-local workspaces
6561 let docks = build_serialized_docks(self, window, cx);
6562 let kvp = db::kvp::KeyValueStore::global(cx);
6563 window.spawn(cx, async move |_| {
6564 persistence::write_default_dock_state(&kvp, docks)
6565 .await
6566 .log_err();
6567 })
6568 }
6569 }
6570 }
6571
6572 fn has_any_items_open(&self, cx: &App) -> bool {
6573 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6574 }
6575
6576 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6577 let paths = PathList::new(&self.root_paths(cx));
6578 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6579 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6580 } else if self.project.read(cx).is_local() {
6581 if !paths.is_empty() || self.has_any_items_open(cx) {
6582 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6583 } else {
6584 WorkspaceLocation::DetachFromSession
6585 }
6586 } else {
6587 WorkspaceLocation::None
6588 }
6589 }
6590
6591 fn update_history(&self, cx: &mut App) {
6592 let Some(id) = self.database_id() else {
6593 return;
6594 };
6595 if !self.project.read(cx).is_local() {
6596 return;
6597 }
6598 if let Some(manager) = HistoryManager::global(cx) {
6599 let paths = PathList::new(&self.root_paths(cx));
6600 manager.update(cx, |this, cx| {
6601 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6602 });
6603 }
6604 }
6605
6606 async fn serialize_items(
6607 this: &WeakEntity<Self>,
6608 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6609 cx: &mut AsyncWindowContext,
6610 ) -> Result<()> {
6611 const CHUNK_SIZE: usize = 200;
6612
6613 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6614
6615 while let Some(items_received) = serializable_items.next().await {
6616 let unique_items =
6617 items_received
6618 .into_iter()
6619 .fold(HashMap::default(), |mut acc, item| {
6620 acc.entry(item.item_id()).or_insert(item);
6621 acc
6622 });
6623
6624 // We use into_iter() here so that the references to the items are moved into
6625 // the tasks and not kept alive while we're sleeping.
6626 for (_, item) in unique_items.into_iter() {
6627 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6628 item.serialize(workspace, false, window, cx)
6629 }) {
6630 cx.background_spawn(async move { task.await.log_err() })
6631 .detach();
6632 }
6633 }
6634
6635 cx.background_executor()
6636 .timer(SERIALIZATION_THROTTLE_TIME)
6637 .await;
6638 }
6639
6640 Ok(())
6641 }
6642
6643 pub(crate) fn enqueue_item_serialization(
6644 &mut self,
6645 item: Box<dyn SerializableItemHandle>,
6646 ) -> Result<()> {
6647 self.serializable_items_tx
6648 .unbounded_send(item)
6649 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6650 }
6651
6652 pub(crate) fn load_workspace(
6653 serialized_workspace: SerializedWorkspace,
6654 paths_to_open: Vec<Option<ProjectPath>>,
6655 window: &mut Window,
6656 cx: &mut Context<Workspace>,
6657 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6658 cx.spawn_in(window, async move |workspace, cx| {
6659 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6660
6661 let mut center_group = None;
6662 let mut center_items = None;
6663
6664 // Traverse the splits tree and add to things
6665 if let Some((group, active_pane, items)) = serialized_workspace
6666 .center_group
6667 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6668 .await
6669 {
6670 center_items = Some(items);
6671 center_group = Some((group, active_pane))
6672 }
6673
6674 let mut items_by_project_path = HashMap::default();
6675 let mut item_ids_by_kind = HashMap::default();
6676 let mut all_deserialized_items = Vec::default();
6677 cx.update(|_, cx| {
6678 for item in center_items.unwrap_or_default().into_iter().flatten() {
6679 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6680 item_ids_by_kind
6681 .entry(serializable_item_handle.serialized_item_kind())
6682 .or_insert(Vec::new())
6683 .push(item.item_id().as_u64() as ItemId);
6684 }
6685
6686 if let Some(project_path) = item.project_path(cx) {
6687 items_by_project_path.insert(project_path, item.clone());
6688 }
6689 all_deserialized_items.push(item);
6690 }
6691 })?;
6692
6693 let opened_items = paths_to_open
6694 .into_iter()
6695 .map(|path_to_open| {
6696 path_to_open
6697 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6698 })
6699 .collect::<Vec<_>>();
6700
6701 // Remove old panes from workspace panes list
6702 workspace.update_in(cx, |workspace, window, cx| {
6703 if let Some((center_group, active_pane)) = center_group {
6704 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6705
6706 // Swap workspace center group
6707 workspace.center = PaneGroup::with_root(center_group);
6708 workspace.center.set_is_center(true);
6709 workspace.center.mark_positions(cx);
6710
6711 if let Some(active_pane) = active_pane {
6712 workspace.set_active_pane(&active_pane, window, cx);
6713 cx.focus_self(window);
6714 } else {
6715 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6716 }
6717 }
6718
6719 let docks = serialized_workspace.docks;
6720
6721 for (dock, serialized_dock) in [
6722 (&mut workspace.right_dock, docks.right),
6723 (&mut workspace.left_dock, docks.left),
6724 (&mut workspace.bottom_dock, docks.bottom),
6725 ]
6726 .iter_mut()
6727 {
6728 dock.update(cx, |dock, cx| {
6729 dock.serialized_dock = Some(serialized_dock.clone());
6730 dock.restore_state(window, cx);
6731 });
6732 }
6733
6734 cx.notify();
6735 })?;
6736
6737 let _ = project
6738 .update(cx, |project, cx| {
6739 project
6740 .breakpoint_store()
6741 .update(cx, |breakpoint_store, cx| {
6742 breakpoint_store
6743 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6744 })
6745 })
6746 .await;
6747
6748 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6749 // after loading the items, we might have different items and in order to avoid
6750 // the database filling up, we delete items that haven't been loaded now.
6751 //
6752 // The items that have been loaded, have been saved after they've been added to the workspace.
6753 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6754 item_ids_by_kind
6755 .into_iter()
6756 .map(|(item_kind, loaded_items)| {
6757 SerializableItemRegistry::cleanup(
6758 item_kind,
6759 serialized_workspace.id,
6760 loaded_items,
6761 window,
6762 cx,
6763 )
6764 .log_err()
6765 })
6766 .collect::<Vec<_>>()
6767 })?;
6768
6769 futures::future::join_all(clean_up_tasks).await;
6770
6771 workspace
6772 .update_in(cx, |workspace, window, cx| {
6773 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6774 workspace.serialize_workspace_internal(window, cx).detach();
6775
6776 // Ensure that we mark the window as edited if we did load dirty items
6777 workspace.update_window_edited(window, cx);
6778 })
6779 .ok();
6780
6781 Ok(opened_items)
6782 })
6783 }
6784
6785 pub fn key_context(&self, cx: &App) -> KeyContext {
6786 let mut context = KeyContext::new_with_defaults();
6787 context.add("Workspace");
6788 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6789 if let Some(status) = self
6790 .debugger_provider
6791 .as_ref()
6792 .and_then(|provider| provider.active_thread_state(cx))
6793 {
6794 match status {
6795 ThreadStatus::Running | ThreadStatus::Stepping => {
6796 context.add("debugger_running");
6797 }
6798 ThreadStatus::Stopped => context.add("debugger_stopped"),
6799 ThreadStatus::Exited | ThreadStatus::Ended => {}
6800 }
6801 }
6802
6803 if self.left_dock.read(cx).is_open() {
6804 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6805 context.set("left_dock", active_panel.panel_key());
6806 }
6807 }
6808
6809 if self.right_dock.read(cx).is_open() {
6810 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6811 context.set("right_dock", active_panel.panel_key());
6812 }
6813 }
6814
6815 if self.bottom_dock.read(cx).is_open() {
6816 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6817 context.set("bottom_dock", active_panel.panel_key());
6818 }
6819 }
6820
6821 context
6822 }
6823
6824 /// Multiworkspace uses this to add workspace action handling to itself
6825 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6826 self.add_workspace_actions_listeners(div, window, cx)
6827 .on_action(cx.listener(
6828 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6829 for action in &action_sequence.0 {
6830 window.dispatch_action(action.boxed_clone(), cx);
6831 }
6832 },
6833 ))
6834 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6835 .on_action(cx.listener(Self::close_all_items_and_panes))
6836 .on_action(cx.listener(Self::close_item_in_all_panes))
6837 .on_action(cx.listener(Self::save_all))
6838 .on_action(cx.listener(Self::send_keystrokes))
6839 .on_action(cx.listener(Self::add_folder_to_project))
6840 .on_action(cx.listener(Self::follow_next_collaborator))
6841 .on_action(cx.listener(Self::activate_pane_at_index))
6842 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6843 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6844 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6845 .on_action(cx.listener(Self::toggle_theme_mode))
6846 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6847 let pane = workspace.active_pane().clone();
6848 workspace.unfollow_in_pane(&pane, window, cx);
6849 }))
6850 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6851 workspace
6852 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6853 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6854 }))
6855 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6856 workspace
6857 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6858 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6859 }))
6860 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6861 workspace
6862 .save_active_item(SaveIntent::SaveAs, window, cx)
6863 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6864 }))
6865 .on_action(
6866 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6867 workspace.activate_previous_pane(window, cx)
6868 }),
6869 )
6870 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6871 workspace.activate_next_pane(window, cx)
6872 }))
6873 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6874 workspace.activate_last_pane(window, cx)
6875 }))
6876 .on_action(
6877 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6878 workspace.activate_next_window(cx)
6879 }),
6880 )
6881 .on_action(
6882 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6883 workspace.activate_previous_window(cx)
6884 }),
6885 )
6886 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6887 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6888 }))
6889 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6890 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6891 }))
6892 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6893 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6894 }))
6895 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6896 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6897 }))
6898 .on_action(cx.listener(
6899 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6900 workspace.move_item_to_pane_in_direction(action, window, cx)
6901 },
6902 ))
6903 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6904 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6905 }))
6906 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6907 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6908 }))
6909 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6910 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6911 }))
6912 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6913 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6914 }))
6915 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6916 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6917 SplitDirection::Down,
6918 SplitDirection::Up,
6919 SplitDirection::Right,
6920 SplitDirection::Left,
6921 ];
6922 for dir in DIRECTION_PRIORITY {
6923 if workspace.find_pane_in_direction(dir, cx).is_some() {
6924 workspace.swap_pane_in_direction(dir, cx);
6925 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6926 break;
6927 }
6928 }
6929 }))
6930 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6931 workspace.move_pane_to_border(SplitDirection::Left, cx)
6932 }))
6933 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6934 workspace.move_pane_to_border(SplitDirection::Right, cx)
6935 }))
6936 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6937 workspace.move_pane_to_border(SplitDirection::Up, cx)
6938 }))
6939 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6940 workspace.move_pane_to_border(SplitDirection::Down, cx)
6941 }))
6942 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6943 this.toggle_dock(DockPosition::Left, window, cx);
6944 }))
6945 .on_action(cx.listener(
6946 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6947 workspace.toggle_dock(DockPosition::Right, window, cx);
6948 },
6949 ))
6950 .on_action(cx.listener(
6951 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6952 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6953 },
6954 ))
6955 .on_action(cx.listener(
6956 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6957 if !workspace.close_active_dock(window, cx) {
6958 cx.propagate();
6959 }
6960 },
6961 ))
6962 .on_action(
6963 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6964 workspace.close_all_docks(window, cx);
6965 }),
6966 )
6967 .on_action(cx.listener(Self::toggle_all_docks))
6968 .on_action(cx.listener(
6969 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6970 workspace.clear_all_notifications(cx);
6971 },
6972 ))
6973 .on_action(cx.listener(
6974 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6975 workspace.clear_navigation_history(window, cx);
6976 },
6977 ))
6978 .on_action(cx.listener(
6979 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6980 if let Some((notification_id, _)) = workspace.notifications.pop() {
6981 workspace.suppress_notification(¬ification_id, cx);
6982 }
6983 },
6984 ))
6985 .on_action(cx.listener(
6986 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6987 workspace.show_worktree_trust_security_modal(true, window, cx);
6988 },
6989 ))
6990 .on_action(
6991 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6992 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6993 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6994 trusted_worktrees.clear_trusted_paths()
6995 });
6996 let db = WorkspaceDb::global(cx);
6997 cx.spawn(async move |_, cx| {
6998 if db.clear_trusted_worktrees().await.log_err().is_some() {
6999 cx.update(|cx| reload(cx));
7000 }
7001 })
7002 .detach();
7003 }
7004 }),
7005 )
7006 .on_action(cx.listener(
7007 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
7008 workspace.reopen_closed_item(window, cx).detach();
7009 },
7010 ))
7011 .on_action(cx.listener(
7012 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
7013 for dock in workspace.all_docks() {
7014 if dock.focus_handle(cx).contains_focused(window, cx) {
7015 let panel = dock.read(cx).active_panel().cloned();
7016 if let Some(panel) = panel {
7017 dock.update(cx, |dock, cx| {
7018 dock.set_panel_size_state(
7019 panel.as_ref(),
7020 dock::PanelSizeState::default(),
7021 cx,
7022 );
7023 });
7024 }
7025 return;
7026 }
7027 }
7028 },
7029 ))
7030 .on_action(cx.listener(
7031 |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
7032 for dock in workspace.all_docks() {
7033 let panel = dock.read(cx).visible_panel().cloned();
7034 if let Some(panel) = panel {
7035 dock.update(cx, |dock, cx| {
7036 dock.set_panel_size_state(
7037 panel.as_ref(),
7038 dock::PanelSizeState::default(),
7039 cx,
7040 );
7041 });
7042 }
7043 }
7044 },
7045 ))
7046 .on_action(cx.listener(
7047 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
7048 adjust_active_dock_size_by_px(
7049 px_with_ui_font_fallback(act.px, cx),
7050 workspace,
7051 window,
7052 cx,
7053 );
7054 },
7055 ))
7056 .on_action(cx.listener(
7057 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
7058 adjust_active_dock_size_by_px(
7059 px_with_ui_font_fallback(act.px, cx) * -1.,
7060 workspace,
7061 window,
7062 cx,
7063 );
7064 },
7065 ))
7066 .on_action(cx.listener(
7067 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
7068 adjust_open_docks_size_by_px(
7069 px_with_ui_font_fallback(act.px, cx),
7070 workspace,
7071 window,
7072 cx,
7073 );
7074 },
7075 ))
7076 .on_action(cx.listener(
7077 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
7078 adjust_open_docks_size_by_px(
7079 px_with_ui_font_fallback(act.px, cx) * -1.,
7080 workspace,
7081 window,
7082 cx,
7083 );
7084 },
7085 ))
7086 .on_action(cx.listener(Workspace::toggle_centered_layout))
7087 .on_action(cx.listener(
7088 |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
7089 if let Some(active_dock) = workspace.active_dock(window, cx) {
7090 let dock = active_dock.read(cx);
7091 if let Some(active_panel) = dock.active_panel() {
7092 if active_panel.pane(cx).is_none() {
7093 let mut recent_pane: Option<Entity<Pane>> = None;
7094 let mut recent_timestamp = 0;
7095 for pane_handle in workspace.panes() {
7096 let pane = pane_handle.read(cx);
7097 for entry in pane.activation_history() {
7098 if entry.timestamp > recent_timestamp {
7099 recent_timestamp = entry.timestamp;
7100 recent_pane = Some(pane_handle.clone());
7101 }
7102 }
7103 }
7104
7105 if let Some(pane) = recent_pane {
7106 let wrap_around = action.wrap_around;
7107 pane.update(cx, |pane, cx| {
7108 let current_index = pane.active_item_index();
7109 let items_len = pane.items_len();
7110 if items_len > 0 {
7111 let next_index = if current_index + 1 < items_len {
7112 current_index + 1
7113 } else if wrap_around {
7114 0
7115 } else {
7116 return;
7117 };
7118 pane.activate_item(
7119 next_index, false, false, window, cx,
7120 );
7121 }
7122 });
7123 return;
7124 }
7125 }
7126 }
7127 }
7128 cx.propagate();
7129 },
7130 ))
7131 .on_action(cx.listener(
7132 |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
7133 if let Some(active_dock) = workspace.active_dock(window, cx) {
7134 let dock = active_dock.read(cx);
7135 if let Some(active_panel) = dock.active_panel() {
7136 if active_panel.pane(cx).is_none() {
7137 let mut recent_pane: Option<Entity<Pane>> = None;
7138 let mut recent_timestamp = 0;
7139 for pane_handle in workspace.panes() {
7140 let pane = pane_handle.read(cx);
7141 for entry in pane.activation_history() {
7142 if entry.timestamp > recent_timestamp {
7143 recent_timestamp = entry.timestamp;
7144 recent_pane = Some(pane_handle.clone());
7145 }
7146 }
7147 }
7148
7149 if let Some(pane) = recent_pane {
7150 let wrap_around = action.wrap_around;
7151 pane.update(cx, |pane, cx| {
7152 let current_index = pane.active_item_index();
7153 let items_len = pane.items_len();
7154 if items_len > 0 {
7155 let prev_index = if current_index > 0 {
7156 current_index - 1
7157 } else if wrap_around {
7158 items_len.saturating_sub(1)
7159 } else {
7160 return;
7161 };
7162 pane.activate_item(
7163 prev_index, false, false, window, cx,
7164 );
7165 }
7166 });
7167 return;
7168 }
7169 }
7170 }
7171 }
7172 cx.propagate();
7173 },
7174 ))
7175 .on_action(cx.listener(
7176 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
7177 if let Some(active_dock) = workspace.active_dock(window, cx) {
7178 let dock = active_dock.read(cx);
7179 if let Some(active_panel) = dock.active_panel() {
7180 if active_panel.pane(cx).is_none() {
7181 let active_pane = workspace.active_pane().clone();
7182 active_pane.update(cx, |pane, cx| {
7183 pane.close_active_item(action, window, cx)
7184 .detach_and_log_err(cx);
7185 });
7186 return;
7187 }
7188 }
7189 }
7190 cx.propagate();
7191 },
7192 ))
7193 .on_action(
7194 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
7195 let pane = workspace.active_pane().clone();
7196 if let Some(item) = pane.read(cx).active_item() {
7197 item.toggle_read_only(window, cx);
7198 }
7199 }),
7200 )
7201 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
7202 workspace.focus_center_pane(window, cx);
7203 }))
7204 .on_action(cx.listener(Workspace::cancel))
7205 }
7206
7207 #[cfg(any(test, feature = "test-support"))]
7208 pub fn set_random_database_id(&mut self) {
7209 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
7210 }
7211
7212 #[cfg(any(test, feature = "test-support"))]
7213 pub(crate) fn test_new(
7214 project: Entity<Project>,
7215 window: &mut Window,
7216 cx: &mut Context<Self>,
7217 ) -> Self {
7218 use node_runtime::NodeRuntime;
7219 use session::Session;
7220
7221 let client = project.read(cx).client();
7222 let user_store = project.read(cx).user_store();
7223 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
7224 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
7225 window.activate_window();
7226 let app_state = Arc::new(AppState {
7227 languages: project.read(cx).languages().clone(),
7228 workspace_store,
7229 client,
7230 user_store,
7231 fs: project.read(cx).fs().clone(),
7232 build_window_options: |_, _| Default::default(),
7233 node_runtime: NodeRuntime::unavailable(),
7234 session,
7235 });
7236 let workspace = Self::new(Default::default(), project, app_state, window, cx);
7237 workspace
7238 .active_pane
7239 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
7240 workspace
7241 }
7242
7243 pub fn register_action<A: Action>(
7244 &mut self,
7245 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
7246 ) -> &mut Self {
7247 let callback = Arc::new(callback);
7248
7249 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
7250 let callback = callback.clone();
7251 div.on_action(cx.listener(move |workspace, event, window, cx| {
7252 (callback)(workspace, event, window, cx)
7253 }))
7254 }));
7255 self
7256 }
7257 pub fn register_action_renderer(
7258 &mut self,
7259 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
7260 ) -> &mut Self {
7261 self.workspace_actions.push(Box::new(callback));
7262 self
7263 }
7264
7265 fn add_workspace_actions_listeners(
7266 &self,
7267 mut div: Div,
7268 window: &mut Window,
7269 cx: &mut Context<Self>,
7270 ) -> Div {
7271 for action in self.workspace_actions.iter() {
7272 div = (action)(div, self, window, cx)
7273 }
7274 div
7275 }
7276
7277 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7278 self.modal_layer.read(cx).has_active_modal()
7279 }
7280
7281 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7282 self.modal_layer
7283 .read(cx)
7284 .is_active_modal_command_palette(cx)
7285 }
7286
7287 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7288 self.modal_layer.read(cx).active_modal()
7289 }
7290
7291 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7292 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7293 /// If no modal is active, the new modal will be shown.
7294 ///
7295 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7296 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7297 /// will not be shown.
7298 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7299 where
7300 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7301 {
7302 self.modal_layer.update(cx, |modal_layer, cx| {
7303 modal_layer.toggle_modal(window, cx, build)
7304 })
7305 }
7306
7307 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7308 self.modal_layer
7309 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7310 }
7311
7312 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7313 self.toast_layer
7314 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7315 }
7316
7317 pub fn toggle_centered_layout(
7318 &mut self,
7319 _: &ToggleCenteredLayout,
7320 _: &mut Window,
7321 cx: &mut Context<Self>,
7322 ) {
7323 self.centered_layout = !self.centered_layout;
7324 if let Some(database_id) = self.database_id() {
7325 let db = WorkspaceDb::global(cx);
7326 let centered_layout = self.centered_layout;
7327 cx.background_spawn(async move {
7328 db.set_centered_layout(database_id, centered_layout).await
7329 })
7330 .detach_and_log_err(cx);
7331 }
7332 cx.notify();
7333 }
7334
7335 fn adjust_padding(padding: Option<f32>) -> f32 {
7336 padding
7337 .unwrap_or(CenteredPaddingSettings::default().0)
7338 .clamp(
7339 CenteredPaddingSettings::MIN_PADDING,
7340 CenteredPaddingSettings::MAX_PADDING,
7341 )
7342 }
7343
7344 fn render_dock(
7345 &self,
7346 position: DockPosition,
7347 dock: &Entity<Dock>,
7348 window: &mut Window,
7349 cx: &mut App,
7350 ) -> Option<Div> {
7351 if self.zoomed_position == Some(position) {
7352 return None;
7353 }
7354
7355 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7356 let pane = panel.pane(cx)?;
7357 let follower_states = &self.follower_states;
7358 leader_border_for_pane(follower_states, &pane, window, cx)
7359 });
7360
7361 let mut container = div()
7362 .flex()
7363 .overflow_hidden()
7364 .flex_none()
7365 .child(dock.clone())
7366 .children(leader_border);
7367
7368 // Apply sizing only when the dock is open. When closed the dock is still
7369 // included in the element tree so its focus handle remains mounted — without
7370 // this, toggle_panel_focus cannot focus the panel when the dock is closed.
7371 let dock = dock.read(cx);
7372 if let Some(panel) = dock.visible_panel() {
7373 let size_state = dock.stored_panel_size_state(panel.as_ref());
7374 if position.axis() == Axis::Horizontal {
7375 let use_flexible = panel.has_flexible_size(window, cx);
7376 let flex_grow = if use_flexible {
7377 size_state
7378 .and_then(|state| state.flex)
7379 .or_else(|| self.default_dock_flex(position))
7380 } else {
7381 None
7382 };
7383 if let Some(grow) = flex_grow {
7384 let grow = grow.max(0.001);
7385 let style = container.style();
7386 style.flex_grow = Some(grow);
7387 style.flex_shrink = Some(1.0);
7388 style.flex_basis = Some(relative(0.).into());
7389 } else {
7390 let size = size_state
7391 .and_then(|state| state.size)
7392 .unwrap_or_else(|| panel.default_size(window, cx));
7393 container = container.w(size);
7394 }
7395 } else {
7396 let size = size_state
7397 .and_then(|state| state.size)
7398 .unwrap_or_else(|| panel.default_size(window, cx));
7399 container = container.h(size);
7400 }
7401 }
7402
7403 Some(container)
7404 }
7405
7406 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7407 window
7408 .root::<MultiWorkspace>()
7409 .flatten()
7410 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7411 }
7412
7413 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7414 self.zoomed.as_ref()
7415 }
7416
7417 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7418 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7419 return;
7420 };
7421 let windows = cx.windows();
7422 let next_window =
7423 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7424 || {
7425 windows
7426 .iter()
7427 .cycle()
7428 .skip_while(|window| window.window_id() != current_window_id)
7429 .nth(1)
7430 },
7431 );
7432
7433 if let Some(window) = next_window {
7434 window
7435 .update(cx, |_, window, _| window.activate_window())
7436 .ok();
7437 }
7438 }
7439
7440 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7441 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7442 return;
7443 };
7444 let windows = cx.windows();
7445 let prev_window =
7446 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7447 || {
7448 windows
7449 .iter()
7450 .rev()
7451 .cycle()
7452 .skip_while(|window| window.window_id() != current_window_id)
7453 .nth(1)
7454 },
7455 );
7456
7457 if let Some(window) = prev_window {
7458 window
7459 .update(cx, |_, window, _| window.activate_window())
7460 .ok();
7461 }
7462 }
7463
7464 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7465 if cx.stop_active_drag(window) {
7466 } else if let Some((notification_id, _)) = self.notifications.pop() {
7467 dismiss_app_notification(¬ification_id, cx);
7468 } else {
7469 cx.propagate();
7470 }
7471 }
7472
7473 fn resize_dock(
7474 &mut self,
7475 dock_pos: DockPosition,
7476 new_size: Pixels,
7477 window: &mut Window,
7478 cx: &mut Context<Self>,
7479 ) {
7480 match dock_pos {
7481 DockPosition::Left => self.resize_left_dock(new_size, window, cx),
7482 DockPosition::Right => self.resize_right_dock(new_size, window, cx),
7483 DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
7484 }
7485 }
7486
7487 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7488 let workspace_width = self.bounds.size.width;
7489 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7490
7491 self.right_dock.read_with(cx, |right_dock, cx| {
7492 let right_dock_size = right_dock
7493 .stored_active_panel_size(window, cx)
7494 .unwrap_or(Pixels::ZERO);
7495 if right_dock_size + size > workspace_width {
7496 size = workspace_width - right_dock_size
7497 }
7498 });
7499
7500 let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
7501 self.left_dock.update(cx, |left_dock, cx| {
7502 if WorkspaceSettings::get_global(cx)
7503 .resize_all_panels_in_dock
7504 .contains(&DockPosition::Left)
7505 {
7506 left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7507 } else {
7508 left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7509 }
7510 });
7511 }
7512
7513 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7514 let workspace_width = self.bounds.size.width;
7515 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7516 self.left_dock.read_with(cx, |left_dock, cx| {
7517 let left_dock_size = left_dock
7518 .stored_active_panel_size(window, cx)
7519 .unwrap_or(Pixels::ZERO);
7520 if left_dock_size + size > workspace_width {
7521 size = workspace_width - left_dock_size
7522 }
7523 });
7524 let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
7525 self.right_dock.update(cx, |right_dock, cx| {
7526 if WorkspaceSettings::get_global(cx)
7527 .resize_all_panels_in_dock
7528 .contains(&DockPosition::Right)
7529 {
7530 right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7531 } else {
7532 right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7533 }
7534 });
7535 }
7536
7537 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7538 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7539 self.bottom_dock.update(cx, |bottom_dock, cx| {
7540 if WorkspaceSettings::get_global(cx)
7541 .resize_all_panels_in_dock
7542 .contains(&DockPosition::Bottom)
7543 {
7544 bottom_dock.resize_all_panels(Some(size), None, window, cx);
7545 } else {
7546 bottom_dock.resize_active_panel(Some(size), None, window, cx);
7547 }
7548 });
7549 }
7550
7551 fn toggle_edit_predictions_all_files(
7552 &mut self,
7553 _: &ToggleEditPrediction,
7554 _window: &mut Window,
7555 cx: &mut Context<Self>,
7556 ) {
7557 let fs = self.project().read(cx).fs().clone();
7558 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7559 update_settings_file(fs, cx, move |file, _| {
7560 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7561 });
7562 }
7563
7564 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7565 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7566 let next_mode = match current_mode {
7567 Some(theme_settings::ThemeAppearanceMode::Light) => {
7568 theme_settings::ThemeAppearanceMode::Dark
7569 }
7570 Some(theme_settings::ThemeAppearanceMode::Dark) => {
7571 theme_settings::ThemeAppearanceMode::Light
7572 }
7573 Some(theme_settings::ThemeAppearanceMode::System) | None => {
7574 match cx.theme().appearance() {
7575 theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
7576 theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
7577 }
7578 }
7579 };
7580
7581 let fs = self.project().read(cx).fs().clone();
7582 settings::update_settings_file(fs, cx, move |settings, _cx| {
7583 theme_settings::set_mode(settings, next_mode);
7584 });
7585 }
7586
7587 pub fn show_worktree_trust_security_modal(
7588 &mut self,
7589 toggle: bool,
7590 window: &mut Window,
7591 cx: &mut Context<Self>,
7592 ) {
7593 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7594 if toggle {
7595 security_modal.update(cx, |security_modal, cx| {
7596 security_modal.dismiss(cx);
7597 })
7598 } else {
7599 security_modal.update(cx, |security_modal, cx| {
7600 security_modal.refresh_restricted_paths(cx);
7601 });
7602 }
7603 } else {
7604 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7605 .map(|trusted_worktrees| {
7606 trusted_worktrees
7607 .read(cx)
7608 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7609 })
7610 .unwrap_or(false);
7611 if has_restricted_worktrees {
7612 let project = self.project().read(cx);
7613 let remote_host = project
7614 .remote_connection_options(cx)
7615 .map(RemoteHostLocation::from);
7616 let worktree_store = project.worktree_store().downgrade();
7617 self.toggle_modal(window, cx, |_, cx| {
7618 SecurityModal::new(worktree_store, remote_host, cx)
7619 });
7620 }
7621 }
7622 }
7623}
7624
7625pub trait AnyActiveCall {
7626 fn entity(&self) -> AnyEntity;
7627 fn is_in_room(&self, _: &App) -> bool;
7628 fn room_id(&self, _: &App) -> Option<u64>;
7629 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7630 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7631 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7632 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7633 fn is_sharing_project(&self, _: &App) -> bool;
7634 fn has_remote_participants(&self, _: &App) -> bool;
7635 fn local_participant_is_guest(&self, _: &App) -> bool;
7636 fn client(&self, _: &App) -> Arc<Client>;
7637 fn share_on_join(&self, _: &App) -> bool;
7638 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7639 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7640 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7641 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7642 fn join_project(
7643 &self,
7644 _: u64,
7645 _: Arc<LanguageRegistry>,
7646 _: Arc<dyn Fs>,
7647 _: &mut App,
7648 ) -> Task<Result<Entity<Project>>>;
7649 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7650 fn subscribe(
7651 &self,
7652 _: &mut Window,
7653 _: &mut Context<Workspace>,
7654 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7655 ) -> Subscription;
7656 fn create_shared_screen(
7657 &self,
7658 _: PeerId,
7659 _: &Entity<Pane>,
7660 _: &mut Window,
7661 _: &mut App,
7662 ) -> Option<Entity<SharedScreen>>;
7663}
7664
7665#[derive(Clone)]
7666pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7667impl Global for GlobalAnyActiveCall {}
7668
7669impl GlobalAnyActiveCall {
7670 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7671 cx.try_global()
7672 }
7673
7674 pub(crate) fn global(cx: &App) -> &Self {
7675 cx.global()
7676 }
7677}
7678
7679pub fn merge_conflict_notification_id() -> NotificationId {
7680 struct MergeConflictNotification;
7681 NotificationId::unique::<MergeConflictNotification>()
7682}
7683
7684/// Workspace-local view of a remote participant's location.
7685#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7686pub enum ParticipantLocation {
7687 SharedProject { project_id: u64 },
7688 UnsharedProject,
7689 External,
7690}
7691
7692impl ParticipantLocation {
7693 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7694 match location
7695 .and_then(|l| l.variant)
7696 .context("participant location was not provided")?
7697 {
7698 proto::participant_location::Variant::SharedProject(project) => {
7699 Ok(Self::SharedProject {
7700 project_id: project.id,
7701 })
7702 }
7703 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7704 proto::participant_location::Variant::External(_) => Ok(Self::External),
7705 }
7706 }
7707}
7708/// Workspace-local view of a remote collaborator's state.
7709/// This is the subset of `call::RemoteParticipant` that workspace needs.
7710#[derive(Clone)]
7711pub struct RemoteCollaborator {
7712 pub user: Arc<User>,
7713 pub peer_id: PeerId,
7714 pub location: ParticipantLocation,
7715 pub participant_index: ParticipantIndex,
7716}
7717
7718pub enum ActiveCallEvent {
7719 ParticipantLocationChanged { participant_id: PeerId },
7720 RemoteVideoTracksChanged { participant_id: PeerId },
7721}
7722
7723fn leader_border_for_pane(
7724 follower_states: &HashMap<CollaboratorId, FollowerState>,
7725 pane: &Entity<Pane>,
7726 _: &Window,
7727 cx: &App,
7728) -> Option<Div> {
7729 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7730 if state.pane() == pane {
7731 Some((*leader_id, state))
7732 } else {
7733 None
7734 }
7735 })?;
7736
7737 let mut leader_color = match leader_id {
7738 CollaboratorId::PeerId(leader_peer_id) => {
7739 let leader = GlobalAnyActiveCall::try_global(cx)?
7740 .0
7741 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7742
7743 cx.theme()
7744 .players()
7745 .color_for_participant(leader.participant_index.0)
7746 .cursor
7747 }
7748 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7749 };
7750 leader_color.fade_out(0.3);
7751 Some(
7752 div()
7753 .absolute()
7754 .size_full()
7755 .left_0()
7756 .top_0()
7757 .border_2()
7758 .border_color(leader_color),
7759 )
7760}
7761
7762fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7763 ZED_WINDOW_POSITION
7764 .zip(*ZED_WINDOW_SIZE)
7765 .map(|(position, size)| Bounds {
7766 origin: position,
7767 size,
7768 })
7769}
7770
7771fn open_items(
7772 serialized_workspace: Option<SerializedWorkspace>,
7773 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7774 window: &mut Window,
7775 cx: &mut Context<Workspace>,
7776) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7777 let restored_items = serialized_workspace.map(|serialized_workspace| {
7778 Workspace::load_workspace(
7779 serialized_workspace,
7780 project_paths_to_open
7781 .iter()
7782 .map(|(_, project_path)| project_path)
7783 .cloned()
7784 .collect(),
7785 window,
7786 cx,
7787 )
7788 });
7789
7790 cx.spawn_in(window, async move |workspace, cx| {
7791 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7792
7793 if let Some(restored_items) = restored_items {
7794 let restored_items = restored_items.await?;
7795
7796 let restored_project_paths = restored_items
7797 .iter()
7798 .filter_map(|item| {
7799 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7800 .ok()
7801 .flatten()
7802 })
7803 .collect::<HashSet<_>>();
7804
7805 for restored_item in restored_items {
7806 opened_items.push(restored_item.map(Ok));
7807 }
7808
7809 project_paths_to_open
7810 .iter_mut()
7811 .for_each(|(_, project_path)| {
7812 if let Some(project_path_to_open) = project_path
7813 && restored_project_paths.contains(project_path_to_open)
7814 {
7815 *project_path = None;
7816 }
7817 });
7818 } else {
7819 for _ in 0..project_paths_to_open.len() {
7820 opened_items.push(None);
7821 }
7822 }
7823 assert!(opened_items.len() == project_paths_to_open.len());
7824
7825 let tasks =
7826 project_paths_to_open
7827 .into_iter()
7828 .enumerate()
7829 .map(|(ix, (abs_path, project_path))| {
7830 let workspace = workspace.clone();
7831 cx.spawn(async move |cx| {
7832 let file_project_path = project_path?;
7833 let abs_path_task = workspace.update(cx, |workspace, cx| {
7834 workspace.project().update(cx, |project, cx| {
7835 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7836 })
7837 });
7838
7839 // We only want to open file paths here. If one of the items
7840 // here is a directory, it was already opened further above
7841 // with a `find_or_create_worktree`.
7842 if let Ok(task) = abs_path_task
7843 && task.await.is_none_or(|p| p.is_file())
7844 {
7845 return Some((
7846 ix,
7847 workspace
7848 .update_in(cx, |workspace, window, cx| {
7849 workspace.open_path(
7850 file_project_path,
7851 None,
7852 true,
7853 window,
7854 cx,
7855 )
7856 })
7857 .log_err()?
7858 .await,
7859 ));
7860 }
7861 None
7862 })
7863 });
7864
7865 let tasks = tasks.collect::<Vec<_>>();
7866
7867 let tasks = futures::future::join_all(tasks);
7868 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7869 opened_items[ix] = Some(path_open_result);
7870 }
7871
7872 Ok(opened_items)
7873 })
7874}
7875
7876#[derive(Clone)]
7877enum ActivateInDirectionTarget {
7878 Pane(Entity<Pane>),
7879 Dock(Entity<Dock>),
7880 Sidebar(FocusHandle),
7881}
7882
7883fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7884 window
7885 .update(cx, |multi_workspace, _, cx| {
7886 let workspace = multi_workspace.workspace().clone();
7887 workspace.update(cx, |workspace, cx| {
7888 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7889 struct DatabaseFailedNotification;
7890
7891 workspace.show_notification(
7892 NotificationId::unique::<DatabaseFailedNotification>(),
7893 cx,
7894 |cx| {
7895 cx.new(|cx| {
7896 MessageNotification::new("Failed to load the database file.", cx)
7897 .primary_message("File an Issue")
7898 .primary_icon(IconName::Plus)
7899 .primary_on_click(|window, cx| {
7900 window.dispatch_action(Box::new(FileBugReport), cx)
7901 })
7902 })
7903 },
7904 );
7905 }
7906 });
7907 })
7908 .log_err();
7909}
7910
7911fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7912 if val == 0 {
7913 ThemeSettings::get_global(cx).ui_font_size(cx)
7914 } else {
7915 px(val as f32)
7916 }
7917}
7918
7919fn adjust_active_dock_size_by_px(
7920 px: Pixels,
7921 workspace: &mut Workspace,
7922 window: &mut Window,
7923 cx: &mut Context<Workspace>,
7924) {
7925 let Some(active_dock) = workspace
7926 .all_docks()
7927 .into_iter()
7928 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7929 else {
7930 return;
7931 };
7932 let dock = active_dock.read(cx);
7933 let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
7934 return;
7935 };
7936 workspace.resize_dock(dock.position(), panel_size + px, window, cx);
7937}
7938
7939fn adjust_open_docks_size_by_px(
7940 px: Pixels,
7941 workspace: &mut Workspace,
7942 window: &mut Window,
7943 cx: &mut Context<Workspace>,
7944) {
7945 let docks = workspace
7946 .all_docks()
7947 .into_iter()
7948 .filter_map(|dock_entity| {
7949 let dock = dock_entity.read(cx);
7950 if dock.is_open() {
7951 let dock_pos = dock.position();
7952 let panel_size = workspace.dock_size(&dock, window, cx)?;
7953 Some((dock_pos, panel_size + px))
7954 } else {
7955 None
7956 }
7957 })
7958 .collect::<Vec<_>>();
7959
7960 for (position, new_size) in docks {
7961 workspace.resize_dock(position, new_size, window, cx);
7962 }
7963}
7964
7965impl Focusable for Workspace {
7966 fn focus_handle(&self, cx: &App) -> FocusHandle {
7967 self.active_pane.focus_handle(cx)
7968 }
7969}
7970
7971#[derive(Clone)]
7972struct DraggedDock(DockPosition);
7973
7974impl Render for DraggedDock {
7975 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7976 gpui::Empty
7977 }
7978}
7979
7980impl Render for Workspace {
7981 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7982 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7983 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7984 log::info!("Rendered first frame");
7985 }
7986
7987 let centered_layout = self.centered_layout
7988 && self.center.panes().len() == 1
7989 && self.active_item(cx).is_some();
7990 let render_padding = |size| {
7991 (size > 0.0).then(|| {
7992 div()
7993 .h_full()
7994 .w(relative(size))
7995 .bg(cx.theme().colors().editor_background)
7996 .border_color(cx.theme().colors().pane_group_border)
7997 })
7998 };
7999 let paddings = if centered_layout {
8000 let settings = WorkspaceSettings::get_global(cx).centered_layout;
8001 (
8002 render_padding(Self::adjust_padding(
8003 settings.left_padding.map(|padding| padding.0),
8004 )),
8005 render_padding(Self::adjust_padding(
8006 settings.right_padding.map(|padding| padding.0),
8007 )),
8008 )
8009 } else {
8010 (None, None)
8011 };
8012 let ui_font = theme_settings::setup_ui_font(window, cx);
8013
8014 let theme = cx.theme().clone();
8015 let colors = theme.colors();
8016 let notification_entities = self
8017 .notifications
8018 .iter()
8019 .map(|(_, notification)| notification.entity_id())
8020 .collect::<Vec<_>>();
8021 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
8022
8023 div()
8024 .relative()
8025 .size_full()
8026 .flex()
8027 .flex_col()
8028 .font(ui_font)
8029 .gap_0()
8030 .justify_start()
8031 .items_start()
8032 .text_color(colors.text)
8033 .overflow_hidden()
8034 .children(self.titlebar_item.clone())
8035 .on_modifiers_changed(move |_, _, cx| {
8036 for &id in ¬ification_entities {
8037 cx.notify(id);
8038 }
8039 })
8040 .child(
8041 div()
8042 .size_full()
8043 .relative()
8044 .flex_1()
8045 .flex()
8046 .flex_col()
8047 .child(
8048 div()
8049 .id("workspace")
8050 .bg(colors.background)
8051 .relative()
8052 .flex_1()
8053 .w_full()
8054 .flex()
8055 .flex_col()
8056 .overflow_hidden()
8057 .border_t_1()
8058 .border_b_1()
8059 .border_color(colors.border)
8060 .child({
8061 let this = cx.entity();
8062 canvas(
8063 move |bounds, window, cx| {
8064 this.update(cx, |this, cx| {
8065 let bounds_changed = this.bounds != bounds;
8066 this.bounds = bounds;
8067
8068 if bounds_changed {
8069 this.left_dock.update(cx, |dock, cx| {
8070 dock.clamp_panel_size(
8071 bounds.size.width,
8072 window,
8073 cx,
8074 )
8075 });
8076
8077 this.right_dock.update(cx, |dock, cx| {
8078 dock.clamp_panel_size(
8079 bounds.size.width,
8080 window,
8081 cx,
8082 )
8083 });
8084
8085 this.bottom_dock.update(cx, |dock, cx| {
8086 dock.clamp_panel_size(
8087 bounds.size.height,
8088 window,
8089 cx,
8090 )
8091 });
8092 }
8093 })
8094 },
8095 |_, _, _, _| {},
8096 )
8097 .absolute()
8098 .size_full()
8099 })
8100 .when(self.zoomed.is_none(), |this| {
8101 this.on_drag_move(cx.listener(
8102 move |workspace,
8103 e: &DragMoveEvent<DraggedDock>,
8104 window,
8105 cx| {
8106 if workspace.previous_dock_drag_coordinates
8107 != Some(e.event.position)
8108 {
8109 workspace.previous_dock_drag_coordinates =
8110 Some(e.event.position);
8111
8112 match e.drag(cx).0 {
8113 DockPosition::Left => {
8114 workspace.resize_left_dock(
8115 e.event.position.x
8116 - workspace.bounds.left(),
8117 window,
8118 cx,
8119 );
8120 }
8121 DockPosition::Right => {
8122 workspace.resize_right_dock(
8123 workspace.bounds.right()
8124 - e.event.position.x,
8125 window,
8126 cx,
8127 );
8128 }
8129 DockPosition::Bottom => {
8130 workspace.resize_bottom_dock(
8131 workspace.bounds.bottom()
8132 - e.event.position.y,
8133 window,
8134 cx,
8135 );
8136 }
8137 };
8138 workspace.serialize_workspace(window, cx);
8139 }
8140 },
8141 ))
8142
8143 })
8144 .child({
8145 match bottom_dock_layout {
8146 BottomDockLayout::Full => div()
8147 .flex()
8148 .flex_col()
8149 .h_full()
8150 .child(
8151 div()
8152 .flex()
8153 .flex_row()
8154 .flex_1()
8155 .overflow_hidden()
8156 .children(self.render_dock(
8157 DockPosition::Left,
8158 &self.left_dock,
8159 window,
8160 cx,
8161 ))
8162
8163 .child(
8164 div()
8165 .flex()
8166 .flex_col()
8167 .flex_1()
8168 .overflow_hidden()
8169 .child(
8170 h_flex()
8171 .flex_1()
8172 .when_some(
8173 paddings.0,
8174 |this, p| {
8175 this.child(
8176 p.border_r_1(),
8177 )
8178 },
8179 )
8180 .child(self.center.render(
8181 self.zoomed.as_ref(),
8182 &PaneRenderContext {
8183 follower_states:
8184 &self.follower_states,
8185 active_call: self.active_call(),
8186 active_pane: &self.active_pane,
8187 app_state: &self.app_state,
8188 project: &self.project,
8189 workspace: &self.weak_self,
8190 },
8191 window,
8192 cx,
8193 ))
8194 .when_some(
8195 paddings.1,
8196 |this, p| {
8197 this.child(
8198 p.border_l_1(),
8199 )
8200 },
8201 ),
8202 ),
8203 )
8204
8205 .children(self.render_dock(
8206 DockPosition::Right,
8207 &self.right_dock,
8208 window,
8209 cx,
8210 )),
8211 )
8212 .child(div().w_full().children(self.render_dock(
8213 DockPosition::Bottom,
8214 &self.bottom_dock,
8215 window,
8216 cx
8217 ))),
8218
8219 BottomDockLayout::LeftAligned => div()
8220 .flex()
8221 .flex_row()
8222 .h_full()
8223 .child(
8224 div()
8225 .flex()
8226 .flex_col()
8227 .flex_1()
8228 .h_full()
8229 .child(
8230 div()
8231 .flex()
8232 .flex_row()
8233 .flex_1()
8234 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
8235
8236 .child(
8237 div()
8238 .flex()
8239 .flex_col()
8240 .flex_1()
8241 .overflow_hidden()
8242 .child(
8243 h_flex()
8244 .flex_1()
8245 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8246 .child(self.center.render(
8247 self.zoomed.as_ref(),
8248 &PaneRenderContext {
8249 follower_states:
8250 &self.follower_states,
8251 active_call: self.active_call(),
8252 active_pane: &self.active_pane,
8253 app_state: &self.app_state,
8254 project: &self.project,
8255 workspace: &self.weak_self,
8256 },
8257 window,
8258 cx,
8259 ))
8260 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8261 )
8262 )
8263
8264 )
8265 .child(
8266 div()
8267 .w_full()
8268 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8269 ),
8270 )
8271 .children(self.render_dock(
8272 DockPosition::Right,
8273 &self.right_dock,
8274 window,
8275 cx,
8276 )),
8277 BottomDockLayout::RightAligned => div()
8278 .flex()
8279 .flex_row()
8280 .h_full()
8281 .children(self.render_dock(
8282 DockPosition::Left,
8283 &self.left_dock,
8284 window,
8285 cx,
8286 ))
8287
8288 .child(
8289 div()
8290 .flex()
8291 .flex_col()
8292 .flex_1()
8293 .h_full()
8294 .child(
8295 div()
8296 .flex()
8297 .flex_row()
8298 .flex_1()
8299 .child(
8300 div()
8301 .flex()
8302 .flex_col()
8303 .flex_1()
8304 .overflow_hidden()
8305 .child(
8306 h_flex()
8307 .flex_1()
8308 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8309 .child(self.center.render(
8310 self.zoomed.as_ref(),
8311 &PaneRenderContext {
8312 follower_states:
8313 &self.follower_states,
8314 active_call: self.active_call(),
8315 active_pane: &self.active_pane,
8316 app_state: &self.app_state,
8317 project: &self.project,
8318 workspace: &self.weak_self,
8319 },
8320 window,
8321 cx,
8322 ))
8323 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8324 )
8325 )
8326
8327 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8328 )
8329 .child(
8330 div()
8331 .w_full()
8332 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8333 ),
8334 ),
8335 BottomDockLayout::Contained => div()
8336 .flex()
8337 .flex_row()
8338 .h_full()
8339 .children(self.render_dock(
8340 DockPosition::Left,
8341 &self.left_dock,
8342 window,
8343 cx,
8344 ))
8345
8346 .child(
8347 div()
8348 .flex()
8349 .flex_col()
8350 .flex_1()
8351 .overflow_hidden()
8352 .child(
8353 h_flex()
8354 .flex_1()
8355 .when_some(paddings.0, |this, p| {
8356 this.child(p.border_r_1())
8357 })
8358 .child(self.center.render(
8359 self.zoomed.as_ref(),
8360 &PaneRenderContext {
8361 follower_states:
8362 &self.follower_states,
8363 active_call: self.active_call(),
8364 active_pane: &self.active_pane,
8365 app_state: &self.app_state,
8366 project: &self.project,
8367 workspace: &self.weak_self,
8368 },
8369 window,
8370 cx,
8371 ))
8372 .when_some(paddings.1, |this, p| {
8373 this.child(p.border_l_1())
8374 }),
8375 )
8376 .children(self.render_dock(
8377 DockPosition::Bottom,
8378 &self.bottom_dock,
8379 window,
8380 cx,
8381 )),
8382 )
8383
8384 .children(self.render_dock(
8385 DockPosition::Right,
8386 &self.right_dock,
8387 window,
8388 cx,
8389 )),
8390 }
8391 })
8392 .children(self.zoomed.as_ref().and_then(|view| {
8393 let zoomed_view = view.upgrade()?;
8394 let div = div()
8395 .occlude()
8396 .absolute()
8397 .overflow_hidden()
8398 .border_color(colors.border)
8399 .bg(colors.background)
8400 .child(zoomed_view)
8401 .inset_0()
8402 .shadow_lg();
8403
8404 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8405 return Some(div);
8406 }
8407
8408 Some(match self.zoomed_position {
8409 Some(DockPosition::Left) => div.right_2().border_r_1(),
8410 Some(DockPosition::Right) => div.left_2().border_l_1(),
8411 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8412 None => {
8413 div.top_2().bottom_2().left_2().right_2().border_1()
8414 }
8415 })
8416 }))
8417 .children(self.render_notifications(window, cx)),
8418 )
8419 .when(self.status_bar_visible(cx), |parent| {
8420 parent.child(self.status_bar.clone())
8421 })
8422 .child(self.toast_layer.clone()),
8423 )
8424 }
8425}
8426
8427impl WorkspaceStore {
8428 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8429 Self {
8430 workspaces: Default::default(),
8431 _subscriptions: vec![
8432 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8433 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8434 ],
8435 client,
8436 }
8437 }
8438
8439 pub fn update_followers(
8440 &self,
8441 project_id: Option<u64>,
8442 update: proto::update_followers::Variant,
8443 cx: &App,
8444 ) -> Option<()> {
8445 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8446 let room_id = active_call.0.room_id(cx)?;
8447 self.client
8448 .send(proto::UpdateFollowers {
8449 room_id,
8450 project_id,
8451 variant: Some(update),
8452 })
8453 .log_err()
8454 }
8455
8456 pub async fn handle_follow(
8457 this: Entity<Self>,
8458 envelope: TypedEnvelope<proto::Follow>,
8459 mut cx: AsyncApp,
8460 ) -> Result<proto::FollowResponse> {
8461 this.update(&mut cx, |this, cx| {
8462 let follower = Follower {
8463 project_id: envelope.payload.project_id,
8464 peer_id: envelope.original_sender_id()?,
8465 };
8466
8467 let mut response = proto::FollowResponse::default();
8468
8469 this.workspaces.retain(|(window_handle, weak_workspace)| {
8470 let Some(workspace) = weak_workspace.upgrade() else {
8471 return false;
8472 };
8473 window_handle
8474 .update(cx, |_, window, cx| {
8475 workspace.update(cx, |workspace, cx| {
8476 let handler_response =
8477 workspace.handle_follow(follower.project_id, window, cx);
8478 if let Some(active_view) = handler_response.active_view
8479 && workspace.project.read(cx).remote_id() == follower.project_id
8480 {
8481 response.active_view = Some(active_view)
8482 }
8483 });
8484 })
8485 .is_ok()
8486 });
8487
8488 Ok(response)
8489 })
8490 }
8491
8492 async fn handle_update_followers(
8493 this: Entity<Self>,
8494 envelope: TypedEnvelope<proto::UpdateFollowers>,
8495 mut cx: AsyncApp,
8496 ) -> Result<()> {
8497 let leader_id = envelope.original_sender_id()?;
8498 let update = envelope.payload;
8499
8500 this.update(&mut cx, |this, cx| {
8501 this.workspaces.retain(|(window_handle, weak_workspace)| {
8502 let Some(workspace) = weak_workspace.upgrade() else {
8503 return false;
8504 };
8505 window_handle
8506 .update(cx, |_, window, cx| {
8507 workspace.update(cx, |workspace, cx| {
8508 let project_id = workspace.project.read(cx).remote_id();
8509 if update.project_id != project_id && update.project_id.is_some() {
8510 return;
8511 }
8512 workspace.handle_update_followers(
8513 leader_id,
8514 update.clone(),
8515 window,
8516 cx,
8517 );
8518 });
8519 })
8520 .is_ok()
8521 });
8522 Ok(())
8523 })
8524 }
8525
8526 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8527 self.workspaces.iter().map(|(_, weak)| weak)
8528 }
8529
8530 pub fn workspaces_with_windows(
8531 &self,
8532 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8533 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8534 }
8535}
8536
8537impl ViewId {
8538 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8539 Ok(Self {
8540 creator: message
8541 .creator
8542 .map(CollaboratorId::PeerId)
8543 .context("creator is missing")?,
8544 id: message.id,
8545 })
8546 }
8547
8548 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8549 if let CollaboratorId::PeerId(peer_id) = self.creator {
8550 Some(proto::ViewId {
8551 creator: Some(peer_id),
8552 id: self.id,
8553 })
8554 } else {
8555 None
8556 }
8557 }
8558}
8559
8560impl FollowerState {
8561 fn pane(&self) -> &Entity<Pane> {
8562 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8563 }
8564}
8565
8566pub trait WorkspaceHandle {
8567 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8568}
8569
8570impl WorkspaceHandle for Entity<Workspace> {
8571 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8572 self.read(cx)
8573 .worktrees(cx)
8574 .flat_map(|worktree| {
8575 let worktree_id = worktree.read(cx).id();
8576 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8577 worktree_id,
8578 path: f.path.clone(),
8579 })
8580 })
8581 .collect::<Vec<_>>()
8582 }
8583}
8584
8585pub async fn last_opened_workspace_location(
8586 db: &WorkspaceDb,
8587 fs: &dyn fs::Fs,
8588) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8589 db.last_workspace(fs)
8590 .await
8591 .log_err()
8592 .flatten()
8593 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8594}
8595
8596pub async fn last_session_workspace_locations(
8597 db: &WorkspaceDb,
8598 last_session_id: &str,
8599 last_session_window_stack: Option<Vec<WindowId>>,
8600 fs: &dyn fs::Fs,
8601) -> Option<Vec<SessionWorkspace>> {
8602 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8603 .await
8604 .log_err()
8605}
8606
8607pub struct MultiWorkspaceRestoreResult {
8608 pub window_handle: WindowHandle<MultiWorkspace>,
8609 pub errors: Vec<anyhow::Error>,
8610}
8611
8612pub async fn restore_multiworkspace(
8613 multi_workspace: SerializedMultiWorkspace,
8614 app_state: Arc<AppState>,
8615 cx: &mut AsyncApp,
8616) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8617 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
8618 let mut group_iter = workspaces.into_iter();
8619 let first = group_iter
8620 .next()
8621 .context("window group must not be empty")?;
8622
8623 let window_handle = if first.paths.is_empty() {
8624 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8625 .await?
8626 } else {
8627 let OpenResult { window, .. } = cx
8628 .update(|cx| {
8629 Workspace::new_local(
8630 first.paths.paths().to_vec(),
8631 app_state.clone(),
8632 None,
8633 None,
8634 None,
8635 OpenMode::Activate,
8636 cx,
8637 )
8638 })
8639 .await?;
8640 window
8641 };
8642
8643 let mut errors = Vec::new();
8644
8645 for session_workspace in group_iter {
8646 let error = if session_workspace.paths.is_empty() {
8647 cx.update(|cx| {
8648 open_workspace_by_id(
8649 session_workspace.workspace_id,
8650 app_state.clone(),
8651 Some(window_handle),
8652 cx,
8653 )
8654 })
8655 .await
8656 .err()
8657 } else {
8658 cx.update(|cx| {
8659 Workspace::new_local(
8660 session_workspace.paths.paths().to_vec(),
8661 app_state.clone(),
8662 Some(window_handle),
8663 None,
8664 None,
8665 OpenMode::Add,
8666 cx,
8667 )
8668 })
8669 .await
8670 .err()
8671 };
8672
8673 if let Some(error) = error {
8674 errors.push(error);
8675 }
8676 }
8677
8678 if let Some(target_id) = state.active_workspace_id {
8679 window_handle
8680 .update(cx, |multi_workspace, window, cx| {
8681 let target_index = multi_workspace
8682 .workspaces()
8683 .iter()
8684 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8685 let index = target_index.unwrap_or(0);
8686 if let Some(workspace) = multi_workspace.workspaces().get(index).cloned() {
8687 multi_workspace.activate(workspace, window, cx);
8688 }
8689 })
8690 .ok();
8691 } else {
8692 window_handle
8693 .update(cx, |multi_workspace, window, cx| {
8694 if let Some(workspace) = multi_workspace.workspaces().first().cloned() {
8695 multi_workspace.activate(workspace, window, cx);
8696 }
8697 })
8698 .ok();
8699 }
8700
8701 if state.sidebar_open {
8702 window_handle
8703 .update(cx, |multi_workspace, _, cx| {
8704 multi_workspace.open_sidebar(cx);
8705 })
8706 .ok();
8707 }
8708
8709 if let Some(sidebar_state) = &state.sidebar_state {
8710 let sidebar_state = sidebar_state.clone();
8711 window_handle
8712 .update(cx, |multi_workspace, window, cx| {
8713 if let Some(sidebar) = multi_workspace.sidebar() {
8714 sidebar.restore_serialized_state(&sidebar_state, window, cx);
8715 }
8716 multi_workspace.serialize(cx);
8717 })
8718 .ok();
8719 }
8720
8721 window_handle
8722 .update(cx, |_, window, _cx| {
8723 window.activate_window();
8724 })
8725 .ok();
8726
8727 Ok(MultiWorkspaceRestoreResult {
8728 window_handle,
8729 errors,
8730 })
8731}
8732
8733actions!(
8734 collab,
8735 [
8736 /// Opens the channel notes for the current call.
8737 ///
8738 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8739 /// channel in the collab panel.
8740 ///
8741 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8742 /// can be copied via "Copy link to section" in the context menu of the channel notes
8743 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8744 OpenChannelNotes,
8745 /// Mutes your microphone.
8746 Mute,
8747 /// Deafens yourself (mute both microphone and speakers).
8748 Deafen,
8749 /// Leaves the current call.
8750 LeaveCall,
8751 /// Shares the current project with collaborators.
8752 ShareProject,
8753 /// Shares your screen with collaborators.
8754 ScreenShare,
8755 /// Copies the current room name and session id for debugging purposes.
8756 CopyRoomId,
8757 ]
8758);
8759
8760/// Opens the channel notes for a specific channel by its ID.
8761#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8762#[action(namespace = collab)]
8763#[serde(deny_unknown_fields)]
8764pub struct OpenChannelNotesById {
8765 pub channel_id: u64,
8766}
8767
8768actions!(
8769 zed,
8770 [
8771 /// Opens the Zed log file.
8772 OpenLog,
8773 /// Reveals the Zed log file in the system file manager.
8774 RevealLogInFileManager
8775 ]
8776);
8777
8778async fn join_channel_internal(
8779 channel_id: ChannelId,
8780 app_state: &Arc<AppState>,
8781 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8782 requesting_workspace: Option<WeakEntity<Workspace>>,
8783 active_call: &dyn AnyActiveCall,
8784 cx: &mut AsyncApp,
8785) -> Result<bool> {
8786 let (should_prompt, already_in_channel) = cx.update(|cx| {
8787 if !active_call.is_in_room(cx) {
8788 return (false, false);
8789 }
8790
8791 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8792 let should_prompt = active_call.is_sharing_project(cx)
8793 && active_call.has_remote_participants(cx)
8794 && !already_in_channel;
8795 (should_prompt, already_in_channel)
8796 });
8797
8798 if already_in_channel {
8799 let task = cx.update(|cx| {
8800 if let Some((project, host)) = active_call.most_active_project(cx) {
8801 Some(join_in_room_project(project, host, app_state.clone(), cx))
8802 } else {
8803 None
8804 }
8805 });
8806 if let Some(task) = task {
8807 task.await?;
8808 }
8809 return anyhow::Ok(true);
8810 }
8811
8812 if should_prompt {
8813 if let Some(multi_workspace) = requesting_window {
8814 let answer = multi_workspace
8815 .update(cx, |_, window, cx| {
8816 window.prompt(
8817 PromptLevel::Warning,
8818 "Do you want to switch channels?",
8819 Some("Leaving this call will unshare your current project."),
8820 &["Yes, Join Channel", "Cancel"],
8821 cx,
8822 )
8823 })?
8824 .await;
8825
8826 if answer == Ok(1) {
8827 return Ok(false);
8828 }
8829 } else {
8830 return Ok(false);
8831 }
8832 }
8833
8834 let client = cx.update(|cx| active_call.client(cx));
8835
8836 let mut client_status = client.status();
8837
8838 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8839 'outer: loop {
8840 let Some(status) = client_status.recv().await else {
8841 anyhow::bail!("error connecting");
8842 };
8843
8844 match status {
8845 Status::Connecting
8846 | Status::Authenticating
8847 | Status::Authenticated
8848 | Status::Reconnecting
8849 | Status::Reauthenticating
8850 | Status::Reauthenticated => continue,
8851 Status::Connected { .. } => break 'outer,
8852 Status::SignedOut | Status::AuthenticationError => {
8853 return Err(ErrorCode::SignedOut.into());
8854 }
8855 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8856 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8857 return Err(ErrorCode::Disconnected.into());
8858 }
8859 }
8860 }
8861
8862 let joined = cx
8863 .update(|cx| active_call.join_channel(channel_id, cx))
8864 .await?;
8865
8866 if !joined {
8867 return anyhow::Ok(true);
8868 }
8869
8870 cx.update(|cx| active_call.room_update_completed(cx)).await;
8871
8872 let task = cx.update(|cx| {
8873 if let Some((project, host)) = active_call.most_active_project(cx) {
8874 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8875 }
8876
8877 // If you are the first to join a channel, see if you should share your project.
8878 if !active_call.has_remote_participants(cx)
8879 && !active_call.local_participant_is_guest(cx)
8880 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8881 {
8882 let project = workspace.update(cx, |workspace, cx| {
8883 let project = workspace.project.read(cx);
8884
8885 if !active_call.share_on_join(cx) {
8886 return None;
8887 }
8888
8889 if (project.is_local() || project.is_via_remote_server())
8890 && project.visible_worktrees(cx).any(|tree| {
8891 tree.read(cx)
8892 .root_entry()
8893 .is_some_and(|entry| entry.is_dir())
8894 })
8895 {
8896 Some(workspace.project.clone())
8897 } else {
8898 None
8899 }
8900 });
8901 if let Some(project) = project {
8902 let share_task = active_call.share_project(project, cx);
8903 return Some(cx.spawn(async move |_cx| -> Result<()> {
8904 share_task.await?;
8905 Ok(())
8906 }));
8907 }
8908 }
8909
8910 None
8911 });
8912 if let Some(task) = task {
8913 task.await?;
8914 return anyhow::Ok(true);
8915 }
8916 anyhow::Ok(false)
8917}
8918
8919pub fn join_channel(
8920 channel_id: ChannelId,
8921 app_state: Arc<AppState>,
8922 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8923 requesting_workspace: Option<WeakEntity<Workspace>>,
8924 cx: &mut App,
8925) -> Task<Result<()>> {
8926 let active_call = GlobalAnyActiveCall::global(cx).clone();
8927 cx.spawn(async move |cx| {
8928 let result = join_channel_internal(
8929 channel_id,
8930 &app_state,
8931 requesting_window,
8932 requesting_workspace,
8933 &*active_call.0,
8934 cx,
8935 )
8936 .await;
8937
8938 // join channel succeeded, and opened a window
8939 if matches!(result, Ok(true)) {
8940 return anyhow::Ok(());
8941 }
8942
8943 // find an existing workspace to focus and show call controls
8944 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8945 if active_window.is_none() {
8946 // no open workspaces, make one to show the error in (blergh)
8947 let OpenResult {
8948 window: window_handle,
8949 ..
8950 } = cx
8951 .update(|cx| {
8952 Workspace::new_local(
8953 vec![],
8954 app_state.clone(),
8955 requesting_window,
8956 None,
8957 None,
8958 OpenMode::Activate,
8959 cx,
8960 )
8961 })
8962 .await?;
8963
8964 window_handle
8965 .update(cx, |_, window, _cx| {
8966 window.activate_window();
8967 })
8968 .ok();
8969
8970 if result.is_ok() {
8971 cx.update(|cx| {
8972 cx.dispatch_action(&OpenChannelNotes);
8973 });
8974 }
8975
8976 active_window = Some(window_handle);
8977 }
8978
8979 if let Err(err) = result {
8980 log::error!("failed to join channel: {}", err);
8981 if let Some(active_window) = active_window {
8982 active_window
8983 .update(cx, |_, window, cx| {
8984 let detail: SharedString = match err.error_code() {
8985 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8986 ErrorCode::UpgradeRequired => concat!(
8987 "Your are running an unsupported version of Zed. ",
8988 "Please update to continue."
8989 )
8990 .into(),
8991 ErrorCode::NoSuchChannel => concat!(
8992 "No matching channel was found. ",
8993 "Please check the link and try again."
8994 )
8995 .into(),
8996 ErrorCode::Forbidden => concat!(
8997 "This channel is private, and you do not have access. ",
8998 "Please ask someone to add you and try again."
8999 )
9000 .into(),
9001 ErrorCode::Disconnected => {
9002 "Please check your internet connection and try again.".into()
9003 }
9004 _ => format!("{}\n\nPlease try again.", err).into(),
9005 };
9006 window.prompt(
9007 PromptLevel::Critical,
9008 "Failed to join channel",
9009 Some(&detail),
9010 &["Ok"],
9011 cx,
9012 )
9013 })?
9014 .await
9015 .ok();
9016 }
9017 }
9018
9019 // return ok, we showed the error to the user.
9020 anyhow::Ok(())
9021 })
9022}
9023
9024pub async fn get_any_active_multi_workspace(
9025 app_state: Arc<AppState>,
9026 mut cx: AsyncApp,
9027) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
9028 // find an existing workspace to focus and show call controls
9029 let active_window = activate_any_workspace_window(&mut cx);
9030 if active_window.is_none() {
9031 cx.update(|cx| {
9032 Workspace::new_local(
9033 vec![],
9034 app_state.clone(),
9035 None,
9036 None,
9037 None,
9038 OpenMode::Activate,
9039 cx,
9040 )
9041 })
9042 .await?;
9043 }
9044 activate_any_workspace_window(&mut cx).context("could not open zed")
9045}
9046
9047fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
9048 cx.update(|cx| {
9049 if let Some(workspace_window) = cx
9050 .active_window()
9051 .and_then(|window| window.downcast::<MultiWorkspace>())
9052 {
9053 return Some(workspace_window);
9054 }
9055
9056 for window in cx.windows() {
9057 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
9058 workspace_window
9059 .update(cx, |_, window, _| window.activate_window())
9060 .ok();
9061 return Some(workspace_window);
9062 }
9063 }
9064 None
9065 })
9066}
9067
9068pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
9069 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
9070}
9071
9072pub fn workspace_windows_for_location(
9073 serialized_location: &SerializedWorkspaceLocation,
9074 cx: &App,
9075) -> Vec<WindowHandle<MultiWorkspace>> {
9076 cx.windows()
9077 .into_iter()
9078 .filter_map(|window| window.downcast::<MultiWorkspace>())
9079 .filter(|multi_workspace| {
9080 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
9081 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
9082 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
9083 }
9084 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
9085 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
9086 a.distro_name == b.distro_name
9087 }
9088 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
9089 a.container_id == b.container_id
9090 }
9091 #[cfg(any(test, feature = "test-support"))]
9092 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
9093 a.id == b.id
9094 }
9095 _ => false,
9096 };
9097
9098 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
9099 multi_workspace.workspaces().iter().any(|workspace| {
9100 match workspace.read(cx).workspace_location(cx) {
9101 WorkspaceLocation::Location(location, _) => {
9102 match (&location, serialized_location) {
9103 (
9104 SerializedWorkspaceLocation::Local,
9105 SerializedWorkspaceLocation::Local,
9106 ) => true,
9107 (
9108 SerializedWorkspaceLocation::Remote(a),
9109 SerializedWorkspaceLocation::Remote(b),
9110 ) => same_host(a, b),
9111 _ => false,
9112 }
9113 }
9114 _ => false,
9115 }
9116 })
9117 })
9118 })
9119 .collect()
9120}
9121
9122pub async fn find_existing_workspace(
9123 abs_paths: &[PathBuf],
9124 open_options: &OpenOptions,
9125 location: &SerializedWorkspaceLocation,
9126 cx: &mut AsyncApp,
9127) -> (
9128 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
9129 OpenVisible,
9130) {
9131 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
9132 let mut open_visible = OpenVisible::All;
9133 let mut best_match = None;
9134
9135 if open_options.open_new_workspace != Some(true) {
9136 cx.update(|cx| {
9137 for window in workspace_windows_for_location(location, cx) {
9138 if let Ok(multi_workspace) = window.read(cx) {
9139 for workspace in multi_workspace.workspaces() {
9140 let project = workspace.read(cx).project.read(cx);
9141 let m = project.visibility_for_paths(
9142 abs_paths,
9143 open_options.open_new_workspace == None,
9144 cx,
9145 );
9146 if m > best_match {
9147 existing = Some((window, workspace.clone()));
9148 best_match = m;
9149 } else if best_match.is_none()
9150 && open_options.open_new_workspace == Some(false)
9151 {
9152 existing = Some((window, workspace.clone()))
9153 }
9154 }
9155 }
9156 }
9157 });
9158
9159 let all_paths_are_files = existing
9160 .as_ref()
9161 .and_then(|(_, target_workspace)| {
9162 cx.update(|cx| {
9163 let workspace = target_workspace.read(cx);
9164 let project = workspace.project.read(cx);
9165 let path_style = workspace.path_style(cx);
9166 Some(!abs_paths.iter().any(|path| {
9167 let path = util::paths::SanitizedPath::new(path);
9168 project.worktrees(cx).any(|worktree| {
9169 let worktree = worktree.read(cx);
9170 let abs_path = worktree.abs_path();
9171 path_style
9172 .strip_prefix(path.as_ref(), abs_path.as_ref())
9173 .and_then(|rel| worktree.entry_for_path(&rel))
9174 .is_some_and(|e| e.is_dir())
9175 })
9176 }))
9177 })
9178 })
9179 .unwrap_or(false);
9180
9181 if open_options.open_new_workspace.is_none()
9182 && existing.is_some()
9183 && open_options.wait
9184 && all_paths_are_files
9185 {
9186 cx.update(|cx| {
9187 let windows = workspace_windows_for_location(location, cx);
9188 let window = cx
9189 .active_window()
9190 .and_then(|window| window.downcast::<MultiWorkspace>())
9191 .filter(|window| windows.contains(window))
9192 .or_else(|| windows.into_iter().next());
9193 if let Some(window) = window {
9194 if let Ok(multi_workspace) = window.read(cx) {
9195 let active_workspace = multi_workspace.workspace().clone();
9196 existing = Some((window, active_workspace));
9197 open_visible = OpenVisible::None;
9198 }
9199 }
9200 });
9201 }
9202 }
9203 (existing, open_visible)
9204}
9205
9206#[derive(Default, Clone)]
9207pub struct OpenOptions {
9208 pub visible: Option<OpenVisible>,
9209 pub focus: Option<bool>,
9210 pub open_new_workspace: Option<bool>,
9211 pub wait: bool,
9212 pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
9213 pub open_mode: OpenMode,
9214 pub env: Option<HashMap<String, String>>,
9215}
9216
9217/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
9218/// or [`Workspace::open_workspace_for_paths`].
9219pub struct OpenResult {
9220 pub window: WindowHandle<MultiWorkspace>,
9221 pub workspace: Entity<Workspace>,
9222 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
9223}
9224
9225/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
9226pub fn open_workspace_by_id(
9227 workspace_id: WorkspaceId,
9228 app_state: Arc<AppState>,
9229 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9230 cx: &mut App,
9231) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
9232 let project_handle = Project::local(
9233 app_state.client.clone(),
9234 app_state.node_runtime.clone(),
9235 app_state.user_store.clone(),
9236 app_state.languages.clone(),
9237 app_state.fs.clone(),
9238 None,
9239 project::LocalProjectFlags {
9240 init_worktree_trust: true,
9241 ..project::LocalProjectFlags::default()
9242 },
9243 cx,
9244 );
9245
9246 let db = WorkspaceDb::global(cx);
9247 let kvp = db::kvp::KeyValueStore::global(cx);
9248 cx.spawn(async move |cx| {
9249 let serialized_workspace = db
9250 .workspace_for_id(workspace_id)
9251 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
9252
9253 let centered_layout = serialized_workspace.centered_layout;
9254
9255 let (window, workspace) = if let Some(window) = requesting_window {
9256 let workspace = window.update(cx, |multi_workspace, window, cx| {
9257 let workspace = cx.new(|cx| {
9258 let mut workspace = Workspace::new(
9259 Some(workspace_id),
9260 project_handle.clone(),
9261 app_state.clone(),
9262 window,
9263 cx,
9264 );
9265 workspace.centered_layout = centered_layout;
9266 workspace
9267 });
9268 multi_workspace.add(workspace.clone(), &*window, cx);
9269 workspace
9270 })?;
9271 (window, workspace)
9272 } else {
9273 let window_bounds_override = window_bounds_env_override();
9274
9275 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
9276 (Some(WindowBounds::Windowed(bounds)), None)
9277 } else if let Some(display) = serialized_workspace.display
9278 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
9279 {
9280 (Some(bounds.0), Some(display))
9281 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
9282 (Some(bounds), Some(display))
9283 } else {
9284 (None, None)
9285 };
9286
9287 let options = cx.update(|cx| {
9288 let mut options = (app_state.build_window_options)(display, cx);
9289 options.window_bounds = window_bounds;
9290 options
9291 });
9292
9293 let window = cx.open_window(options, {
9294 let app_state = app_state.clone();
9295 let project_handle = project_handle.clone();
9296 move |window, cx| {
9297 let workspace = cx.new(|cx| {
9298 let mut workspace = Workspace::new(
9299 Some(workspace_id),
9300 project_handle,
9301 app_state,
9302 window,
9303 cx,
9304 );
9305 workspace.centered_layout = centered_layout;
9306 workspace
9307 });
9308 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9309 }
9310 })?;
9311
9312 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9313 multi_workspace.workspace().clone()
9314 })?;
9315
9316 (window, workspace)
9317 };
9318
9319 notify_if_database_failed(window, cx);
9320
9321 // Restore items from the serialized workspace
9322 window
9323 .update(cx, |_, window, cx| {
9324 workspace.update(cx, |_workspace, cx| {
9325 open_items(Some(serialized_workspace), vec![], window, cx)
9326 })
9327 })?
9328 .await?;
9329
9330 window.update(cx, |_, window, cx| {
9331 workspace.update(cx, |workspace, cx| {
9332 workspace.serialize_workspace(window, cx);
9333 });
9334 })?;
9335
9336 Ok(window)
9337 })
9338}
9339
9340#[allow(clippy::type_complexity)]
9341pub fn open_paths(
9342 abs_paths: &[PathBuf],
9343 app_state: Arc<AppState>,
9344 open_options: OpenOptions,
9345 cx: &mut App,
9346) -> Task<anyhow::Result<OpenResult>> {
9347 let abs_paths = abs_paths.to_vec();
9348 #[cfg(target_os = "windows")]
9349 let wsl_path = abs_paths
9350 .iter()
9351 .find_map(|p| util::paths::WslPath::from_path(p));
9352
9353 cx.spawn(async move |cx| {
9354 let (mut existing, mut open_visible) = find_existing_workspace(
9355 &abs_paths,
9356 &open_options,
9357 &SerializedWorkspaceLocation::Local,
9358 cx,
9359 )
9360 .await;
9361
9362 // Fallback: if no workspace contains the paths and all paths are files,
9363 // prefer an existing local workspace window (active window first).
9364 if open_options.open_new_workspace.is_none() && existing.is_none() {
9365 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9366 let all_metadatas = futures::future::join_all(all_paths)
9367 .await
9368 .into_iter()
9369 .filter_map(|result| result.ok().flatten())
9370 .collect::<Vec<_>>();
9371
9372 if all_metadatas.iter().all(|file| !file.is_dir) {
9373 cx.update(|cx| {
9374 let windows = workspace_windows_for_location(
9375 &SerializedWorkspaceLocation::Local,
9376 cx,
9377 );
9378 let window = cx
9379 .active_window()
9380 .and_then(|window| window.downcast::<MultiWorkspace>())
9381 .filter(|window| windows.contains(window))
9382 .or_else(|| windows.into_iter().next());
9383 if let Some(window) = window {
9384 if let Ok(multi_workspace) = window.read(cx) {
9385 let active_workspace = multi_workspace.workspace().clone();
9386 existing = Some((window, active_workspace));
9387 open_visible = OpenVisible::None;
9388 }
9389 }
9390 });
9391 }
9392 }
9393
9394 let result = if let Some((existing, target_workspace)) = existing {
9395 let open_task = existing
9396 .update(cx, |multi_workspace, window, cx| {
9397 window.activate_window();
9398 multi_workspace.activate(target_workspace.clone(), window, cx);
9399 target_workspace.update(cx, |workspace, cx| {
9400 workspace.open_paths(
9401 abs_paths,
9402 OpenOptions {
9403 visible: Some(open_visible),
9404 ..Default::default()
9405 },
9406 None,
9407 window,
9408 cx,
9409 )
9410 })
9411 })?
9412 .await;
9413
9414 _ = existing.update(cx, |multi_workspace, _, cx| {
9415 let workspace = multi_workspace.workspace().clone();
9416 workspace.update(cx, |workspace, cx| {
9417 for item in open_task.iter().flatten() {
9418 if let Err(e) = item {
9419 workspace.show_error(&e, cx);
9420 }
9421 }
9422 });
9423 });
9424
9425 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9426 } else {
9427 let result = cx
9428 .update(move |cx| {
9429 Workspace::new_local(
9430 abs_paths,
9431 app_state.clone(),
9432 open_options.requesting_window,
9433 open_options.env,
9434 None,
9435 open_options.open_mode,
9436 cx,
9437 )
9438 })
9439 .await;
9440
9441 if let Ok(ref result) = result {
9442 result.window
9443 .update(cx, |_, window, _cx| {
9444 window.activate_window();
9445 })
9446 .log_err();
9447 }
9448
9449 result
9450 };
9451
9452 #[cfg(target_os = "windows")]
9453 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9454 && let Ok(ref result) = result
9455 {
9456 result.window
9457 .update(cx, move |multi_workspace, _window, cx| {
9458 struct OpenInWsl;
9459 let workspace = multi_workspace.workspace().clone();
9460 workspace.update(cx, |workspace, cx| {
9461 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9462 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9463 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9464 cx.new(move |cx| {
9465 MessageNotification::new(msg, cx)
9466 .primary_message("Open in WSL")
9467 .primary_icon(IconName::FolderOpen)
9468 .primary_on_click(move |window, cx| {
9469 window.dispatch_action(Box::new(remote::OpenWslPath {
9470 distro: remote::WslConnectionOptions {
9471 distro_name: distro.clone(),
9472 user: None,
9473 },
9474 paths: vec![path.clone().into()],
9475 }), cx)
9476 })
9477 })
9478 });
9479 });
9480 })
9481 .unwrap();
9482 };
9483 result
9484 })
9485}
9486
9487pub fn open_new(
9488 open_options: OpenOptions,
9489 app_state: Arc<AppState>,
9490 cx: &mut App,
9491 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9492) -> Task<anyhow::Result<()>> {
9493 let addition = open_options.open_mode;
9494 let task = Workspace::new_local(
9495 Vec::new(),
9496 app_state,
9497 open_options.requesting_window,
9498 open_options.env,
9499 Some(Box::new(init)),
9500 addition,
9501 cx,
9502 );
9503 cx.spawn(async move |cx| {
9504 let OpenResult { window, .. } = task.await?;
9505 window
9506 .update(cx, |_, window, _cx| {
9507 window.activate_window();
9508 })
9509 .ok();
9510 Ok(())
9511 })
9512}
9513
9514pub fn create_and_open_local_file(
9515 path: &'static Path,
9516 window: &mut Window,
9517 cx: &mut Context<Workspace>,
9518 default_content: impl 'static + Send + FnOnce() -> Rope,
9519) -> Task<Result<Box<dyn ItemHandle>>> {
9520 cx.spawn_in(window, async move |workspace, cx| {
9521 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9522 if !fs.is_file(path).await {
9523 fs.create_file(path, Default::default()).await?;
9524 fs.save(path, &default_content(), Default::default())
9525 .await?;
9526 }
9527
9528 workspace
9529 .update_in(cx, |workspace, window, cx| {
9530 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9531 let path = workspace
9532 .project
9533 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9534 cx.spawn_in(window, async move |workspace, cx| {
9535 let path = path.await?;
9536
9537 let path = fs.canonicalize(&path).await.unwrap_or(path);
9538
9539 let mut items = workspace
9540 .update_in(cx, |workspace, window, cx| {
9541 workspace.open_paths(
9542 vec![path.to_path_buf()],
9543 OpenOptions {
9544 visible: Some(OpenVisible::None),
9545 ..Default::default()
9546 },
9547 None,
9548 window,
9549 cx,
9550 )
9551 })?
9552 .await;
9553 let item = items.pop().flatten();
9554 item.with_context(|| format!("path {path:?} is not a file"))?
9555 })
9556 })
9557 })?
9558 .await?
9559 .await
9560 })
9561}
9562
9563pub fn open_remote_project_with_new_connection(
9564 window: WindowHandle<MultiWorkspace>,
9565 remote_connection: Arc<dyn RemoteConnection>,
9566 cancel_rx: oneshot::Receiver<()>,
9567 delegate: Arc<dyn RemoteClientDelegate>,
9568 app_state: Arc<AppState>,
9569 paths: Vec<PathBuf>,
9570 cx: &mut App,
9571) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9572 cx.spawn(async move |cx| {
9573 let (workspace_id, serialized_workspace) =
9574 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9575 .await?;
9576
9577 let session = match cx
9578 .update(|cx| {
9579 remote::RemoteClient::new(
9580 ConnectionIdentifier::Workspace(workspace_id.0),
9581 remote_connection,
9582 cancel_rx,
9583 delegate,
9584 cx,
9585 )
9586 })
9587 .await?
9588 {
9589 Some(result) => result,
9590 None => return Ok(Vec::new()),
9591 };
9592
9593 let project = cx.update(|cx| {
9594 project::Project::remote(
9595 session,
9596 app_state.client.clone(),
9597 app_state.node_runtime.clone(),
9598 app_state.user_store.clone(),
9599 app_state.languages.clone(),
9600 app_state.fs.clone(),
9601 true,
9602 cx,
9603 )
9604 });
9605
9606 open_remote_project_inner(
9607 project,
9608 paths,
9609 workspace_id,
9610 serialized_workspace,
9611 app_state,
9612 window,
9613 cx,
9614 )
9615 .await
9616 })
9617}
9618
9619pub fn open_remote_project_with_existing_connection(
9620 connection_options: RemoteConnectionOptions,
9621 project: Entity<Project>,
9622 paths: Vec<PathBuf>,
9623 app_state: Arc<AppState>,
9624 window: WindowHandle<MultiWorkspace>,
9625 cx: &mut AsyncApp,
9626) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9627 cx.spawn(async move |cx| {
9628 let (workspace_id, serialized_workspace) =
9629 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9630
9631 open_remote_project_inner(
9632 project,
9633 paths,
9634 workspace_id,
9635 serialized_workspace,
9636 app_state,
9637 window,
9638 cx,
9639 )
9640 .await
9641 })
9642}
9643
9644async fn open_remote_project_inner(
9645 project: Entity<Project>,
9646 paths: Vec<PathBuf>,
9647 workspace_id: WorkspaceId,
9648 serialized_workspace: Option<SerializedWorkspace>,
9649 app_state: Arc<AppState>,
9650 window: WindowHandle<MultiWorkspace>,
9651 cx: &mut AsyncApp,
9652) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9653 let db = cx.update(|cx| WorkspaceDb::global(cx));
9654 let toolchains = db.toolchains(workspace_id).await?;
9655 for (toolchain, worktree_path, path) in toolchains {
9656 project
9657 .update(cx, |this, cx| {
9658 let Some(worktree_id) =
9659 this.find_worktree(&worktree_path, cx)
9660 .and_then(|(worktree, rel_path)| {
9661 if rel_path.is_empty() {
9662 Some(worktree.read(cx).id())
9663 } else {
9664 None
9665 }
9666 })
9667 else {
9668 return Task::ready(None);
9669 };
9670
9671 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9672 })
9673 .await;
9674 }
9675 let mut project_paths_to_open = vec![];
9676 let mut project_path_errors = vec![];
9677
9678 for path in paths {
9679 let result = cx
9680 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9681 .await;
9682 match result {
9683 Ok((_, project_path)) => {
9684 project_paths_to_open.push((path.clone(), Some(project_path)));
9685 }
9686 Err(error) => {
9687 project_path_errors.push(error);
9688 }
9689 };
9690 }
9691
9692 if project_paths_to_open.is_empty() {
9693 return Err(project_path_errors.pop().context("no paths given")?);
9694 }
9695
9696 let workspace = window.update(cx, |multi_workspace, window, cx| {
9697 telemetry::event!("SSH Project Opened");
9698
9699 let new_workspace = cx.new(|cx| {
9700 let mut workspace =
9701 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9702 workspace.update_history(cx);
9703
9704 if let Some(ref serialized) = serialized_workspace {
9705 workspace.centered_layout = serialized.centered_layout;
9706 }
9707
9708 workspace
9709 });
9710
9711 multi_workspace.activate(new_workspace.clone(), window, cx);
9712 new_workspace
9713 })?;
9714
9715 let items = window
9716 .update(cx, |_, window, cx| {
9717 window.activate_window();
9718 workspace.update(cx, |_workspace, cx| {
9719 open_items(serialized_workspace, project_paths_to_open, window, cx)
9720 })
9721 })?
9722 .await?;
9723
9724 workspace.update(cx, |workspace, cx| {
9725 for error in project_path_errors {
9726 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9727 if let Some(path) = error.error_tag("path") {
9728 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9729 }
9730 } else {
9731 workspace.show_error(&error, cx)
9732 }
9733 }
9734 });
9735
9736 Ok(items.into_iter().map(|item| item?.ok()).collect())
9737}
9738
9739fn deserialize_remote_project(
9740 connection_options: RemoteConnectionOptions,
9741 paths: Vec<PathBuf>,
9742 cx: &AsyncApp,
9743) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9744 let db = cx.update(|cx| WorkspaceDb::global(cx));
9745 cx.background_spawn(async move {
9746 let remote_connection_id = db
9747 .get_or_create_remote_connection(connection_options)
9748 .await?;
9749
9750 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9751
9752 let workspace_id = if let Some(workspace_id) =
9753 serialized_workspace.as_ref().map(|workspace| workspace.id)
9754 {
9755 workspace_id
9756 } else {
9757 db.next_id().await?
9758 };
9759
9760 Ok((workspace_id, serialized_workspace))
9761 })
9762}
9763
9764pub fn join_in_room_project(
9765 project_id: u64,
9766 follow_user_id: u64,
9767 app_state: Arc<AppState>,
9768 cx: &mut App,
9769) -> Task<Result<()>> {
9770 let windows = cx.windows();
9771 cx.spawn(async move |cx| {
9772 let existing_window_and_workspace: Option<(
9773 WindowHandle<MultiWorkspace>,
9774 Entity<Workspace>,
9775 )> = windows.into_iter().find_map(|window_handle| {
9776 window_handle
9777 .downcast::<MultiWorkspace>()
9778 .and_then(|window_handle| {
9779 window_handle
9780 .update(cx, |multi_workspace, _window, cx| {
9781 for workspace in multi_workspace.workspaces() {
9782 if workspace.read(cx).project().read(cx).remote_id()
9783 == Some(project_id)
9784 {
9785 return Some((window_handle, workspace.clone()));
9786 }
9787 }
9788 None
9789 })
9790 .unwrap_or(None)
9791 })
9792 });
9793
9794 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9795 existing_window_and_workspace
9796 {
9797 existing_window
9798 .update(cx, |multi_workspace, window, cx| {
9799 multi_workspace.activate(target_workspace, window, cx);
9800 })
9801 .ok();
9802 existing_window
9803 } else {
9804 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9805 let project = cx
9806 .update(|cx| {
9807 active_call.0.join_project(
9808 project_id,
9809 app_state.languages.clone(),
9810 app_state.fs.clone(),
9811 cx,
9812 )
9813 })
9814 .await?;
9815
9816 let window_bounds_override = window_bounds_env_override();
9817 cx.update(|cx| {
9818 let mut options = (app_state.build_window_options)(None, cx);
9819 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9820 cx.open_window(options, |window, cx| {
9821 let workspace = cx.new(|cx| {
9822 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9823 });
9824 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9825 })
9826 })?
9827 };
9828
9829 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9830 cx.activate(true);
9831 window.activate_window();
9832
9833 // We set the active workspace above, so this is the correct workspace.
9834 let workspace = multi_workspace.workspace().clone();
9835 workspace.update(cx, |workspace, cx| {
9836 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9837 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9838 .or_else(|| {
9839 // If we couldn't follow the given user, follow the host instead.
9840 let collaborator = workspace
9841 .project()
9842 .read(cx)
9843 .collaborators()
9844 .values()
9845 .find(|collaborator| collaborator.is_host)?;
9846 Some(collaborator.peer_id)
9847 });
9848
9849 if let Some(follow_peer_id) = follow_peer_id {
9850 workspace.follow(follow_peer_id, window, cx);
9851 }
9852 });
9853 })?;
9854
9855 anyhow::Ok(())
9856 })
9857}
9858
9859pub fn reload(cx: &mut App) {
9860 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9861 let mut workspace_windows = cx
9862 .windows()
9863 .into_iter()
9864 .filter_map(|window| window.downcast::<MultiWorkspace>())
9865 .collect::<Vec<_>>();
9866
9867 // If multiple windows have unsaved changes, and need a save prompt,
9868 // prompt in the active window before switching to a different window.
9869 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9870
9871 let mut prompt = None;
9872 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9873 prompt = window
9874 .update(cx, |_, window, cx| {
9875 window.prompt(
9876 PromptLevel::Info,
9877 "Are you sure you want to restart?",
9878 None,
9879 &["Restart", "Cancel"],
9880 cx,
9881 )
9882 })
9883 .ok();
9884 }
9885
9886 cx.spawn(async move |cx| {
9887 if let Some(prompt) = prompt {
9888 let answer = prompt.await?;
9889 if answer != 0 {
9890 return anyhow::Ok(());
9891 }
9892 }
9893
9894 // If the user cancels any save prompt, then keep the app open.
9895 for window in workspace_windows {
9896 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9897 let workspace = multi_workspace.workspace().clone();
9898 workspace.update(cx, |workspace, cx| {
9899 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9900 })
9901 }) && !should_close.await?
9902 {
9903 return anyhow::Ok(());
9904 }
9905 }
9906 cx.update(|cx| cx.restart());
9907 anyhow::Ok(())
9908 })
9909 .detach_and_log_err(cx);
9910}
9911
9912fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9913 let mut parts = value.split(',');
9914 let x: usize = parts.next()?.parse().ok()?;
9915 let y: usize = parts.next()?.parse().ok()?;
9916 Some(point(px(x as f32), px(y as f32)))
9917}
9918
9919fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9920 let mut parts = value.split(',');
9921 let width: usize = parts.next()?.parse().ok()?;
9922 let height: usize = parts.next()?.parse().ok()?;
9923 Some(size(px(width as f32), px(height as f32)))
9924}
9925
9926/// Add client-side decorations (rounded corners, shadows, resize handling) when
9927/// appropriate.
9928///
9929/// The `border_radius_tiling` parameter allows overriding which corners get
9930/// rounded, independently of the actual window tiling state. This is used
9931/// specifically for the workspace switcher sidebar: when the sidebar is open,
9932/// we want square corners on the left (so the sidebar appears flush with the
9933/// window edge) but we still need the shadow padding for proper visual
9934/// appearance. Unlike actual window tiling, this only affects border radius -
9935/// not padding or shadows.
9936pub fn client_side_decorations(
9937 element: impl IntoElement,
9938 window: &mut Window,
9939 cx: &mut App,
9940 border_radius_tiling: Tiling,
9941) -> Stateful<Div> {
9942 const BORDER_SIZE: Pixels = px(1.0);
9943 let decorations = window.window_decorations();
9944 let tiling = match decorations {
9945 Decorations::Server => Tiling::default(),
9946 Decorations::Client { tiling } => tiling,
9947 };
9948
9949 match decorations {
9950 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9951 Decorations::Server => window.set_client_inset(px(0.0)),
9952 }
9953
9954 struct GlobalResizeEdge(ResizeEdge);
9955 impl Global for GlobalResizeEdge {}
9956
9957 div()
9958 .id("window-backdrop")
9959 .bg(transparent_black())
9960 .map(|div| match decorations {
9961 Decorations::Server => div,
9962 Decorations::Client { .. } => div
9963 .when(
9964 !(tiling.top
9965 || tiling.right
9966 || border_radius_tiling.top
9967 || border_radius_tiling.right),
9968 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9969 )
9970 .when(
9971 !(tiling.top
9972 || tiling.left
9973 || border_radius_tiling.top
9974 || border_radius_tiling.left),
9975 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9976 )
9977 .when(
9978 !(tiling.bottom
9979 || tiling.right
9980 || border_radius_tiling.bottom
9981 || border_radius_tiling.right),
9982 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9983 )
9984 .when(
9985 !(tiling.bottom
9986 || tiling.left
9987 || border_radius_tiling.bottom
9988 || border_radius_tiling.left),
9989 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9990 )
9991 .when(!tiling.top, |div| {
9992 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9993 })
9994 .when(!tiling.bottom, |div| {
9995 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9996 })
9997 .when(!tiling.left, |div| {
9998 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9999 })
10000 .when(!tiling.right, |div| {
10001 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10002 })
10003 .on_mouse_move(move |e, window, cx| {
10004 let size = window.window_bounds().get_bounds().size;
10005 let pos = e.position;
10006
10007 let new_edge =
10008 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10009
10010 let edge = cx.try_global::<GlobalResizeEdge>();
10011 if new_edge != edge.map(|edge| edge.0) {
10012 window
10013 .window_handle()
10014 .update(cx, |workspace, _, cx| {
10015 cx.notify(workspace.entity_id());
10016 })
10017 .ok();
10018 }
10019 })
10020 .on_mouse_down(MouseButton::Left, move |e, window, _| {
10021 let size = window.window_bounds().get_bounds().size;
10022 let pos = e.position;
10023
10024 let edge = match resize_edge(
10025 pos,
10026 theme::CLIENT_SIDE_DECORATION_SHADOW,
10027 size,
10028 tiling,
10029 ) {
10030 Some(value) => value,
10031 None => return,
10032 };
10033
10034 window.start_window_resize(edge);
10035 }),
10036 })
10037 .size_full()
10038 .child(
10039 div()
10040 .cursor(CursorStyle::Arrow)
10041 .map(|div| match decorations {
10042 Decorations::Server => div,
10043 Decorations::Client { .. } => div
10044 .border_color(cx.theme().colors().border)
10045 .when(
10046 !(tiling.top
10047 || tiling.right
10048 || border_radius_tiling.top
10049 || border_radius_tiling.right),
10050 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10051 )
10052 .when(
10053 !(tiling.top
10054 || tiling.left
10055 || border_radius_tiling.top
10056 || border_radius_tiling.left),
10057 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10058 )
10059 .when(
10060 !(tiling.bottom
10061 || tiling.right
10062 || border_radius_tiling.bottom
10063 || border_radius_tiling.right),
10064 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10065 )
10066 .when(
10067 !(tiling.bottom
10068 || tiling.left
10069 || border_radius_tiling.bottom
10070 || border_radius_tiling.left),
10071 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10072 )
10073 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10074 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10075 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10076 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10077 .when(!tiling.is_tiled(), |div| {
10078 div.shadow(vec![gpui::BoxShadow {
10079 color: Hsla {
10080 h: 0.,
10081 s: 0.,
10082 l: 0.,
10083 a: 0.4,
10084 },
10085 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10086 spread_radius: px(0.),
10087 offset: point(px(0.0), px(0.0)),
10088 }])
10089 }),
10090 })
10091 .on_mouse_move(|_e, _, cx| {
10092 cx.stop_propagation();
10093 })
10094 .size_full()
10095 .child(element),
10096 )
10097 .map(|div| match decorations {
10098 Decorations::Server => div,
10099 Decorations::Client { tiling, .. } => div.child(
10100 canvas(
10101 |_bounds, window, _| {
10102 window.insert_hitbox(
10103 Bounds::new(
10104 point(px(0.0), px(0.0)),
10105 window.window_bounds().get_bounds().size,
10106 ),
10107 HitboxBehavior::Normal,
10108 )
10109 },
10110 move |_bounds, hitbox, window, cx| {
10111 let mouse = window.mouse_position();
10112 let size = window.window_bounds().get_bounds().size;
10113 let Some(edge) =
10114 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10115 else {
10116 return;
10117 };
10118 cx.set_global(GlobalResizeEdge(edge));
10119 window.set_cursor_style(
10120 match edge {
10121 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10122 ResizeEdge::Left | ResizeEdge::Right => {
10123 CursorStyle::ResizeLeftRight
10124 }
10125 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10126 CursorStyle::ResizeUpLeftDownRight
10127 }
10128 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10129 CursorStyle::ResizeUpRightDownLeft
10130 }
10131 },
10132 &hitbox,
10133 );
10134 },
10135 )
10136 .size_full()
10137 .absolute(),
10138 ),
10139 })
10140}
10141
10142fn resize_edge(
10143 pos: Point<Pixels>,
10144 shadow_size: Pixels,
10145 window_size: Size<Pixels>,
10146 tiling: Tiling,
10147) -> Option<ResizeEdge> {
10148 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10149 if bounds.contains(&pos) {
10150 return None;
10151 }
10152
10153 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10154 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10155 if !tiling.top && top_left_bounds.contains(&pos) {
10156 return Some(ResizeEdge::TopLeft);
10157 }
10158
10159 let top_right_bounds = Bounds::new(
10160 Point::new(window_size.width - corner_size.width, px(0.)),
10161 corner_size,
10162 );
10163 if !tiling.top && top_right_bounds.contains(&pos) {
10164 return Some(ResizeEdge::TopRight);
10165 }
10166
10167 let bottom_left_bounds = Bounds::new(
10168 Point::new(px(0.), window_size.height - corner_size.height),
10169 corner_size,
10170 );
10171 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10172 return Some(ResizeEdge::BottomLeft);
10173 }
10174
10175 let bottom_right_bounds = Bounds::new(
10176 Point::new(
10177 window_size.width - corner_size.width,
10178 window_size.height - corner_size.height,
10179 ),
10180 corner_size,
10181 );
10182 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10183 return Some(ResizeEdge::BottomRight);
10184 }
10185
10186 if !tiling.top && pos.y < shadow_size {
10187 Some(ResizeEdge::Top)
10188 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10189 Some(ResizeEdge::Bottom)
10190 } else if !tiling.left && pos.x < shadow_size {
10191 Some(ResizeEdge::Left)
10192 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10193 Some(ResizeEdge::Right)
10194 } else {
10195 None
10196 }
10197}
10198
10199fn join_pane_into_active(
10200 active_pane: &Entity<Pane>,
10201 pane: &Entity<Pane>,
10202 window: &mut Window,
10203 cx: &mut App,
10204) {
10205 if pane == active_pane {
10206 } else if pane.read(cx).items_len() == 0 {
10207 pane.update(cx, |_, cx| {
10208 cx.emit(pane::Event::Remove {
10209 focus_on_pane: None,
10210 });
10211 })
10212 } else {
10213 move_all_items(pane, active_pane, window, cx);
10214 }
10215}
10216
10217fn move_all_items(
10218 from_pane: &Entity<Pane>,
10219 to_pane: &Entity<Pane>,
10220 window: &mut Window,
10221 cx: &mut App,
10222) {
10223 let destination_is_different = from_pane != to_pane;
10224 let mut moved_items = 0;
10225 for (item_ix, item_handle) in from_pane
10226 .read(cx)
10227 .items()
10228 .enumerate()
10229 .map(|(ix, item)| (ix, item.clone()))
10230 .collect::<Vec<_>>()
10231 {
10232 let ix = item_ix - moved_items;
10233 if destination_is_different {
10234 // Close item from previous pane
10235 from_pane.update(cx, |source, cx| {
10236 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10237 });
10238 moved_items += 1;
10239 }
10240
10241 // This automatically removes duplicate items in the pane
10242 to_pane.update(cx, |destination, cx| {
10243 destination.add_item(item_handle, true, true, None, window, cx);
10244 window.focus(&destination.focus_handle(cx), cx)
10245 });
10246 }
10247}
10248
10249pub fn move_item(
10250 source: &Entity<Pane>,
10251 destination: &Entity<Pane>,
10252 item_id_to_move: EntityId,
10253 destination_index: usize,
10254 activate: bool,
10255 window: &mut Window,
10256 cx: &mut App,
10257) {
10258 let Some((item_ix, item_handle)) = source
10259 .read(cx)
10260 .items()
10261 .enumerate()
10262 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10263 .map(|(ix, item)| (ix, item.clone()))
10264 else {
10265 // Tab was closed during drag
10266 return;
10267 };
10268
10269 if source != destination {
10270 // Close item from previous pane
10271 source.update(cx, |source, cx| {
10272 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10273 });
10274 }
10275
10276 // This automatically removes duplicate items in the pane
10277 destination.update(cx, |destination, cx| {
10278 destination.add_item_inner(
10279 item_handle,
10280 activate,
10281 activate,
10282 activate,
10283 Some(destination_index),
10284 window,
10285 cx,
10286 );
10287 if activate {
10288 window.focus(&destination.focus_handle(cx), cx)
10289 }
10290 });
10291}
10292
10293pub fn move_active_item(
10294 source: &Entity<Pane>,
10295 destination: &Entity<Pane>,
10296 focus_destination: bool,
10297 close_if_empty: bool,
10298 window: &mut Window,
10299 cx: &mut App,
10300) {
10301 if source == destination {
10302 return;
10303 }
10304 let Some(active_item) = source.read(cx).active_item() else {
10305 return;
10306 };
10307 source.update(cx, |source_pane, cx| {
10308 let item_id = active_item.item_id();
10309 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10310 destination.update(cx, |target_pane, cx| {
10311 target_pane.add_item(
10312 active_item,
10313 focus_destination,
10314 focus_destination,
10315 Some(target_pane.items_len()),
10316 window,
10317 cx,
10318 );
10319 });
10320 });
10321}
10322
10323pub fn clone_active_item(
10324 workspace_id: Option<WorkspaceId>,
10325 source: &Entity<Pane>,
10326 destination: &Entity<Pane>,
10327 focus_destination: bool,
10328 window: &mut Window,
10329 cx: &mut App,
10330) {
10331 if source == destination {
10332 return;
10333 }
10334 let Some(active_item) = source.read(cx).active_item() else {
10335 return;
10336 };
10337 if !active_item.can_split(cx) {
10338 return;
10339 }
10340 let destination = destination.downgrade();
10341 let task = active_item.clone_on_split(workspace_id, window, cx);
10342 window
10343 .spawn(cx, async move |cx| {
10344 let Some(clone) = task.await else {
10345 return;
10346 };
10347 destination
10348 .update_in(cx, |target_pane, window, cx| {
10349 target_pane.add_item(
10350 clone,
10351 focus_destination,
10352 focus_destination,
10353 Some(target_pane.items_len()),
10354 window,
10355 cx,
10356 );
10357 })
10358 .log_err();
10359 })
10360 .detach();
10361}
10362
10363#[derive(Debug)]
10364pub struct WorkspacePosition {
10365 pub window_bounds: Option<WindowBounds>,
10366 pub display: Option<Uuid>,
10367 pub centered_layout: bool,
10368}
10369
10370pub fn remote_workspace_position_from_db(
10371 connection_options: RemoteConnectionOptions,
10372 paths_to_open: &[PathBuf],
10373 cx: &App,
10374) -> Task<Result<WorkspacePosition>> {
10375 let paths = paths_to_open.to_vec();
10376 let db = WorkspaceDb::global(cx);
10377 let kvp = db::kvp::KeyValueStore::global(cx);
10378
10379 cx.background_spawn(async move {
10380 let remote_connection_id = db
10381 .get_or_create_remote_connection(connection_options)
10382 .await
10383 .context("fetching serialized ssh project")?;
10384 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10385
10386 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10387 (Some(WindowBounds::Windowed(bounds)), None)
10388 } else {
10389 let restorable_bounds = serialized_workspace
10390 .as_ref()
10391 .and_then(|workspace| {
10392 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10393 })
10394 .or_else(|| persistence::read_default_window_bounds(&kvp));
10395
10396 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10397 (Some(serialized_bounds), Some(serialized_display))
10398 } else {
10399 (None, None)
10400 }
10401 };
10402
10403 let centered_layout = serialized_workspace
10404 .as_ref()
10405 .map(|w| w.centered_layout)
10406 .unwrap_or(false);
10407
10408 Ok(WorkspacePosition {
10409 window_bounds,
10410 display,
10411 centered_layout,
10412 })
10413 })
10414}
10415
10416pub fn with_active_or_new_workspace(
10417 cx: &mut App,
10418 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10419) {
10420 match cx
10421 .active_window()
10422 .and_then(|w| w.downcast::<MultiWorkspace>())
10423 {
10424 Some(multi_workspace) => {
10425 cx.defer(move |cx| {
10426 multi_workspace
10427 .update(cx, |multi_workspace, window, cx| {
10428 let workspace = multi_workspace.workspace().clone();
10429 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10430 })
10431 .log_err();
10432 });
10433 }
10434 None => {
10435 let app_state = AppState::global(cx);
10436 open_new(
10437 OpenOptions::default(),
10438 app_state,
10439 cx,
10440 move |workspace, window, cx| f(workspace, window, cx),
10441 )
10442 .detach_and_log_err(cx);
10443 }
10444 }
10445}
10446
10447/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10448/// key. This migration path only runs once per panel per workspace.
10449fn load_legacy_panel_size(
10450 panel_key: &str,
10451 dock_position: DockPosition,
10452 workspace: &Workspace,
10453 cx: &mut App,
10454) -> Option<Pixels> {
10455 #[derive(Deserialize)]
10456 struct LegacyPanelState {
10457 #[serde(default)]
10458 width: Option<Pixels>,
10459 #[serde(default)]
10460 height: Option<Pixels>,
10461 }
10462
10463 let workspace_id = workspace
10464 .database_id()
10465 .map(|id| i64::from(id).to_string())
10466 .or_else(|| workspace.session_id())?;
10467
10468 let legacy_key = match panel_key {
10469 "ProjectPanel" => {
10470 format!("{}-{:?}", "ProjectPanel", workspace_id)
10471 }
10472 "OutlinePanel" => {
10473 format!("{}-{:?}", "OutlinePanel", workspace_id)
10474 }
10475 "GitPanel" => {
10476 format!("{}-{:?}", "GitPanel", workspace_id)
10477 }
10478 "TerminalPanel" => {
10479 format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10480 }
10481 _ => return None,
10482 };
10483
10484 let kvp = db::kvp::KeyValueStore::global(cx);
10485 let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10486 let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10487 let size = match dock_position {
10488 DockPosition::Bottom => state.height,
10489 DockPosition::Left | DockPosition::Right => state.width,
10490 }?;
10491
10492 cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10493 .detach_and_log_err(cx);
10494
10495 Some(size)
10496}
10497
10498#[cfg(test)]
10499mod tests {
10500 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10501
10502 use super::*;
10503 use crate::{
10504 dock::{PanelEvent, test::TestPanel},
10505 item::{
10506 ItemBufferKind, ItemEvent,
10507 test::{TestItem, TestProjectItem},
10508 },
10509 };
10510 use fs::FakeFs;
10511 use gpui::{
10512 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10513 UpdateGlobal, VisualTestContext, px,
10514 };
10515 use project::{Project, ProjectEntryId};
10516 use serde_json::json;
10517 use settings::SettingsStore;
10518 use util::path;
10519 use util::rel_path::rel_path;
10520
10521 #[gpui::test]
10522 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10523 init_test(cx);
10524
10525 let fs = FakeFs::new(cx.executor());
10526 let project = Project::test(fs, [], cx).await;
10527 let (workspace, cx) =
10528 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10529
10530 // Adding an item with no ambiguity renders the tab without detail.
10531 let item1 = cx.new(|cx| {
10532 let mut item = TestItem::new(cx);
10533 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10534 item
10535 });
10536 workspace.update_in(cx, |workspace, window, cx| {
10537 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10538 });
10539 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10540
10541 // Adding an item that creates ambiguity increases the level of detail on
10542 // both tabs.
10543 let item2 = cx.new_window_entity(|_window, cx| {
10544 let mut item = TestItem::new(cx);
10545 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10546 item
10547 });
10548 workspace.update_in(cx, |workspace, window, cx| {
10549 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10550 });
10551 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10552 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10553
10554 // Adding an item that creates ambiguity increases the level of detail only
10555 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10556 // we stop at the highest detail available.
10557 let item3 = cx.new(|cx| {
10558 let mut item = TestItem::new(cx);
10559 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10560 item
10561 });
10562 workspace.update_in(cx, |workspace, window, cx| {
10563 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10564 });
10565 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10566 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10567 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10568 }
10569
10570 #[gpui::test]
10571 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10572 init_test(cx);
10573
10574 let fs = FakeFs::new(cx.executor());
10575 fs.insert_tree(
10576 "/root1",
10577 json!({
10578 "one.txt": "",
10579 "two.txt": "",
10580 }),
10581 )
10582 .await;
10583 fs.insert_tree(
10584 "/root2",
10585 json!({
10586 "three.txt": "",
10587 }),
10588 )
10589 .await;
10590
10591 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10592 let (workspace, cx) =
10593 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10594 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10595 let worktree_id = project.update(cx, |project, cx| {
10596 project.worktrees(cx).next().unwrap().read(cx).id()
10597 });
10598
10599 let item1 = cx.new(|cx| {
10600 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10601 });
10602 let item2 = cx.new(|cx| {
10603 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10604 });
10605
10606 // Add an item to an empty pane
10607 workspace.update_in(cx, |workspace, window, cx| {
10608 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10609 });
10610 project.update(cx, |project, cx| {
10611 assert_eq!(
10612 project.active_entry(),
10613 project
10614 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10615 .map(|e| e.id)
10616 );
10617 });
10618 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10619
10620 // Add a second item to a non-empty pane
10621 workspace.update_in(cx, |workspace, window, cx| {
10622 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10623 });
10624 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10625 project.update(cx, |project, cx| {
10626 assert_eq!(
10627 project.active_entry(),
10628 project
10629 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10630 .map(|e| e.id)
10631 );
10632 });
10633
10634 // Close the active item
10635 pane.update_in(cx, |pane, window, cx| {
10636 pane.close_active_item(&Default::default(), window, cx)
10637 })
10638 .await
10639 .unwrap();
10640 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10641 project.update(cx, |project, cx| {
10642 assert_eq!(
10643 project.active_entry(),
10644 project
10645 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10646 .map(|e| e.id)
10647 );
10648 });
10649
10650 // Add a project folder
10651 project
10652 .update(cx, |project, cx| {
10653 project.find_or_create_worktree("root2", true, cx)
10654 })
10655 .await
10656 .unwrap();
10657 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10658
10659 // Remove a project folder
10660 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10661 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10662 }
10663
10664 #[gpui::test]
10665 async fn test_close_window(cx: &mut TestAppContext) {
10666 init_test(cx);
10667
10668 let fs = FakeFs::new(cx.executor());
10669 fs.insert_tree("/root", json!({ "one": "" })).await;
10670
10671 let project = Project::test(fs, ["root".as_ref()], cx).await;
10672 let (workspace, cx) =
10673 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10674
10675 // When there are no dirty items, there's nothing to do.
10676 let item1 = cx.new(TestItem::new);
10677 workspace.update_in(cx, |w, window, cx| {
10678 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10679 });
10680 let task = workspace.update_in(cx, |w, window, cx| {
10681 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10682 });
10683 assert!(task.await.unwrap());
10684
10685 // When there are dirty untitled items, prompt to save each one. If the user
10686 // cancels any prompt, then abort.
10687 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10688 let item3 = cx.new(|cx| {
10689 TestItem::new(cx)
10690 .with_dirty(true)
10691 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10692 });
10693 workspace.update_in(cx, |w, window, cx| {
10694 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10695 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10696 });
10697 let task = workspace.update_in(cx, |w, window, cx| {
10698 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10699 });
10700 cx.executor().run_until_parked();
10701 cx.simulate_prompt_answer("Cancel"); // cancel save all
10702 cx.executor().run_until_parked();
10703 assert!(!cx.has_pending_prompt());
10704 assert!(!task.await.unwrap());
10705 }
10706
10707 #[gpui::test]
10708 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10709 init_test(cx);
10710
10711 let fs = FakeFs::new(cx.executor());
10712 fs.insert_tree("/root", json!({ "one": "" })).await;
10713
10714 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10715 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10716 let multi_workspace_handle =
10717 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10718 cx.run_until_parked();
10719
10720 let workspace_a = multi_workspace_handle
10721 .read_with(cx, |mw, _| mw.workspace().clone())
10722 .unwrap();
10723
10724 let workspace_b = multi_workspace_handle
10725 .update(cx, |mw, window, cx| {
10726 mw.test_add_workspace(project_b, window, cx)
10727 })
10728 .unwrap();
10729
10730 // Activate workspace A
10731 multi_workspace_handle
10732 .update(cx, |mw, window, cx| {
10733 let workspace = mw.workspaces()[0].clone();
10734 mw.activate(workspace, window, cx);
10735 })
10736 .unwrap();
10737
10738 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10739
10740 // Workspace A has a clean item
10741 let item_a = cx.new(TestItem::new);
10742 workspace_a.update_in(cx, |w, window, cx| {
10743 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10744 });
10745
10746 // Workspace B has a dirty item
10747 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10748 workspace_b.update_in(cx, |w, window, cx| {
10749 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10750 });
10751
10752 // Verify workspace A is active
10753 multi_workspace_handle
10754 .read_with(cx, |mw, _| {
10755 assert_eq!(mw.active_workspace_index(), 0);
10756 })
10757 .unwrap();
10758
10759 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10760 multi_workspace_handle
10761 .update(cx, |mw, window, cx| {
10762 mw.close_window(&CloseWindow, window, cx);
10763 })
10764 .unwrap();
10765 cx.run_until_parked();
10766
10767 // Workspace B should now be active since it has dirty items that need attention
10768 multi_workspace_handle
10769 .read_with(cx, |mw, _| {
10770 assert_eq!(
10771 mw.active_workspace_index(),
10772 1,
10773 "workspace B should be activated when it prompts"
10774 );
10775 })
10776 .unwrap();
10777
10778 // User cancels the save prompt from workspace B
10779 cx.simulate_prompt_answer("Cancel");
10780 cx.run_until_parked();
10781
10782 // Window should still exist because workspace B's close was cancelled
10783 assert!(
10784 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10785 "window should still exist after cancelling one workspace's close"
10786 );
10787 }
10788
10789 #[gpui::test]
10790 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10791 init_test(cx);
10792
10793 // Register TestItem as a serializable item
10794 cx.update(|cx| {
10795 register_serializable_item::<TestItem>(cx);
10796 });
10797
10798 let fs = FakeFs::new(cx.executor());
10799 fs.insert_tree("/root", json!({ "one": "" })).await;
10800
10801 let project = Project::test(fs, ["root".as_ref()], cx).await;
10802 let (workspace, cx) =
10803 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10804
10805 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10806 let item1 = cx.new(|cx| {
10807 TestItem::new(cx)
10808 .with_dirty(true)
10809 .with_serialize(|| Some(Task::ready(Ok(()))))
10810 });
10811 let item2 = cx.new(|cx| {
10812 TestItem::new(cx)
10813 .with_dirty(true)
10814 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10815 .with_serialize(|| Some(Task::ready(Ok(()))))
10816 });
10817 workspace.update_in(cx, |w, window, cx| {
10818 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10819 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10820 });
10821 let task = workspace.update_in(cx, |w, window, cx| {
10822 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10823 });
10824 assert!(task.await.unwrap());
10825 }
10826
10827 #[gpui::test]
10828 async fn test_close_pane_items(cx: &mut TestAppContext) {
10829 init_test(cx);
10830
10831 let fs = FakeFs::new(cx.executor());
10832
10833 let project = Project::test(fs, None, cx).await;
10834 let (workspace, cx) =
10835 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10836
10837 let item1 = cx.new(|cx| {
10838 TestItem::new(cx)
10839 .with_dirty(true)
10840 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10841 });
10842 let item2 = cx.new(|cx| {
10843 TestItem::new(cx)
10844 .with_dirty(true)
10845 .with_conflict(true)
10846 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10847 });
10848 let item3 = cx.new(|cx| {
10849 TestItem::new(cx)
10850 .with_dirty(true)
10851 .with_conflict(true)
10852 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10853 });
10854 let item4 = cx.new(|cx| {
10855 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10856 let project_item = TestProjectItem::new_untitled(cx);
10857 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10858 project_item
10859 }])
10860 });
10861 let pane = workspace.update_in(cx, |workspace, window, cx| {
10862 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10863 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10864 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10865 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10866 workspace.active_pane().clone()
10867 });
10868
10869 let close_items = pane.update_in(cx, |pane, window, cx| {
10870 pane.activate_item(1, true, true, window, cx);
10871 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10872 let item1_id = item1.item_id();
10873 let item3_id = item3.item_id();
10874 let item4_id = item4.item_id();
10875 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10876 [item1_id, item3_id, item4_id].contains(&id)
10877 })
10878 });
10879 cx.executor().run_until_parked();
10880
10881 assert!(cx.has_pending_prompt());
10882 cx.simulate_prompt_answer("Save all");
10883
10884 cx.executor().run_until_parked();
10885
10886 // Item 1 is saved. There's a prompt to save item 3.
10887 pane.update(cx, |pane, cx| {
10888 assert_eq!(item1.read(cx).save_count, 1);
10889 assert_eq!(item1.read(cx).save_as_count, 0);
10890 assert_eq!(item1.read(cx).reload_count, 0);
10891 assert_eq!(pane.items_len(), 3);
10892 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10893 });
10894 assert!(cx.has_pending_prompt());
10895
10896 // Cancel saving item 3.
10897 cx.simulate_prompt_answer("Discard");
10898 cx.executor().run_until_parked();
10899
10900 // Item 3 is reloaded. There's a prompt to save item 4.
10901 pane.update(cx, |pane, cx| {
10902 assert_eq!(item3.read(cx).save_count, 0);
10903 assert_eq!(item3.read(cx).save_as_count, 0);
10904 assert_eq!(item3.read(cx).reload_count, 1);
10905 assert_eq!(pane.items_len(), 2);
10906 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10907 });
10908
10909 // There's a prompt for a path for item 4.
10910 cx.simulate_new_path_selection(|_| Some(Default::default()));
10911 close_items.await.unwrap();
10912
10913 // The requested items are closed.
10914 pane.update(cx, |pane, cx| {
10915 assert_eq!(item4.read(cx).save_count, 0);
10916 assert_eq!(item4.read(cx).save_as_count, 1);
10917 assert_eq!(item4.read(cx).reload_count, 0);
10918 assert_eq!(pane.items_len(), 1);
10919 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10920 });
10921 }
10922
10923 #[gpui::test]
10924 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10925 init_test(cx);
10926
10927 let fs = FakeFs::new(cx.executor());
10928 let project = Project::test(fs, [], cx).await;
10929 let (workspace, cx) =
10930 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10931
10932 // Create several workspace items with single project entries, and two
10933 // workspace items with multiple project entries.
10934 let single_entry_items = (0..=4)
10935 .map(|project_entry_id| {
10936 cx.new(|cx| {
10937 TestItem::new(cx)
10938 .with_dirty(true)
10939 .with_project_items(&[dirty_project_item(
10940 project_entry_id,
10941 &format!("{project_entry_id}.txt"),
10942 cx,
10943 )])
10944 })
10945 })
10946 .collect::<Vec<_>>();
10947 let item_2_3 = cx.new(|cx| {
10948 TestItem::new(cx)
10949 .with_dirty(true)
10950 .with_buffer_kind(ItemBufferKind::Multibuffer)
10951 .with_project_items(&[
10952 single_entry_items[2].read(cx).project_items[0].clone(),
10953 single_entry_items[3].read(cx).project_items[0].clone(),
10954 ])
10955 });
10956 let item_3_4 = cx.new(|cx| {
10957 TestItem::new(cx)
10958 .with_dirty(true)
10959 .with_buffer_kind(ItemBufferKind::Multibuffer)
10960 .with_project_items(&[
10961 single_entry_items[3].read(cx).project_items[0].clone(),
10962 single_entry_items[4].read(cx).project_items[0].clone(),
10963 ])
10964 });
10965
10966 // Create two panes that contain the following project entries:
10967 // left pane:
10968 // multi-entry items: (2, 3)
10969 // single-entry items: 0, 2, 3, 4
10970 // right pane:
10971 // single-entry items: 4, 1
10972 // multi-entry items: (3, 4)
10973 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10974 let left_pane = workspace.active_pane().clone();
10975 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10976 workspace.add_item_to_active_pane(
10977 single_entry_items[0].boxed_clone(),
10978 None,
10979 true,
10980 window,
10981 cx,
10982 );
10983 workspace.add_item_to_active_pane(
10984 single_entry_items[2].boxed_clone(),
10985 None,
10986 true,
10987 window,
10988 cx,
10989 );
10990 workspace.add_item_to_active_pane(
10991 single_entry_items[3].boxed_clone(),
10992 None,
10993 true,
10994 window,
10995 cx,
10996 );
10997 workspace.add_item_to_active_pane(
10998 single_entry_items[4].boxed_clone(),
10999 None,
11000 true,
11001 window,
11002 cx,
11003 );
11004
11005 let right_pane =
11006 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11007
11008 let boxed_clone = single_entry_items[1].boxed_clone();
11009 let right_pane = window.spawn(cx, async move |cx| {
11010 right_pane.await.inspect(|right_pane| {
11011 right_pane
11012 .update_in(cx, |pane, window, cx| {
11013 pane.add_item(boxed_clone, true, true, None, window, cx);
11014 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11015 })
11016 .unwrap();
11017 })
11018 });
11019
11020 (left_pane, right_pane)
11021 });
11022 let right_pane = right_pane.await.unwrap();
11023 cx.focus(&right_pane);
11024
11025 let close = right_pane.update_in(cx, |pane, window, cx| {
11026 pane.close_all_items(&CloseAllItems::default(), window, cx)
11027 .unwrap()
11028 });
11029 cx.executor().run_until_parked();
11030
11031 let msg = cx.pending_prompt().unwrap().0;
11032 assert!(msg.contains("1.txt"));
11033 assert!(!msg.contains("2.txt"));
11034 assert!(!msg.contains("3.txt"));
11035 assert!(!msg.contains("4.txt"));
11036
11037 // With best-effort close, cancelling item 1 keeps it open but items 4
11038 // and (3,4) still close since their entries exist in left pane.
11039 cx.simulate_prompt_answer("Cancel");
11040 close.await;
11041
11042 right_pane.read_with(cx, |pane, _| {
11043 assert_eq!(pane.items_len(), 1);
11044 });
11045
11046 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11047 left_pane
11048 .update_in(cx, |left_pane, window, cx| {
11049 left_pane.close_item_by_id(
11050 single_entry_items[3].entity_id(),
11051 SaveIntent::Skip,
11052 window,
11053 cx,
11054 )
11055 })
11056 .await
11057 .unwrap();
11058
11059 let close = left_pane.update_in(cx, |pane, window, cx| {
11060 pane.close_all_items(&CloseAllItems::default(), window, cx)
11061 .unwrap()
11062 });
11063 cx.executor().run_until_parked();
11064
11065 let details = cx.pending_prompt().unwrap().1;
11066 assert!(details.contains("0.txt"));
11067 assert!(details.contains("3.txt"));
11068 assert!(details.contains("4.txt"));
11069 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11070 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11071 // assert!(!details.contains("2.txt"));
11072
11073 cx.simulate_prompt_answer("Save all");
11074 cx.executor().run_until_parked();
11075 close.await;
11076
11077 left_pane.read_with(cx, |pane, _| {
11078 assert_eq!(pane.items_len(), 0);
11079 });
11080 }
11081
11082 #[gpui::test]
11083 async fn test_autosave(cx: &mut gpui::TestAppContext) {
11084 init_test(cx);
11085
11086 let fs = FakeFs::new(cx.executor());
11087 let project = Project::test(fs, [], cx).await;
11088 let (workspace, cx) =
11089 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11090 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11091
11092 let item = cx.new(|cx| {
11093 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11094 });
11095 let item_id = item.entity_id();
11096 workspace.update_in(cx, |workspace, window, cx| {
11097 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11098 });
11099
11100 // Autosave on window change.
11101 item.update(cx, |item, cx| {
11102 SettingsStore::update_global(cx, |settings, cx| {
11103 settings.update_user_settings(cx, |settings| {
11104 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11105 })
11106 });
11107 item.is_dirty = true;
11108 });
11109
11110 // Deactivating the window saves the file.
11111 cx.deactivate_window();
11112 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11113
11114 // Re-activating the window doesn't save the file.
11115 cx.update(|window, _| window.activate_window());
11116 cx.executor().run_until_parked();
11117 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11118
11119 // Autosave on focus change.
11120 item.update_in(cx, |item, window, cx| {
11121 cx.focus_self(window);
11122 SettingsStore::update_global(cx, |settings, cx| {
11123 settings.update_user_settings(cx, |settings| {
11124 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11125 })
11126 });
11127 item.is_dirty = true;
11128 });
11129 // Blurring the item saves the file.
11130 item.update_in(cx, |_, window, _| window.blur());
11131 cx.executor().run_until_parked();
11132 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11133
11134 // Deactivating the window still saves the file.
11135 item.update_in(cx, |item, window, cx| {
11136 cx.focus_self(window);
11137 item.is_dirty = true;
11138 });
11139 cx.deactivate_window();
11140 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11141
11142 // Autosave after delay.
11143 item.update(cx, |item, cx| {
11144 SettingsStore::update_global(cx, |settings, cx| {
11145 settings.update_user_settings(cx, |settings| {
11146 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11147 milliseconds: 500.into(),
11148 });
11149 })
11150 });
11151 item.is_dirty = true;
11152 cx.emit(ItemEvent::Edit);
11153 });
11154
11155 // Delay hasn't fully expired, so the file is still dirty and unsaved.
11156 cx.executor().advance_clock(Duration::from_millis(250));
11157 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11158
11159 // After delay expires, the file is saved.
11160 cx.executor().advance_clock(Duration::from_millis(250));
11161 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11162
11163 // Autosave after delay, should save earlier than delay if tab is closed
11164 item.update(cx, |item, cx| {
11165 item.is_dirty = true;
11166 cx.emit(ItemEvent::Edit);
11167 });
11168 cx.executor().advance_clock(Duration::from_millis(250));
11169 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11170
11171 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11172 pane.update_in(cx, |pane, window, cx| {
11173 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11174 })
11175 .await
11176 .unwrap();
11177 assert!(!cx.has_pending_prompt());
11178 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11179
11180 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11181 workspace.update_in(cx, |workspace, window, cx| {
11182 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11183 });
11184 item.update_in(cx, |item, _window, cx| {
11185 item.is_dirty = true;
11186 for project_item in &mut item.project_items {
11187 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11188 }
11189 });
11190 cx.run_until_parked();
11191 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11192
11193 // Autosave on focus change, ensuring closing the tab counts as such.
11194 item.update(cx, |item, cx| {
11195 SettingsStore::update_global(cx, |settings, cx| {
11196 settings.update_user_settings(cx, |settings| {
11197 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11198 })
11199 });
11200 item.is_dirty = true;
11201 for project_item in &mut item.project_items {
11202 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11203 }
11204 });
11205
11206 pane.update_in(cx, |pane, window, cx| {
11207 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11208 })
11209 .await
11210 .unwrap();
11211 assert!(!cx.has_pending_prompt());
11212 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11213
11214 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11215 workspace.update_in(cx, |workspace, window, cx| {
11216 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11217 });
11218 item.update_in(cx, |item, window, cx| {
11219 item.project_items[0].update(cx, |item, _| {
11220 item.entry_id = None;
11221 });
11222 item.is_dirty = true;
11223 window.blur();
11224 });
11225 cx.run_until_parked();
11226 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11227
11228 // Ensure autosave is prevented for deleted files also when closing the buffer.
11229 let _close_items = pane.update_in(cx, |pane, window, cx| {
11230 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11231 });
11232 cx.run_until_parked();
11233 assert!(cx.has_pending_prompt());
11234 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11235 }
11236
11237 #[gpui::test]
11238 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11239 init_test(cx);
11240
11241 let fs = FakeFs::new(cx.executor());
11242 let project = Project::test(fs, [], cx).await;
11243 let (workspace, cx) =
11244 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11245
11246 // Create a multibuffer-like item with two child focus handles,
11247 // simulating individual buffer editors within a multibuffer.
11248 let item = cx.new(|cx| {
11249 TestItem::new(cx)
11250 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11251 .with_child_focus_handles(2, cx)
11252 });
11253 workspace.update_in(cx, |workspace, window, cx| {
11254 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11255 });
11256
11257 // Set autosave to OnFocusChange and focus the first child handle,
11258 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11259 item.update_in(cx, |item, window, cx| {
11260 SettingsStore::update_global(cx, |settings, cx| {
11261 settings.update_user_settings(cx, |settings| {
11262 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11263 })
11264 });
11265 item.is_dirty = true;
11266 window.focus(&item.child_focus_handles[0], cx);
11267 });
11268 cx.executor().run_until_parked();
11269 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11270
11271 // Moving focus from one child to another within the same item should
11272 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11273 item.update_in(cx, |item, window, cx| {
11274 window.focus(&item.child_focus_handles[1], cx);
11275 });
11276 cx.executor().run_until_parked();
11277 item.read_with(cx, |item, _| {
11278 assert_eq!(
11279 item.save_count, 0,
11280 "Switching focus between children within the same item should not autosave"
11281 );
11282 });
11283
11284 // Blurring the item saves the file. This is the core regression scenario:
11285 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11286 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11287 // the leaf is always a child focus handle, so `on_blur` never detected
11288 // focus leaving the item.
11289 item.update_in(cx, |_, window, _| window.blur());
11290 cx.executor().run_until_parked();
11291 item.read_with(cx, |item, _| {
11292 assert_eq!(
11293 item.save_count, 1,
11294 "Blurring should trigger autosave when focus was on a child of the item"
11295 );
11296 });
11297
11298 // Deactivating the window should also trigger autosave when a child of
11299 // the multibuffer item currently owns focus.
11300 item.update_in(cx, |item, window, cx| {
11301 item.is_dirty = true;
11302 window.focus(&item.child_focus_handles[0], cx);
11303 });
11304 cx.executor().run_until_parked();
11305 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11306
11307 cx.deactivate_window();
11308 item.read_with(cx, |item, _| {
11309 assert_eq!(
11310 item.save_count, 2,
11311 "Deactivating window should trigger autosave when focus was on a child"
11312 );
11313 });
11314 }
11315
11316 #[gpui::test]
11317 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11318 init_test(cx);
11319
11320 let fs = FakeFs::new(cx.executor());
11321
11322 let project = Project::test(fs, [], cx).await;
11323 let (workspace, cx) =
11324 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11325
11326 let item = cx.new(|cx| {
11327 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11328 });
11329 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11330 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11331 let toolbar_notify_count = Rc::new(RefCell::new(0));
11332
11333 workspace.update_in(cx, |workspace, window, cx| {
11334 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11335 let toolbar_notification_count = toolbar_notify_count.clone();
11336 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11337 *toolbar_notification_count.borrow_mut() += 1
11338 })
11339 .detach();
11340 });
11341
11342 pane.read_with(cx, |pane, _| {
11343 assert!(!pane.can_navigate_backward());
11344 assert!(!pane.can_navigate_forward());
11345 });
11346
11347 item.update_in(cx, |item, _, cx| {
11348 item.set_state("one".to_string(), cx);
11349 });
11350
11351 // Toolbar must be notified to re-render the navigation buttons
11352 assert_eq!(*toolbar_notify_count.borrow(), 1);
11353
11354 pane.read_with(cx, |pane, _| {
11355 assert!(pane.can_navigate_backward());
11356 assert!(!pane.can_navigate_forward());
11357 });
11358
11359 workspace
11360 .update_in(cx, |workspace, window, cx| {
11361 workspace.go_back(pane.downgrade(), window, cx)
11362 })
11363 .await
11364 .unwrap();
11365
11366 assert_eq!(*toolbar_notify_count.borrow(), 2);
11367 pane.read_with(cx, |pane, _| {
11368 assert!(!pane.can_navigate_backward());
11369 assert!(pane.can_navigate_forward());
11370 });
11371 }
11372
11373 /// Tests that the navigation history deduplicates entries for the same item.
11374 ///
11375 /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11376 /// the navigation history deduplicates by keeping only the most recent visit to each item,
11377 /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11378 /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11379 /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11380 ///
11381 /// This behavior prevents the navigation history from growing unnecessarily large and provides
11382 /// a better user experience by eliminating redundant navigation steps when jumping between files.
11383 #[gpui::test]
11384 async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11385 init_test(cx);
11386
11387 let fs = FakeFs::new(cx.executor());
11388 let project = Project::test(fs, [], cx).await;
11389 let (workspace, cx) =
11390 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11391
11392 let item_a = cx.new(|cx| {
11393 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11394 });
11395 let item_b = cx.new(|cx| {
11396 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11397 });
11398 let item_c = cx.new(|cx| {
11399 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11400 });
11401
11402 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11403
11404 workspace.update_in(cx, |workspace, window, cx| {
11405 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11406 workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11407 workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11408 });
11409
11410 workspace.update_in(cx, |workspace, window, cx| {
11411 workspace.activate_item(&item_a, false, false, window, cx);
11412 });
11413 cx.run_until_parked();
11414
11415 workspace.update_in(cx, |workspace, window, cx| {
11416 workspace.activate_item(&item_b, false, false, window, cx);
11417 });
11418 cx.run_until_parked();
11419
11420 workspace.update_in(cx, |workspace, window, cx| {
11421 workspace.activate_item(&item_a, false, false, window, cx);
11422 });
11423 cx.run_until_parked();
11424
11425 workspace.update_in(cx, |workspace, window, cx| {
11426 workspace.activate_item(&item_b, false, false, window, cx);
11427 });
11428 cx.run_until_parked();
11429
11430 workspace.update_in(cx, |workspace, window, cx| {
11431 workspace.activate_item(&item_a, false, false, window, cx);
11432 });
11433 cx.run_until_parked();
11434
11435 workspace.update_in(cx, |workspace, window, cx| {
11436 workspace.activate_item(&item_b, false, false, window, cx);
11437 });
11438 cx.run_until_parked();
11439
11440 workspace.update_in(cx, |workspace, window, cx| {
11441 workspace.activate_item(&item_c, false, false, window, cx);
11442 });
11443 cx.run_until_parked();
11444
11445 let backward_count = pane.read_with(cx, |pane, cx| {
11446 let mut count = 0;
11447 pane.nav_history().for_each_entry(cx, &mut |_, _| {
11448 count += 1;
11449 });
11450 count
11451 });
11452 assert!(
11453 backward_count <= 4,
11454 "Should have at most 4 entries, got {}",
11455 backward_count
11456 );
11457
11458 workspace
11459 .update_in(cx, |workspace, window, cx| {
11460 workspace.go_back(pane.downgrade(), window, cx)
11461 })
11462 .await
11463 .unwrap();
11464
11465 let active_item = workspace.read_with(cx, |workspace, cx| {
11466 workspace.active_item(cx).unwrap().item_id()
11467 });
11468 assert_eq!(
11469 active_item,
11470 item_b.entity_id(),
11471 "After first go_back, should be at item B"
11472 );
11473
11474 workspace
11475 .update_in(cx, |workspace, window, cx| {
11476 workspace.go_back(pane.downgrade(), window, cx)
11477 })
11478 .await
11479 .unwrap();
11480
11481 let active_item = workspace.read_with(cx, |workspace, cx| {
11482 workspace.active_item(cx).unwrap().item_id()
11483 });
11484 assert_eq!(
11485 active_item,
11486 item_a.entity_id(),
11487 "After second go_back, should be at item A"
11488 );
11489
11490 pane.read_with(cx, |pane, _| {
11491 assert!(pane.can_navigate_forward(), "Should be able to go forward");
11492 });
11493 }
11494
11495 #[gpui::test]
11496 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11497 init_test(cx);
11498 let fs = FakeFs::new(cx.executor());
11499 let project = Project::test(fs, [], cx).await;
11500 let (multi_workspace, cx) =
11501 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11502 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11503
11504 workspace.update_in(cx, |workspace, window, cx| {
11505 let first_item = cx.new(|cx| {
11506 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11507 });
11508 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11509 workspace.split_pane(
11510 workspace.active_pane().clone(),
11511 SplitDirection::Right,
11512 window,
11513 cx,
11514 );
11515 workspace.split_pane(
11516 workspace.active_pane().clone(),
11517 SplitDirection::Right,
11518 window,
11519 cx,
11520 );
11521 });
11522
11523 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11524 let panes = workspace.center.panes();
11525 assert!(panes.len() >= 2);
11526 (
11527 panes.first().expect("at least one pane").entity_id(),
11528 panes.last().expect("at least one pane").entity_id(),
11529 )
11530 });
11531
11532 workspace.update_in(cx, |workspace, window, cx| {
11533 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11534 });
11535 workspace.update(cx, |workspace, _| {
11536 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11537 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11538 });
11539
11540 cx.dispatch_action(ActivateLastPane);
11541
11542 workspace.update(cx, |workspace, _| {
11543 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11544 });
11545 }
11546
11547 #[gpui::test]
11548 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11549 init_test(cx);
11550 let fs = FakeFs::new(cx.executor());
11551
11552 let project = Project::test(fs, [], cx).await;
11553 let (workspace, cx) =
11554 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11555
11556 let panel = workspace.update_in(cx, |workspace, window, cx| {
11557 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11558 workspace.add_panel(panel.clone(), window, cx);
11559
11560 workspace
11561 .right_dock()
11562 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11563
11564 panel
11565 });
11566
11567 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11568 pane.update_in(cx, |pane, window, cx| {
11569 let item = cx.new(TestItem::new);
11570 pane.add_item(Box::new(item), true, true, None, window, cx);
11571 });
11572
11573 // Transfer focus from center to panel
11574 workspace.update_in(cx, |workspace, window, cx| {
11575 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11576 });
11577
11578 workspace.update_in(cx, |workspace, window, cx| {
11579 assert!(workspace.right_dock().read(cx).is_open());
11580 assert!(!panel.is_zoomed(window, cx));
11581 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11582 });
11583
11584 // Transfer focus from panel to center
11585 workspace.update_in(cx, |workspace, window, cx| {
11586 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11587 });
11588
11589 workspace.update_in(cx, |workspace, window, cx| {
11590 assert!(workspace.right_dock().read(cx).is_open());
11591 assert!(!panel.is_zoomed(window, cx));
11592 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11593 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11594 });
11595
11596 // Close the dock
11597 workspace.update_in(cx, |workspace, window, cx| {
11598 workspace.toggle_dock(DockPosition::Right, window, cx);
11599 });
11600
11601 workspace.update_in(cx, |workspace, window, cx| {
11602 assert!(!workspace.right_dock().read(cx).is_open());
11603 assert!(!panel.is_zoomed(window, cx));
11604 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11605 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11606 });
11607
11608 // Open the dock
11609 workspace.update_in(cx, |workspace, window, cx| {
11610 workspace.toggle_dock(DockPosition::Right, window, cx);
11611 });
11612
11613 workspace.update_in(cx, |workspace, window, cx| {
11614 assert!(workspace.right_dock().read(cx).is_open());
11615 assert!(!panel.is_zoomed(window, cx));
11616 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11617 });
11618
11619 // Focus and zoom panel
11620 panel.update_in(cx, |panel, window, cx| {
11621 cx.focus_self(window);
11622 panel.set_zoomed(true, window, cx)
11623 });
11624
11625 workspace.update_in(cx, |workspace, window, cx| {
11626 assert!(workspace.right_dock().read(cx).is_open());
11627 assert!(panel.is_zoomed(window, cx));
11628 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11629 });
11630
11631 // Transfer focus to the center closes the dock
11632 workspace.update_in(cx, |workspace, window, cx| {
11633 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11634 });
11635
11636 workspace.update_in(cx, |workspace, window, cx| {
11637 assert!(!workspace.right_dock().read(cx).is_open());
11638 assert!(panel.is_zoomed(window, cx));
11639 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11640 });
11641
11642 // Transferring focus back to the panel keeps it zoomed
11643 workspace.update_in(cx, |workspace, window, cx| {
11644 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11645 });
11646
11647 workspace.update_in(cx, |workspace, window, cx| {
11648 assert!(workspace.right_dock().read(cx).is_open());
11649 assert!(panel.is_zoomed(window, cx));
11650 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11651 });
11652
11653 // Close the dock while it is zoomed
11654 workspace.update_in(cx, |workspace, window, cx| {
11655 workspace.toggle_dock(DockPosition::Right, window, cx)
11656 });
11657
11658 workspace.update_in(cx, |workspace, window, cx| {
11659 assert!(!workspace.right_dock().read(cx).is_open());
11660 assert!(panel.is_zoomed(window, cx));
11661 assert!(workspace.zoomed.is_none());
11662 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11663 });
11664
11665 // Opening the dock, when it's zoomed, retains focus
11666 workspace.update_in(cx, |workspace, window, cx| {
11667 workspace.toggle_dock(DockPosition::Right, window, cx)
11668 });
11669
11670 workspace.update_in(cx, |workspace, window, cx| {
11671 assert!(workspace.right_dock().read(cx).is_open());
11672 assert!(panel.is_zoomed(window, cx));
11673 assert!(workspace.zoomed.is_some());
11674 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11675 });
11676
11677 // Unzoom and close the panel, zoom the active pane.
11678 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11679 workspace.update_in(cx, |workspace, window, cx| {
11680 workspace.toggle_dock(DockPosition::Right, window, cx)
11681 });
11682 pane.update_in(cx, |pane, window, cx| {
11683 pane.toggle_zoom(&Default::default(), window, cx)
11684 });
11685
11686 // Opening a dock unzooms the pane.
11687 workspace.update_in(cx, |workspace, window, cx| {
11688 workspace.toggle_dock(DockPosition::Right, window, cx)
11689 });
11690 workspace.update_in(cx, |workspace, window, cx| {
11691 let pane = pane.read(cx);
11692 assert!(!pane.is_zoomed());
11693 assert!(!pane.focus_handle(cx).is_focused(window));
11694 assert!(workspace.right_dock().read(cx).is_open());
11695 assert!(workspace.zoomed.is_none());
11696 });
11697 }
11698
11699 #[gpui::test]
11700 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11701 init_test(cx);
11702 let fs = FakeFs::new(cx.executor());
11703
11704 let project = Project::test(fs, [], cx).await;
11705 let (workspace, cx) =
11706 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11707
11708 let panel = workspace.update_in(cx, |workspace, window, cx| {
11709 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11710 workspace.add_panel(panel.clone(), window, cx);
11711 panel
11712 });
11713
11714 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11715 pane.update_in(cx, |pane, window, cx| {
11716 let item = cx.new(TestItem::new);
11717 pane.add_item(Box::new(item), true, true, None, window, cx);
11718 });
11719
11720 // Enable close_panel_on_toggle
11721 cx.update_global(|store: &mut SettingsStore, cx| {
11722 store.update_user_settings(cx, |settings| {
11723 settings.workspace.close_panel_on_toggle = Some(true);
11724 });
11725 });
11726
11727 // Panel starts closed. Toggling should open and focus it.
11728 workspace.update_in(cx, |workspace, window, cx| {
11729 assert!(!workspace.right_dock().read(cx).is_open());
11730 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11731 });
11732
11733 workspace.update_in(cx, |workspace, window, cx| {
11734 assert!(
11735 workspace.right_dock().read(cx).is_open(),
11736 "Dock should be open after toggling from center"
11737 );
11738 assert!(
11739 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11740 "Panel should be focused after toggling from center"
11741 );
11742 });
11743
11744 // Panel is open and focused. Toggling should close the panel and
11745 // return focus to the center.
11746 workspace.update_in(cx, |workspace, window, cx| {
11747 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11748 });
11749
11750 workspace.update_in(cx, |workspace, window, cx| {
11751 assert!(
11752 !workspace.right_dock().read(cx).is_open(),
11753 "Dock should be closed after toggling from focused panel"
11754 );
11755 assert!(
11756 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11757 "Panel should not be focused after toggling from focused panel"
11758 );
11759 });
11760
11761 // Open the dock and focus something else so the panel is open but not
11762 // focused. Toggling should focus the panel (not close it).
11763 workspace.update_in(cx, |workspace, window, cx| {
11764 workspace
11765 .right_dock()
11766 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11767 window.focus(&pane.read(cx).focus_handle(cx), cx);
11768 });
11769
11770 workspace.update_in(cx, |workspace, window, cx| {
11771 assert!(workspace.right_dock().read(cx).is_open());
11772 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11773 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11774 });
11775
11776 workspace.update_in(cx, |workspace, window, cx| {
11777 assert!(
11778 workspace.right_dock().read(cx).is_open(),
11779 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11780 );
11781 assert!(
11782 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11783 "Panel should be focused after toggling an open-but-unfocused panel"
11784 );
11785 });
11786
11787 // Now disable the setting and verify the original behavior: toggling
11788 // from a focused panel moves focus to center but leaves the dock open.
11789 cx.update_global(|store: &mut SettingsStore, cx| {
11790 store.update_user_settings(cx, |settings| {
11791 settings.workspace.close_panel_on_toggle = Some(false);
11792 });
11793 });
11794
11795 workspace.update_in(cx, |workspace, window, cx| {
11796 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11797 });
11798
11799 workspace.update_in(cx, |workspace, window, cx| {
11800 assert!(
11801 workspace.right_dock().read(cx).is_open(),
11802 "Dock should remain open when setting is disabled"
11803 );
11804 assert!(
11805 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11806 "Panel should not be focused after toggling with setting disabled"
11807 );
11808 });
11809 }
11810
11811 #[gpui::test]
11812 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11813 init_test(cx);
11814 let fs = FakeFs::new(cx.executor());
11815
11816 let project = Project::test(fs, [], cx).await;
11817 let (workspace, cx) =
11818 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11819
11820 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11821 workspace.active_pane().clone()
11822 });
11823
11824 // Add an item to the pane so it can be zoomed
11825 workspace.update_in(cx, |workspace, window, cx| {
11826 let item = cx.new(TestItem::new);
11827 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11828 });
11829
11830 // Initially not zoomed
11831 workspace.update_in(cx, |workspace, _window, cx| {
11832 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11833 assert!(
11834 workspace.zoomed.is_none(),
11835 "Workspace should track no zoomed pane"
11836 );
11837 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11838 });
11839
11840 // Zoom In
11841 pane.update_in(cx, |pane, window, cx| {
11842 pane.zoom_in(&crate::ZoomIn, window, cx);
11843 });
11844
11845 workspace.update_in(cx, |workspace, window, cx| {
11846 assert!(
11847 pane.read(cx).is_zoomed(),
11848 "Pane should be zoomed after ZoomIn"
11849 );
11850 assert!(
11851 workspace.zoomed.is_some(),
11852 "Workspace should track the zoomed pane"
11853 );
11854 assert!(
11855 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11856 "ZoomIn should focus the pane"
11857 );
11858 });
11859
11860 // Zoom In again is a no-op
11861 pane.update_in(cx, |pane, window, cx| {
11862 pane.zoom_in(&crate::ZoomIn, window, cx);
11863 });
11864
11865 workspace.update_in(cx, |workspace, window, cx| {
11866 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11867 assert!(
11868 workspace.zoomed.is_some(),
11869 "Workspace still tracks zoomed pane"
11870 );
11871 assert!(
11872 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11873 "Pane remains focused after repeated ZoomIn"
11874 );
11875 });
11876
11877 // Zoom Out
11878 pane.update_in(cx, |pane, window, cx| {
11879 pane.zoom_out(&crate::ZoomOut, window, cx);
11880 });
11881
11882 workspace.update_in(cx, |workspace, _window, cx| {
11883 assert!(
11884 !pane.read(cx).is_zoomed(),
11885 "Pane should unzoom after ZoomOut"
11886 );
11887 assert!(
11888 workspace.zoomed.is_none(),
11889 "Workspace clears zoom tracking after ZoomOut"
11890 );
11891 });
11892
11893 // Zoom Out again is a no-op
11894 pane.update_in(cx, |pane, window, cx| {
11895 pane.zoom_out(&crate::ZoomOut, window, cx);
11896 });
11897
11898 workspace.update_in(cx, |workspace, _window, cx| {
11899 assert!(
11900 !pane.read(cx).is_zoomed(),
11901 "Second ZoomOut keeps pane unzoomed"
11902 );
11903 assert!(
11904 workspace.zoomed.is_none(),
11905 "Workspace remains without zoomed pane"
11906 );
11907 });
11908 }
11909
11910 #[gpui::test]
11911 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11912 init_test(cx);
11913 let fs = FakeFs::new(cx.executor());
11914
11915 let project = Project::test(fs, [], cx).await;
11916 let (workspace, cx) =
11917 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11918 workspace.update_in(cx, |workspace, window, cx| {
11919 // Open two docks
11920 let left_dock = workspace.dock_at_position(DockPosition::Left);
11921 let right_dock = workspace.dock_at_position(DockPosition::Right);
11922
11923 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11924 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11925
11926 assert!(left_dock.read(cx).is_open());
11927 assert!(right_dock.read(cx).is_open());
11928 });
11929
11930 workspace.update_in(cx, |workspace, window, cx| {
11931 // Toggle all docks - should close both
11932 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11933
11934 let left_dock = workspace.dock_at_position(DockPosition::Left);
11935 let right_dock = workspace.dock_at_position(DockPosition::Right);
11936 assert!(!left_dock.read(cx).is_open());
11937 assert!(!right_dock.read(cx).is_open());
11938 });
11939
11940 workspace.update_in(cx, |workspace, window, cx| {
11941 // Toggle again - should reopen both
11942 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11943
11944 let left_dock = workspace.dock_at_position(DockPosition::Left);
11945 let right_dock = workspace.dock_at_position(DockPosition::Right);
11946 assert!(left_dock.read(cx).is_open());
11947 assert!(right_dock.read(cx).is_open());
11948 });
11949 }
11950
11951 #[gpui::test]
11952 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11953 init_test(cx);
11954 let fs = FakeFs::new(cx.executor());
11955
11956 let project = Project::test(fs, [], cx).await;
11957 let (workspace, cx) =
11958 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11959 workspace.update_in(cx, |workspace, window, cx| {
11960 // Open two docks
11961 let left_dock = workspace.dock_at_position(DockPosition::Left);
11962 let right_dock = workspace.dock_at_position(DockPosition::Right);
11963
11964 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11965 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11966
11967 assert!(left_dock.read(cx).is_open());
11968 assert!(right_dock.read(cx).is_open());
11969 });
11970
11971 workspace.update_in(cx, |workspace, window, cx| {
11972 // Close them manually
11973 workspace.toggle_dock(DockPosition::Left, window, cx);
11974 workspace.toggle_dock(DockPosition::Right, window, cx);
11975
11976 let left_dock = workspace.dock_at_position(DockPosition::Left);
11977 let right_dock = workspace.dock_at_position(DockPosition::Right);
11978 assert!(!left_dock.read(cx).is_open());
11979 assert!(!right_dock.read(cx).is_open());
11980 });
11981
11982 workspace.update_in(cx, |workspace, window, cx| {
11983 // Toggle all docks - only last closed (right dock) should reopen
11984 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11985
11986 let left_dock = workspace.dock_at_position(DockPosition::Left);
11987 let right_dock = workspace.dock_at_position(DockPosition::Right);
11988 assert!(!left_dock.read(cx).is_open());
11989 assert!(right_dock.read(cx).is_open());
11990 });
11991 }
11992
11993 #[gpui::test]
11994 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11995 init_test(cx);
11996 let fs = FakeFs::new(cx.executor());
11997 let project = Project::test(fs, [], cx).await;
11998 let (multi_workspace, cx) =
11999 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12000 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12001
12002 // Open two docks (left and right) with one panel each
12003 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12004 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12005 workspace.add_panel(left_panel.clone(), window, cx);
12006
12007 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12008 workspace.add_panel(right_panel.clone(), window, cx);
12009
12010 workspace.toggle_dock(DockPosition::Left, window, cx);
12011 workspace.toggle_dock(DockPosition::Right, window, cx);
12012
12013 // Verify initial state
12014 assert!(
12015 workspace.left_dock().read(cx).is_open(),
12016 "Left dock should be open"
12017 );
12018 assert_eq!(
12019 workspace
12020 .left_dock()
12021 .read(cx)
12022 .visible_panel()
12023 .unwrap()
12024 .panel_id(),
12025 left_panel.panel_id(),
12026 "Left panel should be visible in left dock"
12027 );
12028 assert!(
12029 workspace.right_dock().read(cx).is_open(),
12030 "Right dock should be open"
12031 );
12032 assert_eq!(
12033 workspace
12034 .right_dock()
12035 .read(cx)
12036 .visible_panel()
12037 .unwrap()
12038 .panel_id(),
12039 right_panel.panel_id(),
12040 "Right panel should be visible in right dock"
12041 );
12042 assert!(
12043 !workspace.bottom_dock().read(cx).is_open(),
12044 "Bottom dock should be closed"
12045 );
12046
12047 (left_panel, right_panel)
12048 });
12049
12050 // Focus the left panel and move it to the next position (bottom dock)
12051 workspace.update_in(cx, |workspace, window, cx| {
12052 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12053 assert!(
12054 left_panel.read(cx).focus_handle(cx).is_focused(window),
12055 "Left panel should be focused"
12056 );
12057 });
12058
12059 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12060
12061 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12062 workspace.update(cx, |workspace, cx| {
12063 assert!(
12064 !workspace.left_dock().read(cx).is_open(),
12065 "Left dock should be closed"
12066 );
12067 assert!(
12068 workspace.bottom_dock().read(cx).is_open(),
12069 "Bottom dock should now be open"
12070 );
12071 assert_eq!(
12072 left_panel.read(cx).position,
12073 DockPosition::Bottom,
12074 "Left panel should now be in the bottom dock"
12075 );
12076 assert_eq!(
12077 workspace
12078 .bottom_dock()
12079 .read(cx)
12080 .visible_panel()
12081 .unwrap()
12082 .panel_id(),
12083 left_panel.panel_id(),
12084 "Left panel should be the visible panel in the bottom dock"
12085 );
12086 });
12087
12088 // Toggle all docks off
12089 workspace.update_in(cx, |workspace, window, cx| {
12090 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12091 assert!(
12092 !workspace.left_dock().read(cx).is_open(),
12093 "Left dock should be closed"
12094 );
12095 assert!(
12096 !workspace.right_dock().read(cx).is_open(),
12097 "Right dock should be closed"
12098 );
12099 assert!(
12100 !workspace.bottom_dock().read(cx).is_open(),
12101 "Bottom dock should be closed"
12102 );
12103 });
12104
12105 // Toggle all docks back on and verify positions are restored
12106 workspace.update_in(cx, |workspace, window, cx| {
12107 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12108 assert!(
12109 !workspace.left_dock().read(cx).is_open(),
12110 "Left dock should remain closed"
12111 );
12112 assert!(
12113 workspace.right_dock().read(cx).is_open(),
12114 "Right dock should remain open"
12115 );
12116 assert!(
12117 workspace.bottom_dock().read(cx).is_open(),
12118 "Bottom dock should remain open"
12119 );
12120 assert_eq!(
12121 left_panel.read(cx).position,
12122 DockPosition::Bottom,
12123 "Left panel should remain in the bottom dock"
12124 );
12125 assert_eq!(
12126 right_panel.read(cx).position,
12127 DockPosition::Right,
12128 "Right panel should remain in the right dock"
12129 );
12130 assert_eq!(
12131 workspace
12132 .bottom_dock()
12133 .read(cx)
12134 .visible_panel()
12135 .unwrap()
12136 .panel_id(),
12137 left_panel.panel_id(),
12138 "Left panel should be the visible panel in the right dock"
12139 );
12140 });
12141 }
12142
12143 #[gpui::test]
12144 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12145 init_test(cx);
12146
12147 let fs = FakeFs::new(cx.executor());
12148
12149 let project = Project::test(fs, None, cx).await;
12150 let (workspace, cx) =
12151 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12152
12153 // Let's arrange the panes like this:
12154 //
12155 // +-----------------------+
12156 // | top |
12157 // +------+--------+-------+
12158 // | left | center | right |
12159 // +------+--------+-------+
12160 // | bottom |
12161 // +-----------------------+
12162
12163 let top_item = cx.new(|cx| {
12164 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12165 });
12166 let bottom_item = cx.new(|cx| {
12167 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12168 });
12169 let left_item = cx.new(|cx| {
12170 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12171 });
12172 let right_item = cx.new(|cx| {
12173 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12174 });
12175 let center_item = cx.new(|cx| {
12176 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12177 });
12178
12179 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12180 let top_pane_id = workspace.active_pane().entity_id();
12181 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12182 workspace.split_pane(
12183 workspace.active_pane().clone(),
12184 SplitDirection::Down,
12185 window,
12186 cx,
12187 );
12188 top_pane_id
12189 });
12190 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12191 let bottom_pane_id = workspace.active_pane().entity_id();
12192 workspace.add_item_to_active_pane(
12193 Box::new(bottom_item.clone()),
12194 None,
12195 false,
12196 window,
12197 cx,
12198 );
12199 workspace.split_pane(
12200 workspace.active_pane().clone(),
12201 SplitDirection::Up,
12202 window,
12203 cx,
12204 );
12205 bottom_pane_id
12206 });
12207 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12208 let left_pane_id = workspace.active_pane().entity_id();
12209 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12210 workspace.split_pane(
12211 workspace.active_pane().clone(),
12212 SplitDirection::Right,
12213 window,
12214 cx,
12215 );
12216 left_pane_id
12217 });
12218 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12219 let right_pane_id = workspace.active_pane().entity_id();
12220 workspace.add_item_to_active_pane(
12221 Box::new(right_item.clone()),
12222 None,
12223 false,
12224 window,
12225 cx,
12226 );
12227 workspace.split_pane(
12228 workspace.active_pane().clone(),
12229 SplitDirection::Left,
12230 window,
12231 cx,
12232 );
12233 right_pane_id
12234 });
12235 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12236 let center_pane_id = workspace.active_pane().entity_id();
12237 workspace.add_item_to_active_pane(
12238 Box::new(center_item.clone()),
12239 None,
12240 false,
12241 window,
12242 cx,
12243 );
12244 center_pane_id
12245 });
12246 cx.executor().run_until_parked();
12247
12248 workspace.update_in(cx, |workspace, window, cx| {
12249 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12250
12251 // Join into next from center pane into right
12252 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12253 });
12254
12255 workspace.update_in(cx, |workspace, window, cx| {
12256 let active_pane = workspace.active_pane();
12257 assert_eq!(right_pane_id, active_pane.entity_id());
12258 assert_eq!(2, active_pane.read(cx).items_len());
12259 let item_ids_in_pane =
12260 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12261 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12262 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12263
12264 // Join into next from right pane into bottom
12265 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12266 });
12267
12268 workspace.update_in(cx, |workspace, window, cx| {
12269 let active_pane = workspace.active_pane();
12270 assert_eq!(bottom_pane_id, active_pane.entity_id());
12271 assert_eq!(3, active_pane.read(cx).items_len());
12272 let item_ids_in_pane =
12273 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12274 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12275 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12276 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12277
12278 // Join into next from bottom pane into left
12279 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12280 });
12281
12282 workspace.update_in(cx, |workspace, window, cx| {
12283 let active_pane = workspace.active_pane();
12284 assert_eq!(left_pane_id, active_pane.entity_id());
12285 assert_eq!(4, active_pane.read(cx).items_len());
12286 let item_ids_in_pane =
12287 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12288 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12289 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12290 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12291 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12292
12293 // Join into next from left pane into top
12294 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12295 });
12296
12297 workspace.update_in(cx, |workspace, window, cx| {
12298 let active_pane = workspace.active_pane();
12299 assert_eq!(top_pane_id, active_pane.entity_id());
12300 assert_eq!(5, active_pane.read(cx).items_len());
12301 let item_ids_in_pane =
12302 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12303 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12304 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12305 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12306 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12307 assert!(item_ids_in_pane.contains(&top_item.item_id()));
12308
12309 // Single pane left: no-op
12310 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12311 });
12312
12313 workspace.update(cx, |workspace, _cx| {
12314 let active_pane = workspace.active_pane();
12315 assert_eq!(top_pane_id, active_pane.entity_id());
12316 });
12317 }
12318
12319 fn add_an_item_to_active_pane(
12320 cx: &mut VisualTestContext,
12321 workspace: &Entity<Workspace>,
12322 item_id: u64,
12323 ) -> Entity<TestItem> {
12324 let item = cx.new(|cx| {
12325 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12326 item_id,
12327 "item{item_id}.txt",
12328 cx,
12329 )])
12330 });
12331 workspace.update_in(cx, |workspace, window, cx| {
12332 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12333 });
12334 item
12335 }
12336
12337 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12338 workspace.update_in(cx, |workspace, window, cx| {
12339 workspace.split_pane(
12340 workspace.active_pane().clone(),
12341 SplitDirection::Right,
12342 window,
12343 cx,
12344 )
12345 })
12346 }
12347
12348 #[gpui::test]
12349 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12350 init_test(cx);
12351 let fs = FakeFs::new(cx.executor());
12352 let project = Project::test(fs, None, cx).await;
12353 let (workspace, cx) =
12354 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12355
12356 add_an_item_to_active_pane(cx, &workspace, 1);
12357 split_pane(cx, &workspace);
12358 add_an_item_to_active_pane(cx, &workspace, 2);
12359 split_pane(cx, &workspace); // empty pane
12360 split_pane(cx, &workspace);
12361 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12362
12363 cx.executor().run_until_parked();
12364
12365 workspace.update(cx, |workspace, cx| {
12366 let num_panes = workspace.panes().len();
12367 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12368 let active_item = workspace
12369 .active_pane()
12370 .read(cx)
12371 .active_item()
12372 .expect("item is in focus");
12373
12374 assert_eq!(num_panes, 4);
12375 assert_eq!(num_items_in_current_pane, 1);
12376 assert_eq!(active_item.item_id(), last_item.item_id());
12377 });
12378
12379 workspace.update_in(cx, |workspace, window, cx| {
12380 workspace.join_all_panes(window, cx);
12381 });
12382
12383 workspace.update(cx, |workspace, cx| {
12384 let num_panes = workspace.panes().len();
12385 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12386 let active_item = workspace
12387 .active_pane()
12388 .read(cx)
12389 .active_item()
12390 .expect("item is in focus");
12391
12392 assert_eq!(num_panes, 1);
12393 assert_eq!(num_items_in_current_pane, 3);
12394 assert_eq!(active_item.item_id(), last_item.item_id());
12395 });
12396 }
12397
12398 #[gpui::test]
12399 async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12400 init_test(cx);
12401 let fs = FakeFs::new(cx.executor());
12402
12403 let project = Project::test(fs, [], cx).await;
12404 let (multi_workspace, cx) =
12405 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12406 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12407
12408 workspace.update(cx, |workspace, _cx| {
12409 workspace.bounds.size.width = px(800.);
12410 });
12411
12412 workspace.update_in(cx, |workspace, window, cx| {
12413 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12414 workspace.add_panel(panel, window, cx);
12415 workspace.toggle_dock(DockPosition::Right, window, cx);
12416 });
12417
12418 let (panel, resized_width, ratio_basis_width) =
12419 workspace.update_in(cx, |workspace, window, cx| {
12420 let item = cx.new(|cx| {
12421 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12422 });
12423 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12424
12425 let dock = workspace.right_dock().read(cx);
12426 let workspace_width = workspace.bounds.size.width;
12427 let initial_width = workspace
12428 .dock_size(&dock, window, cx)
12429 .expect("flexible dock should have an initial width");
12430
12431 assert_eq!(initial_width, workspace_width / 2.);
12432
12433 workspace.resize_right_dock(px(300.), window, cx);
12434
12435 let dock = workspace.right_dock().read(cx);
12436 let resized_width = workspace
12437 .dock_size(&dock, window, cx)
12438 .expect("flexible dock should keep its resized width");
12439
12440 assert_eq!(resized_width, px(300.));
12441
12442 let panel = workspace
12443 .right_dock()
12444 .read(cx)
12445 .visible_panel()
12446 .expect("flexible dock should have a visible panel")
12447 .panel_id();
12448
12449 (panel, resized_width, workspace_width)
12450 });
12451
12452 workspace.update_in(cx, |workspace, window, cx| {
12453 workspace.toggle_dock(DockPosition::Right, window, cx);
12454 workspace.toggle_dock(DockPosition::Right, window, cx);
12455
12456 let dock = workspace.right_dock().read(cx);
12457 let reopened_width = workspace
12458 .dock_size(&dock, window, cx)
12459 .expect("flexible dock should restore when reopened");
12460
12461 assert_eq!(reopened_width, resized_width);
12462
12463 let right_dock = workspace.right_dock().read(cx);
12464 let flexible_panel = right_dock
12465 .visible_panel()
12466 .expect("flexible dock should still have a visible panel");
12467 assert_eq!(flexible_panel.panel_id(), panel);
12468 assert_eq!(
12469 right_dock
12470 .stored_panel_size_state(flexible_panel.as_ref())
12471 .and_then(|size_state| size_state.flex),
12472 Some(
12473 resized_width.to_f64() as f32
12474 / (workspace.bounds.size.width - resized_width).to_f64() as f32
12475 )
12476 );
12477 });
12478
12479 workspace.update_in(cx, |workspace, window, cx| {
12480 workspace.split_pane(
12481 workspace.active_pane().clone(),
12482 SplitDirection::Right,
12483 window,
12484 cx,
12485 );
12486
12487 let dock = workspace.right_dock().read(cx);
12488 let split_width = workspace
12489 .dock_size(&dock, window, cx)
12490 .expect("flexible dock should keep its user-resized proportion");
12491
12492 assert_eq!(split_width, px(300.));
12493
12494 workspace.bounds.size.width = px(1600.);
12495
12496 let dock = workspace.right_dock().read(cx);
12497 let resized_window_width = workspace
12498 .dock_size(&dock, window, cx)
12499 .expect("flexible dock should preserve proportional size on window resize");
12500
12501 assert_eq!(
12502 resized_window_width,
12503 workspace.bounds.size.width
12504 * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12505 );
12506 });
12507 }
12508
12509 #[gpui::test]
12510 async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12511 init_test(cx);
12512 let fs = FakeFs::new(cx.executor());
12513
12514 // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12515 {
12516 let project = Project::test(fs.clone(), [], cx).await;
12517 let (multi_workspace, cx) =
12518 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12519 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12520
12521 workspace.update(cx, |workspace, _cx| {
12522 workspace.set_random_database_id();
12523 workspace.bounds.size.width = px(800.);
12524 });
12525
12526 let panel = workspace.update_in(cx, |workspace, window, cx| {
12527 let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12528 workspace.add_panel(panel.clone(), window, cx);
12529 workspace.toggle_dock(DockPosition::Left, window, cx);
12530 panel
12531 });
12532
12533 workspace.update_in(cx, |workspace, window, cx| {
12534 workspace.resize_left_dock(px(350.), window, cx);
12535 });
12536
12537 cx.run_until_parked();
12538
12539 let persisted = workspace.read_with(cx, |workspace, cx| {
12540 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12541 });
12542 assert_eq!(
12543 persisted.and_then(|s| s.size),
12544 Some(px(350.)),
12545 "fixed-width panel size should be persisted to KVP"
12546 );
12547
12548 // Remove the panel and re-add a fresh instance with the same key.
12549 // The new instance should have its size state restored from KVP.
12550 workspace.update_in(cx, |workspace, window, cx| {
12551 workspace.remove_panel(&panel, window, cx);
12552 });
12553
12554 workspace.update_in(cx, |workspace, window, cx| {
12555 let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12556 workspace.add_panel(new_panel, window, cx);
12557
12558 let left_dock = workspace.left_dock().read(cx);
12559 let size_state = left_dock
12560 .panel::<TestPanel>()
12561 .and_then(|p| left_dock.stored_panel_size_state(&p));
12562 assert_eq!(
12563 size_state.and_then(|s| s.size),
12564 Some(px(350.)),
12565 "re-added fixed-width panel should restore persisted size from KVP"
12566 );
12567 });
12568 }
12569
12570 // Flexible panel: both pixel size and ratio are persisted and restored.
12571 {
12572 let project = Project::test(fs.clone(), [], cx).await;
12573 let (multi_workspace, cx) =
12574 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12575 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12576
12577 workspace.update(cx, |workspace, _cx| {
12578 workspace.set_random_database_id();
12579 workspace.bounds.size.width = px(800.);
12580 });
12581
12582 let panel = workspace.update_in(cx, |workspace, window, cx| {
12583 let item = cx.new(|cx| {
12584 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12585 });
12586 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12587
12588 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12589 workspace.add_panel(panel.clone(), window, cx);
12590 workspace.toggle_dock(DockPosition::Right, window, cx);
12591 panel
12592 });
12593
12594 workspace.update_in(cx, |workspace, window, cx| {
12595 workspace.resize_right_dock(px(300.), window, cx);
12596 });
12597
12598 cx.run_until_parked();
12599
12600 let persisted = workspace
12601 .read_with(cx, |workspace, cx| {
12602 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12603 })
12604 .expect("flexible panel state should be persisted to KVP");
12605 assert_eq!(
12606 persisted.size, None,
12607 "flexible panel should not persist a redundant pixel size"
12608 );
12609 let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12610
12611 // Remove the panel and re-add: both size and ratio should be restored.
12612 workspace.update_in(cx, |workspace, window, cx| {
12613 workspace.remove_panel(&panel, window, cx);
12614 });
12615
12616 workspace.update_in(cx, |workspace, window, cx| {
12617 let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12618 workspace.add_panel(new_panel, window, cx);
12619
12620 let right_dock = workspace.right_dock().read(cx);
12621 let size_state = right_dock
12622 .panel::<TestPanel>()
12623 .and_then(|p| right_dock.stored_panel_size_state(&p))
12624 .expect("re-added flexible panel should have restored size state from KVP");
12625 assert_eq!(
12626 size_state.size, None,
12627 "re-added flexible panel should not have a persisted pixel size"
12628 );
12629 assert_eq!(
12630 size_state.flex,
12631 Some(original_ratio),
12632 "re-added flexible panel should restore persisted flex"
12633 );
12634 });
12635 }
12636 }
12637
12638 #[gpui::test]
12639 async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12640 init_test(cx);
12641 let fs = FakeFs::new(cx.executor());
12642
12643 let project = Project::test(fs, [], cx).await;
12644 let (multi_workspace, cx) =
12645 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12646 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12647
12648 workspace.update(cx, |workspace, _cx| {
12649 workspace.bounds.size.width = px(900.);
12650 });
12651
12652 // Step 1: Add a tab to the center pane then open a flexible panel in the left
12653 // dock. With one full-width center pane the default ratio is 0.5, so the panel
12654 // and the center pane each take half the workspace width.
12655 workspace.update_in(cx, |workspace, window, cx| {
12656 let item = cx.new(|cx| {
12657 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12658 });
12659 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12660
12661 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12662 workspace.add_panel(panel, window, cx);
12663 workspace.toggle_dock(DockPosition::Left, window, cx);
12664
12665 let left_dock = workspace.left_dock().read(cx);
12666 let left_width = workspace
12667 .dock_size(&left_dock, window, cx)
12668 .expect("left dock should have an active panel");
12669
12670 assert_eq!(
12671 left_width,
12672 workspace.bounds.size.width / 2.,
12673 "flexible left panel should split evenly with the center pane"
12674 );
12675 });
12676
12677 // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12678 // change horizontal width fractions, so the flexible panel stays at the same
12679 // width as each half of the split.
12680 workspace.update_in(cx, |workspace, window, cx| {
12681 workspace.split_pane(
12682 workspace.active_pane().clone(),
12683 SplitDirection::Down,
12684 window,
12685 cx,
12686 );
12687
12688 let left_dock = workspace.left_dock().read(cx);
12689 let left_width = workspace
12690 .dock_size(&left_dock, window, cx)
12691 .expect("left dock should still have an active panel after vertical split");
12692
12693 assert_eq!(
12694 left_width,
12695 workspace.bounds.size.width / 2.,
12696 "flexible left panel width should match each vertically-split pane"
12697 );
12698 });
12699
12700 // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12701 // size reduces the available width, so the flexible left panel and the center
12702 // panes all shrink proportionally to accommodate it.
12703 workspace.update_in(cx, |workspace, window, cx| {
12704 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12705 workspace.add_panel(panel, window, cx);
12706 workspace.toggle_dock(DockPosition::Right, window, cx);
12707
12708 let right_dock = workspace.right_dock().read(cx);
12709 let right_width = workspace
12710 .dock_size(&right_dock, window, cx)
12711 .expect("right dock should have an active panel");
12712
12713 let left_dock = workspace.left_dock().read(cx);
12714 let left_width = workspace
12715 .dock_size(&left_dock, window, cx)
12716 .expect("left dock should still have an active panel");
12717
12718 let available_width = workspace.bounds.size.width - right_width;
12719 assert_eq!(
12720 left_width,
12721 available_width / 2.,
12722 "flexible left panel should shrink proportionally as the right dock takes space"
12723 );
12724 });
12725
12726 // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12727 // flex sizing and the workspace width is divided among left-flex, center
12728 // (implicit flex 1.0), and right-flex.
12729 workspace.update_in(cx, |workspace, window, cx| {
12730 let right_dock = workspace.right_dock().clone();
12731 let right_panel = right_dock
12732 .read(cx)
12733 .visible_panel()
12734 .expect("right dock should have a visible panel")
12735 .clone();
12736 workspace.toggle_dock_panel_flexible_size(
12737 &right_dock,
12738 right_panel.as_ref(),
12739 window,
12740 cx,
12741 );
12742
12743 let right_dock = right_dock.read(cx);
12744 let right_panel = right_dock
12745 .visible_panel()
12746 .expect("right dock should still have a visible panel");
12747 assert!(
12748 right_panel.has_flexible_size(window, cx),
12749 "right panel should now be flexible"
12750 );
12751
12752 let right_size_state = right_dock
12753 .stored_panel_size_state(right_panel.as_ref())
12754 .expect("right panel should have a stored size state after toggling");
12755 let right_flex = right_size_state
12756 .flex
12757 .expect("right panel should have a flex value after toggling");
12758
12759 let left_dock = workspace.left_dock().read(cx);
12760 let left_width = workspace
12761 .dock_size(&left_dock, window, cx)
12762 .expect("left dock should still have an active panel");
12763 let right_width = workspace
12764 .dock_size(&right_dock, window, cx)
12765 .expect("right dock should still have an active panel");
12766
12767 let left_flex = workspace
12768 .default_dock_flex(DockPosition::Left)
12769 .expect("left dock should have a default flex");
12770
12771 let total_flex = left_flex + 1.0 + right_flex;
12772 let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12773 let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12774 assert_eq!(
12775 left_width, expected_left,
12776 "flexible left panel should share workspace width via flex ratios"
12777 );
12778 assert_eq!(
12779 right_width, expected_right,
12780 "flexible right panel should share workspace width via flex ratios"
12781 );
12782 });
12783 }
12784
12785 struct TestModal(FocusHandle);
12786
12787 impl TestModal {
12788 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12789 Self(cx.focus_handle())
12790 }
12791 }
12792
12793 impl EventEmitter<DismissEvent> for TestModal {}
12794
12795 impl Focusable for TestModal {
12796 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12797 self.0.clone()
12798 }
12799 }
12800
12801 impl ModalView for TestModal {}
12802
12803 impl Render for TestModal {
12804 fn render(
12805 &mut self,
12806 _window: &mut Window,
12807 _cx: &mut Context<TestModal>,
12808 ) -> impl IntoElement {
12809 div().track_focus(&self.0)
12810 }
12811 }
12812
12813 #[gpui::test]
12814 async fn test_panels(cx: &mut gpui::TestAppContext) {
12815 init_test(cx);
12816 let fs = FakeFs::new(cx.executor());
12817
12818 let project = Project::test(fs, [], cx).await;
12819 let (multi_workspace, cx) =
12820 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12821 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12822
12823 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12824 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12825 workspace.add_panel(panel_1.clone(), window, cx);
12826 workspace.toggle_dock(DockPosition::Left, window, cx);
12827 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12828 workspace.add_panel(panel_2.clone(), window, cx);
12829 workspace.toggle_dock(DockPosition::Right, window, cx);
12830
12831 let left_dock = workspace.left_dock();
12832 assert_eq!(
12833 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12834 panel_1.panel_id()
12835 );
12836 assert_eq!(
12837 workspace.dock_size(&left_dock.read(cx), window, cx),
12838 Some(px(300.))
12839 );
12840
12841 workspace.resize_left_dock(px(1337.), window, cx);
12842 assert_eq!(
12843 workspace
12844 .right_dock()
12845 .read(cx)
12846 .visible_panel()
12847 .unwrap()
12848 .panel_id(),
12849 panel_2.panel_id(),
12850 );
12851
12852 (panel_1, panel_2)
12853 });
12854
12855 // Move panel_1 to the right
12856 panel_1.update_in(cx, |panel_1, window, cx| {
12857 panel_1.set_position(DockPosition::Right, window, cx)
12858 });
12859
12860 workspace.update_in(cx, |workspace, window, cx| {
12861 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12862 // Since it was the only panel on the left, the left dock should now be closed.
12863 assert!(!workspace.left_dock().read(cx).is_open());
12864 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12865 let right_dock = workspace.right_dock();
12866 assert_eq!(
12867 right_dock.read(cx).visible_panel().unwrap().panel_id(),
12868 panel_1.panel_id()
12869 );
12870 assert_eq!(
12871 right_dock
12872 .read(cx)
12873 .active_panel_size()
12874 .unwrap()
12875 .size
12876 .unwrap(),
12877 px(1337.)
12878 );
12879
12880 // Now we move panel_2 to the left
12881 panel_2.set_position(DockPosition::Left, window, cx);
12882 });
12883
12884 workspace.update(cx, |workspace, cx| {
12885 // Since panel_2 was not visible on the right, we don't open the left dock.
12886 assert!(!workspace.left_dock().read(cx).is_open());
12887 // And the right dock is unaffected in its displaying of panel_1
12888 assert!(workspace.right_dock().read(cx).is_open());
12889 assert_eq!(
12890 workspace
12891 .right_dock()
12892 .read(cx)
12893 .visible_panel()
12894 .unwrap()
12895 .panel_id(),
12896 panel_1.panel_id(),
12897 );
12898 });
12899
12900 // Move panel_1 back to the left
12901 panel_1.update_in(cx, |panel_1, window, cx| {
12902 panel_1.set_position(DockPosition::Left, window, cx)
12903 });
12904
12905 workspace.update_in(cx, |workspace, window, cx| {
12906 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12907 let left_dock = workspace.left_dock();
12908 assert!(left_dock.read(cx).is_open());
12909 assert_eq!(
12910 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12911 panel_1.panel_id()
12912 );
12913 assert_eq!(
12914 workspace.dock_size(&left_dock.read(cx), window, cx),
12915 Some(px(1337.))
12916 );
12917 // And the right dock should be closed as it no longer has any panels.
12918 assert!(!workspace.right_dock().read(cx).is_open());
12919
12920 // Now we move panel_1 to the bottom
12921 panel_1.set_position(DockPosition::Bottom, window, cx);
12922 });
12923
12924 workspace.update_in(cx, |workspace, window, cx| {
12925 // Since panel_1 was visible on the left, we close the left dock.
12926 assert!(!workspace.left_dock().read(cx).is_open());
12927 // The bottom dock is sized based on the panel's default size,
12928 // since the panel orientation changed from vertical to horizontal.
12929 let bottom_dock = workspace.bottom_dock();
12930 assert_eq!(
12931 workspace.dock_size(&bottom_dock.read(cx), window, cx),
12932 Some(px(300.))
12933 );
12934 // Close bottom dock and move panel_1 back to the left.
12935 bottom_dock.update(cx, |bottom_dock, cx| {
12936 bottom_dock.set_open(false, window, cx)
12937 });
12938 panel_1.set_position(DockPosition::Left, window, cx);
12939 });
12940
12941 // Emit activated event on panel 1
12942 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12943
12944 // Now the left dock is open and panel_1 is active and focused.
12945 workspace.update_in(cx, |workspace, window, cx| {
12946 let left_dock = workspace.left_dock();
12947 assert!(left_dock.read(cx).is_open());
12948 assert_eq!(
12949 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12950 panel_1.panel_id(),
12951 );
12952 assert!(panel_1.focus_handle(cx).is_focused(window));
12953 });
12954
12955 // Emit closed event on panel 2, which is not active
12956 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12957
12958 // Wo don't close the left dock, because panel_2 wasn't the active panel
12959 workspace.update(cx, |workspace, cx| {
12960 let left_dock = workspace.left_dock();
12961 assert!(left_dock.read(cx).is_open());
12962 assert_eq!(
12963 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12964 panel_1.panel_id(),
12965 );
12966 });
12967
12968 // Emitting a ZoomIn event shows the panel as zoomed.
12969 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12970 workspace.read_with(cx, |workspace, _| {
12971 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12972 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12973 });
12974
12975 // Move panel to another dock while it is zoomed
12976 panel_1.update_in(cx, |panel, window, cx| {
12977 panel.set_position(DockPosition::Right, window, cx)
12978 });
12979 workspace.read_with(cx, |workspace, _| {
12980 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12981
12982 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12983 });
12984
12985 // This is a helper for getting a:
12986 // - valid focus on an element,
12987 // - that isn't a part of the panes and panels system of the Workspace,
12988 // - and doesn't trigger the 'on_focus_lost' API.
12989 let focus_other_view = {
12990 let workspace = workspace.clone();
12991 move |cx: &mut VisualTestContext| {
12992 workspace.update_in(cx, |workspace, window, cx| {
12993 if workspace.active_modal::<TestModal>(cx).is_some() {
12994 workspace.toggle_modal(window, cx, TestModal::new);
12995 workspace.toggle_modal(window, cx, TestModal::new);
12996 } else {
12997 workspace.toggle_modal(window, cx, TestModal::new);
12998 }
12999 })
13000 }
13001 };
13002
13003 // If focus is transferred to another view that's not a panel or another pane, we still show
13004 // the panel as zoomed.
13005 focus_other_view(cx);
13006 workspace.read_with(cx, |workspace, _| {
13007 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13008 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13009 });
13010
13011 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13012 workspace.update_in(cx, |_workspace, window, cx| {
13013 cx.focus_self(window);
13014 });
13015 workspace.read_with(cx, |workspace, _| {
13016 assert_eq!(workspace.zoomed, None);
13017 assert_eq!(workspace.zoomed_position, None);
13018 });
13019
13020 // If focus is transferred again to another view that's not a panel or a pane, we won't
13021 // show the panel as zoomed because it wasn't zoomed before.
13022 focus_other_view(cx);
13023 workspace.read_with(cx, |workspace, _| {
13024 assert_eq!(workspace.zoomed, None);
13025 assert_eq!(workspace.zoomed_position, None);
13026 });
13027
13028 // When the panel is activated, it is zoomed again.
13029 cx.dispatch_action(ToggleRightDock);
13030 workspace.read_with(cx, |workspace, _| {
13031 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13032 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13033 });
13034
13035 // Emitting a ZoomOut event unzooms the panel.
13036 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13037 workspace.read_with(cx, |workspace, _| {
13038 assert_eq!(workspace.zoomed, None);
13039 assert_eq!(workspace.zoomed_position, None);
13040 });
13041
13042 // Emit closed event on panel 1, which is active
13043 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13044
13045 // Now the left dock is closed, because panel_1 was the active panel
13046 workspace.update(cx, |workspace, cx| {
13047 let right_dock = workspace.right_dock();
13048 assert!(!right_dock.read(cx).is_open());
13049 });
13050 }
13051
13052 #[gpui::test]
13053 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13054 init_test(cx);
13055
13056 let fs = FakeFs::new(cx.background_executor.clone());
13057 let project = Project::test(fs, [], cx).await;
13058 let (workspace, cx) =
13059 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13060 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13061
13062 let dirty_regular_buffer = cx.new(|cx| {
13063 TestItem::new(cx)
13064 .with_dirty(true)
13065 .with_label("1.txt")
13066 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13067 });
13068 let dirty_regular_buffer_2 = cx.new(|cx| {
13069 TestItem::new(cx)
13070 .with_dirty(true)
13071 .with_label("2.txt")
13072 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13073 });
13074 let dirty_multi_buffer_with_both = cx.new(|cx| {
13075 TestItem::new(cx)
13076 .with_dirty(true)
13077 .with_buffer_kind(ItemBufferKind::Multibuffer)
13078 .with_label("Fake Project Search")
13079 .with_project_items(&[
13080 dirty_regular_buffer.read(cx).project_items[0].clone(),
13081 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13082 ])
13083 });
13084 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13085 workspace.update_in(cx, |workspace, window, cx| {
13086 workspace.add_item(
13087 pane.clone(),
13088 Box::new(dirty_regular_buffer.clone()),
13089 None,
13090 false,
13091 false,
13092 window,
13093 cx,
13094 );
13095 workspace.add_item(
13096 pane.clone(),
13097 Box::new(dirty_regular_buffer_2.clone()),
13098 None,
13099 false,
13100 false,
13101 window,
13102 cx,
13103 );
13104 workspace.add_item(
13105 pane.clone(),
13106 Box::new(dirty_multi_buffer_with_both.clone()),
13107 None,
13108 false,
13109 false,
13110 window,
13111 cx,
13112 );
13113 });
13114
13115 pane.update_in(cx, |pane, window, cx| {
13116 pane.activate_item(2, true, true, window, cx);
13117 assert_eq!(
13118 pane.active_item().unwrap().item_id(),
13119 multi_buffer_with_both_files_id,
13120 "Should select the multi buffer in the pane"
13121 );
13122 });
13123 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13124 pane.close_other_items(
13125 &CloseOtherItems {
13126 save_intent: Some(SaveIntent::Save),
13127 close_pinned: true,
13128 },
13129 None,
13130 window,
13131 cx,
13132 )
13133 });
13134 cx.background_executor.run_until_parked();
13135 assert!(!cx.has_pending_prompt());
13136 close_all_but_multi_buffer_task
13137 .await
13138 .expect("Closing all buffers but the multi buffer failed");
13139 pane.update(cx, |pane, cx| {
13140 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13141 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13142 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13143 assert_eq!(pane.items_len(), 1);
13144 assert_eq!(
13145 pane.active_item().unwrap().item_id(),
13146 multi_buffer_with_both_files_id,
13147 "Should have only the multi buffer left in the pane"
13148 );
13149 assert!(
13150 dirty_multi_buffer_with_both.read(cx).is_dirty,
13151 "The multi buffer containing the unsaved buffer should still be dirty"
13152 );
13153 });
13154
13155 dirty_regular_buffer.update(cx, |buffer, cx| {
13156 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13157 });
13158
13159 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13160 pane.close_active_item(
13161 &CloseActiveItem {
13162 save_intent: Some(SaveIntent::Close),
13163 close_pinned: false,
13164 },
13165 window,
13166 cx,
13167 )
13168 });
13169 cx.background_executor.run_until_parked();
13170 assert!(
13171 cx.has_pending_prompt(),
13172 "Dirty multi buffer should prompt a save dialog"
13173 );
13174 cx.simulate_prompt_answer("Save");
13175 cx.background_executor.run_until_parked();
13176 close_multi_buffer_task
13177 .await
13178 .expect("Closing the multi buffer failed");
13179 pane.update(cx, |pane, cx| {
13180 assert_eq!(
13181 dirty_multi_buffer_with_both.read(cx).save_count,
13182 1,
13183 "Multi buffer item should get be saved"
13184 );
13185 // Test impl does not save inner items, so we do not assert them
13186 assert_eq!(
13187 pane.items_len(),
13188 0,
13189 "No more items should be left in the pane"
13190 );
13191 assert!(pane.active_item().is_none());
13192 });
13193 }
13194
13195 #[gpui::test]
13196 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13197 cx: &mut TestAppContext,
13198 ) {
13199 init_test(cx);
13200
13201 let fs = FakeFs::new(cx.background_executor.clone());
13202 let project = Project::test(fs, [], cx).await;
13203 let (workspace, cx) =
13204 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13205 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13206
13207 let dirty_regular_buffer = cx.new(|cx| {
13208 TestItem::new(cx)
13209 .with_dirty(true)
13210 .with_label("1.txt")
13211 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13212 });
13213 let dirty_regular_buffer_2 = cx.new(|cx| {
13214 TestItem::new(cx)
13215 .with_dirty(true)
13216 .with_label("2.txt")
13217 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13218 });
13219 let clear_regular_buffer = cx.new(|cx| {
13220 TestItem::new(cx)
13221 .with_label("3.txt")
13222 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13223 });
13224
13225 let dirty_multi_buffer_with_both = cx.new(|cx| {
13226 TestItem::new(cx)
13227 .with_dirty(true)
13228 .with_buffer_kind(ItemBufferKind::Multibuffer)
13229 .with_label("Fake Project Search")
13230 .with_project_items(&[
13231 dirty_regular_buffer.read(cx).project_items[0].clone(),
13232 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13233 clear_regular_buffer.read(cx).project_items[0].clone(),
13234 ])
13235 });
13236 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13237 workspace.update_in(cx, |workspace, window, cx| {
13238 workspace.add_item(
13239 pane.clone(),
13240 Box::new(dirty_regular_buffer.clone()),
13241 None,
13242 false,
13243 false,
13244 window,
13245 cx,
13246 );
13247 workspace.add_item(
13248 pane.clone(),
13249 Box::new(dirty_multi_buffer_with_both.clone()),
13250 None,
13251 false,
13252 false,
13253 window,
13254 cx,
13255 );
13256 });
13257
13258 pane.update_in(cx, |pane, window, cx| {
13259 pane.activate_item(1, true, true, window, cx);
13260 assert_eq!(
13261 pane.active_item().unwrap().item_id(),
13262 multi_buffer_with_both_files_id,
13263 "Should select the multi buffer in the pane"
13264 );
13265 });
13266 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13267 pane.close_active_item(
13268 &CloseActiveItem {
13269 save_intent: None,
13270 close_pinned: false,
13271 },
13272 window,
13273 cx,
13274 )
13275 });
13276 cx.background_executor.run_until_parked();
13277 assert!(
13278 cx.has_pending_prompt(),
13279 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13280 );
13281 }
13282
13283 /// Tests that when `close_on_file_delete` is enabled, files are automatically
13284 /// closed when they are deleted from disk.
13285 #[gpui::test]
13286 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13287 init_test(cx);
13288
13289 // Enable the close_on_disk_deletion setting
13290 cx.update_global(|store: &mut SettingsStore, cx| {
13291 store.update_user_settings(cx, |settings| {
13292 settings.workspace.close_on_file_delete = Some(true);
13293 });
13294 });
13295
13296 let fs = FakeFs::new(cx.background_executor.clone());
13297 let project = Project::test(fs, [], cx).await;
13298 let (workspace, cx) =
13299 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13300 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13301
13302 // Create a test item that simulates a file
13303 let item = cx.new(|cx| {
13304 TestItem::new(cx)
13305 .with_label("test.txt")
13306 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13307 });
13308
13309 // Add item to workspace
13310 workspace.update_in(cx, |workspace, window, cx| {
13311 workspace.add_item(
13312 pane.clone(),
13313 Box::new(item.clone()),
13314 None,
13315 false,
13316 false,
13317 window,
13318 cx,
13319 );
13320 });
13321
13322 // Verify the item is in the pane
13323 pane.read_with(cx, |pane, _| {
13324 assert_eq!(pane.items().count(), 1);
13325 });
13326
13327 // Simulate file deletion by setting the item's deleted state
13328 item.update(cx, |item, _| {
13329 item.set_has_deleted_file(true);
13330 });
13331
13332 // Emit UpdateTab event to trigger the close behavior
13333 cx.run_until_parked();
13334 item.update(cx, |_, cx| {
13335 cx.emit(ItemEvent::UpdateTab);
13336 });
13337
13338 // Allow the close operation to complete
13339 cx.run_until_parked();
13340
13341 // Verify the item was automatically closed
13342 pane.read_with(cx, |pane, _| {
13343 assert_eq!(
13344 pane.items().count(),
13345 0,
13346 "Item should be automatically closed when file is deleted"
13347 );
13348 });
13349 }
13350
13351 /// Tests that when `close_on_file_delete` is disabled (default), files remain
13352 /// open with a strikethrough when they are deleted from disk.
13353 #[gpui::test]
13354 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13355 init_test(cx);
13356
13357 // Ensure close_on_disk_deletion is disabled (default)
13358 cx.update_global(|store: &mut SettingsStore, cx| {
13359 store.update_user_settings(cx, |settings| {
13360 settings.workspace.close_on_file_delete = Some(false);
13361 });
13362 });
13363
13364 let fs = FakeFs::new(cx.background_executor.clone());
13365 let project = Project::test(fs, [], cx).await;
13366 let (workspace, cx) =
13367 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13368 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13369
13370 // Create a test item that simulates a file
13371 let item = cx.new(|cx| {
13372 TestItem::new(cx)
13373 .with_label("test.txt")
13374 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13375 });
13376
13377 // Add item to workspace
13378 workspace.update_in(cx, |workspace, window, cx| {
13379 workspace.add_item(
13380 pane.clone(),
13381 Box::new(item.clone()),
13382 None,
13383 false,
13384 false,
13385 window,
13386 cx,
13387 );
13388 });
13389
13390 // Verify the item is in the pane
13391 pane.read_with(cx, |pane, _| {
13392 assert_eq!(pane.items().count(), 1);
13393 });
13394
13395 // Simulate file deletion
13396 item.update(cx, |item, _| {
13397 item.set_has_deleted_file(true);
13398 });
13399
13400 // Emit UpdateTab event
13401 cx.run_until_parked();
13402 item.update(cx, |_, cx| {
13403 cx.emit(ItemEvent::UpdateTab);
13404 });
13405
13406 // Allow any potential close operation to complete
13407 cx.run_until_parked();
13408
13409 // Verify the item remains open (with strikethrough)
13410 pane.read_with(cx, |pane, _| {
13411 assert_eq!(
13412 pane.items().count(),
13413 1,
13414 "Item should remain open when close_on_disk_deletion is disabled"
13415 );
13416 });
13417
13418 // Verify the item shows as deleted
13419 item.read_with(cx, |item, _| {
13420 assert!(
13421 item.has_deleted_file,
13422 "Item should be marked as having deleted file"
13423 );
13424 });
13425 }
13426
13427 /// Tests that dirty files are not automatically closed when deleted from disk,
13428 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13429 /// unsaved changes without being prompted.
13430 #[gpui::test]
13431 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13432 init_test(cx);
13433
13434 // Enable the close_on_file_delete setting
13435 cx.update_global(|store: &mut SettingsStore, cx| {
13436 store.update_user_settings(cx, |settings| {
13437 settings.workspace.close_on_file_delete = Some(true);
13438 });
13439 });
13440
13441 let fs = FakeFs::new(cx.background_executor.clone());
13442 let project = Project::test(fs, [], cx).await;
13443 let (workspace, cx) =
13444 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13445 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13446
13447 // Create a dirty test item
13448 let item = cx.new(|cx| {
13449 TestItem::new(cx)
13450 .with_dirty(true)
13451 .with_label("test.txt")
13452 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13453 });
13454
13455 // Add item to workspace
13456 workspace.update_in(cx, |workspace, window, cx| {
13457 workspace.add_item(
13458 pane.clone(),
13459 Box::new(item.clone()),
13460 None,
13461 false,
13462 false,
13463 window,
13464 cx,
13465 );
13466 });
13467
13468 // Simulate file deletion
13469 item.update(cx, |item, _| {
13470 item.set_has_deleted_file(true);
13471 });
13472
13473 // Emit UpdateTab event to trigger the close behavior
13474 cx.run_until_parked();
13475 item.update(cx, |_, cx| {
13476 cx.emit(ItemEvent::UpdateTab);
13477 });
13478
13479 // Allow any potential close operation to complete
13480 cx.run_until_parked();
13481
13482 // Verify the item remains open (dirty files are not auto-closed)
13483 pane.read_with(cx, |pane, _| {
13484 assert_eq!(
13485 pane.items().count(),
13486 1,
13487 "Dirty items should not be automatically closed even when file is deleted"
13488 );
13489 });
13490
13491 // Verify the item is marked as deleted and still dirty
13492 item.read_with(cx, |item, _| {
13493 assert!(
13494 item.has_deleted_file,
13495 "Item should be marked as having deleted file"
13496 );
13497 assert!(item.is_dirty, "Item should still be dirty");
13498 });
13499 }
13500
13501 /// Tests that navigation history is cleaned up when files are auto-closed
13502 /// due to deletion from disk.
13503 #[gpui::test]
13504 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13505 init_test(cx);
13506
13507 // Enable the close_on_file_delete setting
13508 cx.update_global(|store: &mut SettingsStore, cx| {
13509 store.update_user_settings(cx, |settings| {
13510 settings.workspace.close_on_file_delete = Some(true);
13511 });
13512 });
13513
13514 let fs = FakeFs::new(cx.background_executor.clone());
13515 let project = Project::test(fs, [], cx).await;
13516 let (workspace, cx) =
13517 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13518 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13519
13520 // Create test items
13521 let item1 = cx.new(|cx| {
13522 TestItem::new(cx)
13523 .with_label("test1.txt")
13524 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13525 });
13526 let item1_id = item1.item_id();
13527
13528 let item2 = cx.new(|cx| {
13529 TestItem::new(cx)
13530 .with_label("test2.txt")
13531 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13532 });
13533
13534 // Add items to workspace
13535 workspace.update_in(cx, |workspace, window, cx| {
13536 workspace.add_item(
13537 pane.clone(),
13538 Box::new(item1.clone()),
13539 None,
13540 false,
13541 false,
13542 window,
13543 cx,
13544 );
13545 workspace.add_item(
13546 pane.clone(),
13547 Box::new(item2.clone()),
13548 None,
13549 false,
13550 false,
13551 window,
13552 cx,
13553 );
13554 });
13555
13556 // Activate item1 to ensure it gets navigation entries
13557 pane.update_in(cx, |pane, window, cx| {
13558 pane.activate_item(0, true, true, window, cx);
13559 });
13560
13561 // Switch to item2 and back to create navigation history
13562 pane.update_in(cx, |pane, window, cx| {
13563 pane.activate_item(1, true, true, window, cx);
13564 });
13565 cx.run_until_parked();
13566
13567 pane.update_in(cx, |pane, window, cx| {
13568 pane.activate_item(0, true, true, window, cx);
13569 });
13570 cx.run_until_parked();
13571
13572 // Simulate file deletion for item1
13573 item1.update(cx, |item, _| {
13574 item.set_has_deleted_file(true);
13575 });
13576
13577 // Emit UpdateTab event to trigger the close behavior
13578 item1.update(cx, |_, cx| {
13579 cx.emit(ItemEvent::UpdateTab);
13580 });
13581 cx.run_until_parked();
13582
13583 // Verify item1 was closed
13584 pane.read_with(cx, |pane, _| {
13585 assert_eq!(
13586 pane.items().count(),
13587 1,
13588 "Should have 1 item remaining after auto-close"
13589 );
13590 });
13591
13592 // Check navigation history after close
13593 let has_item = pane.read_with(cx, |pane, cx| {
13594 let mut has_item = false;
13595 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13596 if entry.item.id() == item1_id {
13597 has_item = true;
13598 }
13599 });
13600 has_item
13601 });
13602
13603 assert!(
13604 !has_item,
13605 "Navigation history should not contain closed item entries"
13606 );
13607 }
13608
13609 #[gpui::test]
13610 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13611 cx: &mut TestAppContext,
13612 ) {
13613 init_test(cx);
13614
13615 let fs = FakeFs::new(cx.background_executor.clone());
13616 let project = Project::test(fs, [], cx).await;
13617 let (workspace, cx) =
13618 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13619 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13620
13621 let dirty_regular_buffer = cx.new(|cx| {
13622 TestItem::new(cx)
13623 .with_dirty(true)
13624 .with_label("1.txt")
13625 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13626 });
13627 let dirty_regular_buffer_2 = cx.new(|cx| {
13628 TestItem::new(cx)
13629 .with_dirty(true)
13630 .with_label("2.txt")
13631 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13632 });
13633 let clear_regular_buffer = cx.new(|cx| {
13634 TestItem::new(cx)
13635 .with_label("3.txt")
13636 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13637 });
13638
13639 let dirty_multi_buffer = cx.new(|cx| {
13640 TestItem::new(cx)
13641 .with_dirty(true)
13642 .with_buffer_kind(ItemBufferKind::Multibuffer)
13643 .with_label("Fake Project Search")
13644 .with_project_items(&[
13645 dirty_regular_buffer.read(cx).project_items[0].clone(),
13646 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13647 clear_regular_buffer.read(cx).project_items[0].clone(),
13648 ])
13649 });
13650 workspace.update_in(cx, |workspace, window, cx| {
13651 workspace.add_item(
13652 pane.clone(),
13653 Box::new(dirty_regular_buffer.clone()),
13654 None,
13655 false,
13656 false,
13657 window,
13658 cx,
13659 );
13660 workspace.add_item(
13661 pane.clone(),
13662 Box::new(dirty_regular_buffer_2.clone()),
13663 None,
13664 false,
13665 false,
13666 window,
13667 cx,
13668 );
13669 workspace.add_item(
13670 pane.clone(),
13671 Box::new(dirty_multi_buffer.clone()),
13672 None,
13673 false,
13674 false,
13675 window,
13676 cx,
13677 );
13678 });
13679
13680 pane.update_in(cx, |pane, window, cx| {
13681 pane.activate_item(2, true, true, window, cx);
13682 assert_eq!(
13683 pane.active_item().unwrap().item_id(),
13684 dirty_multi_buffer.item_id(),
13685 "Should select the multi buffer in the pane"
13686 );
13687 });
13688 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13689 pane.close_active_item(
13690 &CloseActiveItem {
13691 save_intent: None,
13692 close_pinned: false,
13693 },
13694 window,
13695 cx,
13696 )
13697 });
13698 cx.background_executor.run_until_parked();
13699 assert!(
13700 !cx.has_pending_prompt(),
13701 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13702 );
13703 close_multi_buffer_task
13704 .await
13705 .expect("Closing multi buffer failed");
13706 pane.update(cx, |pane, cx| {
13707 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13708 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13709 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13710 assert_eq!(
13711 pane.items()
13712 .map(|item| item.item_id())
13713 .sorted()
13714 .collect::<Vec<_>>(),
13715 vec![
13716 dirty_regular_buffer.item_id(),
13717 dirty_regular_buffer_2.item_id(),
13718 ],
13719 "Should have no multi buffer left in the pane"
13720 );
13721 assert!(dirty_regular_buffer.read(cx).is_dirty);
13722 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13723 });
13724 }
13725
13726 #[gpui::test]
13727 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13728 init_test(cx);
13729 let fs = FakeFs::new(cx.executor());
13730 let project = Project::test(fs, [], cx).await;
13731 let (multi_workspace, cx) =
13732 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13733 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13734
13735 // Add a new panel to the right dock, opening the dock and setting the
13736 // focus to the new panel.
13737 let panel = workspace.update_in(cx, |workspace, window, cx| {
13738 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13739 workspace.add_panel(panel.clone(), window, cx);
13740
13741 workspace
13742 .right_dock()
13743 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13744
13745 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13746
13747 panel
13748 });
13749
13750 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13751 // panel to the next valid position which, in this case, is the left
13752 // dock.
13753 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13754 workspace.update(cx, |workspace, cx| {
13755 assert!(workspace.left_dock().read(cx).is_open());
13756 assert_eq!(panel.read(cx).position, DockPosition::Left);
13757 });
13758
13759 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13760 // panel to the next valid position which, in this case, is the bottom
13761 // dock.
13762 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13763 workspace.update(cx, |workspace, cx| {
13764 assert!(workspace.bottom_dock().read(cx).is_open());
13765 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13766 });
13767
13768 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13769 // around moving the panel to its initial position, the right dock.
13770 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13771 workspace.update(cx, |workspace, cx| {
13772 assert!(workspace.right_dock().read(cx).is_open());
13773 assert_eq!(panel.read(cx).position, DockPosition::Right);
13774 });
13775
13776 // Remove focus from the panel, ensuring that, if the panel is not
13777 // focused, the `MoveFocusedPanelToNextPosition` action does not update
13778 // the panel's position, so the panel is still in the right dock.
13779 workspace.update_in(cx, |workspace, window, cx| {
13780 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13781 });
13782
13783 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13784 workspace.update(cx, |workspace, cx| {
13785 assert!(workspace.right_dock().read(cx).is_open());
13786 assert_eq!(panel.read(cx).position, DockPosition::Right);
13787 });
13788 }
13789
13790 #[gpui::test]
13791 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13792 init_test(cx);
13793
13794 let fs = FakeFs::new(cx.executor());
13795 let project = Project::test(fs, [], cx).await;
13796 let (workspace, cx) =
13797 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13798
13799 let item_1 = cx.new(|cx| {
13800 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13801 });
13802 workspace.update_in(cx, |workspace, window, cx| {
13803 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13804 workspace.move_item_to_pane_in_direction(
13805 &MoveItemToPaneInDirection {
13806 direction: SplitDirection::Right,
13807 focus: true,
13808 clone: false,
13809 },
13810 window,
13811 cx,
13812 );
13813 workspace.move_item_to_pane_at_index(
13814 &MoveItemToPane {
13815 destination: 3,
13816 focus: true,
13817 clone: false,
13818 },
13819 window,
13820 cx,
13821 );
13822
13823 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13824 assert_eq!(
13825 pane_items_paths(&workspace.active_pane, cx),
13826 vec!["first.txt".to_string()],
13827 "Single item was not moved anywhere"
13828 );
13829 });
13830
13831 let item_2 = cx.new(|cx| {
13832 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13833 });
13834 workspace.update_in(cx, |workspace, window, cx| {
13835 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13836 assert_eq!(
13837 pane_items_paths(&workspace.panes[0], cx),
13838 vec!["first.txt".to_string(), "second.txt".to_string()],
13839 );
13840 workspace.move_item_to_pane_in_direction(
13841 &MoveItemToPaneInDirection {
13842 direction: SplitDirection::Right,
13843 focus: true,
13844 clone: false,
13845 },
13846 window,
13847 cx,
13848 );
13849
13850 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13851 assert_eq!(
13852 pane_items_paths(&workspace.panes[0], cx),
13853 vec!["first.txt".to_string()],
13854 "After moving, one item should be left in the original pane"
13855 );
13856 assert_eq!(
13857 pane_items_paths(&workspace.panes[1], cx),
13858 vec!["second.txt".to_string()],
13859 "New item should have been moved to the new pane"
13860 );
13861 });
13862
13863 let item_3 = cx.new(|cx| {
13864 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13865 });
13866 workspace.update_in(cx, |workspace, window, cx| {
13867 let original_pane = workspace.panes[0].clone();
13868 workspace.set_active_pane(&original_pane, window, cx);
13869 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13870 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13871 assert_eq!(
13872 pane_items_paths(&workspace.active_pane, cx),
13873 vec!["first.txt".to_string(), "third.txt".to_string()],
13874 "New pane should be ready to move one item out"
13875 );
13876
13877 workspace.move_item_to_pane_at_index(
13878 &MoveItemToPane {
13879 destination: 3,
13880 focus: true,
13881 clone: false,
13882 },
13883 window,
13884 cx,
13885 );
13886 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13887 assert_eq!(
13888 pane_items_paths(&workspace.active_pane, cx),
13889 vec!["first.txt".to_string()],
13890 "After moving, one item should be left in the original pane"
13891 );
13892 assert_eq!(
13893 pane_items_paths(&workspace.panes[1], cx),
13894 vec!["second.txt".to_string()],
13895 "Previously created pane should be unchanged"
13896 );
13897 assert_eq!(
13898 pane_items_paths(&workspace.panes[2], cx),
13899 vec!["third.txt".to_string()],
13900 "New item should have been moved to the new pane"
13901 );
13902 });
13903 }
13904
13905 #[gpui::test]
13906 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13907 init_test(cx);
13908
13909 let fs = FakeFs::new(cx.executor());
13910 let project = Project::test(fs, [], cx).await;
13911 let (workspace, cx) =
13912 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13913
13914 let item_1 = cx.new(|cx| {
13915 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13916 });
13917 workspace.update_in(cx, |workspace, window, cx| {
13918 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13919 workspace.move_item_to_pane_in_direction(
13920 &MoveItemToPaneInDirection {
13921 direction: SplitDirection::Right,
13922 focus: true,
13923 clone: true,
13924 },
13925 window,
13926 cx,
13927 );
13928 });
13929 cx.run_until_parked();
13930 workspace.update_in(cx, |workspace, window, cx| {
13931 workspace.move_item_to_pane_at_index(
13932 &MoveItemToPane {
13933 destination: 3,
13934 focus: true,
13935 clone: true,
13936 },
13937 window,
13938 cx,
13939 );
13940 });
13941 cx.run_until_parked();
13942
13943 workspace.update(cx, |workspace, cx| {
13944 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13945 for pane in workspace.panes() {
13946 assert_eq!(
13947 pane_items_paths(pane, cx),
13948 vec!["first.txt".to_string()],
13949 "Single item exists in all panes"
13950 );
13951 }
13952 });
13953
13954 // verify that the active pane has been updated after waiting for the
13955 // pane focus event to fire and resolve
13956 workspace.read_with(cx, |workspace, _app| {
13957 assert_eq!(
13958 workspace.active_pane(),
13959 &workspace.panes[2],
13960 "The third pane should be the active one: {:?}",
13961 workspace.panes
13962 );
13963 })
13964 }
13965
13966 #[gpui::test]
13967 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13968 init_test(cx);
13969
13970 let fs = FakeFs::new(cx.executor());
13971 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13972
13973 let project = Project::test(fs, ["root".as_ref()], cx).await;
13974 let (workspace, cx) =
13975 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13976
13977 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13978 // Add item to pane A with project path
13979 let item_a = cx.new(|cx| {
13980 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13981 });
13982 workspace.update_in(cx, |workspace, window, cx| {
13983 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13984 });
13985
13986 // Split to create pane B
13987 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13988 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13989 });
13990
13991 // Add item with SAME project path to pane B, and pin it
13992 let item_b = cx.new(|cx| {
13993 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13994 });
13995 pane_b.update_in(cx, |pane, window, cx| {
13996 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13997 pane.set_pinned_count(1);
13998 });
13999
14000 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14001 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14002
14003 // close_pinned: false should only close the unpinned copy
14004 workspace.update_in(cx, |workspace, window, cx| {
14005 workspace.close_item_in_all_panes(
14006 &CloseItemInAllPanes {
14007 save_intent: Some(SaveIntent::Close),
14008 close_pinned: false,
14009 },
14010 window,
14011 cx,
14012 )
14013 });
14014 cx.executor().run_until_parked();
14015
14016 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14017 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14018 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14019 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14020
14021 // Split again, seeing as closing the previous item also closed its
14022 // pane, so only pane remains, which does not allow us to properly test
14023 // that both items close when `close_pinned: true`.
14024 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14025 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14026 });
14027
14028 // Add an item with the same project path to pane C so that
14029 // close_item_in_all_panes can determine what to close across all panes
14030 // (it reads the active item from the active pane, and split_pane
14031 // creates an empty pane).
14032 let item_c = cx.new(|cx| {
14033 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14034 });
14035 pane_c.update_in(cx, |pane, window, cx| {
14036 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14037 });
14038
14039 // close_pinned: true should close the pinned copy too
14040 workspace.update_in(cx, |workspace, window, cx| {
14041 let panes_count = workspace.panes().len();
14042 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14043
14044 workspace.close_item_in_all_panes(
14045 &CloseItemInAllPanes {
14046 save_intent: Some(SaveIntent::Close),
14047 close_pinned: true,
14048 },
14049 window,
14050 cx,
14051 )
14052 });
14053 cx.executor().run_until_parked();
14054
14055 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14056 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14057 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14058 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14059 }
14060
14061 mod register_project_item_tests {
14062
14063 use super::*;
14064
14065 // View
14066 struct TestPngItemView {
14067 focus_handle: FocusHandle,
14068 }
14069 // Model
14070 struct TestPngItem {}
14071
14072 impl project::ProjectItem for TestPngItem {
14073 fn try_open(
14074 _project: &Entity<Project>,
14075 path: &ProjectPath,
14076 cx: &mut App,
14077 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14078 if path.path.extension().unwrap() == "png" {
14079 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14080 } else {
14081 None
14082 }
14083 }
14084
14085 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14086 None
14087 }
14088
14089 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14090 None
14091 }
14092
14093 fn is_dirty(&self) -> bool {
14094 false
14095 }
14096 }
14097
14098 impl Item for TestPngItemView {
14099 type Event = ();
14100 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14101 "".into()
14102 }
14103 }
14104 impl EventEmitter<()> for TestPngItemView {}
14105 impl Focusable for TestPngItemView {
14106 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14107 self.focus_handle.clone()
14108 }
14109 }
14110
14111 impl Render for TestPngItemView {
14112 fn render(
14113 &mut self,
14114 _window: &mut Window,
14115 _cx: &mut Context<Self>,
14116 ) -> impl IntoElement {
14117 Empty
14118 }
14119 }
14120
14121 impl ProjectItem for TestPngItemView {
14122 type Item = TestPngItem;
14123
14124 fn for_project_item(
14125 _project: Entity<Project>,
14126 _pane: Option<&Pane>,
14127 _item: Entity<Self::Item>,
14128 _: &mut Window,
14129 cx: &mut Context<Self>,
14130 ) -> Self
14131 where
14132 Self: Sized,
14133 {
14134 Self {
14135 focus_handle: cx.focus_handle(),
14136 }
14137 }
14138 }
14139
14140 // View
14141 struct TestIpynbItemView {
14142 focus_handle: FocusHandle,
14143 }
14144 // Model
14145 struct TestIpynbItem {}
14146
14147 impl project::ProjectItem for TestIpynbItem {
14148 fn try_open(
14149 _project: &Entity<Project>,
14150 path: &ProjectPath,
14151 cx: &mut App,
14152 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14153 if path.path.extension().unwrap() == "ipynb" {
14154 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14155 } else {
14156 None
14157 }
14158 }
14159
14160 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14161 None
14162 }
14163
14164 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14165 None
14166 }
14167
14168 fn is_dirty(&self) -> bool {
14169 false
14170 }
14171 }
14172
14173 impl Item for TestIpynbItemView {
14174 type Event = ();
14175 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14176 "".into()
14177 }
14178 }
14179 impl EventEmitter<()> for TestIpynbItemView {}
14180 impl Focusable for TestIpynbItemView {
14181 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14182 self.focus_handle.clone()
14183 }
14184 }
14185
14186 impl Render for TestIpynbItemView {
14187 fn render(
14188 &mut self,
14189 _window: &mut Window,
14190 _cx: &mut Context<Self>,
14191 ) -> impl IntoElement {
14192 Empty
14193 }
14194 }
14195
14196 impl ProjectItem for TestIpynbItemView {
14197 type Item = TestIpynbItem;
14198
14199 fn for_project_item(
14200 _project: Entity<Project>,
14201 _pane: Option<&Pane>,
14202 _item: Entity<Self::Item>,
14203 _: &mut Window,
14204 cx: &mut Context<Self>,
14205 ) -> Self
14206 where
14207 Self: Sized,
14208 {
14209 Self {
14210 focus_handle: cx.focus_handle(),
14211 }
14212 }
14213 }
14214
14215 struct TestAlternatePngItemView {
14216 focus_handle: FocusHandle,
14217 }
14218
14219 impl Item for TestAlternatePngItemView {
14220 type Event = ();
14221 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14222 "".into()
14223 }
14224 }
14225
14226 impl EventEmitter<()> for TestAlternatePngItemView {}
14227 impl Focusable for TestAlternatePngItemView {
14228 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14229 self.focus_handle.clone()
14230 }
14231 }
14232
14233 impl Render for TestAlternatePngItemView {
14234 fn render(
14235 &mut self,
14236 _window: &mut Window,
14237 _cx: &mut Context<Self>,
14238 ) -> impl IntoElement {
14239 Empty
14240 }
14241 }
14242
14243 impl ProjectItem for TestAlternatePngItemView {
14244 type Item = TestPngItem;
14245
14246 fn for_project_item(
14247 _project: Entity<Project>,
14248 _pane: Option<&Pane>,
14249 _item: Entity<Self::Item>,
14250 _: &mut Window,
14251 cx: &mut Context<Self>,
14252 ) -> Self
14253 where
14254 Self: Sized,
14255 {
14256 Self {
14257 focus_handle: cx.focus_handle(),
14258 }
14259 }
14260 }
14261
14262 #[gpui::test]
14263 async fn test_register_project_item(cx: &mut TestAppContext) {
14264 init_test(cx);
14265
14266 cx.update(|cx| {
14267 register_project_item::<TestPngItemView>(cx);
14268 register_project_item::<TestIpynbItemView>(cx);
14269 });
14270
14271 let fs = FakeFs::new(cx.executor());
14272 fs.insert_tree(
14273 "/root1",
14274 json!({
14275 "one.png": "BINARYDATAHERE",
14276 "two.ipynb": "{ totally a notebook }",
14277 "three.txt": "editing text, sure why not?"
14278 }),
14279 )
14280 .await;
14281
14282 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14283 let (workspace, cx) =
14284 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14285
14286 let worktree_id = project.update(cx, |project, cx| {
14287 project.worktrees(cx).next().unwrap().read(cx).id()
14288 });
14289
14290 let handle = workspace
14291 .update_in(cx, |workspace, window, cx| {
14292 let project_path = (worktree_id, rel_path("one.png"));
14293 workspace.open_path(project_path, None, true, window, cx)
14294 })
14295 .await
14296 .unwrap();
14297
14298 // Now we can check if the handle we got back errored or not
14299 assert_eq!(
14300 handle.to_any_view().entity_type(),
14301 TypeId::of::<TestPngItemView>()
14302 );
14303
14304 let handle = workspace
14305 .update_in(cx, |workspace, window, cx| {
14306 let project_path = (worktree_id, rel_path("two.ipynb"));
14307 workspace.open_path(project_path, None, true, window, cx)
14308 })
14309 .await
14310 .unwrap();
14311
14312 assert_eq!(
14313 handle.to_any_view().entity_type(),
14314 TypeId::of::<TestIpynbItemView>()
14315 );
14316
14317 let handle = workspace
14318 .update_in(cx, |workspace, window, cx| {
14319 let project_path = (worktree_id, rel_path("three.txt"));
14320 workspace.open_path(project_path, None, true, window, cx)
14321 })
14322 .await;
14323 assert!(handle.is_err());
14324 }
14325
14326 #[gpui::test]
14327 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14328 init_test(cx);
14329
14330 cx.update(|cx| {
14331 register_project_item::<TestPngItemView>(cx);
14332 register_project_item::<TestAlternatePngItemView>(cx);
14333 });
14334
14335 let fs = FakeFs::new(cx.executor());
14336 fs.insert_tree(
14337 "/root1",
14338 json!({
14339 "one.png": "BINARYDATAHERE",
14340 "two.ipynb": "{ totally a notebook }",
14341 "three.txt": "editing text, sure why not?"
14342 }),
14343 )
14344 .await;
14345 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14346 let (workspace, cx) =
14347 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14348 let worktree_id = project.update(cx, |project, cx| {
14349 project.worktrees(cx).next().unwrap().read(cx).id()
14350 });
14351
14352 let handle = workspace
14353 .update_in(cx, |workspace, window, cx| {
14354 let project_path = (worktree_id, rel_path("one.png"));
14355 workspace.open_path(project_path, None, true, window, cx)
14356 })
14357 .await
14358 .unwrap();
14359
14360 // This _must_ be the second item registered
14361 assert_eq!(
14362 handle.to_any_view().entity_type(),
14363 TypeId::of::<TestAlternatePngItemView>()
14364 );
14365
14366 let handle = workspace
14367 .update_in(cx, |workspace, window, cx| {
14368 let project_path = (worktree_id, rel_path("three.txt"));
14369 workspace.open_path(project_path, None, true, window, cx)
14370 })
14371 .await;
14372 assert!(handle.is_err());
14373 }
14374 }
14375
14376 #[gpui::test]
14377 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14378 init_test(cx);
14379
14380 let fs = FakeFs::new(cx.executor());
14381 let project = Project::test(fs, [], cx).await;
14382 let (workspace, _cx) =
14383 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14384
14385 // Test with status bar shown (default)
14386 workspace.read_with(cx, |workspace, cx| {
14387 let visible = workspace.status_bar_visible(cx);
14388 assert!(visible, "Status bar should be visible by default");
14389 });
14390
14391 // Test with status bar hidden
14392 cx.update_global(|store: &mut SettingsStore, cx| {
14393 store.update_user_settings(cx, |settings| {
14394 settings.status_bar.get_or_insert_default().show = Some(false);
14395 });
14396 });
14397
14398 workspace.read_with(cx, |workspace, cx| {
14399 let visible = workspace.status_bar_visible(cx);
14400 assert!(!visible, "Status bar should be hidden when show is false");
14401 });
14402
14403 // Test with status bar shown explicitly
14404 cx.update_global(|store: &mut SettingsStore, cx| {
14405 store.update_user_settings(cx, |settings| {
14406 settings.status_bar.get_or_insert_default().show = Some(true);
14407 });
14408 });
14409
14410 workspace.read_with(cx, |workspace, cx| {
14411 let visible = workspace.status_bar_visible(cx);
14412 assert!(visible, "Status bar should be visible when show is true");
14413 });
14414 }
14415
14416 #[gpui::test]
14417 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14418 init_test(cx);
14419
14420 let fs = FakeFs::new(cx.executor());
14421 let project = Project::test(fs, [], cx).await;
14422 let (multi_workspace, cx) =
14423 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14424 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14425 let panel = workspace.update_in(cx, |workspace, window, cx| {
14426 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14427 workspace.add_panel(panel.clone(), window, cx);
14428
14429 workspace
14430 .right_dock()
14431 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14432
14433 panel
14434 });
14435
14436 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14437 let item_a = cx.new(TestItem::new);
14438 let item_b = cx.new(TestItem::new);
14439 let item_a_id = item_a.entity_id();
14440 let item_b_id = item_b.entity_id();
14441
14442 pane.update_in(cx, |pane, window, cx| {
14443 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14444 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14445 });
14446
14447 pane.read_with(cx, |pane, _| {
14448 assert_eq!(pane.items_len(), 2);
14449 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14450 });
14451
14452 workspace.update_in(cx, |workspace, window, cx| {
14453 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14454 });
14455
14456 workspace.update_in(cx, |_, window, cx| {
14457 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14458 });
14459
14460 // Assert that the `pane::CloseActiveItem` action is handled at the
14461 // workspace level when one of the dock panels is focused and, in that
14462 // case, the center pane's active item is closed but the focus is not
14463 // moved.
14464 cx.dispatch_action(pane::CloseActiveItem::default());
14465 cx.run_until_parked();
14466
14467 pane.read_with(cx, |pane, _| {
14468 assert_eq!(pane.items_len(), 1);
14469 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14470 });
14471
14472 workspace.update_in(cx, |workspace, window, cx| {
14473 assert!(workspace.right_dock().read(cx).is_open());
14474 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14475 });
14476 }
14477
14478 #[gpui::test]
14479 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14480 init_test(cx);
14481 let fs = FakeFs::new(cx.executor());
14482
14483 let project_a = Project::test(fs.clone(), [], cx).await;
14484 let project_b = Project::test(fs, [], cx).await;
14485
14486 let multi_workspace_handle =
14487 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14488 cx.run_until_parked();
14489
14490 let workspace_a = multi_workspace_handle
14491 .read_with(cx, |mw, _| mw.workspace().clone())
14492 .unwrap();
14493
14494 let _workspace_b = multi_workspace_handle
14495 .update(cx, |mw, window, cx| {
14496 mw.test_add_workspace(project_b, window, cx)
14497 })
14498 .unwrap();
14499
14500 // Switch to workspace A
14501 multi_workspace_handle
14502 .update(cx, |mw, window, cx| {
14503 let workspace = mw.workspaces()[0].clone();
14504 mw.activate(workspace, window, cx);
14505 })
14506 .unwrap();
14507
14508 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14509
14510 // Add a panel to workspace A's right dock and open the dock
14511 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14512 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14513 workspace.add_panel(panel.clone(), window, cx);
14514 workspace
14515 .right_dock()
14516 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14517 panel
14518 });
14519
14520 // Focus the panel through the workspace (matching existing test pattern)
14521 workspace_a.update_in(cx, |workspace, window, cx| {
14522 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14523 });
14524
14525 // Zoom the panel
14526 panel.update_in(cx, |panel, window, cx| {
14527 panel.set_zoomed(true, window, cx);
14528 });
14529
14530 // Verify the panel is zoomed and the dock is open
14531 workspace_a.update_in(cx, |workspace, window, cx| {
14532 assert!(
14533 workspace.right_dock().read(cx).is_open(),
14534 "dock should be open before switch"
14535 );
14536 assert!(
14537 panel.is_zoomed(window, cx),
14538 "panel should be zoomed before switch"
14539 );
14540 assert!(
14541 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14542 "panel should be focused before switch"
14543 );
14544 });
14545
14546 // Switch to workspace B
14547 multi_workspace_handle
14548 .update(cx, |mw, window, cx| {
14549 let workspace = mw.workspaces()[1].clone();
14550 mw.activate(workspace, window, cx);
14551 })
14552 .unwrap();
14553 cx.run_until_parked();
14554
14555 // Switch back to workspace A
14556 multi_workspace_handle
14557 .update(cx, |mw, window, cx| {
14558 let workspace = mw.workspaces()[0].clone();
14559 mw.activate(workspace, window, cx);
14560 })
14561 .unwrap();
14562 cx.run_until_parked();
14563
14564 // Verify the panel is still zoomed and the dock is still open
14565 workspace_a.update_in(cx, |workspace, window, cx| {
14566 assert!(
14567 workspace.right_dock().read(cx).is_open(),
14568 "dock should still be open after switching back"
14569 );
14570 assert!(
14571 panel.is_zoomed(window, cx),
14572 "panel should still be zoomed after switching back"
14573 );
14574 });
14575 }
14576
14577 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14578 pane.read(cx)
14579 .items()
14580 .flat_map(|item| {
14581 item.project_paths(cx)
14582 .into_iter()
14583 .map(|path| path.path.display(PathStyle::local()).into_owned())
14584 })
14585 .collect()
14586 }
14587
14588 pub fn init_test(cx: &mut TestAppContext) {
14589 cx.update(|cx| {
14590 let settings_store = SettingsStore::test(cx);
14591 cx.set_global(settings_store);
14592 cx.set_global(db::AppDatabase::test_new());
14593 theme_settings::init(theme::LoadThemes::JustBase, cx);
14594 });
14595 }
14596
14597 #[gpui::test]
14598 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14599 use settings::{ThemeName, ThemeSelection};
14600 use theme::SystemAppearance;
14601 use zed_actions::theme::ToggleMode;
14602
14603 init_test(cx);
14604
14605 let fs = FakeFs::new(cx.executor());
14606 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14607
14608 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14609 .await;
14610
14611 // Build a test project and workspace view so the test can invoke
14612 // the workspace action handler the same way the UI would.
14613 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14614 let (workspace, cx) =
14615 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14616
14617 // Seed the settings file with a plain static light theme so the
14618 // first toggle always starts from a known persisted state.
14619 workspace.update_in(cx, |_workspace, _window, cx| {
14620 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14621 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14622 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14623 });
14624 });
14625 cx.executor().advance_clock(Duration::from_millis(200));
14626 cx.run_until_parked();
14627
14628 // Confirm the initial persisted settings contain the static theme
14629 // we just wrote before any toggling happens.
14630 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14631 assert!(settings_text.contains(r#""theme": "One Light""#));
14632
14633 // Toggle once. This should migrate the persisted theme settings
14634 // into light/dark slots and enable system mode.
14635 workspace.update_in(cx, |workspace, window, cx| {
14636 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14637 });
14638 cx.executor().advance_clock(Duration::from_millis(200));
14639 cx.run_until_parked();
14640
14641 // 1. Static -> Dynamic
14642 // this assertion checks theme changed from static to dynamic.
14643 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14644 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14645 assert_eq!(
14646 parsed["theme"],
14647 serde_json::json!({
14648 "mode": "system",
14649 "light": "One Light",
14650 "dark": "One Dark"
14651 })
14652 );
14653
14654 // 2. Toggle again, suppose it will change the mode to light
14655 workspace.update_in(cx, |workspace, window, cx| {
14656 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14657 });
14658 cx.executor().advance_clock(Duration::from_millis(200));
14659 cx.run_until_parked();
14660
14661 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14662 assert!(settings_text.contains(r#""mode": "light""#));
14663 }
14664
14665 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14666 let item = TestProjectItem::new(id, path, cx);
14667 item.update(cx, |item, _| {
14668 item.is_dirty = true;
14669 });
14670 item
14671 }
14672
14673 #[gpui::test]
14674 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14675 cx: &mut gpui::TestAppContext,
14676 ) {
14677 init_test(cx);
14678 let fs = FakeFs::new(cx.executor());
14679
14680 let project = Project::test(fs, [], cx).await;
14681 let (workspace, cx) =
14682 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14683
14684 let panel = workspace.update_in(cx, |workspace, window, cx| {
14685 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14686 workspace.add_panel(panel.clone(), window, cx);
14687 workspace
14688 .right_dock()
14689 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14690 panel
14691 });
14692
14693 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14694 pane.update_in(cx, |pane, window, cx| {
14695 let item = cx.new(TestItem::new);
14696 pane.add_item(Box::new(item), true, true, None, window, cx);
14697 });
14698
14699 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14700 // mirrors the real-world flow and avoids side effects from directly
14701 // focusing the panel while the center pane is active.
14702 workspace.update_in(cx, |workspace, window, cx| {
14703 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14704 });
14705
14706 panel.update_in(cx, |panel, window, cx| {
14707 panel.set_zoomed(true, window, cx);
14708 });
14709
14710 workspace.update_in(cx, |workspace, window, cx| {
14711 assert!(workspace.right_dock().read(cx).is_open());
14712 assert!(panel.is_zoomed(window, cx));
14713 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14714 });
14715
14716 // Simulate a spurious pane::Event::Focus on the center pane while the
14717 // panel still has focus. This mirrors what happens during macOS window
14718 // activation: the center pane fires a focus event even though actual
14719 // focus remains on the dock panel.
14720 pane.update_in(cx, |_, _, cx| {
14721 cx.emit(pane::Event::Focus);
14722 });
14723
14724 // The dock must remain open because the panel had focus at the time the
14725 // event was processed. Before the fix, dock_to_preserve was None for
14726 // panels that don't implement pane(), causing the dock to close.
14727 workspace.update_in(cx, |workspace, window, cx| {
14728 assert!(
14729 workspace.right_dock().read(cx).is_open(),
14730 "Dock should stay open when its zoomed panel (without pane()) still has focus"
14731 );
14732 assert!(panel.is_zoomed(window, cx));
14733 });
14734 }
14735
14736 #[gpui::test]
14737 async fn test_panels_stay_open_after_position_change_and_settings_update(
14738 cx: &mut gpui::TestAppContext,
14739 ) {
14740 init_test(cx);
14741 let fs = FakeFs::new(cx.executor());
14742 let project = Project::test(fs, [], cx).await;
14743 let (workspace, cx) =
14744 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14745
14746 // Add two panels to the left dock and open it.
14747 let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14748 let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14749 let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14750 workspace.add_panel(panel_a.clone(), window, cx);
14751 workspace.add_panel(panel_b.clone(), window, cx);
14752 workspace.left_dock().update(cx, |dock, cx| {
14753 dock.set_open(true, window, cx);
14754 dock.activate_panel(0, window, cx);
14755 });
14756 (panel_a, panel_b)
14757 });
14758
14759 workspace.update_in(cx, |workspace, _, cx| {
14760 assert!(workspace.left_dock().read(cx).is_open());
14761 });
14762
14763 // Simulate a feature flag changing default dock positions: both panels
14764 // move from Left to Right.
14765 workspace.update_in(cx, |_workspace, _window, cx| {
14766 panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14767 panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14768 cx.update_global::<SettingsStore, _>(|_, _| {});
14769 });
14770
14771 // Both panels should now be in the right dock.
14772 workspace.update_in(cx, |workspace, _, cx| {
14773 let right_dock = workspace.right_dock().read(cx);
14774 assert_eq!(right_dock.panels_len(), 2);
14775 });
14776
14777 // Open the right dock and activate panel_b (simulating the user
14778 // opening the panel after it moved).
14779 workspace.update_in(cx, |workspace, window, cx| {
14780 workspace.right_dock().update(cx, |dock, cx| {
14781 dock.set_open(true, window, cx);
14782 dock.activate_panel(1, window, cx);
14783 });
14784 });
14785
14786 // Now trigger another SettingsStore change
14787 workspace.update_in(cx, |_workspace, _window, cx| {
14788 cx.update_global::<SettingsStore, _>(|_, _| {});
14789 });
14790
14791 workspace.update_in(cx, |workspace, _, cx| {
14792 assert!(
14793 workspace.right_dock().read(cx).is_open(),
14794 "Right dock should still be open after a settings change"
14795 );
14796 assert_eq!(
14797 workspace.right_dock().read(cx).panels_len(),
14798 2,
14799 "Both panels should still be in the right dock"
14800 );
14801 });
14802 }
14803}