1pub mod dock;
2pub mod history_manager;
3pub mod invalid_item_view;
4pub mod item;
5mod modal_layer;
6mod multi_workspace;
7pub mod notifications;
8pub mod pane;
9pub mod pane_group;
10pub mod path_list {
11 pub use util::path_list::{PathList, SerializedPathList};
12}
13mod persistence;
14pub mod searchable;
15mod security_modal;
16pub mod shared_screen;
17use db::smol::future::yield_now;
18pub use shared_screen::SharedScreen;
19mod status_bar;
20pub mod tasks;
21mod theme_preview;
22mod toast_layer;
23mod toolbar;
24pub mod welcome;
25mod workspace_settings;
26
27pub use crate::notifications::NotificationFrame;
28pub use dock::Panel;
29pub use multi_workspace::{
30 CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
31 MultiWorkspaceEvent, NextWorkspace, PreviousWorkspace, Sidebar, SidebarHandle,
32 SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar, sidebar_side_context_menu,
33};
34pub use path_list::{PathList, SerializedPathList};
35pub use toast_layer::{ToastAction, ToastLayer, ToastView};
36
37use anyhow::{Context as _, Result, anyhow};
38use client::{
39 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
40 proto::{self, ErrorCode, PanelId, PeerId},
41};
42use collections::{HashMap, HashSet, hash_map};
43use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
44use fs::Fs;
45use futures::{
46 Future, FutureExt, StreamExt,
47 channel::{
48 mpsc::{self, UnboundedReceiver, UnboundedSender},
49 oneshot,
50 },
51 future::{Shared, try_join_all},
52};
53use gpui::{
54 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
55 Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
56 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
57 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
58 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
59 WindowOptions, actions, canvas, point, relative, size, transparent_black,
60};
61pub use history_manager::*;
62pub use item::{
63 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
64 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
65};
66use itertools::Itertools;
67use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
68pub use modal_layer::*;
69use node_runtime::NodeRuntime;
70use notifications::{
71 DetachAndPromptErr, Notifications, dismiss_app_notification,
72 simple_message_notification::MessageNotification,
73};
74pub use pane::*;
75pub use pane_group::{
76 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
77 SplitDirection,
78};
79use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
80pub use persistence::{
81 WorkspaceDb, delete_unloaded_items,
82 model::{
83 DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
84 SessionWorkspace,
85 },
86 read_serialized_multi_workspaces, resolve_worktree_workspaces,
87};
88use postage::stream::Stream;
89use project::{
90 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
91 WorktreeSettings,
92 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
93 project_settings::ProjectSettings,
94 toolchain_store::ToolchainStoreEvent,
95 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
96};
97use remote::{
98 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
99 remote_client::ConnectionIdentifier,
100};
101use schemars::JsonSchema;
102use serde::Deserialize;
103use session::AppSession;
104use settings::{
105 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
106};
107
108use sqlez::{
109 bindable::{Bind, Column, StaticColumnCount},
110 statement::Statement,
111};
112use status_bar::StatusBar;
113pub use status_bar::StatusItemView;
114use std::{
115 any::TypeId,
116 borrow::Cow,
117 cell::RefCell,
118 cmp,
119 collections::VecDeque,
120 env,
121 hash::Hash,
122 path::{Path, PathBuf},
123 process::ExitStatus,
124 rc::Rc,
125 sync::{
126 Arc, LazyLock, Weak,
127 atomic::{AtomicBool, AtomicUsize},
128 },
129 time::Duration,
130};
131use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
132use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
133pub use toolbar::{
134 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
135};
136pub use ui;
137use ui::{Window, prelude::*};
138use util::{
139 ResultExt, TryFutureExt,
140 paths::{PathStyle, SanitizedPath},
141 rel_path::RelPath,
142 serde::default_true,
143};
144use uuid::Uuid;
145pub use workspace_settings::{
146 AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
147 WorkspaceSettings,
148};
149use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
150
151use crate::{item::ItemBufferKind, notifications::NotificationId};
152use crate::{
153 persistence::{
154 SerializedAxis,
155 model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
156 },
157 security_modal::SecurityModal,
158};
159
160pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
161
162static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
163 env::var("ZED_WINDOW_SIZE")
164 .ok()
165 .as_deref()
166 .and_then(parse_pixel_size_env_var)
167});
168
169static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
170 env::var("ZED_WINDOW_POSITION")
171 .ok()
172 .as_deref()
173 .and_then(parse_pixel_position_env_var)
174});
175
176pub trait TerminalProvider {
177 fn spawn(
178 &self,
179 task: SpawnInTerminal,
180 window: &mut Window,
181 cx: &mut App,
182 ) -> Task<Option<Result<ExitStatus>>>;
183}
184
185pub trait DebuggerProvider {
186 // `active_buffer` is used to resolve build task's name against language-specific tasks.
187 fn start_session(
188 &self,
189 definition: DebugScenario,
190 task_context: SharedTaskContext,
191 active_buffer: Option<Entity<Buffer>>,
192 worktree_id: Option<WorktreeId>,
193 window: &mut Window,
194 cx: &mut App,
195 );
196
197 fn spawn_task_or_modal(
198 &self,
199 workspace: &mut Workspace,
200 action: &Spawn,
201 window: &mut Window,
202 cx: &mut Context<Workspace>,
203 );
204
205 fn task_scheduled(&self, cx: &mut App);
206 fn debug_scenario_scheduled(&self, cx: &mut App);
207 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
208
209 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
210}
211
212/// Opens a file or directory.
213#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
214#[action(namespace = workspace)]
215pub struct Open {
216 /// When true, opens in a new window. When false, adds to the current
217 /// window as a new workspace (multi-workspace).
218 #[serde(default = "Open::default_create_new_window")]
219 pub create_new_window: bool,
220}
221
222impl Open {
223 pub const DEFAULT: Self = Self {
224 create_new_window: true,
225 };
226
227 /// Used by `#[serde(default)]` on the `create_new_window` field so that
228 /// the serde default and `Open::DEFAULT` stay in sync.
229 fn default_create_new_window() -> bool {
230 Self::DEFAULT.create_new_window
231 }
232}
233
234impl Default for Open {
235 fn default() -> Self {
236 Self::DEFAULT
237 }
238}
239
240actions!(
241 workspace,
242 [
243 /// Activates the next pane in the workspace.
244 ActivateNextPane,
245 /// Activates the previous pane in the workspace.
246 ActivatePreviousPane,
247 /// Activates the last pane in the workspace.
248 ActivateLastPane,
249 /// Switches to the next window.
250 ActivateNextWindow,
251 /// Switches to the previous window.
252 ActivatePreviousWindow,
253 /// Adds a folder to the current project.
254 AddFolderToProject,
255 /// Clears all notifications.
256 ClearAllNotifications,
257 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
258 ClearNavigationHistory,
259 /// Closes the active dock.
260 CloseActiveDock,
261 /// Closes all docks.
262 CloseAllDocks,
263 /// Toggles all docks.
264 ToggleAllDocks,
265 /// Closes the current window.
266 CloseWindow,
267 /// Closes the current project.
268 CloseProject,
269 /// Opens the feedback dialog.
270 Feedback,
271 /// Follows the next collaborator in the session.
272 FollowNextCollaborator,
273 /// Moves the focused panel to the next position.
274 MoveFocusedPanelToNextPosition,
275 /// Creates a new file.
276 NewFile,
277 /// Creates a new file in a vertical split.
278 NewFileSplitVertical,
279 /// Creates a new file in a horizontal split.
280 NewFileSplitHorizontal,
281 /// Opens a new search.
282 NewSearch,
283 /// Opens a new window.
284 NewWindow,
285 /// Opens multiple files.
286 OpenFiles,
287 /// Opens the current location in terminal.
288 OpenInTerminal,
289 /// Opens the component preview.
290 OpenComponentPreview,
291 /// Reloads the active item.
292 ReloadActiveItem,
293 /// Resets the active dock to its default size.
294 ResetActiveDockSize,
295 /// Resets all open docks to their default sizes.
296 ResetOpenDocksSize,
297 /// Reloads the application
298 Reload,
299 /// Saves the current file with a new name.
300 SaveAs,
301 /// Saves without formatting.
302 SaveWithoutFormat,
303 /// Shuts down all debug adapters.
304 ShutdownDebugAdapters,
305 /// Suppresses the current notification.
306 SuppressNotification,
307 /// Toggles the bottom dock.
308 ToggleBottomDock,
309 /// Toggles centered layout mode.
310 ToggleCenteredLayout,
311 /// Toggles edit prediction feature globally for all files.
312 ToggleEditPrediction,
313 /// Toggles the left dock.
314 ToggleLeftDock,
315 /// Toggles the right dock.
316 ToggleRightDock,
317 /// Toggles zoom on the active pane.
318 ToggleZoom,
319 /// Toggles read-only mode for the active item (if supported by that item).
320 ToggleReadOnlyFile,
321 /// Zooms in on the active pane.
322 ZoomIn,
323 /// Zooms out of the active pane.
324 ZoomOut,
325 /// If any worktrees are in restricted mode, shows a modal with possible actions.
326 /// If the modal is shown already, closes it without trusting any worktree.
327 ToggleWorktreeSecurity,
328 /// Clears all trusted worktrees, placing them in restricted mode on next open.
329 /// Requires restart to take effect on already opened projects.
330 ClearTrustedWorktrees,
331 /// Stops following a collaborator.
332 Unfollow,
333 /// Restores the banner.
334 RestoreBanner,
335 /// Toggles expansion of the selected item.
336 ToggleExpandItem,
337 ]
338);
339
340/// Activates a specific pane by its index.
341#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
342#[action(namespace = workspace)]
343pub struct ActivatePane(pub usize);
344
345/// Moves an item to a specific pane by index.
346#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
347#[action(namespace = workspace)]
348#[serde(deny_unknown_fields)]
349pub struct MoveItemToPane {
350 #[serde(default = "default_1")]
351 pub destination: usize,
352 #[serde(default = "default_true")]
353 pub focus: bool,
354 #[serde(default)]
355 pub clone: bool,
356}
357
358fn default_1() -> usize {
359 1
360}
361
362/// Moves an item to a pane in the specified direction.
363#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
364#[action(namespace = workspace)]
365#[serde(deny_unknown_fields)]
366pub struct MoveItemToPaneInDirection {
367 #[serde(default = "default_right")]
368 pub direction: SplitDirection,
369 #[serde(default = "default_true")]
370 pub focus: bool,
371 #[serde(default)]
372 pub clone: bool,
373}
374
375/// Creates a new file in a split of the desired direction.
376#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
377#[action(namespace = workspace)]
378#[serde(deny_unknown_fields)]
379pub struct NewFileSplit(pub SplitDirection);
380
381fn default_right() -> SplitDirection {
382 SplitDirection::Right
383}
384
385/// Saves all open files in the workspace.
386#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
387#[action(namespace = workspace)]
388#[serde(deny_unknown_fields)]
389pub struct SaveAll {
390 #[serde(default)]
391 pub save_intent: Option<SaveIntent>,
392}
393
394/// Saves the current file with the specified options.
395#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
396#[action(namespace = workspace)]
397#[serde(deny_unknown_fields)]
398pub struct Save {
399 #[serde(default)]
400 pub save_intent: Option<SaveIntent>,
401}
402
403/// Moves Focus to the central panes in the workspace.
404#[derive(Clone, Debug, PartialEq, Eq, Action)]
405#[action(namespace = workspace)]
406pub struct FocusCenterPane;
407
408/// Closes all items and panes in the workspace.
409#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
410#[action(namespace = workspace)]
411#[serde(deny_unknown_fields)]
412pub struct CloseAllItemsAndPanes {
413 #[serde(default)]
414 pub save_intent: Option<SaveIntent>,
415}
416
417/// Closes all inactive tabs and panes in the workspace.
418#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
419#[action(namespace = workspace)]
420#[serde(deny_unknown_fields)]
421pub struct CloseInactiveTabsAndPanes {
422 #[serde(default)]
423 pub save_intent: Option<SaveIntent>,
424}
425
426/// Closes the active item across all panes.
427#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
428#[action(namespace = workspace)]
429#[serde(deny_unknown_fields)]
430pub struct CloseItemInAllPanes {
431 #[serde(default)]
432 pub save_intent: Option<SaveIntent>,
433 #[serde(default)]
434 pub close_pinned: bool,
435}
436
437/// Sends a sequence of keystrokes to the active element.
438#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
439#[action(namespace = workspace)]
440pub struct SendKeystrokes(pub String);
441
442actions!(
443 project_symbols,
444 [
445 /// Toggles the project symbols search.
446 #[action(name = "Toggle")]
447 ToggleProjectSymbols
448 ]
449);
450
451/// Toggles the file finder interface.
452#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
453#[action(namespace = file_finder, name = "Toggle")]
454#[serde(deny_unknown_fields)]
455pub struct ToggleFileFinder {
456 #[serde(default)]
457 pub separate_history: bool,
458}
459
460/// Opens a new terminal in the center.
461#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
462#[action(namespace = workspace)]
463#[serde(deny_unknown_fields)]
464pub struct NewCenterTerminal {
465 /// If true, creates a local terminal even in remote projects.
466 #[serde(default)]
467 pub local: bool,
468}
469
470/// Opens a new terminal.
471#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
472#[action(namespace = workspace)]
473#[serde(deny_unknown_fields)]
474pub struct NewTerminal {
475 /// If true, creates a local terminal even in remote projects.
476 #[serde(default)]
477 pub local: bool,
478}
479
480/// Increases size of a currently focused dock by a given amount of pixels.
481#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
482#[action(namespace = workspace)]
483#[serde(deny_unknown_fields)]
484pub struct IncreaseActiveDockSize {
485 /// For 0px parameter, uses UI font size value.
486 #[serde(default)]
487 pub px: u32,
488}
489
490/// Decreases size of a currently focused dock by a given amount of pixels.
491#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
492#[action(namespace = workspace)]
493#[serde(deny_unknown_fields)]
494pub struct DecreaseActiveDockSize {
495 /// For 0px parameter, uses UI font size value.
496 #[serde(default)]
497 pub px: u32,
498}
499
500/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
501#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
502#[action(namespace = workspace)]
503#[serde(deny_unknown_fields)]
504pub struct IncreaseOpenDocksSize {
505 /// For 0px parameter, uses UI font size value.
506 #[serde(default)]
507 pub px: u32,
508}
509
510/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
511#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
512#[action(namespace = workspace)]
513#[serde(deny_unknown_fields)]
514pub struct DecreaseOpenDocksSize {
515 /// For 0px parameter, uses UI font size value.
516 #[serde(default)]
517 pub px: u32,
518}
519
520actions!(
521 workspace,
522 [
523 /// Activates the pane to the left.
524 ActivatePaneLeft,
525 /// Activates the pane to the right.
526 ActivatePaneRight,
527 /// Activates the pane above.
528 ActivatePaneUp,
529 /// Activates the pane below.
530 ActivatePaneDown,
531 /// Swaps the current pane with the one to the left.
532 SwapPaneLeft,
533 /// Swaps the current pane with the one to the right.
534 SwapPaneRight,
535 /// Swaps the current pane with the one above.
536 SwapPaneUp,
537 /// Swaps the current pane with the one below.
538 SwapPaneDown,
539 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
540 SwapPaneAdjacent,
541 /// Move the current pane to be at the far left.
542 MovePaneLeft,
543 /// Move the current pane to be at the far right.
544 MovePaneRight,
545 /// Move the current pane to be at the very top.
546 MovePaneUp,
547 /// Move the current pane to be at the very bottom.
548 MovePaneDown,
549 ]
550);
551
552#[derive(PartialEq, Eq, Debug)]
553pub enum CloseIntent {
554 /// Quit the program entirely.
555 Quit,
556 /// Close a window.
557 CloseWindow,
558 /// Replace the workspace in an existing window.
559 ReplaceWindow,
560}
561
562#[derive(Clone)]
563pub struct Toast {
564 id: NotificationId,
565 msg: Cow<'static, str>,
566 autohide: bool,
567 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
568}
569
570impl Toast {
571 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
572 Toast {
573 id,
574 msg: msg.into(),
575 on_click: None,
576 autohide: false,
577 }
578 }
579
580 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
581 where
582 M: Into<Cow<'static, str>>,
583 F: Fn(&mut Window, &mut App) + 'static,
584 {
585 self.on_click = Some((message.into(), Arc::new(on_click)));
586 self
587 }
588
589 pub fn autohide(mut self) -> Self {
590 self.autohide = true;
591 self
592 }
593}
594
595impl PartialEq for Toast {
596 fn eq(&self, other: &Self) -> bool {
597 self.id == other.id
598 && self.msg == other.msg
599 && self.on_click.is_some() == other.on_click.is_some()
600 }
601}
602
603/// Opens a new terminal with the specified working directory.
604#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
605#[action(namespace = workspace)]
606#[serde(deny_unknown_fields)]
607pub struct OpenTerminal {
608 pub working_directory: PathBuf,
609 /// If true, creates a local terminal even in remote projects.
610 #[serde(default)]
611 pub local: bool,
612}
613
614#[derive(
615 Clone,
616 Copy,
617 Debug,
618 Default,
619 Hash,
620 PartialEq,
621 Eq,
622 PartialOrd,
623 Ord,
624 serde::Serialize,
625 serde::Deserialize,
626)]
627pub struct WorkspaceId(i64);
628
629impl WorkspaceId {
630 pub fn from_i64(value: i64) -> Self {
631 Self(value)
632 }
633}
634
635impl StaticColumnCount for WorkspaceId {}
636impl Bind for WorkspaceId {
637 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
638 self.0.bind(statement, start_index)
639 }
640}
641impl Column for WorkspaceId {
642 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
643 i64::column(statement, start_index)
644 .map(|(i, next_index)| (Self(i), next_index))
645 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
646 }
647}
648impl From<WorkspaceId> for i64 {
649 fn from(val: WorkspaceId) -> Self {
650 val.0
651 }
652}
653
654fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
655 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
656 workspace_window
657 .update(cx, |multi_workspace, window, cx| {
658 let workspace = multi_workspace.workspace().clone();
659 workspace.update(cx, |workspace, cx| {
660 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
661 });
662 })
663 .ok();
664 } else {
665 let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, true, cx);
666 cx.spawn(async move |cx| {
667 let OpenResult { window, .. } = task.await?;
668 window.update(cx, |multi_workspace, window, cx| {
669 window.activate_window();
670 let workspace = multi_workspace.workspace().clone();
671 workspace.update(cx, |workspace, cx| {
672 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
673 });
674 })?;
675 anyhow::Ok(())
676 })
677 .detach_and_log_err(cx);
678 }
679}
680
681pub fn prompt_for_open_path_and_open(
682 workspace: &mut Workspace,
683 app_state: Arc<AppState>,
684 options: PathPromptOptions,
685 create_new_window: bool,
686 window: &mut Window,
687 cx: &mut Context<Workspace>,
688) {
689 let paths = workspace.prompt_for_open_path(
690 options,
691 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
692 window,
693 cx,
694 );
695 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
696 cx.spawn_in(window, async move |this, cx| {
697 let Some(paths) = paths.await.log_err().flatten() else {
698 return;
699 };
700 if !create_new_window {
701 if let Some(handle) = multi_workspace_handle {
702 if let Some(task) = handle
703 .update(cx, |multi_workspace, window, cx| {
704 multi_workspace.open_project(paths, window, cx)
705 })
706 .log_err()
707 {
708 task.await.log_err();
709 }
710 return;
711 }
712 }
713 if let Some(task) = this
714 .update_in(cx, |this, window, cx| {
715 this.open_workspace_for_paths(false, paths, window, cx)
716 })
717 .log_err()
718 {
719 task.await.log_err();
720 }
721 })
722 .detach();
723}
724
725pub fn init(app_state: Arc<AppState>, cx: &mut App) {
726 component::init();
727 theme_preview::init(cx);
728 toast_layer::init(cx);
729 history_manager::init(app_state.fs.clone(), cx);
730
731 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
732 .on_action(|_: &Reload, cx| reload(cx))
733 .on_action({
734 let app_state = Arc::downgrade(&app_state);
735 move |_: &Open, cx: &mut App| {
736 if let Some(app_state) = app_state.upgrade() {
737 prompt_and_open_paths(
738 app_state,
739 PathPromptOptions {
740 files: true,
741 directories: true,
742 multiple: true,
743 prompt: None,
744 },
745 cx,
746 );
747 }
748 }
749 })
750 .on_action({
751 let app_state = Arc::downgrade(&app_state);
752 move |_: &OpenFiles, cx: &mut App| {
753 let directories = cx.can_select_mixed_files_and_dirs();
754 if let Some(app_state) = app_state.upgrade() {
755 prompt_and_open_paths(
756 app_state,
757 PathPromptOptions {
758 files: true,
759 directories,
760 multiple: true,
761 prompt: None,
762 },
763 cx,
764 );
765 }
766 }
767 });
768}
769
770type BuildProjectItemFn =
771 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
772
773type BuildProjectItemForPathFn =
774 fn(
775 &Entity<Project>,
776 &ProjectPath,
777 &mut Window,
778 &mut App,
779 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
780
781#[derive(Clone, Default)]
782struct ProjectItemRegistry {
783 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
784 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
785}
786
787impl ProjectItemRegistry {
788 fn register<T: ProjectItem>(&mut self) {
789 self.build_project_item_fns_by_type.insert(
790 TypeId::of::<T::Item>(),
791 |item, project, pane, window, cx| {
792 let item = item.downcast().unwrap();
793 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
794 as Box<dyn ItemHandle>
795 },
796 );
797 self.build_project_item_for_path_fns
798 .push(|project, project_path, window, cx| {
799 let project_path = project_path.clone();
800 let is_file = project
801 .read(cx)
802 .entry_for_path(&project_path, cx)
803 .is_some_and(|entry| entry.is_file());
804 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
805 let is_local = project.read(cx).is_local();
806 let project_item =
807 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
808 let project = project.clone();
809 Some(window.spawn(cx, async move |cx| {
810 match project_item.await.with_context(|| {
811 format!(
812 "opening project path {:?}",
813 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
814 )
815 }) {
816 Ok(project_item) => {
817 let project_item = project_item;
818 let project_entry_id: Option<ProjectEntryId> =
819 project_item.read_with(cx, project::ProjectItem::entry_id);
820 let build_workspace_item = Box::new(
821 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
822 Box::new(cx.new(|cx| {
823 T::for_project_item(
824 project,
825 Some(pane),
826 project_item,
827 window,
828 cx,
829 )
830 })) as Box<dyn ItemHandle>
831 },
832 ) as Box<_>;
833 Ok((project_entry_id, build_workspace_item))
834 }
835 Err(e) => {
836 log::warn!("Failed to open a project item: {e:#}");
837 if e.error_code() == ErrorCode::Internal {
838 if let Some(abs_path) =
839 entry_abs_path.as_deref().filter(|_| is_file)
840 {
841 if let Some(broken_project_item_view) =
842 cx.update(|window, cx| {
843 T::for_broken_project_item(
844 abs_path, is_local, &e, window, cx,
845 )
846 })?
847 {
848 let build_workspace_item = Box::new(
849 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
850 cx.new(|_| broken_project_item_view).boxed_clone()
851 },
852 )
853 as Box<_>;
854 return Ok((None, build_workspace_item));
855 }
856 }
857 }
858 Err(e)
859 }
860 }
861 }))
862 });
863 }
864
865 fn open_path(
866 &self,
867 project: &Entity<Project>,
868 path: &ProjectPath,
869 window: &mut Window,
870 cx: &mut App,
871 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
872 let Some(open_project_item) = self
873 .build_project_item_for_path_fns
874 .iter()
875 .rev()
876 .find_map(|open_project_item| open_project_item(project, path, window, cx))
877 else {
878 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
879 };
880 open_project_item
881 }
882
883 fn build_item<T: project::ProjectItem>(
884 &self,
885 item: Entity<T>,
886 project: Entity<Project>,
887 pane: Option<&Pane>,
888 window: &mut Window,
889 cx: &mut App,
890 ) -> Option<Box<dyn ItemHandle>> {
891 let build = self
892 .build_project_item_fns_by_type
893 .get(&TypeId::of::<T>())?;
894 Some(build(item.into_any(), project, pane, window, cx))
895 }
896}
897
898type WorkspaceItemBuilder =
899 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
900
901impl Global for ProjectItemRegistry {}
902
903/// Registers a [ProjectItem] for the app. When opening a file, all the registered
904/// items will get a chance to open the file, starting from the project item that
905/// was added last.
906pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
907 cx.default_global::<ProjectItemRegistry>().register::<I>();
908}
909
910#[derive(Default)]
911pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
912
913struct FollowableViewDescriptor {
914 from_state_proto: fn(
915 Entity<Workspace>,
916 ViewId,
917 &mut Option<proto::view::Variant>,
918 &mut Window,
919 &mut App,
920 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
921 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
922}
923
924impl Global for FollowableViewRegistry {}
925
926impl FollowableViewRegistry {
927 pub fn register<I: FollowableItem>(cx: &mut App) {
928 cx.default_global::<Self>().0.insert(
929 TypeId::of::<I>(),
930 FollowableViewDescriptor {
931 from_state_proto: |workspace, id, state, window, cx| {
932 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
933 cx.foreground_executor()
934 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
935 })
936 },
937 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
938 },
939 );
940 }
941
942 pub fn from_state_proto(
943 workspace: Entity<Workspace>,
944 view_id: ViewId,
945 mut state: Option<proto::view::Variant>,
946 window: &mut Window,
947 cx: &mut App,
948 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
949 cx.update_default_global(|this: &mut Self, cx| {
950 this.0.values().find_map(|descriptor| {
951 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
952 })
953 })
954 }
955
956 pub fn to_followable_view(
957 view: impl Into<AnyView>,
958 cx: &App,
959 ) -> Option<Box<dyn FollowableItemHandle>> {
960 let this = cx.try_global::<Self>()?;
961 let view = view.into();
962 let descriptor = this.0.get(&view.entity_type())?;
963 Some((descriptor.to_followable_view)(&view))
964 }
965}
966
967#[derive(Copy, Clone)]
968struct SerializableItemDescriptor {
969 deserialize: fn(
970 Entity<Project>,
971 WeakEntity<Workspace>,
972 WorkspaceId,
973 ItemId,
974 &mut Window,
975 &mut Context<Pane>,
976 ) -> Task<Result<Box<dyn ItemHandle>>>,
977 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
978 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
979}
980
981#[derive(Default)]
982struct SerializableItemRegistry {
983 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
984 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
985}
986
987impl Global for SerializableItemRegistry {}
988
989impl SerializableItemRegistry {
990 fn deserialize(
991 item_kind: &str,
992 project: Entity<Project>,
993 workspace: WeakEntity<Workspace>,
994 workspace_id: WorkspaceId,
995 item_item: ItemId,
996 window: &mut Window,
997 cx: &mut Context<Pane>,
998 ) -> Task<Result<Box<dyn ItemHandle>>> {
999 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1000 return Task::ready(Err(anyhow!(
1001 "cannot deserialize {}, descriptor not found",
1002 item_kind
1003 )));
1004 };
1005
1006 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1007 }
1008
1009 fn cleanup(
1010 item_kind: &str,
1011 workspace_id: WorkspaceId,
1012 loaded_items: Vec<ItemId>,
1013 window: &mut Window,
1014 cx: &mut App,
1015 ) -> Task<Result<()>> {
1016 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1017 return Task::ready(Err(anyhow!(
1018 "cannot cleanup {}, descriptor not found",
1019 item_kind
1020 )));
1021 };
1022
1023 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1024 }
1025
1026 fn view_to_serializable_item_handle(
1027 view: AnyView,
1028 cx: &App,
1029 ) -> Option<Box<dyn SerializableItemHandle>> {
1030 let this = cx.try_global::<Self>()?;
1031 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1032 Some((descriptor.view_to_serializable_item)(view))
1033 }
1034
1035 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1036 let this = cx.try_global::<Self>()?;
1037 this.descriptors_by_kind.get(item_kind).copied()
1038 }
1039}
1040
1041pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1042 let serialized_item_kind = I::serialized_item_kind();
1043
1044 let registry = cx.default_global::<SerializableItemRegistry>();
1045 let descriptor = SerializableItemDescriptor {
1046 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1047 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1048 cx.foreground_executor()
1049 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1050 },
1051 cleanup: |workspace_id, loaded_items, window, cx| {
1052 I::cleanup(workspace_id, loaded_items, window, cx)
1053 },
1054 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1055 };
1056 registry
1057 .descriptors_by_kind
1058 .insert(Arc::from(serialized_item_kind), descriptor);
1059 registry
1060 .descriptors_by_type
1061 .insert(TypeId::of::<I>(), descriptor);
1062}
1063
1064pub struct AppState {
1065 pub languages: Arc<LanguageRegistry>,
1066 pub client: Arc<Client>,
1067 pub user_store: Entity<UserStore>,
1068 pub workspace_store: Entity<WorkspaceStore>,
1069 pub fs: Arc<dyn fs::Fs>,
1070 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1071 pub node_runtime: NodeRuntime,
1072 pub session: Entity<AppSession>,
1073}
1074
1075struct GlobalAppState(Weak<AppState>);
1076
1077impl Global for GlobalAppState {}
1078
1079pub struct WorkspaceStore {
1080 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1081 client: Arc<Client>,
1082 _subscriptions: Vec<client::Subscription>,
1083}
1084
1085#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1086pub enum CollaboratorId {
1087 PeerId(PeerId),
1088 Agent,
1089}
1090
1091impl From<PeerId> for CollaboratorId {
1092 fn from(peer_id: PeerId) -> Self {
1093 CollaboratorId::PeerId(peer_id)
1094 }
1095}
1096
1097impl From<&PeerId> for CollaboratorId {
1098 fn from(peer_id: &PeerId) -> Self {
1099 CollaboratorId::PeerId(*peer_id)
1100 }
1101}
1102
1103#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1104struct Follower {
1105 project_id: Option<u64>,
1106 peer_id: PeerId,
1107}
1108
1109impl AppState {
1110 #[track_caller]
1111 pub fn global(cx: &App) -> Weak<Self> {
1112 cx.global::<GlobalAppState>().0.clone()
1113 }
1114 pub fn try_global(cx: &App) -> Option<Weak<Self>> {
1115 cx.try_global::<GlobalAppState>()
1116 .map(|state| state.0.clone())
1117 }
1118 pub fn set_global(state: Weak<AppState>, cx: &mut App) {
1119 cx.set_global(GlobalAppState(state));
1120 }
1121
1122 #[cfg(any(test, feature = "test-support"))]
1123 pub fn test(cx: &mut App) -> Arc<Self> {
1124 use fs::Fs;
1125 use node_runtime::NodeRuntime;
1126 use session::Session;
1127 use settings::SettingsStore;
1128
1129 if !cx.has_global::<SettingsStore>() {
1130 let settings_store = SettingsStore::test(cx);
1131 cx.set_global(settings_store);
1132 }
1133
1134 let fs = fs::FakeFs::new(cx.background_executor().clone());
1135 <dyn Fs>::set_global(fs.clone(), cx);
1136 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1137 let clock = Arc::new(clock::FakeSystemClock::new());
1138 let http_client = http_client::FakeHttpClient::with_404_response();
1139 let client = Client::new(clock, http_client, cx);
1140 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1141 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1142 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1143
1144 theme::init(theme::LoadThemes::JustBase, cx);
1145 client::init(&client, cx);
1146
1147 Arc::new(Self {
1148 client,
1149 fs,
1150 languages,
1151 user_store,
1152 workspace_store,
1153 node_runtime: NodeRuntime::unavailable(),
1154 build_window_options: |_, _| Default::default(),
1155 session,
1156 })
1157 }
1158}
1159
1160struct DelayedDebouncedEditAction {
1161 task: Option<Task<()>>,
1162 cancel_channel: Option<oneshot::Sender<()>>,
1163}
1164
1165impl DelayedDebouncedEditAction {
1166 fn new() -> DelayedDebouncedEditAction {
1167 DelayedDebouncedEditAction {
1168 task: None,
1169 cancel_channel: None,
1170 }
1171 }
1172
1173 fn fire_new<F>(
1174 &mut self,
1175 delay: Duration,
1176 window: &mut Window,
1177 cx: &mut Context<Workspace>,
1178 func: F,
1179 ) where
1180 F: 'static
1181 + Send
1182 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1183 {
1184 if let Some(channel) = self.cancel_channel.take() {
1185 _ = channel.send(());
1186 }
1187
1188 let (sender, mut receiver) = oneshot::channel::<()>();
1189 self.cancel_channel = Some(sender);
1190
1191 let previous_task = self.task.take();
1192 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1193 let mut timer = cx.background_executor().timer(delay).fuse();
1194 if let Some(previous_task) = previous_task {
1195 previous_task.await;
1196 }
1197
1198 futures::select_biased! {
1199 _ = receiver => return,
1200 _ = timer => {}
1201 }
1202
1203 if let Some(result) = workspace
1204 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1205 .log_err()
1206 {
1207 result.await.log_err();
1208 }
1209 }));
1210 }
1211}
1212
1213pub enum Event {
1214 PaneAdded(Entity<Pane>),
1215 PaneRemoved,
1216 ItemAdded {
1217 item: Box<dyn ItemHandle>,
1218 },
1219 ActiveItemChanged,
1220 ItemRemoved {
1221 item_id: EntityId,
1222 },
1223 UserSavedItem {
1224 pane: WeakEntity<Pane>,
1225 item: Box<dyn WeakItemHandle>,
1226 save_intent: SaveIntent,
1227 },
1228 ContactRequestedJoin(u64),
1229 WorkspaceCreated(WeakEntity<Workspace>),
1230 OpenBundledFile {
1231 text: Cow<'static, str>,
1232 title: &'static str,
1233 language: &'static str,
1234 },
1235 ZoomChanged,
1236 ModalOpened,
1237 Activate,
1238 PanelAdded(AnyView),
1239}
1240
1241#[derive(Debug, Clone)]
1242pub enum OpenVisible {
1243 All,
1244 None,
1245 OnlyFiles,
1246 OnlyDirectories,
1247}
1248
1249enum WorkspaceLocation {
1250 // Valid local paths or SSH project to serialize
1251 Location(SerializedWorkspaceLocation, PathList),
1252 // No valid location found hence clear session id
1253 DetachFromSession,
1254 // No valid location found to serialize
1255 None,
1256}
1257
1258type PromptForNewPath = Box<
1259 dyn Fn(
1260 &mut Workspace,
1261 DirectoryLister,
1262 Option<String>,
1263 &mut Window,
1264 &mut Context<Workspace>,
1265 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1266>;
1267
1268type PromptForOpenPath = Box<
1269 dyn Fn(
1270 &mut Workspace,
1271 DirectoryLister,
1272 &mut Window,
1273 &mut Context<Workspace>,
1274 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1275>;
1276
1277#[derive(Default)]
1278struct DispatchingKeystrokes {
1279 dispatched: HashSet<Vec<Keystroke>>,
1280 queue: VecDeque<Keystroke>,
1281 task: Option<Shared<Task<()>>>,
1282}
1283
1284/// Collects everything project-related for a certain window opened.
1285/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1286///
1287/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1288/// The `Workspace` owns everybody's state and serves as a default, "global context",
1289/// that can be used to register a global action to be triggered from any place in the window.
1290pub struct Workspace {
1291 weak_self: WeakEntity<Self>,
1292 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1293 zoomed: Option<AnyWeakView>,
1294 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1295 zoomed_position: Option<DockPosition>,
1296 center: PaneGroup,
1297 left_dock: Entity<Dock>,
1298 bottom_dock: Entity<Dock>,
1299 right_dock: Entity<Dock>,
1300 panes: Vec<Entity<Pane>>,
1301 active_worktree_override: Option<WorktreeId>,
1302 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1303 active_pane: Entity<Pane>,
1304 last_active_center_pane: Option<WeakEntity<Pane>>,
1305 last_active_view_id: Option<proto::ViewId>,
1306 status_bar: Entity<StatusBar>,
1307 pub(crate) modal_layer: Entity<ModalLayer>,
1308 toast_layer: Entity<ToastLayer>,
1309 titlebar_item: Option<AnyView>,
1310 notifications: Notifications,
1311 suppressed_notifications: HashSet<NotificationId>,
1312 project: Entity<Project>,
1313 follower_states: HashMap<CollaboratorId, FollowerState>,
1314 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1315 window_edited: bool,
1316 last_window_title: Option<String>,
1317 dirty_items: HashMap<EntityId, Subscription>,
1318 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1319 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1320 database_id: Option<WorkspaceId>,
1321 app_state: Arc<AppState>,
1322 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1323 _subscriptions: Vec<Subscription>,
1324 _apply_leader_updates: Task<Result<()>>,
1325 _observe_current_user: Task<Result<()>>,
1326 _schedule_serialize_workspace: Option<Task<()>>,
1327 _serialize_workspace_task: Option<Task<()>>,
1328 _schedule_serialize_ssh_paths: Option<Task<()>>,
1329 pane_history_timestamp: Arc<AtomicUsize>,
1330 bounds: Bounds<Pixels>,
1331 pub centered_layout: bool,
1332 bounds_save_task_queued: Option<Task<()>>,
1333 on_prompt_for_new_path: Option<PromptForNewPath>,
1334 on_prompt_for_open_path: Option<PromptForOpenPath>,
1335 terminal_provider: Option<Box<dyn TerminalProvider>>,
1336 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1337 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1338 _items_serializer: Task<Result<()>>,
1339 session_id: Option<String>,
1340 scheduled_tasks: Vec<Task<()>>,
1341 last_open_dock_positions: Vec<DockPosition>,
1342 removing: bool,
1343 _panels_task: Option<Task<Result<()>>>,
1344 sidebar_focus_handle: Option<FocusHandle>,
1345 multi_workspace: Option<WeakEntity<MultiWorkspace>>,
1346}
1347
1348impl EventEmitter<Event> for Workspace {}
1349
1350#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1351pub struct ViewId {
1352 pub creator: CollaboratorId,
1353 pub id: u64,
1354}
1355
1356pub struct FollowerState {
1357 center_pane: Entity<Pane>,
1358 dock_pane: Option<Entity<Pane>>,
1359 active_view_id: Option<ViewId>,
1360 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1361}
1362
1363struct FollowerView {
1364 view: Box<dyn FollowableItemHandle>,
1365 location: Option<proto::PanelId>,
1366}
1367
1368impl Workspace {
1369 pub fn new(
1370 workspace_id: Option<WorkspaceId>,
1371 project: Entity<Project>,
1372 app_state: Arc<AppState>,
1373 window: &mut Window,
1374 cx: &mut Context<Self>,
1375 ) -> Self {
1376 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1377 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1378 if let TrustedWorktreesEvent::Trusted(..) = e {
1379 // Do not persist auto trusted worktrees
1380 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1381 worktrees_store.update(cx, |worktrees_store, cx| {
1382 worktrees_store.schedule_serialization(
1383 cx,
1384 |new_trusted_worktrees, cx| {
1385 let timeout =
1386 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1387 let db = WorkspaceDb::global(cx);
1388 cx.background_spawn(async move {
1389 timeout.await;
1390 db.save_trusted_worktrees(new_trusted_worktrees)
1391 .await
1392 .log_err();
1393 })
1394 },
1395 )
1396 });
1397 }
1398 }
1399 })
1400 .detach();
1401
1402 cx.observe_global::<SettingsStore>(|_, cx| {
1403 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1404 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1405 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1406 trusted_worktrees.auto_trust_all(cx);
1407 })
1408 }
1409 }
1410 })
1411 .detach();
1412 }
1413
1414 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1415 match event {
1416 project::Event::RemoteIdChanged(_) => {
1417 this.update_window_title(window, cx);
1418 }
1419
1420 project::Event::CollaboratorLeft(peer_id) => {
1421 this.collaborator_left(*peer_id, window, cx);
1422 }
1423
1424 &project::Event::WorktreeRemoved(_) => {
1425 this.update_window_title(window, cx);
1426 this.serialize_workspace(window, cx);
1427 this.update_history(cx);
1428 }
1429
1430 &project::Event::WorktreeAdded(id) => {
1431 this.update_window_title(window, cx);
1432 if this
1433 .project()
1434 .read(cx)
1435 .worktree_for_id(id, cx)
1436 .is_some_and(|wt| wt.read(cx).is_visible())
1437 {
1438 this.serialize_workspace(window, cx);
1439 this.update_history(cx);
1440 }
1441 }
1442 project::Event::WorktreeUpdatedEntries(..) => {
1443 this.update_window_title(window, cx);
1444 this.serialize_workspace(window, cx);
1445 }
1446
1447 project::Event::DisconnectedFromHost => {
1448 this.update_window_edited(window, cx);
1449 let leaders_to_unfollow =
1450 this.follower_states.keys().copied().collect::<Vec<_>>();
1451 for leader_id in leaders_to_unfollow {
1452 this.unfollow(leader_id, window, cx);
1453 }
1454 }
1455
1456 project::Event::DisconnectedFromRemote {
1457 server_not_running: _,
1458 } => {
1459 this.update_window_edited(window, cx);
1460 }
1461
1462 project::Event::Closed => {
1463 window.remove_window();
1464 }
1465
1466 project::Event::DeletedEntry(_, entry_id) => {
1467 for pane in this.panes.iter() {
1468 pane.update(cx, |pane, cx| {
1469 pane.handle_deleted_project_item(*entry_id, window, cx)
1470 });
1471 }
1472 }
1473
1474 project::Event::Toast {
1475 notification_id,
1476 message,
1477 link,
1478 } => this.show_notification(
1479 NotificationId::named(notification_id.clone()),
1480 cx,
1481 |cx| {
1482 let mut notification = MessageNotification::new(message.clone(), cx);
1483 if let Some(link) = link {
1484 notification = notification
1485 .more_info_message(link.label)
1486 .more_info_url(link.url);
1487 }
1488
1489 cx.new(|_| notification)
1490 },
1491 ),
1492
1493 project::Event::HideToast { notification_id } => {
1494 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1495 }
1496
1497 project::Event::LanguageServerPrompt(request) => {
1498 struct LanguageServerPrompt;
1499
1500 this.show_notification(
1501 NotificationId::composite::<LanguageServerPrompt>(request.id),
1502 cx,
1503 |cx| {
1504 cx.new(|cx| {
1505 notifications::LanguageServerPrompt::new(request.clone(), cx)
1506 })
1507 },
1508 );
1509 }
1510
1511 project::Event::AgentLocationChanged => {
1512 this.handle_agent_location_changed(window, cx)
1513 }
1514
1515 _ => {}
1516 }
1517 cx.notify()
1518 })
1519 .detach();
1520
1521 cx.subscribe_in(
1522 &project.read(cx).breakpoint_store(),
1523 window,
1524 |workspace, _, event, window, cx| match event {
1525 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1526 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1527 workspace.serialize_workspace(window, cx);
1528 }
1529 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1530 },
1531 )
1532 .detach();
1533 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1534 cx.subscribe_in(
1535 &toolchain_store,
1536 window,
1537 |workspace, _, event, window, cx| match event {
1538 ToolchainStoreEvent::CustomToolchainsModified => {
1539 workspace.serialize_workspace(window, cx);
1540 }
1541 _ => {}
1542 },
1543 )
1544 .detach();
1545 }
1546
1547 cx.on_focus_lost(window, |this, window, cx| {
1548 let focus_handle = this.focus_handle(cx);
1549 window.focus(&focus_handle, cx);
1550 })
1551 .detach();
1552
1553 let weak_handle = cx.entity().downgrade();
1554 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1555
1556 let center_pane = cx.new(|cx| {
1557 let mut center_pane = Pane::new(
1558 weak_handle.clone(),
1559 project.clone(),
1560 pane_history_timestamp.clone(),
1561 None,
1562 NewFile.boxed_clone(),
1563 true,
1564 window,
1565 cx,
1566 );
1567 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1568 center_pane.set_should_display_welcome_page(true);
1569 center_pane
1570 });
1571 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1572 .detach();
1573
1574 window.focus(¢er_pane.focus_handle(cx), cx);
1575
1576 cx.emit(Event::PaneAdded(center_pane.clone()));
1577
1578 let any_window_handle = window.window_handle();
1579 app_state.workspace_store.update(cx, |store, _| {
1580 store
1581 .workspaces
1582 .insert((any_window_handle, weak_handle.clone()));
1583 });
1584
1585 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1586 let mut connection_status = app_state.client.status();
1587 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1588 current_user.next().await;
1589 connection_status.next().await;
1590 let mut stream =
1591 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1592
1593 while stream.recv().await.is_some() {
1594 this.update(cx, |_, cx| cx.notify())?;
1595 }
1596 anyhow::Ok(())
1597 });
1598
1599 // All leader updates are enqueued and then processed in a single task, so
1600 // that each asynchronous operation can be run in order.
1601 let (leader_updates_tx, mut leader_updates_rx) =
1602 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1603 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1604 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1605 Self::process_leader_update(&this, leader_id, update, cx)
1606 .await
1607 .log_err();
1608 }
1609
1610 Ok(())
1611 });
1612
1613 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1614 let modal_layer = cx.new(|_| ModalLayer::new());
1615 let toast_layer = cx.new(|_| ToastLayer::new());
1616 cx.subscribe(
1617 &modal_layer,
1618 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1619 cx.emit(Event::ModalOpened);
1620 },
1621 )
1622 .detach();
1623
1624 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1625 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1626 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1627 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1628 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1629 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1630 let multi_workspace = window
1631 .root::<MultiWorkspace>()
1632 .flatten()
1633 .map(|mw| mw.downgrade());
1634 let status_bar = cx.new(|cx| {
1635 let mut status_bar =
1636 StatusBar::new(¢er_pane.clone(), multi_workspace.clone(), window, cx);
1637 status_bar.add_left_item(left_dock_buttons, window, cx);
1638 status_bar.add_right_item(right_dock_buttons, window, cx);
1639 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1640 status_bar
1641 });
1642
1643 let session_id = app_state.session.read(cx).id().to_owned();
1644
1645 let mut active_call = None;
1646 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1647 let subscriptions =
1648 vec![
1649 call.0
1650 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1651 ];
1652 active_call = Some((call, subscriptions));
1653 }
1654
1655 let (serializable_items_tx, serializable_items_rx) =
1656 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1657 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1658 Self::serialize_items(&this, serializable_items_rx, cx).await
1659 });
1660
1661 let subscriptions = vec![
1662 cx.observe_window_activation(window, Self::on_window_activation_changed),
1663 cx.observe_window_bounds(window, move |this, window, cx| {
1664 if this.bounds_save_task_queued.is_some() {
1665 return;
1666 }
1667 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1668 cx.background_executor()
1669 .timer(Duration::from_millis(100))
1670 .await;
1671 this.update_in(cx, |this, window, cx| {
1672 this.save_window_bounds(window, cx).detach();
1673 this.bounds_save_task_queued.take();
1674 })
1675 .ok();
1676 }));
1677 cx.notify();
1678 }),
1679 cx.observe_window_appearance(window, |_, window, cx| {
1680 let window_appearance = window.appearance();
1681
1682 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1683
1684 GlobalTheme::reload_theme(cx);
1685 GlobalTheme::reload_icon_theme(cx);
1686 }),
1687 cx.on_release({
1688 let weak_handle = weak_handle.clone();
1689 move |this, cx| {
1690 this.app_state.workspace_store.update(cx, move |store, _| {
1691 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1692 })
1693 }
1694 }),
1695 ];
1696
1697 cx.defer_in(window, move |this, window, cx| {
1698 this.update_window_title(window, cx);
1699 this.show_initial_notifications(cx);
1700 });
1701
1702 let mut center = PaneGroup::new(center_pane.clone());
1703 center.set_is_center(true);
1704 center.mark_positions(cx);
1705
1706 Workspace {
1707 weak_self: weak_handle.clone(),
1708 zoomed: None,
1709 zoomed_position: None,
1710 previous_dock_drag_coordinates: None,
1711 center,
1712 panes: vec![center_pane.clone()],
1713 panes_by_item: Default::default(),
1714 active_pane: center_pane.clone(),
1715 last_active_center_pane: Some(center_pane.downgrade()),
1716 last_active_view_id: None,
1717 status_bar,
1718 modal_layer,
1719 toast_layer,
1720 titlebar_item: None,
1721 active_worktree_override: None,
1722 notifications: Notifications::default(),
1723 suppressed_notifications: HashSet::default(),
1724 left_dock,
1725 bottom_dock,
1726 right_dock,
1727 _panels_task: None,
1728 project: project.clone(),
1729 follower_states: Default::default(),
1730 last_leaders_by_pane: Default::default(),
1731 dispatching_keystrokes: Default::default(),
1732 window_edited: false,
1733 last_window_title: None,
1734 dirty_items: Default::default(),
1735 active_call,
1736 database_id: workspace_id,
1737 app_state,
1738 _observe_current_user,
1739 _apply_leader_updates,
1740 _schedule_serialize_workspace: None,
1741 _serialize_workspace_task: None,
1742 _schedule_serialize_ssh_paths: None,
1743 leader_updates_tx,
1744 _subscriptions: subscriptions,
1745 pane_history_timestamp,
1746 workspace_actions: Default::default(),
1747 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1748 bounds: Default::default(),
1749 centered_layout: false,
1750 bounds_save_task_queued: None,
1751 on_prompt_for_new_path: None,
1752 on_prompt_for_open_path: None,
1753 terminal_provider: None,
1754 debugger_provider: None,
1755 serializable_items_tx,
1756 _items_serializer,
1757 session_id: Some(session_id),
1758
1759 scheduled_tasks: Vec::new(),
1760 last_open_dock_positions: Vec::new(),
1761 removing: false,
1762 sidebar_focus_handle: None,
1763 multi_workspace,
1764 }
1765 }
1766
1767 pub fn new_local(
1768 abs_paths: Vec<PathBuf>,
1769 app_state: Arc<AppState>,
1770 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1771 env: Option<HashMap<String, String>>,
1772 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1773 activate: bool,
1774 cx: &mut App,
1775 ) -> Task<anyhow::Result<OpenResult>> {
1776 let project_handle = Project::local(
1777 app_state.client.clone(),
1778 app_state.node_runtime.clone(),
1779 app_state.user_store.clone(),
1780 app_state.languages.clone(),
1781 app_state.fs.clone(),
1782 env,
1783 Default::default(),
1784 cx,
1785 );
1786
1787 let db = WorkspaceDb::global(cx);
1788 let kvp = db::kvp::KeyValueStore::global(cx);
1789 cx.spawn(async move |cx| {
1790 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1791 for path in abs_paths.into_iter() {
1792 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1793 paths_to_open.push(canonical)
1794 } else {
1795 paths_to_open.push(path)
1796 }
1797 }
1798
1799 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1800
1801 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1802 paths_to_open = paths.ordered_paths().cloned().collect();
1803 if !paths.is_lexicographically_ordered() {
1804 project_handle.update(cx, |project, cx| {
1805 project.set_worktrees_reordered(true, cx);
1806 });
1807 }
1808 }
1809
1810 // Get project paths for all of the abs_paths
1811 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1812 Vec::with_capacity(paths_to_open.len());
1813
1814 for path in paths_to_open.into_iter() {
1815 if let Some((_, project_entry)) = cx
1816 .update(|cx| {
1817 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1818 })
1819 .await
1820 .log_err()
1821 {
1822 project_paths.push((path, Some(project_entry)));
1823 } else {
1824 project_paths.push((path, None));
1825 }
1826 }
1827
1828 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1829 serialized_workspace.id
1830 } else {
1831 db.next_id().await.unwrap_or_else(|_| Default::default())
1832 };
1833
1834 let toolchains = db.toolchains(workspace_id).await?;
1835
1836 for (toolchain, worktree_path, path) in toolchains {
1837 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1838 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1839 this.find_worktree(&worktree_path, cx)
1840 .and_then(|(worktree, rel_path)| {
1841 if rel_path.is_empty() {
1842 Some(worktree.read(cx).id())
1843 } else {
1844 None
1845 }
1846 })
1847 }) else {
1848 // We did not find a worktree with a given path, but that's whatever.
1849 continue;
1850 };
1851 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1852 continue;
1853 }
1854
1855 project_handle
1856 .update(cx, |this, cx| {
1857 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1858 })
1859 .await;
1860 }
1861 if let Some(workspace) = serialized_workspace.as_ref() {
1862 project_handle.update(cx, |this, cx| {
1863 for (scope, toolchains) in &workspace.user_toolchains {
1864 for toolchain in toolchains {
1865 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1866 }
1867 }
1868 });
1869 }
1870
1871 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1872 if let Some(window) = requesting_window {
1873 let centered_layout = serialized_workspace
1874 .as_ref()
1875 .map(|w| w.centered_layout)
1876 .unwrap_or(false);
1877
1878 let workspace = window.update(cx, |multi_workspace, window, cx| {
1879 let workspace = cx.new(|cx| {
1880 let mut workspace = Workspace::new(
1881 Some(workspace_id),
1882 project_handle.clone(),
1883 app_state.clone(),
1884 window,
1885 cx,
1886 );
1887
1888 workspace.centered_layout = centered_layout;
1889
1890 // Call init callback to add items before window renders
1891 if let Some(init) = init {
1892 init(&mut workspace, window, cx);
1893 }
1894
1895 workspace
1896 });
1897 if activate {
1898 multi_workspace.activate(workspace.clone(), cx);
1899 } else {
1900 multi_workspace.add_workspace(workspace.clone(), cx);
1901 }
1902 workspace
1903 })?;
1904 (window, workspace)
1905 } else {
1906 let window_bounds_override = window_bounds_env_override();
1907
1908 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1909 (Some(WindowBounds::Windowed(bounds)), None)
1910 } else if let Some(workspace) = serialized_workspace.as_ref()
1911 && let Some(display) = workspace.display
1912 && let Some(bounds) = workspace.window_bounds.as_ref()
1913 {
1914 // Reopening an existing workspace - restore its saved bounds
1915 (Some(bounds.0), Some(display))
1916 } else if let Some((display, bounds)) =
1917 persistence::read_default_window_bounds(&kvp)
1918 {
1919 // New or empty workspace - use the last known window bounds
1920 (Some(bounds), Some(display))
1921 } else {
1922 // New window - let GPUI's default_bounds() handle cascading
1923 (None, None)
1924 };
1925
1926 // Use the serialized workspace to construct the new window
1927 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1928 options.window_bounds = window_bounds;
1929 let centered_layout = serialized_workspace
1930 .as_ref()
1931 .map(|w| w.centered_layout)
1932 .unwrap_or(false);
1933 let window = cx.open_window(options, {
1934 let app_state = app_state.clone();
1935 let project_handle = project_handle.clone();
1936 move |window, cx| {
1937 let workspace = cx.new(|cx| {
1938 let mut workspace = Workspace::new(
1939 Some(workspace_id),
1940 project_handle,
1941 app_state,
1942 window,
1943 cx,
1944 );
1945 workspace.centered_layout = centered_layout;
1946
1947 // Call init callback to add items before window renders
1948 if let Some(init) = init {
1949 init(&mut workspace, window, cx);
1950 }
1951
1952 workspace
1953 });
1954 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1955 }
1956 })?;
1957 let workspace =
1958 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1959 multi_workspace.workspace().clone()
1960 })?;
1961 (window, workspace)
1962 };
1963
1964 notify_if_database_failed(window, cx);
1965 // Check if this is an empty workspace (no paths to open)
1966 // An empty workspace is one where project_paths is empty
1967 let is_empty_workspace = project_paths.is_empty();
1968 // Check if serialized workspace has paths before it's moved
1969 let serialized_workspace_has_paths = serialized_workspace
1970 .as_ref()
1971 .map(|ws| !ws.paths.is_empty())
1972 .unwrap_or(false);
1973
1974 let opened_items = window
1975 .update(cx, |_, window, cx| {
1976 workspace.update(cx, |_workspace: &mut Workspace, cx| {
1977 open_items(serialized_workspace, project_paths, window, cx)
1978 })
1979 })?
1980 .await
1981 .unwrap_or_default();
1982
1983 // Restore default dock state for empty workspaces
1984 // Only restore if:
1985 // 1. This is an empty workspace (no paths), AND
1986 // 2. The serialized workspace either doesn't exist or has no paths
1987 if is_empty_workspace && !serialized_workspace_has_paths {
1988 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
1989 window
1990 .update(cx, |_, window, cx| {
1991 workspace.update(cx, |workspace, cx| {
1992 for (dock, serialized_dock) in [
1993 (&workspace.right_dock, &default_docks.right),
1994 (&workspace.left_dock, &default_docks.left),
1995 (&workspace.bottom_dock, &default_docks.bottom),
1996 ] {
1997 dock.update(cx, |dock, cx| {
1998 dock.serialized_dock = Some(serialized_dock.clone());
1999 dock.restore_state(window, cx);
2000 });
2001 }
2002 cx.notify();
2003 });
2004 })
2005 .log_err();
2006 }
2007 }
2008
2009 window
2010 .update(cx, |_, _window, cx| {
2011 workspace.update(cx, |this: &mut Workspace, cx| {
2012 this.update_history(cx);
2013 });
2014 })
2015 .log_err();
2016 Ok(OpenResult {
2017 window,
2018 workspace,
2019 opened_items,
2020 })
2021 })
2022 }
2023
2024 pub fn weak_handle(&self) -> WeakEntity<Self> {
2025 self.weak_self.clone()
2026 }
2027
2028 pub fn left_dock(&self) -> &Entity<Dock> {
2029 &self.left_dock
2030 }
2031
2032 pub fn bottom_dock(&self) -> &Entity<Dock> {
2033 &self.bottom_dock
2034 }
2035
2036 pub fn set_bottom_dock_layout(
2037 &mut self,
2038 layout: BottomDockLayout,
2039 window: &mut Window,
2040 cx: &mut Context<Self>,
2041 ) {
2042 let fs = self.project().read(cx).fs();
2043 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2044 content.workspace.bottom_dock_layout = Some(layout);
2045 });
2046
2047 cx.notify();
2048 self.serialize_workspace(window, cx);
2049 }
2050
2051 pub fn right_dock(&self) -> &Entity<Dock> {
2052 &self.right_dock
2053 }
2054
2055 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2056 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2057 }
2058
2059 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2060 let left_dock = self.left_dock.read(cx);
2061 let left_visible = left_dock.is_open();
2062 let left_active_panel = left_dock
2063 .active_panel()
2064 .map(|panel| panel.persistent_name().to_string());
2065 // `zoomed_position` is kept in sync with individual panel zoom state
2066 // by the dock code in `Dock::new` and `Dock::add_panel`.
2067 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2068
2069 let right_dock = self.right_dock.read(cx);
2070 let right_visible = right_dock.is_open();
2071 let right_active_panel = right_dock
2072 .active_panel()
2073 .map(|panel| panel.persistent_name().to_string());
2074 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2075
2076 let bottom_dock = self.bottom_dock.read(cx);
2077 let bottom_visible = bottom_dock.is_open();
2078 let bottom_active_panel = bottom_dock
2079 .active_panel()
2080 .map(|panel| panel.persistent_name().to_string());
2081 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2082
2083 DockStructure {
2084 left: DockData {
2085 visible: left_visible,
2086 active_panel: left_active_panel,
2087 zoom: left_dock_zoom,
2088 },
2089 right: DockData {
2090 visible: right_visible,
2091 active_panel: right_active_panel,
2092 zoom: right_dock_zoom,
2093 },
2094 bottom: DockData {
2095 visible: bottom_visible,
2096 active_panel: bottom_active_panel,
2097 zoom: bottom_dock_zoom,
2098 },
2099 }
2100 }
2101
2102 pub fn set_dock_structure(
2103 &self,
2104 docks: DockStructure,
2105 window: &mut Window,
2106 cx: &mut Context<Self>,
2107 ) {
2108 for (dock, data) in [
2109 (&self.left_dock, docks.left),
2110 (&self.bottom_dock, docks.bottom),
2111 (&self.right_dock, docks.right),
2112 ] {
2113 dock.update(cx, |dock, cx| {
2114 dock.serialized_dock = Some(data);
2115 dock.restore_state(window, cx);
2116 });
2117 }
2118 }
2119
2120 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2121 self.items(cx)
2122 .filter_map(|item| {
2123 let project_path = item.project_path(cx)?;
2124 self.project.read(cx).absolute_path(&project_path, cx)
2125 })
2126 .collect()
2127 }
2128
2129 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2130 match position {
2131 DockPosition::Left => &self.left_dock,
2132 DockPosition::Bottom => &self.bottom_dock,
2133 DockPosition::Right => &self.right_dock,
2134 }
2135 }
2136
2137 pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
2138 self.all_docks().into_iter().find_map(|dock| {
2139 let dock = dock.read(cx);
2140 dock.has_agent_panel(cx).then_some(dock.position())
2141 })
2142 }
2143
2144 pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
2145 self.all_docks().into_iter().find_map(|dock| {
2146 let dock = dock.read(cx);
2147 let panel = dock.panel::<T>()?;
2148 dock.stored_panel_size_state(&panel)
2149 })
2150 }
2151
2152 pub fn persisted_panel_size_state(
2153 &self,
2154 panel_key: &'static str,
2155 cx: &App,
2156 ) -> Option<dock::PanelSizeState> {
2157 dock::Dock::load_persisted_size_state(self, panel_key, cx)
2158 }
2159
2160 pub fn persist_panel_size_state(
2161 &self,
2162 panel_key: &str,
2163 size_state: dock::PanelSizeState,
2164 cx: &mut App,
2165 ) {
2166 let Some(workspace_id) = self
2167 .database_id()
2168 .map(|id| i64::from(id).to_string())
2169 .or(self.session_id())
2170 else {
2171 return;
2172 };
2173
2174 let kvp = db::kvp::KeyValueStore::global(cx);
2175 let panel_key = panel_key.to_string();
2176 cx.background_spawn(async move {
2177 let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
2178 scope
2179 .write(
2180 format!("{workspace_id}:{panel_key}"),
2181 serde_json::to_string(&size_state)?,
2182 )
2183 .await
2184 })
2185 .detach_and_log_err(cx);
2186 }
2187
2188 pub fn set_panel_size_state<T: Panel>(
2189 &mut self,
2190 size_state: dock::PanelSizeState,
2191 window: &mut Window,
2192 cx: &mut Context<Self>,
2193 ) -> bool {
2194 let Some(panel) = self.panel::<T>(cx) else {
2195 return false;
2196 };
2197
2198 let dock = self.dock_at_position(panel.position(window, cx));
2199 let did_set = dock.update(cx, |dock, cx| {
2200 dock.set_panel_size_state(&panel, size_state, cx)
2201 });
2202
2203 if did_set {
2204 self.persist_panel_size_state(T::panel_key(), size_state, cx);
2205 }
2206
2207 did_set
2208 }
2209
2210 pub fn flexible_dock_size(
2211 &self,
2212 position: DockPosition,
2213 ratio: f32,
2214 window: &Window,
2215 cx: &App,
2216 ) -> Option<Pixels> {
2217 if position.axis() != Axis::Horizontal {
2218 return None;
2219 }
2220
2221 let available_width = self.available_width_for_horizontal_dock(position, window, cx)?;
2222 Some((available_width * ratio.clamp(0.0, 1.0)).max(RESIZE_HANDLE_SIZE))
2223 }
2224
2225 pub fn resolved_dock_panel_size(
2226 &self,
2227 dock: &Dock,
2228 panel: &dyn PanelHandle,
2229 window: &Window,
2230 cx: &App,
2231 ) -> Pixels {
2232 let size_state = dock.stored_panel_size_state(panel).unwrap_or_default();
2233 dock::resolve_panel_size(size_state, panel, dock.position(), self, window, cx)
2234 }
2235
2236 pub fn flexible_dock_ratio_for_size(
2237 &self,
2238 position: DockPosition,
2239 size: Pixels,
2240 window: &Window,
2241 cx: &App,
2242 ) -> Option<f32> {
2243 if position.axis() != Axis::Horizontal {
2244 return None;
2245 }
2246
2247 let available_width = self.available_width_for_horizontal_dock(position, window, cx)?;
2248 let available_width = available_width.max(RESIZE_HANDLE_SIZE);
2249 Some((size / available_width).clamp(0.0, 1.0))
2250 }
2251
2252 fn available_width_for_horizontal_dock(
2253 &self,
2254 position: DockPosition,
2255 window: &Window,
2256 cx: &App,
2257 ) -> Option<Pixels> {
2258 let workspace_width = self.bounds.size.width;
2259 if workspace_width <= Pixels::ZERO {
2260 return None;
2261 }
2262
2263 let opposite_position = match position {
2264 DockPosition::Left => DockPosition::Right,
2265 DockPosition::Right => DockPosition::Left,
2266 DockPosition::Bottom => return None,
2267 };
2268
2269 let opposite_width = self
2270 .dock_at_position(opposite_position)
2271 .read(cx)
2272 .stored_active_panel_size(window, cx)
2273 .unwrap_or(Pixels::ZERO);
2274
2275 Some((workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE))
2276 }
2277
2278 pub fn default_flexible_dock_ratio(&self, position: DockPosition) -> Option<f32> {
2279 if position.axis() != Axis::Horizontal {
2280 return None;
2281 }
2282
2283 let pane = self.last_active_center_pane.clone()?.upgrade()?;
2284 let pane_fraction = self.center.width_fraction_for_pane(&pane).unwrap_or(1.0);
2285 Some((pane_fraction / (1.0 + pane_fraction)).clamp(0.0, 1.0))
2286 }
2287
2288 pub fn is_edited(&self) -> bool {
2289 self.window_edited
2290 }
2291
2292 pub fn add_panel<T: Panel>(
2293 &mut self,
2294 panel: Entity<T>,
2295 window: &mut Window,
2296 cx: &mut Context<Self>,
2297 ) {
2298 let focus_handle = panel.panel_focus_handle(cx);
2299 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2300 .detach();
2301
2302 let dock_position = panel.position(window, cx);
2303 let dock = self.dock_at_position(dock_position);
2304 let any_panel = panel.to_any();
2305 let persisted_size_state =
2306 self.persisted_panel_size_state(T::panel_key(), cx)
2307 .or_else(|| {
2308 load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
2309 let state = dock::PanelSizeState {
2310 size: Some(size),
2311 flexible_size_ratio: None,
2312 };
2313 self.persist_panel_size_state(T::panel_key(), state, cx);
2314 state
2315 })
2316 });
2317
2318 dock.update(cx, |dock, cx| {
2319 let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
2320 if let Some(size_state) = persisted_size_state {
2321 dock.set_panel_size_state(&panel, size_state, cx);
2322 }
2323 index
2324 });
2325
2326 cx.emit(Event::PanelAdded(any_panel));
2327 }
2328
2329 pub fn remove_panel<T: Panel>(
2330 &mut self,
2331 panel: &Entity<T>,
2332 window: &mut Window,
2333 cx: &mut Context<Self>,
2334 ) {
2335 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2336 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2337 }
2338 }
2339
2340 pub fn status_bar(&self) -> &Entity<StatusBar> {
2341 &self.status_bar
2342 }
2343
2344 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2345 self.sidebar_focus_handle = handle;
2346 }
2347
2348 pub fn status_bar_visible(&self, cx: &App) -> bool {
2349 StatusBarSettings::get_global(cx).show
2350 }
2351
2352 pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
2353 self.multi_workspace.as_ref()
2354 }
2355
2356 pub fn set_multi_workspace(
2357 &mut self,
2358 multi_workspace: WeakEntity<MultiWorkspace>,
2359 cx: &mut App,
2360 ) {
2361 self.status_bar.update(cx, |status_bar, cx| {
2362 status_bar.set_multi_workspace(multi_workspace.clone(), cx);
2363 });
2364 self.multi_workspace = Some(multi_workspace);
2365 }
2366
2367 pub fn app_state(&self) -> &Arc<AppState> {
2368 &self.app_state
2369 }
2370
2371 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2372 self._panels_task = Some(task);
2373 }
2374
2375 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2376 self._panels_task.take()
2377 }
2378
2379 pub fn user_store(&self) -> &Entity<UserStore> {
2380 &self.app_state.user_store
2381 }
2382
2383 pub fn project(&self) -> &Entity<Project> {
2384 &self.project
2385 }
2386
2387 pub fn path_style(&self, cx: &App) -> PathStyle {
2388 self.project.read(cx).path_style(cx)
2389 }
2390
2391 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2392 let mut history: HashMap<EntityId, usize> = HashMap::default();
2393
2394 for pane_handle in &self.panes {
2395 let pane = pane_handle.read(cx);
2396
2397 for entry in pane.activation_history() {
2398 history.insert(
2399 entry.entity_id,
2400 history
2401 .get(&entry.entity_id)
2402 .cloned()
2403 .unwrap_or(0)
2404 .max(entry.timestamp),
2405 );
2406 }
2407 }
2408
2409 history
2410 }
2411
2412 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2413 let mut recent_item: Option<Entity<T>> = None;
2414 let mut recent_timestamp = 0;
2415 for pane_handle in &self.panes {
2416 let pane = pane_handle.read(cx);
2417 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2418 pane.items().map(|item| (item.item_id(), item)).collect();
2419 for entry in pane.activation_history() {
2420 if entry.timestamp > recent_timestamp
2421 && let Some(&item) = item_map.get(&entry.entity_id)
2422 && let Some(typed_item) = item.act_as::<T>(cx)
2423 {
2424 recent_timestamp = entry.timestamp;
2425 recent_item = Some(typed_item);
2426 }
2427 }
2428 }
2429 recent_item
2430 }
2431
2432 pub fn recent_navigation_history_iter(
2433 &self,
2434 cx: &App,
2435 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2436 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2437 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2438
2439 for pane in &self.panes {
2440 let pane = pane.read(cx);
2441
2442 pane.nav_history()
2443 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2444 if let Some(fs_path) = &fs_path {
2445 abs_paths_opened
2446 .entry(fs_path.clone())
2447 .or_default()
2448 .insert(project_path.clone());
2449 }
2450 let timestamp = entry.timestamp;
2451 match history.entry(project_path) {
2452 hash_map::Entry::Occupied(mut entry) => {
2453 let (_, old_timestamp) = entry.get();
2454 if ×tamp > old_timestamp {
2455 entry.insert((fs_path, timestamp));
2456 }
2457 }
2458 hash_map::Entry::Vacant(entry) => {
2459 entry.insert((fs_path, timestamp));
2460 }
2461 }
2462 });
2463
2464 if let Some(item) = pane.active_item()
2465 && let Some(project_path) = item.project_path(cx)
2466 {
2467 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2468
2469 if let Some(fs_path) = &fs_path {
2470 abs_paths_opened
2471 .entry(fs_path.clone())
2472 .or_default()
2473 .insert(project_path.clone());
2474 }
2475
2476 history.insert(project_path, (fs_path, std::usize::MAX));
2477 }
2478 }
2479
2480 history
2481 .into_iter()
2482 .sorted_by_key(|(_, (_, order))| *order)
2483 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2484 .rev()
2485 .filter(move |(history_path, abs_path)| {
2486 let latest_project_path_opened = abs_path
2487 .as_ref()
2488 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2489 .and_then(|project_paths| {
2490 project_paths
2491 .iter()
2492 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2493 });
2494
2495 latest_project_path_opened.is_none_or(|path| path == history_path)
2496 })
2497 }
2498
2499 pub fn recent_navigation_history(
2500 &self,
2501 limit: Option<usize>,
2502 cx: &App,
2503 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2504 self.recent_navigation_history_iter(cx)
2505 .take(limit.unwrap_or(usize::MAX))
2506 .collect()
2507 }
2508
2509 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2510 for pane in &self.panes {
2511 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2512 }
2513 }
2514
2515 fn navigate_history(
2516 &mut self,
2517 pane: WeakEntity<Pane>,
2518 mode: NavigationMode,
2519 window: &mut Window,
2520 cx: &mut Context<Workspace>,
2521 ) -> Task<Result<()>> {
2522 self.navigate_history_impl(
2523 pane,
2524 mode,
2525 window,
2526 &mut |history, cx| history.pop(mode, cx),
2527 cx,
2528 )
2529 }
2530
2531 fn navigate_tag_history(
2532 &mut self,
2533 pane: WeakEntity<Pane>,
2534 mode: TagNavigationMode,
2535 window: &mut Window,
2536 cx: &mut Context<Workspace>,
2537 ) -> Task<Result<()>> {
2538 self.navigate_history_impl(
2539 pane,
2540 NavigationMode::Normal,
2541 window,
2542 &mut |history, _cx| history.pop_tag(mode),
2543 cx,
2544 )
2545 }
2546
2547 fn navigate_history_impl(
2548 &mut self,
2549 pane: WeakEntity<Pane>,
2550 mode: NavigationMode,
2551 window: &mut Window,
2552 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2553 cx: &mut Context<Workspace>,
2554 ) -> Task<Result<()>> {
2555 let to_load = if let Some(pane) = pane.upgrade() {
2556 pane.update(cx, |pane, cx| {
2557 window.focus(&pane.focus_handle(cx), cx);
2558 loop {
2559 // Retrieve the weak item handle from the history.
2560 let entry = cb(pane.nav_history_mut(), cx)?;
2561
2562 // If the item is still present in this pane, then activate it.
2563 if let Some(index) = entry
2564 .item
2565 .upgrade()
2566 .and_then(|v| pane.index_for_item(v.as_ref()))
2567 {
2568 let prev_active_item_index = pane.active_item_index();
2569 pane.nav_history_mut().set_mode(mode);
2570 pane.activate_item(index, true, true, window, cx);
2571 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2572
2573 let mut navigated = prev_active_item_index != pane.active_item_index();
2574 if let Some(data) = entry.data {
2575 navigated |= pane.active_item()?.navigate(data, window, cx);
2576 }
2577
2578 if navigated {
2579 break None;
2580 }
2581 } else {
2582 // If the item is no longer present in this pane, then retrieve its
2583 // path info in order to reopen it.
2584 break pane
2585 .nav_history()
2586 .path_for_item(entry.item.id())
2587 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2588 }
2589 }
2590 })
2591 } else {
2592 None
2593 };
2594
2595 if let Some((project_path, abs_path, entry)) = to_load {
2596 // If the item was no longer present, then load it again from its previous path, first try the local path
2597 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2598
2599 cx.spawn_in(window, async move |workspace, cx| {
2600 let open_by_project_path = open_by_project_path.await;
2601 let mut navigated = false;
2602 match open_by_project_path
2603 .with_context(|| format!("Navigating to {project_path:?}"))
2604 {
2605 Ok((project_entry_id, build_item)) => {
2606 let prev_active_item_id = pane.update(cx, |pane, _| {
2607 pane.nav_history_mut().set_mode(mode);
2608 pane.active_item().map(|p| p.item_id())
2609 })?;
2610
2611 pane.update_in(cx, |pane, window, cx| {
2612 let item = pane.open_item(
2613 project_entry_id,
2614 project_path,
2615 true,
2616 entry.is_preview,
2617 true,
2618 None,
2619 window, cx,
2620 build_item,
2621 );
2622 navigated |= Some(item.item_id()) != prev_active_item_id;
2623 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2624 if let Some(data) = entry.data {
2625 navigated |= item.navigate(data, window, cx);
2626 }
2627 })?;
2628 }
2629 Err(open_by_project_path_e) => {
2630 // Fall back to opening by abs path, in case an external file was opened and closed,
2631 // and its worktree is now dropped
2632 if let Some(abs_path) = abs_path {
2633 let prev_active_item_id = pane.update(cx, |pane, _| {
2634 pane.nav_history_mut().set_mode(mode);
2635 pane.active_item().map(|p| p.item_id())
2636 })?;
2637 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2638 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2639 })?;
2640 match open_by_abs_path
2641 .await
2642 .with_context(|| format!("Navigating to {abs_path:?}"))
2643 {
2644 Ok(item) => {
2645 pane.update_in(cx, |pane, window, cx| {
2646 navigated |= Some(item.item_id()) != prev_active_item_id;
2647 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2648 if let Some(data) = entry.data {
2649 navigated |= item.navigate(data, window, cx);
2650 }
2651 })?;
2652 }
2653 Err(open_by_abs_path_e) => {
2654 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2655 }
2656 }
2657 }
2658 }
2659 }
2660
2661 if !navigated {
2662 workspace
2663 .update_in(cx, |workspace, window, cx| {
2664 Self::navigate_history(workspace, pane, mode, window, cx)
2665 })?
2666 .await?;
2667 }
2668
2669 Ok(())
2670 })
2671 } else {
2672 Task::ready(Ok(()))
2673 }
2674 }
2675
2676 pub fn go_back(
2677 &mut self,
2678 pane: WeakEntity<Pane>,
2679 window: &mut Window,
2680 cx: &mut Context<Workspace>,
2681 ) -> Task<Result<()>> {
2682 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2683 }
2684
2685 pub fn go_forward(
2686 &mut self,
2687 pane: WeakEntity<Pane>,
2688 window: &mut Window,
2689 cx: &mut Context<Workspace>,
2690 ) -> Task<Result<()>> {
2691 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2692 }
2693
2694 pub fn reopen_closed_item(
2695 &mut self,
2696 window: &mut Window,
2697 cx: &mut Context<Workspace>,
2698 ) -> Task<Result<()>> {
2699 self.navigate_history(
2700 self.active_pane().downgrade(),
2701 NavigationMode::ReopeningClosedItem,
2702 window,
2703 cx,
2704 )
2705 }
2706
2707 pub fn client(&self) -> &Arc<Client> {
2708 &self.app_state.client
2709 }
2710
2711 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2712 self.titlebar_item = Some(item);
2713 cx.notify();
2714 }
2715
2716 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2717 self.on_prompt_for_new_path = Some(prompt)
2718 }
2719
2720 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2721 self.on_prompt_for_open_path = Some(prompt)
2722 }
2723
2724 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2725 self.terminal_provider = Some(Box::new(provider));
2726 }
2727
2728 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2729 self.debugger_provider = Some(Arc::new(provider));
2730 }
2731
2732 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2733 self.debugger_provider.clone()
2734 }
2735
2736 pub fn prompt_for_open_path(
2737 &mut self,
2738 path_prompt_options: PathPromptOptions,
2739 lister: DirectoryLister,
2740 window: &mut Window,
2741 cx: &mut Context<Self>,
2742 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2743 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2744 let prompt = self.on_prompt_for_open_path.take().unwrap();
2745 let rx = prompt(self, lister, window, cx);
2746 self.on_prompt_for_open_path = Some(prompt);
2747 rx
2748 } else {
2749 let (tx, rx) = oneshot::channel();
2750 let abs_path = cx.prompt_for_paths(path_prompt_options);
2751
2752 cx.spawn_in(window, async move |workspace, cx| {
2753 let Ok(result) = abs_path.await else {
2754 return Ok(());
2755 };
2756
2757 match result {
2758 Ok(result) => {
2759 tx.send(result).ok();
2760 }
2761 Err(err) => {
2762 let rx = workspace.update_in(cx, |workspace, window, cx| {
2763 workspace.show_portal_error(err.to_string(), cx);
2764 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2765 let rx = prompt(workspace, lister, window, cx);
2766 workspace.on_prompt_for_open_path = Some(prompt);
2767 rx
2768 })?;
2769 if let Ok(path) = rx.await {
2770 tx.send(path).ok();
2771 }
2772 }
2773 };
2774 anyhow::Ok(())
2775 })
2776 .detach();
2777
2778 rx
2779 }
2780 }
2781
2782 pub fn prompt_for_new_path(
2783 &mut self,
2784 lister: DirectoryLister,
2785 suggested_name: Option<String>,
2786 window: &mut Window,
2787 cx: &mut Context<Self>,
2788 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2789 if self.project.read(cx).is_via_collab()
2790 || self.project.read(cx).is_via_remote_server()
2791 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2792 {
2793 let prompt = self.on_prompt_for_new_path.take().unwrap();
2794 let rx = prompt(self, lister, suggested_name, window, cx);
2795 self.on_prompt_for_new_path = Some(prompt);
2796 return rx;
2797 }
2798
2799 let (tx, rx) = oneshot::channel();
2800 cx.spawn_in(window, async move |workspace, cx| {
2801 let abs_path = workspace.update(cx, |workspace, cx| {
2802 let relative_to = workspace
2803 .most_recent_active_path(cx)
2804 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2805 .or_else(|| {
2806 let project = workspace.project.read(cx);
2807 project.visible_worktrees(cx).find_map(|worktree| {
2808 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2809 })
2810 })
2811 .or_else(std::env::home_dir)
2812 .unwrap_or_else(|| PathBuf::from(""));
2813 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2814 })?;
2815 let abs_path = match abs_path.await? {
2816 Ok(path) => path,
2817 Err(err) => {
2818 let rx = workspace.update_in(cx, |workspace, window, cx| {
2819 workspace.show_portal_error(err.to_string(), cx);
2820
2821 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2822 let rx = prompt(workspace, lister, suggested_name, window, cx);
2823 workspace.on_prompt_for_new_path = Some(prompt);
2824 rx
2825 })?;
2826 if let Ok(path) = rx.await {
2827 tx.send(path).ok();
2828 }
2829 return anyhow::Ok(());
2830 }
2831 };
2832
2833 tx.send(abs_path.map(|path| vec![path])).ok();
2834 anyhow::Ok(())
2835 })
2836 .detach();
2837
2838 rx
2839 }
2840
2841 pub fn titlebar_item(&self) -> Option<AnyView> {
2842 self.titlebar_item.clone()
2843 }
2844
2845 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2846 /// When set, git-related operations should use this worktree instead of deriving
2847 /// the active worktree from the focused file.
2848 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2849 self.active_worktree_override
2850 }
2851
2852 pub fn set_active_worktree_override(
2853 &mut self,
2854 worktree_id: Option<WorktreeId>,
2855 cx: &mut Context<Self>,
2856 ) {
2857 self.active_worktree_override = worktree_id;
2858 cx.notify();
2859 }
2860
2861 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2862 self.active_worktree_override = None;
2863 cx.notify();
2864 }
2865
2866 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2867 ///
2868 /// If the given workspace has a local project, then it will be passed
2869 /// to the callback. Otherwise, a new empty window will be created.
2870 pub fn with_local_workspace<T, F>(
2871 &mut self,
2872 window: &mut Window,
2873 cx: &mut Context<Self>,
2874 callback: F,
2875 ) -> Task<Result<T>>
2876 where
2877 T: 'static,
2878 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2879 {
2880 if self.project.read(cx).is_local() {
2881 Task::ready(Ok(callback(self, window, cx)))
2882 } else {
2883 let env = self.project.read(cx).cli_environment(cx);
2884 let task = Self::new_local(
2885 Vec::new(),
2886 self.app_state.clone(),
2887 None,
2888 env,
2889 None,
2890 true,
2891 cx,
2892 );
2893 cx.spawn_in(window, async move |_vh, cx| {
2894 let OpenResult {
2895 window: multi_workspace_window,
2896 ..
2897 } = task.await?;
2898 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2899 let workspace = multi_workspace.workspace().clone();
2900 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2901 })
2902 })
2903 }
2904 }
2905
2906 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2907 ///
2908 /// If the given workspace has a local project, then it will be passed
2909 /// to the callback. Otherwise, a new empty window will be created.
2910 pub fn with_local_or_wsl_workspace<T, F>(
2911 &mut self,
2912 window: &mut Window,
2913 cx: &mut Context<Self>,
2914 callback: F,
2915 ) -> Task<Result<T>>
2916 where
2917 T: 'static,
2918 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2919 {
2920 let project = self.project.read(cx);
2921 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2922 Task::ready(Ok(callback(self, window, cx)))
2923 } else {
2924 let env = self.project.read(cx).cli_environment(cx);
2925 let task = Self::new_local(
2926 Vec::new(),
2927 self.app_state.clone(),
2928 None,
2929 env,
2930 None,
2931 true,
2932 cx,
2933 );
2934 cx.spawn_in(window, async move |_vh, cx| {
2935 let OpenResult {
2936 window: multi_workspace_window,
2937 ..
2938 } = task.await?;
2939 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2940 let workspace = multi_workspace.workspace().clone();
2941 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2942 })
2943 })
2944 }
2945 }
2946
2947 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2948 self.project.read(cx).worktrees(cx)
2949 }
2950
2951 pub fn visible_worktrees<'a>(
2952 &self,
2953 cx: &'a App,
2954 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2955 self.project.read(cx).visible_worktrees(cx)
2956 }
2957
2958 #[cfg(any(test, feature = "test-support"))]
2959 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2960 let futures = self
2961 .worktrees(cx)
2962 .filter_map(|worktree| worktree.read(cx).as_local())
2963 .map(|worktree| worktree.scan_complete())
2964 .collect::<Vec<_>>();
2965 async move {
2966 for future in futures {
2967 future.await;
2968 }
2969 }
2970 }
2971
2972 pub fn close_global(cx: &mut App) {
2973 cx.defer(|cx| {
2974 cx.windows().iter().find(|window| {
2975 window
2976 .update(cx, |_, window, _| {
2977 if window.is_window_active() {
2978 //This can only get called when the window's project connection has been lost
2979 //so we don't need to prompt the user for anything and instead just close the window
2980 window.remove_window();
2981 true
2982 } else {
2983 false
2984 }
2985 })
2986 .unwrap_or(false)
2987 });
2988 });
2989 }
2990
2991 pub fn move_focused_panel_to_next_position(
2992 &mut self,
2993 _: &MoveFocusedPanelToNextPosition,
2994 window: &mut Window,
2995 cx: &mut Context<Self>,
2996 ) {
2997 let docks = self.all_docks();
2998 let active_dock = docks
2999 .into_iter()
3000 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
3001
3002 if let Some(dock) = active_dock {
3003 dock.update(cx, |dock, cx| {
3004 let active_panel = dock
3005 .active_panel()
3006 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
3007
3008 if let Some(panel) = active_panel {
3009 panel.move_to_next_position(window, cx);
3010 }
3011 })
3012 }
3013 }
3014
3015 pub fn prepare_to_close(
3016 &mut self,
3017 close_intent: CloseIntent,
3018 window: &mut Window,
3019 cx: &mut Context<Self>,
3020 ) -> Task<Result<bool>> {
3021 let active_call = self.active_global_call();
3022
3023 cx.spawn_in(window, async move |this, cx| {
3024 this.update(cx, |this, _| {
3025 if close_intent == CloseIntent::CloseWindow {
3026 this.removing = true;
3027 }
3028 })?;
3029
3030 let workspace_count = cx.update(|_window, cx| {
3031 cx.windows()
3032 .iter()
3033 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
3034 .count()
3035 })?;
3036
3037 #[cfg(target_os = "macos")]
3038 let save_last_workspace = false;
3039
3040 // On Linux and Windows, closing the last window should restore the last workspace.
3041 #[cfg(not(target_os = "macos"))]
3042 let save_last_workspace = {
3043 let remaining_workspaces = cx.update(|_window, cx| {
3044 cx.windows()
3045 .iter()
3046 .filter_map(|window| window.downcast::<MultiWorkspace>())
3047 .filter_map(|multi_workspace| {
3048 multi_workspace
3049 .update(cx, |multi_workspace, _, cx| {
3050 multi_workspace.workspace().read(cx).removing
3051 })
3052 .ok()
3053 })
3054 .filter(|removing| !removing)
3055 .count()
3056 })?;
3057
3058 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
3059 };
3060
3061 if let Some(active_call) = active_call
3062 && workspace_count == 1
3063 && cx
3064 .update(|_window, cx| active_call.0.is_in_room(cx))
3065 .unwrap_or(false)
3066 {
3067 if close_intent == CloseIntent::CloseWindow {
3068 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
3069 let answer = cx.update(|window, cx| {
3070 window.prompt(
3071 PromptLevel::Warning,
3072 "Do you want to leave the current call?",
3073 None,
3074 &["Close window and hang up", "Cancel"],
3075 cx,
3076 )
3077 })?;
3078
3079 if answer.await.log_err() == Some(1) {
3080 return anyhow::Ok(false);
3081 } else {
3082 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
3083 task.await.log_err();
3084 }
3085 }
3086 }
3087 if close_intent == CloseIntent::ReplaceWindow {
3088 _ = cx.update(|_window, cx| {
3089 let multi_workspace = cx
3090 .windows()
3091 .iter()
3092 .filter_map(|window| window.downcast::<MultiWorkspace>())
3093 .next()
3094 .unwrap();
3095 let project = multi_workspace
3096 .read(cx)?
3097 .workspace()
3098 .read(cx)
3099 .project
3100 .clone();
3101 if project.read(cx).is_shared() {
3102 active_call.0.unshare_project(project, cx)?;
3103 }
3104 Ok::<_, anyhow::Error>(())
3105 });
3106 }
3107 }
3108
3109 let save_result = this
3110 .update_in(cx, |this, window, cx| {
3111 this.save_all_internal(SaveIntent::Close, window, cx)
3112 })?
3113 .await;
3114
3115 // If we're not quitting, but closing, we remove the workspace from
3116 // the current session.
3117 if close_intent != CloseIntent::Quit
3118 && !save_last_workspace
3119 && save_result.as_ref().is_ok_and(|&res| res)
3120 {
3121 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
3122 .await;
3123 }
3124
3125 save_result
3126 })
3127 }
3128
3129 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
3130 self.save_all_internal(
3131 action.save_intent.unwrap_or(SaveIntent::SaveAll),
3132 window,
3133 cx,
3134 )
3135 .detach_and_log_err(cx);
3136 }
3137
3138 fn send_keystrokes(
3139 &mut self,
3140 action: &SendKeystrokes,
3141 window: &mut Window,
3142 cx: &mut Context<Self>,
3143 ) {
3144 let keystrokes: Vec<Keystroke> = action
3145 .0
3146 .split(' ')
3147 .flat_map(|k| Keystroke::parse(k).log_err())
3148 .map(|k| {
3149 cx.keyboard_mapper()
3150 .map_key_equivalent(k, false)
3151 .inner()
3152 .clone()
3153 })
3154 .collect();
3155 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
3156 }
3157
3158 pub fn send_keystrokes_impl(
3159 &mut self,
3160 keystrokes: Vec<Keystroke>,
3161 window: &mut Window,
3162 cx: &mut Context<Self>,
3163 ) -> Shared<Task<()>> {
3164 let mut state = self.dispatching_keystrokes.borrow_mut();
3165 if !state.dispatched.insert(keystrokes.clone()) {
3166 cx.propagate();
3167 return state.task.clone().unwrap();
3168 }
3169
3170 state.queue.extend(keystrokes);
3171
3172 let keystrokes = self.dispatching_keystrokes.clone();
3173 if state.task.is_none() {
3174 state.task = Some(
3175 window
3176 .spawn(cx, async move |cx| {
3177 // limit to 100 keystrokes to avoid infinite recursion.
3178 for _ in 0..100 {
3179 let keystroke = {
3180 let mut state = keystrokes.borrow_mut();
3181 let Some(keystroke) = state.queue.pop_front() else {
3182 state.dispatched.clear();
3183 state.task.take();
3184 return;
3185 };
3186 keystroke
3187 };
3188 cx.update(|window, cx| {
3189 let focused = window.focused(cx);
3190 window.dispatch_keystroke(keystroke.clone(), cx);
3191 if window.focused(cx) != focused {
3192 // dispatch_keystroke may cause the focus to change.
3193 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3194 // And we need that to happen before the next keystroke to keep vim mode happy...
3195 // (Note that the tests always do this implicitly, so you must manually test with something like:
3196 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3197 // )
3198 window.draw(cx).clear();
3199 }
3200 })
3201 .ok();
3202
3203 // Yield between synthetic keystrokes so deferred focus and
3204 // other effects can settle before dispatching the next key.
3205 yield_now().await;
3206 }
3207
3208 *keystrokes.borrow_mut() = Default::default();
3209 log::error!("over 100 keystrokes passed to send_keystrokes");
3210 })
3211 .shared(),
3212 );
3213 }
3214 state.task.clone().unwrap()
3215 }
3216
3217 fn save_all_internal(
3218 &mut self,
3219 mut save_intent: SaveIntent,
3220 window: &mut Window,
3221 cx: &mut Context<Self>,
3222 ) -> Task<Result<bool>> {
3223 if self.project.read(cx).is_disconnected(cx) {
3224 return Task::ready(Ok(true));
3225 }
3226 let dirty_items = self
3227 .panes
3228 .iter()
3229 .flat_map(|pane| {
3230 pane.read(cx).items().filter_map(|item| {
3231 if item.is_dirty(cx) {
3232 item.tab_content_text(0, cx);
3233 Some((pane.downgrade(), item.boxed_clone()))
3234 } else {
3235 None
3236 }
3237 })
3238 })
3239 .collect::<Vec<_>>();
3240
3241 let project = self.project.clone();
3242 cx.spawn_in(window, async move |workspace, cx| {
3243 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3244 let (serialize_tasks, remaining_dirty_items) =
3245 workspace.update_in(cx, |workspace, window, cx| {
3246 let mut remaining_dirty_items = Vec::new();
3247 let mut serialize_tasks = Vec::new();
3248 for (pane, item) in dirty_items {
3249 if let Some(task) = item
3250 .to_serializable_item_handle(cx)
3251 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3252 {
3253 serialize_tasks.push(task);
3254 } else {
3255 remaining_dirty_items.push((pane, item));
3256 }
3257 }
3258 (serialize_tasks, remaining_dirty_items)
3259 })?;
3260
3261 futures::future::try_join_all(serialize_tasks).await?;
3262
3263 if !remaining_dirty_items.is_empty() {
3264 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3265 }
3266
3267 if remaining_dirty_items.len() > 1 {
3268 let answer = workspace.update_in(cx, |_, window, cx| {
3269 let detail = Pane::file_names_for_prompt(
3270 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3271 cx,
3272 );
3273 window.prompt(
3274 PromptLevel::Warning,
3275 "Do you want to save all changes in the following files?",
3276 Some(&detail),
3277 &["Save all", "Discard all", "Cancel"],
3278 cx,
3279 )
3280 })?;
3281 match answer.await.log_err() {
3282 Some(0) => save_intent = SaveIntent::SaveAll,
3283 Some(1) => save_intent = SaveIntent::Skip,
3284 Some(2) => return Ok(false),
3285 _ => {}
3286 }
3287 }
3288
3289 remaining_dirty_items
3290 } else {
3291 dirty_items
3292 };
3293
3294 for (pane, item) in dirty_items {
3295 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3296 (
3297 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3298 item.project_entry_ids(cx),
3299 )
3300 })?;
3301 if (singleton || !project_entry_ids.is_empty())
3302 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3303 {
3304 return Ok(false);
3305 }
3306 }
3307 Ok(true)
3308 })
3309 }
3310
3311 pub fn open_workspace_for_paths(
3312 &mut self,
3313 replace_current_window: bool,
3314 paths: Vec<PathBuf>,
3315 window: &mut Window,
3316 cx: &mut Context<Self>,
3317 ) -> Task<Result<Entity<Workspace>>> {
3318 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
3319 let is_remote = self.project.read(cx).is_via_collab();
3320 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3321 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3322
3323 let window_to_replace = if replace_current_window {
3324 window_handle
3325 } else if is_remote || has_worktree || has_dirty_items {
3326 None
3327 } else {
3328 window_handle
3329 };
3330 let app_state = self.app_state.clone();
3331
3332 cx.spawn(async move |_, cx| {
3333 let OpenResult { workspace, .. } = cx
3334 .update(|cx| {
3335 open_paths(
3336 &paths,
3337 app_state,
3338 OpenOptions {
3339 replace_window: window_to_replace,
3340 ..Default::default()
3341 },
3342 cx,
3343 )
3344 })
3345 .await?;
3346 Ok(workspace)
3347 })
3348 }
3349
3350 #[allow(clippy::type_complexity)]
3351 pub fn open_paths(
3352 &mut self,
3353 mut abs_paths: Vec<PathBuf>,
3354 options: OpenOptions,
3355 pane: Option<WeakEntity<Pane>>,
3356 window: &mut Window,
3357 cx: &mut Context<Self>,
3358 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3359 let fs = self.app_state.fs.clone();
3360
3361 let caller_ordered_abs_paths = abs_paths.clone();
3362
3363 // Sort the paths to ensure we add worktrees for parents before their children.
3364 abs_paths.sort_unstable();
3365 cx.spawn_in(window, async move |this, cx| {
3366 let mut tasks = Vec::with_capacity(abs_paths.len());
3367
3368 for abs_path in &abs_paths {
3369 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3370 OpenVisible::All => Some(true),
3371 OpenVisible::None => Some(false),
3372 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3373 Some(Some(metadata)) => Some(!metadata.is_dir),
3374 Some(None) => Some(true),
3375 None => None,
3376 },
3377 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3378 Some(Some(metadata)) => Some(metadata.is_dir),
3379 Some(None) => Some(false),
3380 None => None,
3381 },
3382 };
3383 let project_path = match visible {
3384 Some(visible) => match this
3385 .update(cx, |this, cx| {
3386 Workspace::project_path_for_path(
3387 this.project.clone(),
3388 abs_path,
3389 visible,
3390 cx,
3391 )
3392 })
3393 .log_err()
3394 {
3395 Some(project_path) => project_path.await.log_err(),
3396 None => None,
3397 },
3398 None => None,
3399 };
3400
3401 let this = this.clone();
3402 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3403 let fs = fs.clone();
3404 let pane = pane.clone();
3405 let task = cx.spawn(async move |cx| {
3406 let (_worktree, project_path) = project_path?;
3407 if fs.is_dir(&abs_path).await {
3408 // Opening a directory should not race to update the active entry.
3409 // We'll select/reveal a deterministic final entry after all paths finish opening.
3410 None
3411 } else {
3412 Some(
3413 this.update_in(cx, |this, window, cx| {
3414 this.open_path(
3415 project_path,
3416 pane,
3417 options.focus.unwrap_or(true),
3418 window,
3419 cx,
3420 )
3421 })
3422 .ok()?
3423 .await,
3424 )
3425 }
3426 });
3427 tasks.push(task);
3428 }
3429
3430 let results = futures::future::join_all(tasks).await;
3431
3432 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3433 let mut winner: Option<(PathBuf, bool)> = None;
3434 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3435 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3436 if !metadata.is_dir {
3437 winner = Some((abs_path, false));
3438 break;
3439 }
3440 if winner.is_none() {
3441 winner = Some((abs_path, true));
3442 }
3443 } else if winner.is_none() {
3444 winner = Some((abs_path, false));
3445 }
3446 }
3447
3448 // Compute the winner entry id on the foreground thread and emit once, after all
3449 // paths finish opening. This avoids races between concurrently-opening paths
3450 // (directories in particular) and makes the resulting project panel selection
3451 // deterministic.
3452 if let Some((winner_abs_path, winner_is_dir)) = winner {
3453 'emit_winner: {
3454 let winner_abs_path: Arc<Path> =
3455 SanitizedPath::new(&winner_abs_path).as_path().into();
3456
3457 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3458 OpenVisible::All => true,
3459 OpenVisible::None => false,
3460 OpenVisible::OnlyFiles => !winner_is_dir,
3461 OpenVisible::OnlyDirectories => winner_is_dir,
3462 };
3463
3464 let Some(worktree_task) = this
3465 .update(cx, |workspace, cx| {
3466 workspace.project.update(cx, |project, cx| {
3467 project.find_or_create_worktree(
3468 winner_abs_path.as_ref(),
3469 visible,
3470 cx,
3471 )
3472 })
3473 })
3474 .ok()
3475 else {
3476 break 'emit_winner;
3477 };
3478
3479 let Ok((worktree, _)) = worktree_task.await else {
3480 break 'emit_winner;
3481 };
3482
3483 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3484 let worktree = worktree.read(cx);
3485 let worktree_abs_path = worktree.abs_path();
3486 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3487 worktree.root_entry()
3488 } else {
3489 winner_abs_path
3490 .strip_prefix(worktree_abs_path.as_ref())
3491 .ok()
3492 .and_then(|relative_path| {
3493 let relative_path =
3494 RelPath::new(relative_path, PathStyle::local())
3495 .log_err()?;
3496 worktree.entry_for_path(&relative_path)
3497 })
3498 }?;
3499 Some(entry.id)
3500 }) else {
3501 break 'emit_winner;
3502 };
3503
3504 this.update(cx, |workspace, cx| {
3505 workspace.project.update(cx, |_, cx| {
3506 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3507 });
3508 })
3509 .ok();
3510 }
3511 }
3512
3513 results
3514 })
3515 }
3516
3517 pub fn open_resolved_path(
3518 &mut self,
3519 path: ResolvedPath,
3520 window: &mut Window,
3521 cx: &mut Context<Self>,
3522 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3523 match path {
3524 ResolvedPath::ProjectPath { project_path, .. } => {
3525 self.open_path(project_path, None, true, window, cx)
3526 }
3527 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3528 PathBuf::from(path),
3529 OpenOptions {
3530 visible: Some(OpenVisible::None),
3531 ..Default::default()
3532 },
3533 window,
3534 cx,
3535 ),
3536 }
3537 }
3538
3539 pub fn absolute_path_of_worktree(
3540 &self,
3541 worktree_id: WorktreeId,
3542 cx: &mut Context<Self>,
3543 ) -> Option<PathBuf> {
3544 self.project
3545 .read(cx)
3546 .worktree_for_id(worktree_id, cx)
3547 // TODO: use `abs_path` or `root_dir`
3548 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3549 }
3550
3551 pub fn add_folder_to_project(
3552 &mut self,
3553 _: &AddFolderToProject,
3554 window: &mut Window,
3555 cx: &mut Context<Self>,
3556 ) {
3557 let project = self.project.read(cx);
3558 if project.is_via_collab() {
3559 self.show_error(
3560 &anyhow!("You cannot add folders to someone else's project"),
3561 cx,
3562 );
3563 return;
3564 }
3565 let paths = self.prompt_for_open_path(
3566 PathPromptOptions {
3567 files: false,
3568 directories: true,
3569 multiple: true,
3570 prompt: None,
3571 },
3572 DirectoryLister::Project(self.project.clone()),
3573 window,
3574 cx,
3575 );
3576 cx.spawn_in(window, async move |this, cx| {
3577 if let Some(paths) = paths.await.log_err().flatten() {
3578 let results = this
3579 .update_in(cx, |this, window, cx| {
3580 this.open_paths(
3581 paths,
3582 OpenOptions {
3583 visible: Some(OpenVisible::All),
3584 ..Default::default()
3585 },
3586 None,
3587 window,
3588 cx,
3589 )
3590 })?
3591 .await;
3592 for result in results.into_iter().flatten() {
3593 result.log_err();
3594 }
3595 }
3596 anyhow::Ok(())
3597 })
3598 .detach_and_log_err(cx);
3599 }
3600
3601 pub fn project_path_for_path(
3602 project: Entity<Project>,
3603 abs_path: &Path,
3604 visible: bool,
3605 cx: &mut App,
3606 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3607 let entry = project.update(cx, |project, cx| {
3608 project.find_or_create_worktree(abs_path, visible, cx)
3609 });
3610 cx.spawn(async move |cx| {
3611 let (worktree, path) = entry.await?;
3612 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3613 Ok((worktree, ProjectPath { worktree_id, path }))
3614 })
3615 }
3616
3617 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3618 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3619 }
3620
3621 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3622 self.items_of_type(cx).max_by_key(|item| item.item_id())
3623 }
3624
3625 pub fn items_of_type<'a, T: Item>(
3626 &'a self,
3627 cx: &'a App,
3628 ) -> impl 'a + Iterator<Item = Entity<T>> {
3629 self.panes
3630 .iter()
3631 .flat_map(|pane| pane.read(cx).items_of_type())
3632 }
3633
3634 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3635 self.active_pane().read(cx).active_item()
3636 }
3637
3638 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3639 let item = self.active_item(cx)?;
3640 item.to_any_view().downcast::<I>().ok()
3641 }
3642
3643 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3644 self.active_item(cx).and_then(|item| item.project_path(cx))
3645 }
3646
3647 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3648 self.recent_navigation_history_iter(cx)
3649 .filter_map(|(path, abs_path)| {
3650 let worktree = self
3651 .project
3652 .read(cx)
3653 .worktree_for_id(path.worktree_id, cx)?;
3654 if worktree.read(cx).is_visible() {
3655 abs_path
3656 } else {
3657 None
3658 }
3659 })
3660 .next()
3661 }
3662
3663 pub fn save_active_item(
3664 &mut self,
3665 save_intent: SaveIntent,
3666 window: &mut Window,
3667 cx: &mut App,
3668 ) -> Task<Result<()>> {
3669 let project = self.project.clone();
3670 let pane = self.active_pane();
3671 let item = pane.read(cx).active_item();
3672 let pane = pane.downgrade();
3673
3674 window.spawn(cx, async move |cx| {
3675 if let Some(item) = item {
3676 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3677 .await
3678 .map(|_| ())
3679 } else {
3680 Ok(())
3681 }
3682 })
3683 }
3684
3685 pub fn close_inactive_items_and_panes(
3686 &mut self,
3687 action: &CloseInactiveTabsAndPanes,
3688 window: &mut Window,
3689 cx: &mut Context<Self>,
3690 ) {
3691 if let Some(task) = self.close_all_internal(
3692 true,
3693 action.save_intent.unwrap_or(SaveIntent::Close),
3694 window,
3695 cx,
3696 ) {
3697 task.detach_and_log_err(cx)
3698 }
3699 }
3700
3701 pub fn close_all_items_and_panes(
3702 &mut self,
3703 action: &CloseAllItemsAndPanes,
3704 window: &mut Window,
3705 cx: &mut Context<Self>,
3706 ) {
3707 if let Some(task) = self.close_all_internal(
3708 false,
3709 action.save_intent.unwrap_or(SaveIntent::Close),
3710 window,
3711 cx,
3712 ) {
3713 task.detach_and_log_err(cx)
3714 }
3715 }
3716
3717 /// Closes the active item across all panes.
3718 pub fn close_item_in_all_panes(
3719 &mut self,
3720 action: &CloseItemInAllPanes,
3721 window: &mut Window,
3722 cx: &mut Context<Self>,
3723 ) {
3724 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3725 return;
3726 };
3727
3728 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3729 let close_pinned = action.close_pinned;
3730
3731 if let Some(project_path) = active_item.project_path(cx) {
3732 self.close_items_with_project_path(
3733 &project_path,
3734 save_intent,
3735 close_pinned,
3736 window,
3737 cx,
3738 );
3739 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3740 let item_id = active_item.item_id();
3741 self.active_pane().update(cx, |pane, cx| {
3742 pane.close_item_by_id(item_id, save_intent, window, cx)
3743 .detach_and_log_err(cx);
3744 });
3745 }
3746 }
3747
3748 /// Closes all items with the given project path across all panes.
3749 pub fn close_items_with_project_path(
3750 &mut self,
3751 project_path: &ProjectPath,
3752 save_intent: SaveIntent,
3753 close_pinned: bool,
3754 window: &mut Window,
3755 cx: &mut Context<Self>,
3756 ) {
3757 let panes = self.panes().to_vec();
3758 for pane in panes {
3759 pane.update(cx, |pane, cx| {
3760 pane.close_items_for_project_path(
3761 project_path,
3762 save_intent,
3763 close_pinned,
3764 window,
3765 cx,
3766 )
3767 .detach_and_log_err(cx);
3768 });
3769 }
3770 }
3771
3772 fn close_all_internal(
3773 &mut self,
3774 retain_active_pane: bool,
3775 save_intent: SaveIntent,
3776 window: &mut Window,
3777 cx: &mut Context<Self>,
3778 ) -> Option<Task<Result<()>>> {
3779 let current_pane = self.active_pane();
3780
3781 let mut tasks = Vec::new();
3782
3783 if retain_active_pane {
3784 let current_pane_close = current_pane.update(cx, |pane, cx| {
3785 pane.close_other_items(
3786 &CloseOtherItems {
3787 save_intent: None,
3788 close_pinned: false,
3789 },
3790 None,
3791 window,
3792 cx,
3793 )
3794 });
3795
3796 tasks.push(current_pane_close);
3797 }
3798
3799 for pane in self.panes() {
3800 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3801 continue;
3802 }
3803
3804 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3805 pane.close_all_items(
3806 &CloseAllItems {
3807 save_intent: Some(save_intent),
3808 close_pinned: false,
3809 },
3810 window,
3811 cx,
3812 )
3813 });
3814
3815 tasks.push(close_pane_items)
3816 }
3817
3818 if tasks.is_empty() {
3819 None
3820 } else {
3821 Some(cx.spawn_in(window, async move |_, _| {
3822 for task in tasks {
3823 task.await?
3824 }
3825 Ok(())
3826 }))
3827 }
3828 }
3829
3830 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3831 self.dock_at_position(position).read(cx).is_open()
3832 }
3833
3834 pub fn toggle_dock(
3835 &mut self,
3836 dock_side: DockPosition,
3837 window: &mut Window,
3838 cx: &mut Context<Self>,
3839 ) {
3840 let mut focus_center = false;
3841 let mut reveal_dock = false;
3842
3843 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3844 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3845
3846 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3847 telemetry::event!(
3848 "Panel Button Clicked",
3849 name = panel.persistent_name(),
3850 toggle_state = !was_visible
3851 );
3852 }
3853 if was_visible {
3854 self.save_open_dock_positions(cx);
3855 }
3856
3857 let dock = self.dock_at_position(dock_side);
3858 dock.update(cx, |dock, cx| {
3859 dock.set_open(!was_visible, window, cx);
3860
3861 if dock.active_panel().is_none() {
3862 let Some(panel_ix) = dock
3863 .first_enabled_panel_idx(cx)
3864 .log_with_level(log::Level::Info)
3865 else {
3866 return;
3867 };
3868 dock.activate_panel(panel_ix, window, cx);
3869 }
3870
3871 if let Some(active_panel) = dock.active_panel() {
3872 if was_visible {
3873 if active_panel
3874 .panel_focus_handle(cx)
3875 .contains_focused(window, cx)
3876 {
3877 focus_center = true;
3878 }
3879 } else {
3880 let focus_handle = &active_panel.panel_focus_handle(cx);
3881 window.focus(focus_handle, cx);
3882 reveal_dock = true;
3883 }
3884 }
3885 });
3886
3887 if reveal_dock {
3888 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3889 }
3890
3891 if focus_center {
3892 self.active_pane
3893 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3894 }
3895
3896 cx.notify();
3897 self.serialize_workspace(window, cx);
3898 }
3899
3900 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3901 self.all_docks().into_iter().find(|&dock| {
3902 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3903 })
3904 }
3905
3906 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3907 if let Some(dock) = self.active_dock(window, cx).cloned() {
3908 self.save_open_dock_positions(cx);
3909 dock.update(cx, |dock, cx| {
3910 dock.set_open(false, window, cx);
3911 });
3912 return true;
3913 }
3914 false
3915 }
3916
3917 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3918 self.save_open_dock_positions(cx);
3919 for dock in self.all_docks() {
3920 dock.update(cx, |dock, cx| {
3921 dock.set_open(false, window, cx);
3922 });
3923 }
3924
3925 cx.focus_self(window);
3926 cx.notify();
3927 self.serialize_workspace(window, cx);
3928 }
3929
3930 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3931 self.all_docks()
3932 .into_iter()
3933 .filter_map(|dock| {
3934 let dock_ref = dock.read(cx);
3935 if dock_ref.is_open() {
3936 Some(dock_ref.position())
3937 } else {
3938 None
3939 }
3940 })
3941 .collect()
3942 }
3943
3944 /// Saves the positions of currently open docks.
3945 ///
3946 /// Updates `last_open_dock_positions` with positions of all currently open
3947 /// docks, to later be restored by the 'Toggle All Docks' action.
3948 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3949 let open_dock_positions = self.get_open_dock_positions(cx);
3950 if !open_dock_positions.is_empty() {
3951 self.last_open_dock_positions = open_dock_positions;
3952 }
3953 }
3954
3955 /// Toggles all docks between open and closed states.
3956 ///
3957 /// If any docks are open, closes all and remembers their positions. If all
3958 /// docks are closed, restores the last remembered dock configuration.
3959 fn toggle_all_docks(
3960 &mut self,
3961 _: &ToggleAllDocks,
3962 window: &mut Window,
3963 cx: &mut Context<Self>,
3964 ) {
3965 let open_dock_positions = self.get_open_dock_positions(cx);
3966
3967 if !open_dock_positions.is_empty() {
3968 self.close_all_docks(window, cx);
3969 } else if !self.last_open_dock_positions.is_empty() {
3970 self.restore_last_open_docks(window, cx);
3971 }
3972 }
3973
3974 /// Reopens docks from the most recently remembered configuration.
3975 ///
3976 /// Opens all docks whose positions are stored in `last_open_dock_positions`
3977 /// and clears the stored positions.
3978 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3979 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
3980
3981 for position in positions_to_open {
3982 let dock = self.dock_at_position(position);
3983 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
3984 }
3985
3986 cx.focus_self(window);
3987 cx.notify();
3988 self.serialize_workspace(window, cx);
3989 }
3990
3991 /// Transfer focus to the panel of the given type.
3992 pub fn focus_panel<T: Panel>(
3993 &mut self,
3994 window: &mut Window,
3995 cx: &mut Context<Self>,
3996 ) -> Option<Entity<T>> {
3997 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
3998 panel.to_any().downcast().ok()
3999 }
4000
4001 /// Focus the panel of the given type if it isn't already focused. If it is
4002 /// already focused, then transfer focus back to the workspace center.
4003 /// When the `close_panel_on_toggle` setting is enabled, also closes the
4004 /// panel when transferring focus back to the center.
4005 pub fn toggle_panel_focus<T: Panel>(
4006 &mut self,
4007 window: &mut Window,
4008 cx: &mut Context<Self>,
4009 ) -> bool {
4010 let mut did_focus_panel = false;
4011 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
4012 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
4013 did_focus_panel
4014 });
4015
4016 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
4017 self.close_panel::<T>(window, cx);
4018 }
4019
4020 telemetry::event!(
4021 "Panel Button Clicked",
4022 name = T::persistent_name(),
4023 toggle_state = did_focus_panel
4024 );
4025
4026 did_focus_panel
4027 }
4028
4029 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4030 if let Some(item) = self.active_item(cx) {
4031 item.item_focus_handle(cx).focus(window, cx);
4032 } else {
4033 log::error!("Could not find a focus target when switching focus to the center panes",);
4034 }
4035 }
4036
4037 pub fn activate_panel_for_proto_id(
4038 &mut self,
4039 panel_id: PanelId,
4040 window: &mut Window,
4041 cx: &mut Context<Self>,
4042 ) -> Option<Arc<dyn PanelHandle>> {
4043 let mut panel = None;
4044 for dock in self.all_docks() {
4045 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
4046 panel = dock.update(cx, |dock, cx| {
4047 dock.activate_panel(panel_index, window, cx);
4048 dock.set_open(true, window, cx);
4049 dock.active_panel().cloned()
4050 });
4051 break;
4052 }
4053 }
4054
4055 if panel.is_some() {
4056 cx.notify();
4057 self.serialize_workspace(window, cx);
4058 }
4059
4060 panel
4061 }
4062
4063 /// Focus or unfocus the given panel type, depending on the given callback.
4064 fn focus_or_unfocus_panel<T: Panel>(
4065 &mut self,
4066 window: &mut Window,
4067 cx: &mut Context<Self>,
4068 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
4069 ) -> Option<Arc<dyn PanelHandle>> {
4070 let mut result_panel = None;
4071 let mut serialize = false;
4072 for dock in self.all_docks() {
4073 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4074 let mut focus_center = false;
4075 let panel = dock.update(cx, |dock, cx| {
4076 dock.activate_panel(panel_index, window, cx);
4077
4078 let panel = dock.active_panel().cloned();
4079 if let Some(panel) = panel.as_ref() {
4080 if should_focus(&**panel, window, cx) {
4081 dock.set_open(true, window, cx);
4082 panel.panel_focus_handle(cx).focus(window, cx);
4083 } else {
4084 focus_center = true;
4085 }
4086 }
4087 panel
4088 });
4089
4090 if focus_center {
4091 self.active_pane
4092 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4093 }
4094
4095 result_panel = panel;
4096 serialize = true;
4097 break;
4098 }
4099 }
4100
4101 if serialize {
4102 self.serialize_workspace(window, cx);
4103 }
4104
4105 cx.notify();
4106 result_panel
4107 }
4108
4109 /// Open the panel of the given type
4110 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4111 for dock in self.all_docks() {
4112 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4113 dock.update(cx, |dock, cx| {
4114 dock.activate_panel(panel_index, window, cx);
4115 dock.set_open(true, window, cx);
4116 });
4117 }
4118 }
4119 }
4120
4121 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
4122 for dock in self.all_docks().iter() {
4123 dock.update(cx, |dock, cx| {
4124 if dock.panel::<T>().is_some() {
4125 dock.set_open(false, window, cx)
4126 }
4127 })
4128 }
4129 }
4130
4131 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
4132 self.all_docks()
4133 .iter()
4134 .find_map(|dock| dock.read(cx).panel::<T>())
4135 }
4136
4137 fn dismiss_zoomed_items_to_reveal(
4138 &mut self,
4139 dock_to_reveal: Option<DockPosition>,
4140 window: &mut Window,
4141 cx: &mut Context<Self>,
4142 ) {
4143 // If a center pane is zoomed, unzoom it.
4144 for pane in &self.panes {
4145 if pane != &self.active_pane || dock_to_reveal.is_some() {
4146 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4147 }
4148 }
4149
4150 // If another dock is zoomed, hide it.
4151 let mut focus_center = false;
4152 for dock in self.all_docks() {
4153 dock.update(cx, |dock, cx| {
4154 if Some(dock.position()) != dock_to_reveal
4155 && let Some(panel) = dock.active_panel()
4156 && panel.is_zoomed(window, cx)
4157 {
4158 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
4159 dock.set_open(false, window, cx);
4160 }
4161 });
4162 }
4163
4164 if focus_center {
4165 self.active_pane
4166 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4167 }
4168
4169 if self.zoomed_position != dock_to_reveal {
4170 self.zoomed = None;
4171 self.zoomed_position = None;
4172 cx.emit(Event::ZoomChanged);
4173 }
4174
4175 cx.notify();
4176 }
4177
4178 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4179 let pane = cx.new(|cx| {
4180 let mut pane = Pane::new(
4181 self.weak_handle(),
4182 self.project.clone(),
4183 self.pane_history_timestamp.clone(),
4184 None,
4185 NewFile.boxed_clone(),
4186 true,
4187 window,
4188 cx,
4189 );
4190 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4191 pane
4192 });
4193 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4194 .detach();
4195 self.panes.push(pane.clone());
4196
4197 window.focus(&pane.focus_handle(cx), cx);
4198
4199 cx.emit(Event::PaneAdded(pane.clone()));
4200 pane
4201 }
4202
4203 pub fn add_item_to_center(
4204 &mut self,
4205 item: Box<dyn ItemHandle>,
4206 window: &mut Window,
4207 cx: &mut Context<Self>,
4208 ) -> bool {
4209 if let Some(center_pane) = self.last_active_center_pane.clone() {
4210 if let Some(center_pane) = center_pane.upgrade() {
4211 center_pane.update(cx, |pane, cx| {
4212 pane.add_item(item, true, true, None, window, cx)
4213 });
4214 true
4215 } else {
4216 false
4217 }
4218 } else {
4219 false
4220 }
4221 }
4222
4223 pub fn add_item_to_active_pane(
4224 &mut self,
4225 item: Box<dyn ItemHandle>,
4226 destination_index: Option<usize>,
4227 focus_item: bool,
4228 window: &mut Window,
4229 cx: &mut App,
4230 ) {
4231 self.add_item(
4232 self.active_pane.clone(),
4233 item,
4234 destination_index,
4235 false,
4236 focus_item,
4237 window,
4238 cx,
4239 )
4240 }
4241
4242 pub fn add_item(
4243 &mut self,
4244 pane: Entity<Pane>,
4245 item: Box<dyn ItemHandle>,
4246 destination_index: Option<usize>,
4247 activate_pane: bool,
4248 focus_item: bool,
4249 window: &mut Window,
4250 cx: &mut App,
4251 ) {
4252 pane.update(cx, |pane, cx| {
4253 pane.add_item(
4254 item,
4255 activate_pane,
4256 focus_item,
4257 destination_index,
4258 window,
4259 cx,
4260 )
4261 });
4262 }
4263
4264 pub fn split_item(
4265 &mut self,
4266 split_direction: SplitDirection,
4267 item: Box<dyn ItemHandle>,
4268 window: &mut Window,
4269 cx: &mut Context<Self>,
4270 ) {
4271 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4272 self.add_item(new_pane, item, None, true, true, window, cx);
4273 }
4274
4275 pub fn open_abs_path(
4276 &mut self,
4277 abs_path: PathBuf,
4278 options: OpenOptions,
4279 window: &mut Window,
4280 cx: &mut Context<Self>,
4281 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4282 cx.spawn_in(window, async move |workspace, cx| {
4283 let open_paths_task_result = workspace
4284 .update_in(cx, |workspace, window, cx| {
4285 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4286 })
4287 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4288 .await;
4289 anyhow::ensure!(
4290 open_paths_task_result.len() == 1,
4291 "open abs path {abs_path:?} task returned incorrect number of results"
4292 );
4293 match open_paths_task_result
4294 .into_iter()
4295 .next()
4296 .expect("ensured single task result")
4297 {
4298 Some(open_result) => {
4299 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4300 }
4301 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4302 }
4303 })
4304 }
4305
4306 pub fn split_abs_path(
4307 &mut self,
4308 abs_path: PathBuf,
4309 visible: bool,
4310 window: &mut Window,
4311 cx: &mut Context<Self>,
4312 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4313 let project_path_task =
4314 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4315 cx.spawn_in(window, async move |this, cx| {
4316 let (_, path) = project_path_task.await?;
4317 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4318 .await
4319 })
4320 }
4321
4322 pub fn open_path(
4323 &mut self,
4324 path: impl Into<ProjectPath>,
4325 pane: Option<WeakEntity<Pane>>,
4326 focus_item: bool,
4327 window: &mut Window,
4328 cx: &mut App,
4329 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4330 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4331 }
4332
4333 pub fn open_path_preview(
4334 &mut self,
4335 path: impl Into<ProjectPath>,
4336 pane: Option<WeakEntity<Pane>>,
4337 focus_item: bool,
4338 allow_preview: bool,
4339 activate: bool,
4340 window: &mut Window,
4341 cx: &mut App,
4342 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4343 let pane = pane.unwrap_or_else(|| {
4344 self.last_active_center_pane.clone().unwrap_or_else(|| {
4345 self.panes
4346 .first()
4347 .expect("There must be an active pane")
4348 .downgrade()
4349 })
4350 });
4351
4352 let project_path = path.into();
4353 let task = self.load_path(project_path.clone(), window, cx);
4354 window.spawn(cx, async move |cx| {
4355 let (project_entry_id, build_item) = task.await?;
4356
4357 pane.update_in(cx, |pane, window, cx| {
4358 pane.open_item(
4359 project_entry_id,
4360 project_path,
4361 focus_item,
4362 allow_preview,
4363 activate,
4364 None,
4365 window,
4366 cx,
4367 build_item,
4368 )
4369 })
4370 })
4371 }
4372
4373 pub fn split_path(
4374 &mut self,
4375 path: impl Into<ProjectPath>,
4376 window: &mut Window,
4377 cx: &mut Context<Self>,
4378 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4379 self.split_path_preview(path, false, None, window, cx)
4380 }
4381
4382 pub fn split_path_preview(
4383 &mut self,
4384 path: impl Into<ProjectPath>,
4385 allow_preview: bool,
4386 split_direction: Option<SplitDirection>,
4387 window: &mut Window,
4388 cx: &mut Context<Self>,
4389 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4390 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4391 self.panes
4392 .first()
4393 .expect("There must be an active pane")
4394 .downgrade()
4395 });
4396
4397 if let Member::Pane(center_pane) = &self.center.root
4398 && center_pane.read(cx).items_len() == 0
4399 {
4400 return self.open_path(path, Some(pane), true, window, cx);
4401 }
4402
4403 let project_path = path.into();
4404 let task = self.load_path(project_path.clone(), window, cx);
4405 cx.spawn_in(window, async move |this, cx| {
4406 let (project_entry_id, build_item) = task.await?;
4407 this.update_in(cx, move |this, window, cx| -> Option<_> {
4408 let pane = pane.upgrade()?;
4409 let new_pane = this.split_pane(
4410 pane,
4411 split_direction.unwrap_or(SplitDirection::Right),
4412 window,
4413 cx,
4414 );
4415 new_pane.update(cx, |new_pane, cx| {
4416 Some(new_pane.open_item(
4417 project_entry_id,
4418 project_path,
4419 true,
4420 allow_preview,
4421 true,
4422 None,
4423 window,
4424 cx,
4425 build_item,
4426 ))
4427 })
4428 })
4429 .map(|option| option.context("pane was dropped"))?
4430 })
4431 }
4432
4433 fn load_path(
4434 &mut self,
4435 path: ProjectPath,
4436 window: &mut Window,
4437 cx: &mut App,
4438 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4439 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4440 registry.open_path(self.project(), &path, window, cx)
4441 }
4442
4443 pub fn find_project_item<T>(
4444 &self,
4445 pane: &Entity<Pane>,
4446 project_item: &Entity<T::Item>,
4447 cx: &App,
4448 ) -> Option<Entity<T>>
4449 where
4450 T: ProjectItem,
4451 {
4452 use project::ProjectItem as _;
4453 let project_item = project_item.read(cx);
4454 let entry_id = project_item.entry_id(cx);
4455 let project_path = project_item.project_path(cx);
4456
4457 let mut item = None;
4458 if let Some(entry_id) = entry_id {
4459 item = pane.read(cx).item_for_entry(entry_id, cx);
4460 }
4461 if item.is_none()
4462 && let Some(project_path) = project_path
4463 {
4464 item = pane.read(cx).item_for_path(project_path, cx);
4465 }
4466
4467 item.and_then(|item| item.downcast::<T>())
4468 }
4469
4470 pub fn is_project_item_open<T>(
4471 &self,
4472 pane: &Entity<Pane>,
4473 project_item: &Entity<T::Item>,
4474 cx: &App,
4475 ) -> bool
4476 where
4477 T: ProjectItem,
4478 {
4479 self.find_project_item::<T>(pane, project_item, cx)
4480 .is_some()
4481 }
4482
4483 pub fn open_project_item<T>(
4484 &mut self,
4485 pane: Entity<Pane>,
4486 project_item: Entity<T::Item>,
4487 activate_pane: bool,
4488 focus_item: bool,
4489 keep_old_preview: bool,
4490 allow_new_preview: bool,
4491 window: &mut Window,
4492 cx: &mut Context<Self>,
4493 ) -> Entity<T>
4494 where
4495 T: ProjectItem,
4496 {
4497 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4498
4499 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4500 if !keep_old_preview
4501 && let Some(old_id) = old_item_id
4502 && old_id != item.item_id()
4503 {
4504 // switching to a different item, so unpreview old active item
4505 pane.update(cx, |pane, _| {
4506 pane.unpreview_item_if_preview(old_id);
4507 });
4508 }
4509
4510 self.activate_item(&item, activate_pane, focus_item, window, cx);
4511 if !allow_new_preview {
4512 pane.update(cx, |pane, _| {
4513 pane.unpreview_item_if_preview(item.item_id());
4514 });
4515 }
4516 return item;
4517 }
4518
4519 let item = pane.update(cx, |pane, cx| {
4520 cx.new(|cx| {
4521 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4522 })
4523 });
4524 let mut destination_index = None;
4525 pane.update(cx, |pane, cx| {
4526 if !keep_old_preview && let Some(old_id) = old_item_id {
4527 pane.unpreview_item_if_preview(old_id);
4528 }
4529 if allow_new_preview {
4530 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4531 }
4532 });
4533
4534 self.add_item(
4535 pane,
4536 Box::new(item.clone()),
4537 destination_index,
4538 activate_pane,
4539 focus_item,
4540 window,
4541 cx,
4542 );
4543 item
4544 }
4545
4546 pub fn open_shared_screen(
4547 &mut self,
4548 peer_id: PeerId,
4549 window: &mut Window,
4550 cx: &mut Context<Self>,
4551 ) {
4552 if let Some(shared_screen) =
4553 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4554 {
4555 self.active_pane.update(cx, |pane, cx| {
4556 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4557 });
4558 }
4559 }
4560
4561 pub fn activate_item(
4562 &mut self,
4563 item: &dyn ItemHandle,
4564 activate_pane: bool,
4565 focus_item: bool,
4566 window: &mut Window,
4567 cx: &mut App,
4568 ) -> bool {
4569 let result = self.panes.iter().find_map(|pane| {
4570 pane.read(cx)
4571 .index_for_item(item)
4572 .map(|ix| (pane.clone(), ix))
4573 });
4574 if let Some((pane, ix)) = result {
4575 pane.update(cx, |pane, cx| {
4576 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4577 });
4578 true
4579 } else {
4580 false
4581 }
4582 }
4583
4584 fn activate_pane_at_index(
4585 &mut self,
4586 action: &ActivatePane,
4587 window: &mut Window,
4588 cx: &mut Context<Self>,
4589 ) {
4590 let panes = self.center.panes();
4591 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4592 window.focus(&pane.focus_handle(cx), cx);
4593 } else {
4594 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4595 .detach();
4596 }
4597 }
4598
4599 fn move_item_to_pane_at_index(
4600 &mut self,
4601 action: &MoveItemToPane,
4602 window: &mut Window,
4603 cx: &mut Context<Self>,
4604 ) {
4605 let panes = self.center.panes();
4606 let destination = match panes.get(action.destination) {
4607 Some(&destination) => destination.clone(),
4608 None => {
4609 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4610 return;
4611 }
4612 let direction = SplitDirection::Right;
4613 let split_off_pane = self
4614 .find_pane_in_direction(direction, cx)
4615 .unwrap_or_else(|| self.active_pane.clone());
4616 let new_pane = self.add_pane(window, cx);
4617 self.center.split(&split_off_pane, &new_pane, direction, cx);
4618 new_pane
4619 }
4620 };
4621
4622 if action.clone {
4623 if self
4624 .active_pane
4625 .read(cx)
4626 .active_item()
4627 .is_some_and(|item| item.can_split(cx))
4628 {
4629 clone_active_item(
4630 self.database_id(),
4631 &self.active_pane,
4632 &destination,
4633 action.focus,
4634 window,
4635 cx,
4636 );
4637 return;
4638 }
4639 }
4640 move_active_item(
4641 &self.active_pane,
4642 &destination,
4643 action.focus,
4644 true,
4645 window,
4646 cx,
4647 )
4648 }
4649
4650 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4651 let panes = self.center.panes();
4652 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4653 let next_ix = (ix + 1) % panes.len();
4654 let next_pane = panes[next_ix].clone();
4655 window.focus(&next_pane.focus_handle(cx), cx);
4656 }
4657 }
4658
4659 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4660 let panes = self.center.panes();
4661 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4662 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4663 let prev_pane = panes[prev_ix].clone();
4664 window.focus(&prev_pane.focus_handle(cx), cx);
4665 }
4666 }
4667
4668 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4669 let last_pane = self.center.last_pane();
4670 window.focus(&last_pane.focus_handle(cx), cx);
4671 }
4672
4673 pub fn activate_pane_in_direction(
4674 &mut self,
4675 direction: SplitDirection,
4676 window: &mut Window,
4677 cx: &mut App,
4678 ) {
4679 use ActivateInDirectionTarget as Target;
4680 enum Origin {
4681 Sidebar,
4682 LeftDock,
4683 RightDock,
4684 BottomDock,
4685 Center,
4686 }
4687
4688 let origin: Origin = if self
4689 .sidebar_focus_handle
4690 .as_ref()
4691 .is_some_and(|h| h.contains_focused(window, cx))
4692 {
4693 Origin::Sidebar
4694 } else {
4695 [
4696 (&self.left_dock, Origin::LeftDock),
4697 (&self.right_dock, Origin::RightDock),
4698 (&self.bottom_dock, Origin::BottomDock),
4699 ]
4700 .into_iter()
4701 .find_map(|(dock, origin)| {
4702 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4703 Some(origin)
4704 } else {
4705 None
4706 }
4707 })
4708 .unwrap_or(Origin::Center)
4709 };
4710
4711 let get_last_active_pane = || {
4712 let pane = self
4713 .last_active_center_pane
4714 .clone()
4715 .unwrap_or_else(|| {
4716 self.panes
4717 .first()
4718 .expect("There must be an active pane")
4719 .downgrade()
4720 })
4721 .upgrade()?;
4722 (pane.read(cx).items_len() != 0).then_some(pane)
4723 };
4724
4725 let try_dock =
4726 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4727
4728 let sidebar_target = self
4729 .sidebar_focus_handle
4730 .as_ref()
4731 .map(|h| Target::Sidebar(h.clone()));
4732
4733 let sidebar_on_left = self
4734 .multi_workspace
4735 .as_ref()
4736 .and_then(|mw| mw.upgrade())
4737 .map_or(true, |mw| mw.read(cx).sidebar_side(cx) == SidebarSide::Left);
4738
4739 let sidebar_on_side = |side: SplitDirection| -> Option<ActivateInDirectionTarget> {
4740 if (side == SplitDirection::Left) == sidebar_on_left {
4741 sidebar_target.clone()
4742 } else {
4743 None
4744 }
4745 };
4746
4747 let target = match (origin, direction) {
4748 // From the sidebar, only the inward direction navigates into
4749 // the workspace. Which direction is "inward" depends on which
4750 // side the sidebar is on.
4751 (Origin::Sidebar, SplitDirection::Right) if sidebar_on_left => {
4752 try_dock(&self.left_dock)
4753 .or_else(|| get_last_active_pane().map(Target::Pane))
4754 .or_else(|| try_dock(&self.bottom_dock))
4755 .or_else(|| try_dock(&self.right_dock))
4756 }
4757 (Origin::Sidebar, SplitDirection::Left) if !sidebar_on_left => {
4758 try_dock(&self.right_dock)
4759 .or_else(|| get_last_active_pane().map(Target::Pane))
4760 .or_else(|| try_dock(&self.bottom_dock))
4761 .or_else(|| try_dock(&self.left_dock))
4762 }
4763
4764 (Origin::Sidebar, _) => None,
4765
4766 // We're in the center, so we first try to go to a different pane,
4767 // otherwise try to go to a dock.
4768 (Origin::Center, direction) => {
4769 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4770 Some(Target::Pane(pane))
4771 } else {
4772 match direction {
4773 SplitDirection::Up => None,
4774 SplitDirection::Down => try_dock(&self.bottom_dock),
4775 SplitDirection::Left => {
4776 try_dock(&self.left_dock).or_else(|| sidebar_on_side(direction))
4777 }
4778 SplitDirection::Right => {
4779 try_dock(&self.right_dock).or_else(|| sidebar_on_side(direction))
4780 }
4781 }
4782 }
4783 }
4784
4785 (Origin::LeftDock, SplitDirection::Right) => {
4786 if let Some(last_active_pane) = get_last_active_pane() {
4787 Some(Target::Pane(last_active_pane))
4788 } else {
4789 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4790 }
4791 }
4792
4793 (Origin::LeftDock, SplitDirection::Left) => sidebar_on_side(SplitDirection::Left),
4794
4795 (Origin::LeftDock, SplitDirection::Down)
4796 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4797
4798 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4799 (Origin::BottomDock, SplitDirection::Left) => {
4800 try_dock(&self.left_dock).or_else(|| sidebar_on_side(SplitDirection::Left))
4801 }
4802 (Origin::BottomDock, SplitDirection::Right) => {
4803 try_dock(&self.right_dock).or_else(|| sidebar_on_side(SplitDirection::Right))
4804 }
4805
4806 (Origin::RightDock, SplitDirection::Left) => {
4807 if let Some(last_active_pane) = get_last_active_pane() {
4808 Some(Target::Pane(last_active_pane))
4809 } else {
4810 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
4811 }
4812 }
4813
4814 (Origin::RightDock, SplitDirection::Right) => sidebar_on_side(SplitDirection::Right),
4815
4816 _ => None,
4817 };
4818
4819 match target {
4820 Some(ActivateInDirectionTarget::Pane(pane)) => {
4821 let pane = pane.read(cx);
4822 if let Some(item) = pane.active_item() {
4823 item.item_focus_handle(cx).focus(window, cx);
4824 } else {
4825 log::error!(
4826 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4827 );
4828 }
4829 }
4830 Some(ActivateInDirectionTarget::Dock(dock)) => {
4831 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4832 window.defer(cx, move |window, cx| {
4833 let dock = dock.read(cx);
4834 if let Some(panel) = dock.active_panel() {
4835 panel.panel_focus_handle(cx).focus(window, cx);
4836 } else {
4837 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4838 }
4839 })
4840 }
4841 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4842 focus_handle.focus(window, cx);
4843 }
4844 None => {}
4845 }
4846 }
4847
4848 pub fn move_item_to_pane_in_direction(
4849 &mut self,
4850 action: &MoveItemToPaneInDirection,
4851 window: &mut Window,
4852 cx: &mut Context<Self>,
4853 ) {
4854 let destination = match self.find_pane_in_direction(action.direction, cx) {
4855 Some(destination) => destination,
4856 None => {
4857 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4858 return;
4859 }
4860 let new_pane = self.add_pane(window, cx);
4861 self.center
4862 .split(&self.active_pane, &new_pane, action.direction, cx);
4863 new_pane
4864 }
4865 };
4866
4867 if action.clone {
4868 if self
4869 .active_pane
4870 .read(cx)
4871 .active_item()
4872 .is_some_and(|item| item.can_split(cx))
4873 {
4874 clone_active_item(
4875 self.database_id(),
4876 &self.active_pane,
4877 &destination,
4878 action.focus,
4879 window,
4880 cx,
4881 );
4882 return;
4883 }
4884 }
4885 move_active_item(
4886 &self.active_pane,
4887 &destination,
4888 action.focus,
4889 true,
4890 window,
4891 cx,
4892 );
4893 }
4894
4895 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4896 self.center.bounding_box_for_pane(pane)
4897 }
4898
4899 pub fn find_pane_in_direction(
4900 &mut self,
4901 direction: SplitDirection,
4902 cx: &App,
4903 ) -> Option<Entity<Pane>> {
4904 self.center
4905 .find_pane_in_direction(&self.active_pane, direction, cx)
4906 .cloned()
4907 }
4908
4909 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4910 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4911 self.center.swap(&self.active_pane, &to, cx);
4912 cx.notify();
4913 }
4914 }
4915
4916 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4917 if self
4918 .center
4919 .move_to_border(&self.active_pane, direction, cx)
4920 .unwrap()
4921 {
4922 cx.notify();
4923 }
4924 }
4925
4926 pub fn resize_pane(
4927 &mut self,
4928 axis: gpui::Axis,
4929 amount: Pixels,
4930 window: &mut Window,
4931 cx: &mut Context<Self>,
4932 ) {
4933 let docks = self.all_docks();
4934 let active_dock = docks
4935 .into_iter()
4936 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4937
4938 if let Some(dock_entity) = active_dock {
4939 let dock = dock_entity.read(cx);
4940 let Some(panel_size) = dock
4941 .active_panel()
4942 .map(|panel| self.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx))
4943 else {
4944 return;
4945 };
4946 match dock.position() {
4947 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4948 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4949 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4950 }
4951 } else {
4952 self.center
4953 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4954 }
4955 cx.notify();
4956 }
4957
4958 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4959 self.center.reset_pane_sizes(cx);
4960 cx.notify();
4961 }
4962
4963 fn handle_pane_focused(
4964 &mut self,
4965 pane: Entity<Pane>,
4966 window: &mut Window,
4967 cx: &mut Context<Self>,
4968 ) {
4969 // This is explicitly hoisted out of the following check for pane identity as
4970 // terminal panel panes are not registered as a center panes.
4971 self.status_bar.update(cx, |status_bar, cx| {
4972 status_bar.set_active_pane(&pane, window, cx);
4973 });
4974 if self.active_pane != pane {
4975 self.set_active_pane(&pane, window, cx);
4976 }
4977
4978 if self.last_active_center_pane.is_none() {
4979 self.last_active_center_pane = Some(pane.downgrade());
4980 }
4981
4982 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
4983 // This prevents the dock from closing when focus events fire during window activation.
4984 // We also preserve any dock whose active panel itself has focus — this covers
4985 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
4986 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
4987 let dock_read = dock.read(cx);
4988 if let Some(panel) = dock_read.active_panel() {
4989 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
4990 || panel.panel_focus_handle(cx).contains_focused(window, cx)
4991 {
4992 return Some(dock_read.position());
4993 }
4994 }
4995 None
4996 });
4997
4998 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
4999 if pane.read(cx).is_zoomed() {
5000 self.zoomed = Some(pane.downgrade().into());
5001 } else {
5002 self.zoomed = None;
5003 }
5004 self.zoomed_position = None;
5005 cx.emit(Event::ZoomChanged);
5006 self.update_active_view_for_followers(window, cx);
5007 pane.update(cx, |pane, _| {
5008 pane.track_alternate_file_items();
5009 });
5010
5011 cx.notify();
5012 }
5013
5014 fn set_active_pane(
5015 &mut self,
5016 pane: &Entity<Pane>,
5017 window: &mut Window,
5018 cx: &mut Context<Self>,
5019 ) {
5020 self.active_pane = pane.clone();
5021 self.active_item_path_changed(true, window, cx);
5022 self.last_active_center_pane = Some(pane.downgrade());
5023 }
5024
5025 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5026 self.update_active_view_for_followers(window, cx);
5027 }
5028
5029 fn handle_pane_event(
5030 &mut self,
5031 pane: &Entity<Pane>,
5032 event: &pane::Event,
5033 window: &mut Window,
5034 cx: &mut Context<Self>,
5035 ) {
5036 let mut serialize_workspace = true;
5037 match event {
5038 pane::Event::AddItem { item } => {
5039 item.added_to_pane(self, pane.clone(), window, cx);
5040 cx.emit(Event::ItemAdded {
5041 item: item.boxed_clone(),
5042 });
5043 }
5044 pane::Event::Split { direction, mode } => {
5045 match mode {
5046 SplitMode::ClonePane => {
5047 self.split_and_clone(pane.clone(), *direction, window, cx)
5048 .detach();
5049 }
5050 SplitMode::EmptyPane => {
5051 self.split_pane(pane.clone(), *direction, window, cx);
5052 }
5053 SplitMode::MovePane => {
5054 self.split_and_move(pane.clone(), *direction, window, cx);
5055 }
5056 };
5057 }
5058 pane::Event::JoinIntoNext => {
5059 self.join_pane_into_next(pane.clone(), window, cx);
5060 }
5061 pane::Event::JoinAll => {
5062 self.join_all_panes(window, cx);
5063 }
5064 pane::Event::Remove { focus_on_pane } => {
5065 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
5066 }
5067 pane::Event::ActivateItem {
5068 local,
5069 focus_changed,
5070 } => {
5071 window.invalidate_character_coordinates();
5072
5073 pane.update(cx, |pane, _| {
5074 pane.track_alternate_file_items();
5075 });
5076 if *local {
5077 self.unfollow_in_pane(pane, window, cx);
5078 }
5079 serialize_workspace = *focus_changed || pane != self.active_pane();
5080 if pane == self.active_pane() {
5081 self.active_item_path_changed(*focus_changed, window, cx);
5082 self.update_active_view_for_followers(window, cx);
5083 } else if *local {
5084 self.set_active_pane(pane, window, cx);
5085 }
5086 }
5087 pane::Event::UserSavedItem { item, save_intent } => {
5088 cx.emit(Event::UserSavedItem {
5089 pane: pane.downgrade(),
5090 item: item.boxed_clone(),
5091 save_intent: *save_intent,
5092 });
5093 serialize_workspace = false;
5094 }
5095 pane::Event::ChangeItemTitle => {
5096 if *pane == self.active_pane {
5097 self.active_item_path_changed(false, window, cx);
5098 }
5099 serialize_workspace = false;
5100 }
5101 pane::Event::RemovedItem { item } => {
5102 cx.emit(Event::ActiveItemChanged);
5103 self.update_window_edited(window, cx);
5104 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
5105 && entry.get().entity_id() == pane.entity_id()
5106 {
5107 entry.remove();
5108 }
5109 cx.emit(Event::ItemRemoved {
5110 item_id: item.item_id(),
5111 });
5112 }
5113 pane::Event::Focus => {
5114 window.invalidate_character_coordinates();
5115 self.handle_pane_focused(pane.clone(), window, cx);
5116 }
5117 pane::Event::ZoomIn => {
5118 if *pane == self.active_pane {
5119 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
5120 if pane.read(cx).has_focus(window, cx) {
5121 self.zoomed = Some(pane.downgrade().into());
5122 self.zoomed_position = None;
5123 cx.emit(Event::ZoomChanged);
5124 }
5125 cx.notify();
5126 }
5127 }
5128 pane::Event::ZoomOut => {
5129 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
5130 if self.zoomed_position.is_none() {
5131 self.zoomed = None;
5132 cx.emit(Event::ZoomChanged);
5133 }
5134 cx.notify();
5135 }
5136 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
5137 }
5138
5139 if serialize_workspace {
5140 self.serialize_workspace(window, cx);
5141 }
5142 }
5143
5144 pub fn unfollow_in_pane(
5145 &mut self,
5146 pane: &Entity<Pane>,
5147 window: &mut Window,
5148 cx: &mut Context<Workspace>,
5149 ) -> Option<CollaboratorId> {
5150 let leader_id = self.leader_for_pane(pane)?;
5151 self.unfollow(leader_id, window, cx);
5152 Some(leader_id)
5153 }
5154
5155 pub fn split_pane(
5156 &mut self,
5157 pane_to_split: Entity<Pane>,
5158 split_direction: SplitDirection,
5159 window: &mut Window,
5160 cx: &mut Context<Self>,
5161 ) -> Entity<Pane> {
5162 let new_pane = self.add_pane(window, cx);
5163 self.center
5164 .split(&pane_to_split, &new_pane, split_direction, cx);
5165 cx.notify();
5166 new_pane
5167 }
5168
5169 pub fn split_and_move(
5170 &mut self,
5171 pane: Entity<Pane>,
5172 direction: SplitDirection,
5173 window: &mut Window,
5174 cx: &mut Context<Self>,
5175 ) {
5176 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
5177 return;
5178 };
5179 let new_pane = self.add_pane(window, cx);
5180 new_pane.update(cx, |pane, cx| {
5181 pane.add_item(item, true, true, None, window, cx)
5182 });
5183 self.center.split(&pane, &new_pane, direction, cx);
5184 cx.notify();
5185 }
5186
5187 pub fn split_and_clone(
5188 &mut self,
5189 pane: Entity<Pane>,
5190 direction: SplitDirection,
5191 window: &mut Window,
5192 cx: &mut Context<Self>,
5193 ) -> Task<Option<Entity<Pane>>> {
5194 let Some(item) = pane.read(cx).active_item() else {
5195 return Task::ready(None);
5196 };
5197 if !item.can_split(cx) {
5198 return Task::ready(None);
5199 }
5200 let task = item.clone_on_split(self.database_id(), window, cx);
5201 cx.spawn_in(window, async move |this, cx| {
5202 if let Some(clone) = task.await {
5203 this.update_in(cx, |this, window, cx| {
5204 let new_pane = this.add_pane(window, cx);
5205 let nav_history = pane.read(cx).fork_nav_history();
5206 new_pane.update(cx, |pane, cx| {
5207 pane.set_nav_history(nav_history, cx);
5208 pane.add_item(clone, true, true, None, window, cx)
5209 });
5210 this.center.split(&pane, &new_pane, direction, cx);
5211 cx.notify();
5212 new_pane
5213 })
5214 .ok()
5215 } else {
5216 None
5217 }
5218 })
5219 }
5220
5221 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5222 let active_item = self.active_pane.read(cx).active_item();
5223 for pane in &self.panes {
5224 join_pane_into_active(&self.active_pane, pane, window, cx);
5225 }
5226 if let Some(active_item) = active_item {
5227 self.activate_item(active_item.as_ref(), true, true, window, cx);
5228 }
5229 cx.notify();
5230 }
5231
5232 pub fn join_pane_into_next(
5233 &mut self,
5234 pane: Entity<Pane>,
5235 window: &mut Window,
5236 cx: &mut Context<Self>,
5237 ) {
5238 let next_pane = self
5239 .find_pane_in_direction(SplitDirection::Right, cx)
5240 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5241 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5242 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5243 let Some(next_pane) = next_pane else {
5244 return;
5245 };
5246 move_all_items(&pane, &next_pane, window, cx);
5247 cx.notify();
5248 }
5249
5250 fn remove_pane(
5251 &mut self,
5252 pane: Entity<Pane>,
5253 focus_on: Option<Entity<Pane>>,
5254 window: &mut Window,
5255 cx: &mut Context<Self>,
5256 ) {
5257 if self.center.remove(&pane, cx).unwrap() {
5258 self.force_remove_pane(&pane, &focus_on, window, cx);
5259 self.unfollow_in_pane(&pane, window, cx);
5260 self.last_leaders_by_pane.remove(&pane.downgrade());
5261 for removed_item in pane.read(cx).items() {
5262 self.panes_by_item.remove(&removed_item.item_id());
5263 }
5264
5265 cx.notify();
5266 } else {
5267 self.active_item_path_changed(true, window, cx);
5268 }
5269 cx.emit(Event::PaneRemoved);
5270 }
5271
5272 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5273 &mut self.panes
5274 }
5275
5276 pub fn panes(&self) -> &[Entity<Pane>] {
5277 &self.panes
5278 }
5279
5280 pub fn active_pane(&self) -> &Entity<Pane> {
5281 &self.active_pane
5282 }
5283
5284 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5285 for dock in self.all_docks() {
5286 if dock.focus_handle(cx).contains_focused(window, cx)
5287 && let Some(pane) = dock
5288 .read(cx)
5289 .active_panel()
5290 .and_then(|panel| panel.pane(cx))
5291 {
5292 return pane;
5293 }
5294 }
5295 self.active_pane().clone()
5296 }
5297
5298 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5299 self.find_pane_in_direction(SplitDirection::Right, cx)
5300 .unwrap_or_else(|| {
5301 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5302 })
5303 }
5304
5305 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5306 self.pane_for_item_id(handle.item_id())
5307 }
5308
5309 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5310 let weak_pane = self.panes_by_item.get(&item_id)?;
5311 weak_pane.upgrade()
5312 }
5313
5314 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5315 self.panes
5316 .iter()
5317 .find(|pane| pane.entity_id() == entity_id)
5318 .cloned()
5319 }
5320
5321 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5322 self.follower_states.retain(|leader_id, state| {
5323 if *leader_id == CollaboratorId::PeerId(peer_id) {
5324 for item in state.items_by_leader_view_id.values() {
5325 item.view.set_leader_id(None, window, cx);
5326 }
5327 false
5328 } else {
5329 true
5330 }
5331 });
5332 cx.notify();
5333 }
5334
5335 pub fn start_following(
5336 &mut self,
5337 leader_id: impl Into<CollaboratorId>,
5338 window: &mut Window,
5339 cx: &mut Context<Self>,
5340 ) -> Option<Task<Result<()>>> {
5341 let leader_id = leader_id.into();
5342 let pane = self.active_pane().clone();
5343
5344 self.last_leaders_by_pane
5345 .insert(pane.downgrade(), leader_id);
5346 self.unfollow(leader_id, window, cx);
5347 self.unfollow_in_pane(&pane, window, cx);
5348 self.follower_states.insert(
5349 leader_id,
5350 FollowerState {
5351 center_pane: pane.clone(),
5352 dock_pane: None,
5353 active_view_id: None,
5354 items_by_leader_view_id: Default::default(),
5355 },
5356 );
5357 cx.notify();
5358
5359 match leader_id {
5360 CollaboratorId::PeerId(leader_peer_id) => {
5361 let room_id = self.active_call()?.room_id(cx)?;
5362 let project_id = self.project.read(cx).remote_id();
5363 let request = self.app_state.client.request(proto::Follow {
5364 room_id,
5365 project_id,
5366 leader_id: Some(leader_peer_id),
5367 });
5368
5369 Some(cx.spawn_in(window, async move |this, cx| {
5370 let response = request.await?;
5371 this.update(cx, |this, _| {
5372 let state = this
5373 .follower_states
5374 .get_mut(&leader_id)
5375 .context("following interrupted")?;
5376 state.active_view_id = response
5377 .active_view
5378 .as_ref()
5379 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5380 anyhow::Ok(())
5381 })??;
5382 if let Some(view) = response.active_view {
5383 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5384 }
5385 this.update_in(cx, |this, window, cx| {
5386 this.leader_updated(leader_id, window, cx)
5387 })?;
5388 Ok(())
5389 }))
5390 }
5391 CollaboratorId::Agent => {
5392 self.leader_updated(leader_id, window, cx)?;
5393 Some(Task::ready(Ok(())))
5394 }
5395 }
5396 }
5397
5398 pub fn follow_next_collaborator(
5399 &mut self,
5400 _: &FollowNextCollaborator,
5401 window: &mut Window,
5402 cx: &mut Context<Self>,
5403 ) {
5404 let collaborators = self.project.read(cx).collaborators();
5405 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5406 let mut collaborators = collaborators.keys().copied();
5407 for peer_id in collaborators.by_ref() {
5408 if CollaboratorId::PeerId(peer_id) == leader_id {
5409 break;
5410 }
5411 }
5412 collaborators.next().map(CollaboratorId::PeerId)
5413 } else if let Some(last_leader_id) =
5414 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5415 {
5416 match last_leader_id {
5417 CollaboratorId::PeerId(peer_id) => {
5418 if collaborators.contains_key(peer_id) {
5419 Some(*last_leader_id)
5420 } else {
5421 None
5422 }
5423 }
5424 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5425 }
5426 } else {
5427 None
5428 };
5429
5430 let pane = self.active_pane.clone();
5431 let Some(leader_id) = next_leader_id.or_else(|| {
5432 Some(CollaboratorId::PeerId(
5433 collaborators.keys().copied().next()?,
5434 ))
5435 }) else {
5436 return;
5437 };
5438 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5439 return;
5440 }
5441 if let Some(task) = self.start_following(leader_id, window, cx) {
5442 task.detach_and_log_err(cx)
5443 }
5444 }
5445
5446 pub fn follow(
5447 &mut self,
5448 leader_id: impl Into<CollaboratorId>,
5449 window: &mut Window,
5450 cx: &mut Context<Self>,
5451 ) {
5452 let leader_id = leader_id.into();
5453
5454 if let CollaboratorId::PeerId(peer_id) = leader_id {
5455 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5456 return;
5457 };
5458 let Some(remote_participant) =
5459 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5460 else {
5461 return;
5462 };
5463
5464 let project = self.project.read(cx);
5465
5466 let other_project_id = match remote_participant.location {
5467 ParticipantLocation::External => None,
5468 ParticipantLocation::UnsharedProject => None,
5469 ParticipantLocation::SharedProject { project_id } => {
5470 if Some(project_id) == project.remote_id() {
5471 None
5472 } else {
5473 Some(project_id)
5474 }
5475 }
5476 };
5477
5478 // if they are active in another project, follow there.
5479 if let Some(project_id) = other_project_id {
5480 let app_state = self.app_state.clone();
5481 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5482 .detach_and_log_err(cx);
5483 }
5484 }
5485
5486 // if you're already following, find the right pane and focus it.
5487 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5488 window.focus(&follower_state.pane().focus_handle(cx), cx);
5489
5490 return;
5491 }
5492
5493 // Otherwise, follow.
5494 if let Some(task) = self.start_following(leader_id, window, cx) {
5495 task.detach_and_log_err(cx)
5496 }
5497 }
5498
5499 pub fn unfollow(
5500 &mut self,
5501 leader_id: impl Into<CollaboratorId>,
5502 window: &mut Window,
5503 cx: &mut Context<Self>,
5504 ) -> Option<()> {
5505 cx.notify();
5506
5507 let leader_id = leader_id.into();
5508 let state = self.follower_states.remove(&leader_id)?;
5509 for (_, item) in state.items_by_leader_view_id {
5510 item.view.set_leader_id(None, window, cx);
5511 }
5512
5513 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5514 let project_id = self.project.read(cx).remote_id();
5515 let room_id = self.active_call()?.room_id(cx)?;
5516 self.app_state
5517 .client
5518 .send(proto::Unfollow {
5519 room_id,
5520 project_id,
5521 leader_id: Some(leader_peer_id),
5522 })
5523 .log_err();
5524 }
5525
5526 Some(())
5527 }
5528
5529 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5530 self.follower_states.contains_key(&id.into())
5531 }
5532
5533 fn active_item_path_changed(
5534 &mut self,
5535 focus_changed: bool,
5536 window: &mut Window,
5537 cx: &mut Context<Self>,
5538 ) {
5539 cx.emit(Event::ActiveItemChanged);
5540 let active_entry = self.active_project_path(cx);
5541 self.project.update(cx, |project, cx| {
5542 project.set_active_path(active_entry.clone(), cx)
5543 });
5544
5545 if focus_changed && let Some(project_path) = &active_entry {
5546 let git_store_entity = self.project.read(cx).git_store().clone();
5547 git_store_entity.update(cx, |git_store, cx| {
5548 git_store.set_active_repo_for_path(project_path, cx);
5549 });
5550 }
5551
5552 self.update_window_title(window, cx);
5553 }
5554
5555 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5556 let project = self.project().read(cx);
5557 let mut title = String::new();
5558
5559 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5560 let name = {
5561 let settings_location = SettingsLocation {
5562 worktree_id: worktree.read(cx).id(),
5563 path: RelPath::empty(),
5564 };
5565
5566 let settings = WorktreeSettings::get(Some(settings_location), cx);
5567 match &settings.project_name {
5568 Some(name) => name.as_str(),
5569 None => worktree.read(cx).root_name_str(),
5570 }
5571 };
5572 if i > 0 {
5573 title.push_str(", ");
5574 }
5575 title.push_str(name);
5576 }
5577
5578 if title.is_empty() {
5579 title = "empty project".to_string();
5580 }
5581
5582 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5583 let filename = path.path.file_name().or_else(|| {
5584 Some(
5585 project
5586 .worktree_for_id(path.worktree_id, cx)?
5587 .read(cx)
5588 .root_name_str(),
5589 )
5590 });
5591
5592 if let Some(filename) = filename {
5593 title.push_str(" — ");
5594 title.push_str(filename.as_ref());
5595 }
5596 }
5597
5598 if project.is_via_collab() {
5599 title.push_str(" ↙");
5600 } else if project.is_shared() {
5601 title.push_str(" ↗");
5602 }
5603
5604 if let Some(last_title) = self.last_window_title.as_ref()
5605 && &title == last_title
5606 {
5607 return;
5608 }
5609 window.set_window_title(&title);
5610 SystemWindowTabController::update_tab_title(
5611 cx,
5612 window.window_handle().window_id(),
5613 SharedString::from(&title),
5614 );
5615 self.last_window_title = Some(title);
5616 }
5617
5618 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5619 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5620 if is_edited != self.window_edited {
5621 self.window_edited = is_edited;
5622 window.set_window_edited(self.window_edited)
5623 }
5624 }
5625
5626 fn update_item_dirty_state(
5627 &mut self,
5628 item: &dyn ItemHandle,
5629 window: &mut Window,
5630 cx: &mut App,
5631 ) {
5632 let is_dirty = item.is_dirty(cx);
5633 let item_id = item.item_id();
5634 let was_dirty = self.dirty_items.contains_key(&item_id);
5635 if is_dirty == was_dirty {
5636 return;
5637 }
5638 if was_dirty {
5639 self.dirty_items.remove(&item_id);
5640 self.update_window_edited(window, cx);
5641 return;
5642 }
5643
5644 let workspace = self.weak_handle();
5645 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5646 return;
5647 };
5648 let on_release_callback = Box::new(move |cx: &mut App| {
5649 window_handle
5650 .update(cx, |_, window, cx| {
5651 workspace
5652 .update(cx, |workspace, cx| {
5653 workspace.dirty_items.remove(&item_id);
5654 workspace.update_window_edited(window, cx)
5655 })
5656 .ok();
5657 })
5658 .ok();
5659 });
5660
5661 let s = item.on_release(cx, on_release_callback);
5662 self.dirty_items.insert(item_id, s);
5663 self.update_window_edited(window, cx);
5664 }
5665
5666 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5667 if self.notifications.is_empty() {
5668 None
5669 } else {
5670 Some(
5671 div()
5672 .absolute()
5673 .right_3()
5674 .bottom_3()
5675 .w_112()
5676 .h_full()
5677 .flex()
5678 .flex_col()
5679 .justify_end()
5680 .gap_2()
5681 .children(
5682 self.notifications
5683 .iter()
5684 .map(|(_, notification)| notification.clone().into_any()),
5685 ),
5686 )
5687 }
5688 }
5689
5690 // RPC handlers
5691
5692 fn active_view_for_follower(
5693 &self,
5694 follower_project_id: Option<u64>,
5695 window: &mut Window,
5696 cx: &mut Context<Self>,
5697 ) -> Option<proto::View> {
5698 let (item, panel_id) = self.active_item_for_followers(window, cx);
5699 let item = item?;
5700 let leader_id = self
5701 .pane_for(&*item)
5702 .and_then(|pane| self.leader_for_pane(&pane));
5703 let leader_peer_id = match leader_id {
5704 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5705 Some(CollaboratorId::Agent) | None => None,
5706 };
5707
5708 let item_handle = item.to_followable_item_handle(cx)?;
5709 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5710 let variant = item_handle.to_state_proto(window, cx)?;
5711
5712 if item_handle.is_project_item(window, cx)
5713 && (follower_project_id.is_none()
5714 || follower_project_id != self.project.read(cx).remote_id())
5715 {
5716 return None;
5717 }
5718
5719 Some(proto::View {
5720 id: id.to_proto(),
5721 leader_id: leader_peer_id,
5722 variant: Some(variant),
5723 panel_id: panel_id.map(|id| id as i32),
5724 })
5725 }
5726
5727 fn handle_follow(
5728 &mut self,
5729 follower_project_id: Option<u64>,
5730 window: &mut Window,
5731 cx: &mut Context<Self>,
5732 ) -> proto::FollowResponse {
5733 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5734
5735 cx.notify();
5736 proto::FollowResponse {
5737 views: active_view.iter().cloned().collect(),
5738 active_view,
5739 }
5740 }
5741
5742 fn handle_update_followers(
5743 &mut self,
5744 leader_id: PeerId,
5745 message: proto::UpdateFollowers,
5746 _window: &mut Window,
5747 _cx: &mut Context<Self>,
5748 ) {
5749 self.leader_updates_tx
5750 .unbounded_send((leader_id, message))
5751 .ok();
5752 }
5753
5754 async fn process_leader_update(
5755 this: &WeakEntity<Self>,
5756 leader_id: PeerId,
5757 update: proto::UpdateFollowers,
5758 cx: &mut AsyncWindowContext,
5759 ) -> Result<()> {
5760 match update.variant.context("invalid update")? {
5761 proto::update_followers::Variant::CreateView(view) => {
5762 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5763 let should_add_view = this.update(cx, |this, _| {
5764 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5765 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5766 } else {
5767 anyhow::Ok(false)
5768 }
5769 })??;
5770
5771 if should_add_view {
5772 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5773 }
5774 }
5775 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5776 let should_add_view = this.update(cx, |this, _| {
5777 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5778 state.active_view_id = update_active_view
5779 .view
5780 .as_ref()
5781 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5782
5783 if state.active_view_id.is_some_and(|view_id| {
5784 !state.items_by_leader_view_id.contains_key(&view_id)
5785 }) {
5786 anyhow::Ok(true)
5787 } else {
5788 anyhow::Ok(false)
5789 }
5790 } else {
5791 anyhow::Ok(false)
5792 }
5793 })??;
5794
5795 if should_add_view && let Some(view) = update_active_view.view {
5796 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5797 }
5798 }
5799 proto::update_followers::Variant::UpdateView(update_view) => {
5800 let variant = update_view.variant.context("missing update view variant")?;
5801 let id = update_view.id.context("missing update view id")?;
5802 let mut tasks = Vec::new();
5803 this.update_in(cx, |this, window, cx| {
5804 let project = this.project.clone();
5805 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5806 let view_id = ViewId::from_proto(id.clone())?;
5807 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5808 tasks.push(item.view.apply_update_proto(
5809 &project,
5810 variant.clone(),
5811 window,
5812 cx,
5813 ));
5814 }
5815 }
5816 anyhow::Ok(())
5817 })??;
5818 try_join_all(tasks).await.log_err();
5819 }
5820 }
5821 this.update_in(cx, |this, window, cx| {
5822 this.leader_updated(leader_id, window, cx)
5823 })?;
5824 Ok(())
5825 }
5826
5827 async fn add_view_from_leader(
5828 this: WeakEntity<Self>,
5829 leader_id: PeerId,
5830 view: &proto::View,
5831 cx: &mut AsyncWindowContext,
5832 ) -> Result<()> {
5833 let this = this.upgrade().context("workspace dropped")?;
5834
5835 let Some(id) = view.id.clone() else {
5836 anyhow::bail!("no id for view");
5837 };
5838 let id = ViewId::from_proto(id)?;
5839 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5840
5841 let pane = this.update(cx, |this, _cx| {
5842 let state = this
5843 .follower_states
5844 .get(&leader_id.into())
5845 .context("stopped following")?;
5846 anyhow::Ok(state.pane().clone())
5847 })?;
5848 let existing_item = pane.update_in(cx, |pane, window, cx| {
5849 let client = this.read(cx).client().clone();
5850 pane.items().find_map(|item| {
5851 let item = item.to_followable_item_handle(cx)?;
5852 if item.remote_id(&client, window, cx) == Some(id) {
5853 Some(item)
5854 } else {
5855 None
5856 }
5857 })
5858 })?;
5859 let item = if let Some(existing_item) = existing_item {
5860 existing_item
5861 } else {
5862 let variant = view.variant.clone();
5863 anyhow::ensure!(variant.is_some(), "missing view variant");
5864
5865 let task = cx.update(|window, cx| {
5866 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5867 })?;
5868
5869 let Some(task) = task else {
5870 anyhow::bail!(
5871 "failed to construct view from leader (maybe from a different version of zed?)"
5872 );
5873 };
5874
5875 let mut new_item = task.await?;
5876 pane.update_in(cx, |pane, window, cx| {
5877 let mut item_to_remove = None;
5878 for (ix, item) in pane.items().enumerate() {
5879 if let Some(item) = item.to_followable_item_handle(cx) {
5880 match new_item.dedup(item.as_ref(), window, cx) {
5881 Some(item::Dedup::KeepExisting) => {
5882 new_item =
5883 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5884 break;
5885 }
5886 Some(item::Dedup::ReplaceExisting) => {
5887 item_to_remove = Some((ix, item.item_id()));
5888 break;
5889 }
5890 None => {}
5891 }
5892 }
5893 }
5894
5895 if let Some((ix, id)) = item_to_remove {
5896 pane.remove_item(id, false, false, window, cx);
5897 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5898 }
5899 })?;
5900
5901 new_item
5902 };
5903
5904 this.update_in(cx, |this, window, cx| {
5905 let state = this.follower_states.get_mut(&leader_id.into())?;
5906 item.set_leader_id(Some(leader_id.into()), window, cx);
5907 state.items_by_leader_view_id.insert(
5908 id,
5909 FollowerView {
5910 view: item,
5911 location: panel_id,
5912 },
5913 );
5914
5915 Some(())
5916 })
5917 .context("no follower state")?;
5918
5919 Ok(())
5920 }
5921
5922 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5923 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5924 return;
5925 };
5926
5927 if let Some(agent_location) = self.project.read(cx).agent_location() {
5928 let buffer_entity_id = agent_location.buffer.entity_id();
5929 let view_id = ViewId {
5930 creator: CollaboratorId::Agent,
5931 id: buffer_entity_id.as_u64(),
5932 };
5933 follower_state.active_view_id = Some(view_id);
5934
5935 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5936 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5937 hash_map::Entry::Vacant(entry) => {
5938 let existing_view =
5939 follower_state
5940 .center_pane
5941 .read(cx)
5942 .items()
5943 .find_map(|item| {
5944 let item = item.to_followable_item_handle(cx)?;
5945 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5946 && item.project_item_model_ids(cx).as_slice()
5947 == [buffer_entity_id]
5948 {
5949 Some(item)
5950 } else {
5951 None
5952 }
5953 });
5954 let view = existing_view.or_else(|| {
5955 agent_location.buffer.upgrade().and_then(|buffer| {
5956 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5957 registry.build_item(buffer, self.project.clone(), None, window, cx)
5958 })?
5959 .to_followable_item_handle(cx)
5960 })
5961 });
5962
5963 view.map(|view| {
5964 entry.insert(FollowerView {
5965 view,
5966 location: None,
5967 })
5968 })
5969 }
5970 };
5971
5972 if let Some(item) = item {
5973 item.view
5974 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5975 item.view
5976 .update_agent_location(agent_location.position, window, cx);
5977 }
5978 } else {
5979 follower_state.active_view_id = None;
5980 }
5981
5982 self.leader_updated(CollaboratorId::Agent, window, cx);
5983 }
5984
5985 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5986 let mut is_project_item = true;
5987 let mut update = proto::UpdateActiveView::default();
5988 if window.is_window_active() {
5989 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5990
5991 if let Some(item) = active_item
5992 && item.item_focus_handle(cx).contains_focused(window, cx)
5993 {
5994 let leader_id = self
5995 .pane_for(&*item)
5996 .and_then(|pane| self.leader_for_pane(&pane));
5997 let leader_peer_id = match leader_id {
5998 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5999 Some(CollaboratorId::Agent) | None => None,
6000 };
6001
6002 if let Some(item) = item.to_followable_item_handle(cx) {
6003 let id = item
6004 .remote_id(&self.app_state.client, window, cx)
6005 .map(|id| id.to_proto());
6006
6007 if let Some(id) = id
6008 && let Some(variant) = item.to_state_proto(window, cx)
6009 {
6010 let view = Some(proto::View {
6011 id,
6012 leader_id: leader_peer_id,
6013 variant: Some(variant),
6014 panel_id: panel_id.map(|id| id as i32),
6015 });
6016
6017 is_project_item = item.is_project_item(window, cx);
6018 update = proto::UpdateActiveView { view };
6019 };
6020 }
6021 }
6022 }
6023
6024 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
6025 if active_view_id != self.last_active_view_id.as_ref() {
6026 self.last_active_view_id = active_view_id.cloned();
6027 self.update_followers(
6028 is_project_item,
6029 proto::update_followers::Variant::UpdateActiveView(update),
6030 window,
6031 cx,
6032 );
6033 }
6034 }
6035
6036 fn active_item_for_followers(
6037 &self,
6038 window: &mut Window,
6039 cx: &mut App,
6040 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
6041 let mut active_item = None;
6042 let mut panel_id = None;
6043 for dock in self.all_docks() {
6044 if dock.focus_handle(cx).contains_focused(window, cx)
6045 && let Some(panel) = dock.read(cx).active_panel()
6046 && let Some(pane) = panel.pane(cx)
6047 && let Some(item) = pane.read(cx).active_item()
6048 {
6049 active_item = Some(item);
6050 panel_id = panel.remote_id();
6051 break;
6052 }
6053 }
6054
6055 if active_item.is_none() {
6056 active_item = self.active_pane().read(cx).active_item();
6057 }
6058 (active_item, panel_id)
6059 }
6060
6061 fn update_followers(
6062 &self,
6063 project_only: bool,
6064 update: proto::update_followers::Variant,
6065 _: &mut Window,
6066 cx: &mut App,
6067 ) -> Option<()> {
6068 // If this update only applies to for followers in the current project,
6069 // then skip it unless this project is shared. If it applies to all
6070 // followers, regardless of project, then set `project_id` to none,
6071 // indicating that it goes to all followers.
6072 let project_id = if project_only {
6073 Some(self.project.read(cx).remote_id()?)
6074 } else {
6075 None
6076 };
6077 self.app_state().workspace_store.update(cx, |store, cx| {
6078 store.update_followers(project_id, update, cx)
6079 })
6080 }
6081
6082 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
6083 self.follower_states.iter().find_map(|(leader_id, state)| {
6084 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
6085 Some(*leader_id)
6086 } else {
6087 None
6088 }
6089 })
6090 }
6091
6092 fn leader_updated(
6093 &mut self,
6094 leader_id: impl Into<CollaboratorId>,
6095 window: &mut Window,
6096 cx: &mut Context<Self>,
6097 ) -> Option<Box<dyn ItemHandle>> {
6098 cx.notify();
6099
6100 let leader_id = leader_id.into();
6101 let (panel_id, item) = match leader_id {
6102 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
6103 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
6104 };
6105
6106 let state = self.follower_states.get(&leader_id)?;
6107 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
6108 let pane;
6109 if let Some(panel_id) = panel_id {
6110 pane = self
6111 .activate_panel_for_proto_id(panel_id, window, cx)?
6112 .pane(cx)?;
6113 let state = self.follower_states.get_mut(&leader_id)?;
6114 state.dock_pane = Some(pane.clone());
6115 } else {
6116 pane = state.center_pane.clone();
6117 let state = self.follower_states.get_mut(&leader_id)?;
6118 if let Some(dock_pane) = state.dock_pane.take() {
6119 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
6120 }
6121 }
6122
6123 pane.update(cx, |pane, cx| {
6124 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
6125 if let Some(index) = pane.index_for_item(item.as_ref()) {
6126 pane.activate_item(index, false, false, window, cx);
6127 } else {
6128 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
6129 }
6130
6131 if focus_active_item {
6132 pane.focus_active_item(window, cx)
6133 }
6134 });
6135
6136 Some(item)
6137 }
6138
6139 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
6140 let state = self.follower_states.get(&CollaboratorId::Agent)?;
6141 let active_view_id = state.active_view_id?;
6142 Some(
6143 state
6144 .items_by_leader_view_id
6145 .get(&active_view_id)?
6146 .view
6147 .boxed_clone(),
6148 )
6149 }
6150
6151 fn active_item_for_peer(
6152 &self,
6153 peer_id: PeerId,
6154 window: &mut Window,
6155 cx: &mut Context<Self>,
6156 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
6157 let call = self.active_call()?;
6158 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
6159 let leader_in_this_app;
6160 let leader_in_this_project;
6161 match participant.location {
6162 ParticipantLocation::SharedProject { project_id } => {
6163 leader_in_this_app = true;
6164 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
6165 }
6166 ParticipantLocation::UnsharedProject => {
6167 leader_in_this_app = true;
6168 leader_in_this_project = false;
6169 }
6170 ParticipantLocation::External => {
6171 leader_in_this_app = false;
6172 leader_in_this_project = false;
6173 }
6174 };
6175 let state = self.follower_states.get(&peer_id.into())?;
6176 let mut item_to_activate = None;
6177 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
6178 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
6179 && (leader_in_this_project || !item.view.is_project_item(window, cx))
6180 {
6181 item_to_activate = Some((item.location, item.view.boxed_clone()));
6182 }
6183 } else if let Some(shared_screen) =
6184 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
6185 {
6186 item_to_activate = Some((None, Box::new(shared_screen)));
6187 }
6188 item_to_activate
6189 }
6190
6191 fn shared_screen_for_peer(
6192 &self,
6193 peer_id: PeerId,
6194 pane: &Entity<Pane>,
6195 window: &mut Window,
6196 cx: &mut App,
6197 ) -> Option<Entity<SharedScreen>> {
6198 self.active_call()?
6199 .create_shared_screen(peer_id, pane, window, cx)
6200 }
6201
6202 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6203 if window.is_window_active() {
6204 self.update_active_view_for_followers(window, cx);
6205
6206 if let Some(database_id) = self.database_id {
6207 let db = WorkspaceDb::global(cx);
6208 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6209 .detach();
6210 }
6211 } else {
6212 for pane in &self.panes {
6213 pane.update(cx, |pane, cx| {
6214 if let Some(item) = pane.active_item() {
6215 item.workspace_deactivated(window, cx);
6216 }
6217 for item in pane.items() {
6218 if matches!(
6219 item.workspace_settings(cx).autosave,
6220 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6221 ) {
6222 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6223 .detach_and_log_err(cx);
6224 }
6225 }
6226 });
6227 }
6228 }
6229 }
6230
6231 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6232 self.active_call.as_ref().map(|(call, _)| &*call.0)
6233 }
6234
6235 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6236 self.active_call.as_ref().map(|(call, _)| call.clone())
6237 }
6238
6239 fn on_active_call_event(
6240 &mut self,
6241 event: &ActiveCallEvent,
6242 window: &mut Window,
6243 cx: &mut Context<Self>,
6244 ) {
6245 match event {
6246 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6247 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6248 self.leader_updated(participant_id, window, cx);
6249 }
6250 }
6251 }
6252
6253 pub fn database_id(&self) -> Option<WorkspaceId> {
6254 self.database_id
6255 }
6256
6257 #[cfg(any(test, feature = "test-support"))]
6258 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6259 self.database_id = Some(id);
6260 }
6261
6262 pub fn session_id(&self) -> Option<String> {
6263 self.session_id.clone()
6264 }
6265
6266 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6267 let Some(display) = window.display(cx) else {
6268 return Task::ready(());
6269 };
6270 let Ok(display_uuid) = display.uuid() else {
6271 return Task::ready(());
6272 };
6273
6274 let window_bounds = window.inner_window_bounds();
6275 let database_id = self.database_id;
6276 let has_paths = !self.root_paths(cx).is_empty();
6277 let db = WorkspaceDb::global(cx);
6278 let kvp = db::kvp::KeyValueStore::global(cx);
6279
6280 cx.background_executor().spawn(async move {
6281 if !has_paths {
6282 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6283 .await
6284 .log_err();
6285 }
6286 if let Some(database_id) = database_id {
6287 db.set_window_open_status(
6288 database_id,
6289 SerializedWindowBounds(window_bounds),
6290 display_uuid,
6291 )
6292 .await
6293 .log_err();
6294 } else {
6295 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6296 .await
6297 .log_err();
6298 }
6299 })
6300 }
6301
6302 /// Bypass the 200ms serialization throttle and write workspace state to
6303 /// the DB immediately. Returns a task the caller can await to ensure the
6304 /// write completes. Used by the quit handler so the most recent state
6305 /// isn't lost to a pending throttle timer when the process exits.
6306 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6307 self._schedule_serialize_workspace.take();
6308 self._serialize_workspace_task.take();
6309 self.bounds_save_task_queued.take();
6310
6311 let bounds_task = self.save_window_bounds(window, cx);
6312 let serialize_task = self.serialize_workspace_internal(window, cx);
6313 cx.spawn(async move |_| {
6314 bounds_task.await;
6315 serialize_task.await;
6316 })
6317 }
6318
6319 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6320 let project = self.project().read(cx);
6321 project
6322 .visible_worktrees(cx)
6323 .map(|worktree| worktree.read(cx).abs_path())
6324 .collect::<Vec<_>>()
6325 }
6326
6327 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6328 match member {
6329 Member::Axis(PaneAxis { members, .. }) => {
6330 for child in members.iter() {
6331 self.remove_panes(child.clone(), window, cx)
6332 }
6333 }
6334 Member::Pane(pane) => {
6335 self.force_remove_pane(&pane, &None, window, cx);
6336 }
6337 }
6338 }
6339
6340 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6341 self.session_id.take();
6342 self.serialize_workspace_internal(window, cx)
6343 }
6344
6345 fn force_remove_pane(
6346 &mut self,
6347 pane: &Entity<Pane>,
6348 focus_on: &Option<Entity<Pane>>,
6349 window: &mut Window,
6350 cx: &mut Context<Workspace>,
6351 ) {
6352 self.panes.retain(|p| p != pane);
6353 if let Some(focus_on) = focus_on {
6354 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6355 } else if self.active_pane() == pane {
6356 self.panes
6357 .last()
6358 .unwrap()
6359 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6360 }
6361 if self.last_active_center_pane == Some(pane.downgrade()) {
6362 self.last_active_center_pane = None;
6363 }
6364 cx.notify();
6365 }
6366
6367 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6368 if self._schedule_serialize_workspace.is_none() {
6369 self._schedule_serialize_workspace =
6370 Some(cx.spawn_in(window, async move |this, cx| {
6371 cx.background_executor()
6372 .timer(SERIALIZATION_THROTTLE_TIME)
6373 .await;
6374 this.update_in(cx, |this, window, cx| {
6375 this._serialize_workspace_task =
6376 Some(this.serialize_workspace_internal(window, cx));
6377 this._schedule_serialize_workspace.take();
6378 })
6379 .log_err();
6380 }));
6381 }
6382 }
6383
6384 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6385 let Some(database_id) = self.database_id() else {
6386 return Task::ready(());
6387 };
6388
6389 fn serialize_pane_handle(
6390 pane_handle: &Entity<Pane>,
6391 window: &mut Window,
6392 cx: &mut App,
6393 ) -> SerializedPane {
6394 let (items, active, pinned_count) = {
6395 let pane = pane_handle.read(cx);
6396 let active_item_id = pane.active_item().map(|item| item.item_id());
6397 (
6398 pane.items()
6399 .filter_map(|handle| {
6400 let handle = handle.to_serializable_item_handle(cx)?;
6401
6402 Some(SerializedItem {
6403 kind: Arc::from(handle.serialized_item_kind()),
6404 item_id: handle.item_id().as_u64(),
6405 active: Some(handle.item_id()) == active_item_id,
6406 preview: pane.is_active_preview_item(handle.item_id()),
6407 })
6408 })
6409 .collect::<Vec<_>>(),
6410 pane.has_focus(window, cx),
6411 pane.pinned_count(),
6412 )
6413 };
6414
6415 SerializedPane::new(items, active, pinned_count)
6416 }
6417
6418 fn build_serialized_pane_group(
6419 pane_group: &Member,
6420 window: &mut Window,
6421 cx: &mut App,
6422 ) -> SerializedPaneGroup {
6423 match pane_group {
6424 Member::Axis(PaneAxis {
6425 axis,
6426 members,
6427 flexes,
6428 bounding_boxes: _,
6429 }) => SerializedPaneGroup::Group {
6430 axis: SerializedAxis(*axis),
6431 children: members
6432 .iter()
6433 .map(|member| build_serialized_pane_group(member, window, cx))
6434 .collect::<Vec<_>>(),
6435 flexes: Some(flexes.lock().clone()),
6436 },
6437 Member::Pane(pane_handle) => {
6438 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6439 }
6440 }
6441 }
6442
6443 fn build_serialized_docks(
6444 this: &Workspace,
6445 window: &mut Window,
6446 cx: &mut App,
6447 ) -> DockStructure {
6448 this.capture_dock_state(window, cx)
6449 }
6450
6451 match self.workspace_location(cx) {
6452 WorkspaceLocation::Location(location, paths) => {
6453 let breakpoints = self.project.update(cx, |project, cx| {
6454 project
6455 .breakpoint_store()
6456 .read(cx)
6457 .all_source_breakpoints(cx)
6458 });
6459 let user_toolchains = self
6460 .project
6461 .read(cx)
6462 .user_toolchains(cx)
6463 .unwrap_or_default();
6464
6465 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6466 let docks = build_serialized_docks(self, window, cx);
6467 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6468
6469 let serialized_workspace = SerializedWorkspace {
6470 id: database_id,
6471 location,
6472 paths,
6473 center_group,
6474 window_bounds,
6475 display: Default::default(),
6476 docks,
6477 centered_layout: self.centered_layout,
6478 session_id: self.session_id.clone(),
6479 breakpoints,
6480 window_id: Some(window.window_handle().window_id().as_u64()),
6481 user_toolchains,
6482 };
6483
6484 let db = WorkspaceDb::global(cx);
6485 window.spawn(cx, async move |_| {
6486 db.save_workspace(serialized_workspace).await;
6487 })
6488 }
6489 WorkspaceLocation::DetachFromSession => {
6490 let window_bounds = SerializedWindowBounds(window.window_bounds());
6491 let display = window.display(cx).and_then(|d| d.uuid().ok());
6492 // Save dock state for empty local workspaces
6493 let docks = build_serialized_docks(self, window, cx);
6494 let db = WorkspaceDb::global(cx);
6495 let kvp = db::kvp::KeyValueStore::global(cx);
6496 window.spawn(cx, async move |_| {
6497 db.set_window_open_status(
6498 database_id,
6499 window_bounds,
6500 display.unwrap_or_default(),
6501 )
6502 .await
6503 .log_err();
6504 db.set_session_id(database_id, None).await.log_err();
6505 persistence::write_default_dock_state(&kvp, docks)
6506 .await
6507 .log_err();
6508 })
6509 }
6510 WorkspaceLocation::None => {
6511 // Save dock state for empty non-local workspaces
6512 let docks = build_serialized_docks(self, window, cx);
6513 let kvp = db::kvp::KeyValueStore::global(cx);
6514 window.spawn(cx, async move |_| {
6515 persistence::write_default_dock_state(&kvp, docks)
6516 .await
6517 .log_err();
6518 })
6519 }
6520 }
6521 }
6522
6523 fn has_any_items_open(&self, cx: &App) -> bool {
6524 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6525 }
6526
6527 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6528 let paths = PathList::new(&self.root_paths(cx));
6529 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6530 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6531 } else if self.project.read(cx).is_local() {
6532 if !paths.is_empty() || self.has_any_items_open(cx) {
6533 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6534 } else {
6535 WorkspaceLocation::DetachFromSession
6536 }
6537 } else {
6538 WorkspaceLocation::None
6539 }
6540 }
6541
6542 fn update_history(&self, cx: &mut App) {
6543 let Some(id) = self.database_id() else {
6544 return;
6545 };
6546 if !self.project.read(cx).is_local() {
6547 return;
6548 }
6549 if let Some(manager) = HistoryManager::global(cx) {
6550 let paths = PathList::new(&self.root_paths(cx));
6551 manager.update(cx, |this, cx| {
6552 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6553 });
6554 }
6555 }
6556
6557 async fn serialize_items(
6558 this: &WeakEntity<Self>,
6559 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6560 cx: &mut AsyncWindowContext,
6561 ) -> Result<()> {
6562 const CHUNK_SIZE: usize = 200;
6563
6564 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6565
6566 while let Some(items_received) = serializable_items.next().await {
6567 let unique_items =
6568 items_received
6569 .into_iter()
6570 .fold(HashMap::default(), |mut acc, item| {
6571 acc.entry(item.item_id()).or_insert(item);
6572 acc
6573 });
6574
6575 // We use into_iter() here so that the references to the items are moved into
6576 // the tasks and not kept alive while we're sleeping.
6577 for (_, item) in unique_items.into_iter() {
6578 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6579 item.serialize(workspace, false, window, cx)
6580 }) {
6581 cx.background_spawn(async move { task.await.log_err() })
6582 .detach();
6583 }
6584 }
6585
6586 cx.background_executor()
6587 .timer(SERIALIZATION_THROTTLE_TIME)
6588 .await;
6589 }
6590
6591 Ok(())
6592 }
6593
6594 pub(crate) fn enqueue_item_serialization(
6595 &mut self,
6596 item: Box<dyn SerializableItemHandle>,
6597 ) -> Result<()> {
6598 self.serializable_items_tx
6599 .unbounded_send(item)
6600 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6601 }
6602
6603 pub(crate) fn load_workspace(
6604 serialized_workspace: SerializedWorkspace,
6605 paths_to_open: Vec<Option<ProjectPath>>,
6606 window: &mut Window,
6607 cx: &mut Context<Workspace>,
6608 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6609 cx.spawn_in(window, async move |workspace, cx| {
6610 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6611
6612 let mut center_group = None;
6613 let mut center_items = None;
6614
6615 // Traverse the splits tree and add to things
6616 if let Some((group, active_pane, items)) = serialized_workspace
6617 .center_group
6618 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6619 .await
6620 {
6621 center_items = Some(items);
6622 center_group = Some((group, active_pane))
6623 }
6624
6625 let mut items_by_project_path = HashMap::default();
6626 let mut item_ids_by_kind = HashMap::default();
6627 let mut all_deserialized_items = Vec::default();
6628 cx.update(|_, cx| {
6629 for item in center_items.unwrap_or_default().into_iter().flatten() {
6630 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6631 item_ids_by_kind
6632 .entry(serializable_item_handle.serialized_item_kind())
6633 .or_insert(Vec::new())
6634 .push(item.item_id().as_u64() as ItemId);
6635 }
6636
6637 if let Some(project_path) = item.project_path(cx) {
6638 items_by_project_path.insert(project_path, item.clone());
6639 }
6640 all_deserialized_items.push(item);
6641 }
6642 })?;
6643
6644 let opened_items = paths_to_open
6645 .into_iter()
6646 .map(|path_to_open| {
6647 path_to_open
6648 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6649 })
6650 .collect::<Vec<_>>();
6651
6652 // Remove old panes from workspace panes list
6653 workspace.update_in(cx, |workspace, window, cx| {
6654 if let Some((center_group, active_pane)) = center_group {
6655 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6656
6657 // Swap workspace center group
6658 workspace.center = PaneGroup::with_root(center_group);
6659 workspace.center.set_is_center(true);
6660 workspace.center.mark_positions(cx);
6661
6662 if let Some(active_pane) = active_pane {
6663 workspace.set_active_pane(&active_pane, window, cx);
6664 cx.focus_self(window);
6665 } else {
6666 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6667 }
6668 }
6669
6670 let docks = serialized_workspace.docks;
6671
6672 for (dock, serialized_dock) in [
6673 (&mut workspace.right_dock, docks.right),
6674 (&mut workspace.left_dock, docks.left),
6675 (&mut workspace.bottom_dock, docks.bottom),
6676 ]
6677 .iter_mut()
6678 {
6679 dock.update(cx, |dock, cx| {
6680 dock.serialized_dock = Some(serialized_dock.clone());
6681 dock.restore_state(window, cx);
6682 });
6683 }
6684
6685 cx.notify();
6686 })?;
6687
6688 let _ = project
6689 .update(cx, |project, cx| {
6690 project
6691 .breakpoint_store()
6692 .update(cx, |breakpoint_store, cx| {
6693 breakpoint_store
6694 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6695 })
6696 })
6697 .await;
6698
6699 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6700 // after loading the items, we might have different items and in order to avoid
6701 // the database filling up, we delete items that haven't been loaded now.
6702 //
6703 // The items that have been loaded, have been saved after they've been added to the workspace.
6704 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6705 item_ids_by_kind
6706 .into_iter()
6707 .map(|(item_kind, loaded_items)| {
6708 SerializableItemRegistry::cleanup(
6709 item_kind,
6710 serialized_workspace.id,
6711 loaded_items,
6712 window,
6713 cx,
6714 )
6715 .log_err()
6716 })
6717 .collect::<Vec<_>>()
6718 })?;
6719
6720 futures::future::join_all(clean_up_tasks).await;
6721
6722 workspace
6723 .update_in(cx, |workspace, window, cx| {
6724 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6725 workspace.serialize_workspace_internal(window, cx).detach();
6726
6727 // Ensure that we mark the window as edited if we did load dirty items
6728 workspace.update_window_edited(window, cx);
6729 })
6730 .ok();
6731
6732 Ok(opened_items)
6733 })
6734 }
6735
6736 pub fn key_context(&self, cx: &App) -> KeyContext {
6737 let mut context = KeyContext::new_with_defaults();
6738 context.add("Workspace");
6739 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6740 if let Some(status) = self
6741 .debugger_provider
6742 .as_ref()
6743 .and_then(|provider| provider.active_thread_state(cx))
6744 {
6745 match status {
6746 ThreadStatus::Running | ThreadStatus::Stepping => {
6747 context.add("debugger_running");
6748 }
6749 ThreadStatus::Stopped => context.add("debugger_stopped"),
6750 ThreadStatus::Exited | ThreadStatus::Ended => {}
6751 }
6752 }
6753
6754 if self.left_dock.read(cx).is_open() {
6755 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6756 context.set("left_dock", active_panel.panel_key());
6757 }
6758 }
6759
6760 if self.right_dock.read(cx).is_open() {
6761 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6762 context.set("right_dock", active_panel.panel_key());
6763 }
6764 }
6765
6766 if self.bottom_dock.read(cx).is_open() {
6767 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6768 context.set("bottom_dock", active_panel.panel_key());
6769 }
6770 }
6771
6772 context
6773 }
6774
6775 /// Multiworkspace uses this to add workspace action handling to itself
6776 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6777 self.add_workspace_actions_listeners(div, window, cx)
6778 .on_action(cx.listener(
6779 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6780 for action in &action_sequence.0 {
6781 window.dispatch_action(action.boxed_clone(), cx);
6782 }
6783 },
6784 ))
6785 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6786 .on_action(cx.listener(Self::close_all_items_and_panes))
6787 .on_action(cx.listener(Self::close_item_in_all_panes))
6788 .on_action(cx.listener(Self::save_all))
6789 .on_action(cx.listener(Self::send_keystrokes))
6790 .on_action(cx.listener(Self::add_folder_to_project))
6791 .on_action(cx.listener(Self::follow_next_collaborator))
6792 .on_action(cx.listener(Self::activate_pane_at_index))
6793 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6794 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6795 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6796 .on_action(cx.listener(Self::toggle_theme_mode))
6797 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6798 let pane = workspace.active_pane().clone();
6799 workspace.unfollow_in_pane(&pane, window, cx);
6800 }))
6801 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6802 workspace
6803 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6804 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6805 }))
6806 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6807 workspace
6808 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6809 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6810 }))
6811 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6812 workspace
6813 .save_active_item(SaveIntent::SaveAs, window, cx)
6814 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6815 }))
6816 .on_action(
6817 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6818 workspace.activate_previous_pane(window, cx)
6819 }),
6820 )
6821 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6822 workspace.activate_next_pane(window, cx)
6823 }))
6824 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6825 workspace.activate_last_pane(window, cx)
6826 }))
6827 .on_action(
6828 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6829 workspace.activate_next_window(cx)
6830 }),
6831 )
6832 .on_action(
6833 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6834 workspace.activate_previous_window(cx)
6835 }),
6836 )
6837 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6838 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6839 }))
6840 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6841 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6842 }))
6843 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6844 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6845 }))
6846 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6847 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6848 }))
6849 .on_action(cx.listener(
6850 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6851 workspace.move_item_to_pane_in_direction(action, window, cx)
6852 },
6853 ))
6854 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6855 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6856 }))
6857 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6858 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6859 }))
6860 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6861 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6862 }))
6863 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6864 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6865 }))
6866 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6867 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6868 SplitDirection::Down,
6869 SplitDirection::Up,
6870 SplitDirection::Right,
6871 SplitDirection::Left,
6872 ];
6873 for dir in DIRECTION_PRIORITY {
6874 if workspace.find_pane_in_direction(dir, cx).is_some() {
6875 workspace.swap_pane_in_direction(dir, cx);
6876 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6877 break;
6878 }
6879 }
6880 }))
6881 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6882 workspace.move_pane_to_border(SplitDirection::Left, cx)
6883 }))
6884 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6885 workspace.move_pane_to_border(SplitDirection::Right, cx)
6886 }))
6887 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6888 workspace.move_pane_to_border(SplitDirection::Up, cx)
6889 }))
6890 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6891 workspace.move_pane_to_border(SplitDirection::Down, cx)
6892 }))
6893 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6894 this.toggle_dock(DockPosition::Left, window, cx);
6895 }))
6896 .on_action(cx.listener(
6897 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6898 workspace.toggle_dock(DockPosition::Right, window, cx);
6899 },
6900 ))
6901 .on_action(cx.listener(
6902 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6903 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6904 },
6905 ))
6906 .on_action(cx.listener(
6907 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6908 if !workspace.close_active_dock(window, cx) {
6909 cx.propagate();
6910 }
6911 },
6912 ))
6913 .on_action(
6914 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6915 workspace.close_all_docks(window, cx);
6916 }),
6917 )
6918 .on_action(cx.listener(Self::toggle_all_docks))
6919 .on_action(cx.listener(
6920 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6921 workspace.clear_all_notifications(cx);
6922 },
6923 ))
6924 .on_action(cx.listener(
6925 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6926 workspace.clear_navigation_history(window, cx);
6927 },
6928 ))
6929 .on_action(cx.listener(
6930 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6931 if let Some((notification_id, _)) = workspace.notifications.pop() {
6932 workspace.suppress_notification(¬ification_id, cx);
6933 }
6934 },
6935 ))
6936 .on_action(cx.listener(
6937 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6938 workspace.show_worktree_trust_security_modal(true, window, cx);
6939 },
6940 ))
6941 .on_action(
6942 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6943 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6944 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6945 trusted_worktrees.clear_trusted_paths()
6946 });
6947 let db = WorkspaceDb::global(cx);
6948 cx.spawn(async move |_, cx| {
6949 if db.clear_trusted_worktrees().await.log_err().is_some() {
6950 cx.update(|cx| reload(cx));
6951 }
6952 })
6953 .detach();
6954 }
6955 }),
6956 )
6957 .on_action(cx.listener(
6958 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6959 workspace.reopen_closed_item(window, cx).detach();
6960 },
6961 ))
6962 .on_action(cx.listener(
6963 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6964 for dock in workspace.all_docks() {
6965 if dock.focus_handle(cx).contains_focused(window, cx) {
6966 let panel = dock.read(cx).active_panel().cloned();
6967 if let Some(panel) = panel {
6968 dock.update(cx, |dock, cx| {
6969 dock.set_panel_size_state(
6970 panel.as_ref(),
6971 dock::PanelSizeState::default(),
6972 cx,
6973 );
6974 });
6975 }
6976 return;
6977 }
6978 }
6979 },
6980 ))
6981 .on_action(cx.listener(
6982 |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
6983 for dock in workspace.all_docks() {
6984 let panel = dock.read(cx).visible_panel().cloned();
6985 if let Some(panel) = panel {
6986 dock.update(cx, |dock, cx| {
6987 dock.set_panel_size_state(
6988 panel.as_ref(),
6989 dock::PanelSizeState::default(),
6990 cx,
6991 );
6992 });
6993 }
6994 }
6995 },
6996 ))
6997 .on_action(cx.listener(
6998 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6999 adjust_active_dock_size_by_px(
7000 px_with_ui_font_fallback(act.px, cx),
7001 workspace,
7002 window,
7003 cx,
7004 );
7005 },
7006 ))
7007 .on_action(cx.listener(
7008 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
7009 adjust_active_dock_size_by_px(
7010 px_with_ui_font_fallback(act.px, cx) * -1.,
7011 workspace,
7012 window,
7013 cx,
7014 );
7015 },
7016 ))
7017 .on_action(cx.listener(
7018 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
7019 adjust_open_docks_size_by_px(
7020 px_with_ui_font_fallback(act.px, cx),
7021 workspace,
7022 window,
7023 cx,
7024 );
7025 },
7026 ))
7027 .on_action(cx.listener(
7028 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
7029 adjust_open_docks_size_by_px(
7030 px_with_ui_font_fallback(act.px, cx) * -1.,
7031 workspace,
7032 window,
7033 cx,
7034 );
7035 },
7036 ))
7037 .on_action(cx.listener(Workspace::toggle_centered_layout))
7038 .on_action(cx.listener(
7039 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
7040 if let Some(active_dock) = workspace.active_dock(window, cx) {
7041 let dock = active_dock.read(cx);
7042 if let Some(active_panel) = dock.active_panel() {
7043 if active_panel.pane(cx).is_none() {
7044 let mut recent_pane: Option<Entity<Pane>> = None;
7045 let mut recent_timestamp = 0;
7046 for pane_handle in workspace.panes() {
7047 let pane = pane_handle.read(cx);
7048 for entry in pane.activation_history() {
7049 if entry.timestamp > recent_timestamp {
7050 recent_timestamp = entry.timestamp;
7051 recent_pane = Some(pane_handle.clone());
7052 }
7053 }
7054 }
7055
7056 if let Some(pane) = recent_pane {
7057 pane.update(cx, |pane, cx| {
7058 let current_index = pane.active_item_index();
7059 let items_len = pane.items_len();
7060 if items_len > 0 {
7061 let next_index = if current_index + 1 < items_len {
7062 current_index + 1
7063 } else {
7064 0
7065 };
7066 pane.activate_item(
7067 next_index, false, false, window, cx,
7068 );
7069 }
7070 });
7071 return;
7072 }
7073 }
7074 }
7075 }
7076 cx.propagate();
7077 },
7078 ))
7079 .on_action(cx.listener(
7080 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
7081 if let Some(active_dock) = workspace.active_dock(window, cx) {
7082 let dock = active_dock.read(cx);
7083 if let Some(active_panel) = dock.active_panel() {
7084 if active_panel.pane(cx).is_none() {
7085 let mut recent_pane: Option<Entity<Pane>> = None;
7086 let mut recent_timestamp = 0;
7087 for pane_handle in workspace.panes() {
7088 let pane = pane_handle.read(cx);
7089 for entry in pane.activation_history() {
7090 if entry.timestamp > recent_timestamp {
7091 recent_timestamp = entry.timestamp;
7092 recent_pane = Some(pane_handle.clone());
7093 }
7094 }
7095 }
7096
7097 if let Some(pane) = recent_pane {
7098 pane.update(cx, |pane, cx| {
7099 let current_index = pane.active_item_index();
7100 let items_len = pane.items_len();
7101 if items_len > 0 {
7102 let prev_index = if current_index > 0 {
7103 current_index - 1
7104 } else {
7105 items_len.saturating_sub(1)
7106 };
7107 pane.activate_item(
7108 prev_index, false, false, window, cx,
7109 );
7110 }
7111 });
7112 return;
7113 }
7114 }
7115 }
7116 }
7117 cx.propagate();
7118 },
7119 ))
7120 .on_action(cx.listener(
7121 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
7122 if let Some(active_dock) = workspace.active_dock(window, cx) {
7123 let dock = active_dock.read(cx);
7124 if let Some(active_panel) = dock.active_panel() {
7125 if active_panel.pane(cx).is_none() {
7126 let active_pane = workspace.active_pane().clone();
7127 active_pane.update(cx, |pane, cx| {
7128 pane.close_active_item(action, window, cx)
7129 .detach_and_log_err(cx);
7130 });
7131 return;
7132 }
7133 }
7134 }
7135 cx.propagate();
7136 },
7137 ))
7138 .on_action(
7139 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
7140 let pane = workspace.active_pane().clone();
7141 if let Some(item) = pane.read(cx).active_item() {
7142 item.toggle_read_only(window, cx);
7143 }
7144 }),
7145 )
7146 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
7147 workspace.focus_center_pane(window, cx);
7148 }))
7149 .on_action(cx.listener(Workspace::cancel))
7150 }
7151
7152 #[cfg(any(test, feature = "test-support"))]
7153 pub fn set_random_database_id(&mut self) {
7154 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
7155 }
7156
7157 #[cfg(any(test, feature = "test-support"))]
7158 pub(crate) fn test_new(
7159 project: Entity<Project>,
7160 window: &mut Window,
7161 cx: &mut Context<Self>,
7162 ) -> Self {
7163 use node_runtime::NodeRuntime;
7164 use session::Session;
7165
7166 let client = project.read(cx).client();
7167 let user_store = project.read(cx).user_store();
7168 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
7169 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
7170 window.activate_window();
7171 let app_state = Arc::new(AppState {
7172 languages: project.read(cx).languages().clone(),
7173 workspace_store,
7174 client,
7175 user_store,
7176 fs: project.read(cx).fs().clone(),
7177 build_window_options: |_, _| Default::default(),
7178 node_runtime: NodeRuntime::unavailable(),
7179 session,
7180 });
7181 let workspace = Self::new(Default::default(), project, app_state, window, cx);
7182 workspace
7183 .active_pane
7184 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
7185 workspace
7186 }
7187
7188 pub fn register_action<A: Action>(
7189 &mut self,
7190 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
7191 ) -> &mut Self {
7192 let callback = Arc::new(callback);
7193
7194 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
7195 let callback = callback.clone();
7196 div.on_action(cx.listener(move |workspace, event, window, cx| {
7197 (callback)(workspace, event, window, cx)
7198 }))
7199 }));
7200 self
7201 }
7202 pub fn register_action_renderer(
7203 &mut self,
7204 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
7205 ) -> &mut Self {
7206 self.workspace_actions.push(Box::new(callback));
7207 self
7208 }
7209
7210 fn add_workspace_actions_listeners(
7211 &self,
7212 mut div: Div,
7213 window: &mut Window,
7214 cx: &mut Context<Self>,
7215 ) -> Div {
7216 for action in self.workspace_actions.iter() {
7217 div = (action)(div, self, window, cx)
7218 }
7219 div
7220 }
7221
7222 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7223 self.modal_layer.read(cx).has_active_modal()
7224 }
7225
7226 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7227 self.modal_layer
7228 .read(cx)
7229 .is_active_modal_command_palette(cx)
7230 }
7231
7232 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7233 self.modal_layer.read(cx).active_modal()
7234 }
7235
7236 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7237 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7238 /// If no modal is active, the new modal will be shown.
7239 ///
7240 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7241 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7242 /// will not be shown.
7243 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7244 where
7245 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7246 {
7247 self.modal_layer.update(cx, |modal_layer, cx| {
7248 modal_layer.toggle_modal(window, cx, build)
7249 })
7250 }
7251
7252 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7253 self.modal_layer
7254 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7255 }
7256
7257 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7258 self.toast_layer
7259 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7260 }
7261
7262 pub fn toggle_centered_layout(
7263 &mut self,
7264 _: &ToggleCenteredLayout,
7265 _: &mut Window,
7266 cx: &mut Context<Self>,
7267 ) {
7268 self.centered_layout = !self.centered_layout;
7269 if let Some(database_id) = self.database_id() {
7270 let db = WorkspaceDb::global(cx);
7271 let centered_layout = self.centered_layout;
7272 cx.background_spawn(async move {
7273 db.set_centered_layout(database_id, centered_layout).await
7274 })
7275 .detach_and_log_err(cx);
7276 }
7277 cx.notify();
7278 }
7279
7280 fn adjust_padding(padding: Option<f32>) -> f32 {
7281 padding
7282 .unwrap_or(CenteredPaddingSettings::default().0)
7283 .clamp(
7284 CenteredPaddingSettings::MIN_PADDING,
7285 CenteredPaddingSettings::MAX_PADDING,
7286 )
7287 }
7288
7289 fn render_dock(
7290 &self,
7291 position: DockPosition,
7292 dock: &Entity<Dock>,
7293 window: &mut Window,
7294 cx: &mut App,
7295 ) -> Option<Div> {
7296 if self.zoomed_position == Some(position) {
7297 return None;
7298 }
7299
7300 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7301 let pane = panel.pane(cx)?;
7302 let follower_states = &self.follower_states;
7303 leader_border_for_pane(follower_states, &pane, window, cx)
7304 });
7305
7306 Some(
7307 div()
7308 .flex()
7309 .flex_none()
7310 .overflow_hidden()
7311 .child(dock.clone())
7312 .children(leader_border),
7313 )
7314 }
7315
7316 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7317 window
7318 .root::<MultiWorkspace>()
7319 .flatten()
7320 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7321 }
7322
7323 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7324 self.zoomed.as_ref()
7325 }
7326
7327 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7328 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7329 return;
7330 };
7331 let windows = cx.windows();
7332 let next_window =
7333 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7334 || {
7335 windows
7336 .iter()
7337 .cycle()
7338 .skip_while(|window| window.window_id() != current_window_id)
7339 .nth(1)
7340 },
7341 );
7342
7343 if let Some(window) = next_window {
7344 window
7345 .update(cx, |_, window, _| window.activate_window())
7346 .ok();
7347 }
7348 }
7349
7350 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7351 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7352 return;
7353 };
7354 let windows = cx.windows();
7355 let prev_window =
7356 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7357 || {
7358 windows
7359 .iter()
7360 .rev()
7361 .cycle()
7362 .skip_while(|window| window.window_id() != current_window_id)
7363 .nth(1)
7364 },
7365 );
7366
7367 if let Some(window) = prev_window {
7368 window
7369 .update(cx, |_, window, _| window.activate_window())
7370 .ok();
7371 }
7372 }
7373
7374 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7375 if cx.stop_active_drag(window) {
7376 } else if let Some((notification_id, _)) = self.notifications.pop() {
7377 dismiss_app_notification(¬ification_id, cx);
7378 } else {
7379 cx.propagate();
7380 }
7381 }
7382
7383 fn adjust_dock_size_by_px(
7384 &mut self,
7385 panel_size: Pixels,
7386 dock_pos: DockPosition,
7387 px: Pixels,
7388 window: &mut Window,
7389 cx: &mut Context<Self>,
7390 ) {
7391 match dock_pos {
7392 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
7393 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
7394 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
7395 }
7396 }
7397
7398 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7399 let workspace_width = self.bounds.size.width;
7400 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7401
7402 self.right_dock.read_with(cx, |right_dock, cx| {
7403 let right_dock_size = right_dock
7404 .stored_active_panel_size(window, cx)
7405 .unwrap_or(Pixels::ZERO);
7406 if right_dock_size + size > workspace_width {
7407 size = workspace_width - right_dock_size
7408 }
7409 });
7410
7411 let ratio = self.flexible_dock_ratio_for_size(DockPosition::Left, size, window, cx);
7412 self.left_dock.update(cx, |left_dock, cx| {
7413 if WorkspaceSettings::get_global(cx)
7414 .resize_all_panels_in_dock
7415 .contains(&DockPosition::Left)
7416 {
7417 left_dock.resize_all_panels(Some(size), ratio, window, cx);
7418 } else {
7419 left_dock.resize_active_panel(Some(size), ratio, window, cx);
7420 }
7421 });
7422 }
7423
7424 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7425 let workspace_width = self.bounds.size.width;
7426 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7427 self.left_dock.read_with(cx, |left_dock, cx| {
7428 let left_dock_size = left_dock
7429 .stored_active_panel_size(window, cx)
7430 .unwrap_or(Pixels::ZERO);
7431 if left_dock_size + size > workspace_width {
7432 size = workspace_width - left_dock_size
7433 }
7434 });
7435 let ratio = self.flexible_dock_ratio_for_size(DockPosition::Right, size, window, cx);
7436 self.right_dock.update(cx, |right_dock, cx| {
7437 if WorkspaceSettings::get_global(cx)
7438 .resize_all_panels_in_dock
7439 .contains(&DockPosition::Right)
7440 {
7441 right_dock.resize_all_panels(Some(size), ratio, window, cx);
7442 } else {
7443 right_dock.resize_active_panel(Some(size), ratio, window, cx);
7444 }
7445 });
7446 }
7447
7448 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7449 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7450 self.bottom_dock.update(cx, |bottom_dock, cx| {
7451 if WorkspaceSettings::get_global(cx)
7452 .resize_all_panels_in_dock
7453 .contains(&DockPosition::Bottom)
7454 {
7455 bottom_dock.resize_all_panels(Some(size), None, window, cx);
7456 } else {
7457 bottom_dock.resize_active_panel(Some(size), None, window, cx);
7458 }
7459 });
7460 }
7461
7462 fn toggle_edit_predictions_all_files(
7463 &mut self,
7464 _: &ToggleEditPrediction,
7465 _window: &mut Window,
7466 cx: &mut Context<Self>,
7467 ) {
7468 let fs = self.project().read(cx).fs().clone();
7469 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7470 update_settings_file(fs, cx, move |file, _| {
7471 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7472 });
7473 }
7474
7475 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7476 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7477 let next_mode = match current_mode {
7478 Some(theme::ThemeAppearanceMode::Light) => theme::ThemeAppearanceMode::Dark,
7479 Some(theme::ThemeAppearanceMode::Dark) => theme::ThemeAppearanceMode::Light,
7480 Some(theme::ThemeAppearanceMode::System) | None => match cx.theme().appearance() {
7481 theme::Appearance::Light => theme::ThemeAppearanceMode::Dark,
7482 theme::Appearance::Dark => theme::ThemeAppearanceMode::Light,
7483 },
7484 };
7485
7486 let fs = self.project().read(cx).fs().clone();
7487 settings::update_settings_file(fs, cx, move |settings, _cx| {
7488 theme::set_mode(settings, next_mode);
7489 });
7490 }
7491
7492 pub fn show_worktree_trust_security_modal(
7493 &mut self,
7494 toggle: bool,
7495 window: &mut Window,
7496 cx: &mut Context<Self>,
7497 ) {
7498 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7499 if toggle {
7500 security_modal.update(cx, |security_modal, cx| {
7501 security_modal.dismiss(cx);
7502 })
7503 } else {
7504 security_modal.update(cx, |security_modal, cx| {
7505 security_modal.refresh_restricted_paths(cx);
7506 });
7507 }
7508 } else {
7509 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7510 .map(|trusted_worktrees| {
7511 trusted_worktrees
7512 .read(cx)
7513 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7514 })
7515 .unwrap_or(false);
7516 if has_restricted_worktrees {
7517 let project = self.project().read(cx);
7518 let remote_host = project
7519 .remote_connection_options(cx)
7520 .map(RemoteHostLocation::from);
7521 let worktree_store = project.worktree_store().downgrade();
7522 self.toggle_modal(window, cx, |_, cx| {
7523 SecurityModal::new(worktree_store, remote_host, cx)
7524 });
7525 }
7526 }
7527 }
7528}
7529
7530pub trait AnyActiveCall {
7531 fn entity(&self) -> AnyEntity;
7532 fn is_in_room(&self, _: &App) -> bool;
7533 fn room_id(&self, _: &App) -> Option<u64>;
7534 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7535 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7536 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7537 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7538 fn is_sharing_project(&self, _: &App) -> bool;
7539 fn has_remote_participants(&self, _: &App) -> bool;
7540 fn local_participant_is_guest(&self, _: &App) -> bool;
7541 fn client(&self, _: &App) -> Arc<Client>;
7542 fn share_on_join(&self, _: &App) -> bool;
7543 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7544 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7545 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7546 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7547 fn join_project(
7548 &self,
7549 _: u64,
7550 _: Arc<LanguageRegistry>,
7551 _: Arc<dyn Fs>,
7552 _: &mut App,
7553 ) -> Task<Result<Entity<Project>>>;
7554 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7555 fn subscribe(
7556 &self,
7557 _: &mut Window,
7558 _: &mut Context<Workspace>,
7559 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7560 ) -> Subscription;
7561 fn create_shared_screen(
7562 &self,
7563 _: PeerId,
7564 _: &Entity<Pane>,
7565 _: &mut Window,
7566 _: &mut App,
7567 ) -> Option<Entity<SharedScreen>>;
7568}
7569
7570#[derive(Clone)]
7571pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7572impl Global for GlobalAnyActiveCall {}
7573
7574impl GlobalAnyActiveCall {
7575 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7576 cx.try_global()
7577 }
7578
7579 pub(crate) fn global(cx: &App) -> &Self {
7580 cx.global()
7581 }
7582}
7583
7584pub fn merge_conflict_notification_id() -> NotificationId {
7585 struct MergeConflictNotification;
7586 NotificationId::unique::<MergeConflictNotification>()
7587}
7588
7589/// Workspace-local view of a remote participant's location.
7590#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7591pub enum ParticipantLocation {
7592 SharedProject { project_id: u64 },
7593 UnsharedProject,
7594 External,
7595}
7596
7597impl ParticipantLocation {
7598 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7599 match location
7600 .and_then(|l| l.variant)
7601 .context("participant location was not provided")?
7602 {
7603 proto::participant_location::Variant::SharedProject(project) => {
7604 Ok(Self::SharedProject {
7605 project_id: project.id,
7606 })
7607 }
7608 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7609 proto::participant_location::Variant::External(_) => Ok(Self::External),
7610 }
7611 }
7612}
7613/// Workspace-local view of a remote collaborator's state.
7614/// This is the subset of `call::RemoteParticipant` that workspace needs.
7615#[derive(Clone)]
7616pub struct RemoteCollaborator {
7617 pub user: Arc<User>,
7618 pub peer_id: PeerId,
7619 pub location: ParticipantLocation,
7620 pub participant_index: ParticipantIndex,
7621}
7622
7623pub enum ActiveCallEvent {
7624 ParticipantLocationChanged { participant_id: PeerId },
7625 RemoteVideoTracksChanged { participant_id: PeerId },
7626}
7627
7628fn leader_border_for_pane(
7629 follower_states: &HashMap<CollaboratorId, FollowerState>,
7630 pane: &Entity<Pane>,
7631 _: &Window,
7632 cx: &App,
7633) -> Option<Div> {
7634 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7635 if state.pane() == pane {
7636 Some((*leader_id, state))
7637 } else {
7638 None
7639 }
7640 })?;
7641
7642 let mut leader_color = match leader_id {
7643 CollaboratorId::PeerId(leader_peer_id) => {
7644 let leader = GlobalAnyActiveCall::try_global(cx)?
7645 .0
7646 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7647
7648 cx.theme()
7649 .players()
7650 .color_for_participant(leader.participant_index.0)
7651 .cursor
7652 }
7653 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7654 };
7655 leader_color.fade_out(0.3);
7656 Some(
7657 div()
7658 .absolute()
7659 .size_full()
7660 .left_0()
7661 .top_0()
7662 .border_2()
7663 .border_color(leader_color),
7664 )
7665}
7666
7667fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7668 ZED_WINDOW_POSITION
7669 .zip(*ZED_WINDOW_SIZE)
7670 .map(|(position, size)| Bounds {
7671 origin: position,
7672 size,
7673 })
7674}
7675
7676fn open_items(
7677 serialized_workspace: Option<SerializedWorkspace>,
7678 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7679 window: &mut Window,
7680 cx: &mut Context<Workspace>,
7681) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7682 let restored_items = serialized_workspace.map(|serialized_workspace| {
7683 Workspace::load_workspace(
7684 serialized_workspace,
7685 project_paths_to_open
7686 .iter()
7687 .map(|(_, project_path)| project_path)
7688 .cloned()
7689 .collect(),
7690 window,
7691 cx,
7692 )
7693 });
7694
7695 cx.spawn_in(window, async move |workspace, cx| {
7696 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7697
7698 if let Some(restored_items) = restored_items {
7699 let restored_items = restored_items.await?;
7700
7701 let restored_project_paths = restored_items
7702 .iter()
7703 .filter_map(|item| {
7704 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7705 .ok()
7706 .flatten()
7707 })
7708 .collect::<HashSet<_>>();
7709
7710 for restored_item in restored_items {
7711 opened_items.push(restored_item.map(Ok));
7712 }
7713
7714 project_paths_to_open
7715 .iter_mut()
7716 .for_each(|(_, project_path)| {
7717 if let Some(project_path_to_open) = project_path
7718 && restored_project_paths.contains(project_path_to_open)
7719 {
7720 *project_path = None;
7721 }
7722 });
7723 } else {
7724 for _ in 0..project_paths_to_open.len() {
7725 opened_items.push(None);
7726 }
7727 }
7728 assert!(opened_items.len() == project_paths_to_open.len());
7729
7730 let tasks =
7731 project_paths_to_open
7732 .into_iter()
7733 .enumerate()
7734 .map(|(ix, (abs_path, project_path))| {
7735 let workspace = workspace.clone();
7736 cx.spawn(async move |cx| {
7737 let file_project_path = project_path?;
7738 let abs_path_task = workspace.update(cx, |workspace, cx| {
7739 workspace.project().update(cx, |project, cx| {
7740 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7741 })
7742 });
7743
7744 // We only want to open file paths here. If one of the items
7745 // here is a directory, it was already opened further above
7746 // with a `find_or_create_worktree`.
7747 if let Ok(task) = abs_path_task
7748 && task.await.is_none_or(|p| p.is_file())
7749 {
7750 return Some((
7751 ix,
7752 workspace
7753 .update_in(cx, |workspace, window, cx| {
7754 workspace.open_path(
7755 file_project_path,
7756 None,
7757 true,
7758 window,
7759 cx,
7760 )
7761 })
7762 .log_err()?
7763 .await,
7764 ));
7765 }
7766 None
7767 })
7768 });
7769
7770 let tasks = tasks.collect::<Vec<_>>();
7771
7772 let tasks = futures::future::join_all(tasks);
7773 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7774 opened_items[ix] = Some(path_open_result);
7775 }
7776
7777 Ok(opened_items)
7778 })
7779}
7780
7781#[derive(Clone)]
7782enum ActivateInDirectionTarget {
7783 Pane(Entity<Pane>),
7784 Dock(Entity<Dock>),
7785 Sidebar(FocusHandle),
7786}
7787
7788fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7789 window
7790 .update(cx, |multi_workspace, _, cx| {
7791 let workspace = multi_workspace.workspace().clone();
7792 workspace.update(cx, |workspace, cx| {
7793 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7794 struct DatabaseFailedNotification;
7795
7796 workspace.show_notification(
7797 NotificationId::unique::<DatabaseFailedNotification>(),
7798 cx,
7799 |cx| {
7800 cx.new(|cx| {
7801 MessageNotification::new("Failed to load the database file.", cx)
7802 .primary_message("File an Issue")
7803 .primary_icon(IconName::Plus)
7804 .primary_on_click(|window, cx| {
7805 window.dispatch_action(Box::new(FileBugReport), cx)
7806 })
7807 })
7808 },
7809 );
7810 }
7811 });
7812 })
7813 .log_err();
7814}
7815
7816fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7817 if val == 0 {
7818 ThemeSettings::get_global(cx).ui_font_size(cx)
7819 } else {
7820 px(val as f32)
7821 }
7822}
7823
7824fn adjust_active_dock_size_by_px(
7825 px: Pixels,
7826 workspace: &mut Workspace,
7827 window: &mut Window,
7828 cx: &mut Context<Workspace>,
7829) {
7830 let Some(active_dock) = workspace
7831 .all_docks()
7832 .into_iter()
7833 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7834 else {
7835 return;
7836 };
7837 let dock = active_dock.read(cx);
7838 let Some(panel_size) = dock
7839 .active_panel()
7840 .map(|panel| workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx))
7841 else {
7842 return;
7843 };
7844 let dock_pos = dock.position();
7845 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
7846}
7847
7848fn adjust_open_docks_size_by_px(
7849 px: Pixels,
7850 workspace: &mut Workspace,
7851 window: &mut Window,
7852 cx: &mut Context<Workspace>,
7853) {
7854 let docks = workspace
7855 .all_docks()
7856 .into_iter()
7857 .filter_map(|dock_entity| {
7858 let dock = dock_entity.read(cx);
7859 if dock.is_open() {
7860 let panel_size = dock.active_panel().map(|panel| {
7861 workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx)
7862 })?;
7863 let dock_pos = dock.position();
7864 Some((panel_size, dock_pos, px))
7865 } else {
7866 None
7867 }
7868 })
7869 .collect::<Vec<_>>();
7870
7871 docks
7872 .into_iter()
7873 .for_each(|(panel_size, dock_pos, offset)| {
7874 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
7875 });
7876}
7877
7878impl Focusable for Workspace {
7879 fn focus_handle(&self, cx: &App) -> FocusHandle {
7880 self.active_pane.focus_handle(cx)
7881 }
7882}
7883
7884#[derive(Clone)]
7885struct DraggedDock(DockPosition);
7886
7887impl Render for DraggedDock {
7888 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7889 gpui::Empty
7890 }
7891}
7892
7893impl Render for Workspace {
7894 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7895 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7896 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7897 log::info!("Rendered first frame");
7898 }
7899
7900 let centered_layout = self.centered_layout
7901 && self.center.panes().len() == 1
7902 && self.active_item(cx).is_some();
7903 let render_padding = |size| {
7904 (size > 0.0).then(|| {
7905 div()
7906 .h_full()
7907 .w(relative(size))
7908 .bg(cx.theme().colors().editor_background)
7909 .border_color(cx.theme().colors().pane_group_border)
7910 })
7911 };
7912 let paddings = if centered_layout {
7913 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7914 (
7915 render_padding(Self::adjust_padding(
7916 settings.left_padding.map(|padding| padding.0),
7917 )),
7918 render_padding(Self::adjust_padding(
7919 settings.right_padding.map(|padding| padding.0),
7920 )),
7921 )
7922 } else {
7923 (None, None)
7924 };
7925 let ui_font = theme::setup_ui_font(window, cx);
7926
7927 let theme = cx.theme().clone();
7928 let colors = theme.colors();
7929 let notification_entities = self
7930 .notifications
7931 .iter()
7932 .map(|(_, notification)| notification.entity_id())
7933 .collect::<Vec<_>>();
7934 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
7935
7936 div()
7937 .relative()
7938 .size_full()
7939 .flex()
7940 .flex_col()
7941 .font(ui_font)
7942 .gap_0()
7943 .justify_start()
7944 .items_start()
7945 .text_color(colors.text)
7946 .overflow_hidden()
7947 .children(self.titlebar_item.clone())
7948 .on_modifiers_changed(move |_, _, cx| {
7949 for &id in ¬ification_entities {
7950 cx.notify(id);
7951 }
7952 })
7953 .child(
7954 div()
7955 .size_full()
7956 .relative()
7957 .flex_1()
7958 .flex()
7959 .flex_col()
7960 .child(
7961 div()
7962 .id("workspace")
7963 .bg(colors.background)
7964 .relative()
7965 .flex_1()
7966 .w_full()
7967 .flex()
7968 .flex_col()
7969 .overflow_hidden()
7970 .border_t_1()
7971 .border_b_1()
7972 .border_color(colors.border)
7973 .child({
7974 let this = cx.entity();
7975 canvas(
7976 move |bounds, window, cx| {
7977 this.update(cx, |this, cx| {
7978 let bounds_changed = this.bounds != bounds;
7979 this.bounds = bounds;
7980
7981 if bounds_changed {
7982 this.left_dock.update(cx, |dock, cx| {
7983 dock.clamp_panel_size(
7984 bounds.size.width,
7985 window,
7986 cx,
7987 )
7988 });
7989
7990 this.right_dock.update(cx, |dock, cx| {
7991 dock.clamp_panel_size(
7992 bounds.size.width,
7993 window,
7994 cx,
7995 )
7996 });
7997
7998 this.bottom_dock.update(cx, |dock, cx| {
7999 dock.clamp_panel_size(
8000 bounds.size.height,
8001 window,
8002 cx,
8003 )
8004 });
8005 }
8006 })
8007 },
8008 |_, _, _, _| {},
8009 )
8010 .absolute()
8011 .size_full()
8012 })
8013 .when(self.zoomed.is_none(), |this| {
8014 this.on_drag_move(cx.listener(
8015 move |workspace,
8016 e: &DragMoveEvent<DraggedDock>,
8017 window,
8018 cx| {
8019 if workspace.previous_dock_drag_coordinates
8020 != Some(e.event.position)
8021 {
8022 workspace.previous_dock_drag_coordinates =
8023 Some(e.event.position);
8024
8025 match e.drag(cx).0 {
8026 DockPosition::Left => {
8027 workspace.resize_left_dock(
8028 e.event.position.x
8029 - workspace.bounds.left(),
8030 window,
8031 cx,
8032 );
8033 }
8034 DockPosition::Right => {
8035 workspace.resize_right_dock(
8036 workspace.bounds.right()
8037 - e.event.position.x,
8038 window,
8039 cx,
8040 );
8041 }
8042 DockPosition::Bottom => {
8043 workspace.resize_bottom_dock(
8044 workspace.bounds.bottom()
8045 - e.event.position.y,
8046 window,
8047 cx,
8048 );
8049 }
8050 };
8051 workspace.serialize_workspace(window, cx);
8052 }
8053 },
8054 ))
8055
8056 })
8057 .child({
8058 match bottom_dock_layout {
8059 BottomDockLayout::Full => div()
8060 .flex()
8061 .flex_col()
8062 .h_full()
8063 .child(
8064 div()
8065 .flex()
8066 .flex_row()
8067 .flex_1()
8068 .overflow_hidden()
8069 .children(self.render_dock(
8070 DockPosition::Left,
8071 &self.left_dock,
8072 window,
8073 cx,
8074 ))
8075
8076 .child(
8077 div()
8078 .flex()
8079 .flex_col()
8080 .flex_1()
8081 .overflow_hidden()
8082 .child(
8083 h_flex()
8084 .flex_1()
8085 .when_some(
8086 paddings.0,
8087 |this, p| {
8088 this.child(
8089 p.border_r_1(),
8090 )
8091 },
8092 )
8093 .child(self.center.render(
8094 self.zoomed.as_ref(),
8095 &PaneRenderContext {
8096 follower_states:
8097 &self.follower_states,
8098 active_call: self.active_call(),
8099 active_pane: &self.active_pane,
8100 app_state: &self.app_state,
8101 project: &self.project,
8102 workspace: &self.weak_self,
8103 },
8104 window,
8105 cx,
8106 ))
8107 .when_some(
8108 paddings.1,
8109 |this, p| {
8110 this.child(
8111 p.border_l_1(),
8112 )
8113 },
8114 ),
8115 ),
8116 )
8117
8118 .children(self.render_dock(
8119 DockPosition::Right,
8120 &self.right_dock,
8121 window,
8122 cx,
8123 )),
8124 )
8125 .child(div().w_full().children(self.render_dock(
8126 DockPosition::Bottom,
8127 &self.bottom_dock,
8128 window,
8129 cx
8130 ))),
8131
8132 BottomDockLayout::LeftAligned => div()
8133 .flex()
8134 .flex_row()
8135 .h_full()
8136 .child(
8137 div()
8138 .flex()
8139 .flex_col()
8140 .flex_1()
8141 .h_full()
8142 .child(
8143 div()
8144 .flex()
8145 .flex_row()
8146 .flex_1()
8147 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
8148
8149 .child(
8150 div()
8151 .flex()
8152 .flex_col()
8153 .flex_1()
8154 .overflow_hidden()
8155 .child(
8156 h_flex()
8157 .flex_1()
8158 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8159 .child(self.center.render(
8160 self.zoomed.as_ref(),
8161 &PaneRenderContext {
8162 follower_states:
8163 &self.follower_states,
8164 active_call: self.active_call(),
8165 active_pane: &self.active_pane,
8166 app_state: &self.app_state,
8167 project: &self.project,
8168 workspace: &self.weak_self,
8169 },
8170 window,
8171 cx,
8172 ))
8173 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8174 )
8175 )
8176
8177 )
8178 .child(
8179 div()
8180 .w_full()
8181 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8182 ),
8183 )
8184 .children(self.render_dock(
8185 DockPosition::Right,
8186 &self.right_dock,
8187 window,
8188 cx,
8189 )),
8190 BottomDockLayout::RightAligned => div()
8191 .flex()
8192 .flex_row()
8193 .h_full()
8194 .children(self.render_dock(
8195 DockPosition::Left,
8196 &self.left_dock,
8197 window,
8198 cx,
8199 ))
8200
8201 .child(
8202 div()
8203 .flex()
8204 .flex_col()
8205 .flex_1()
8206 .h_full()
8207 .child(
8208 div()
8209 .flex()
8210 .flex_row()
8211 .flex_1()
8212 .child(
8213 div()
8214 .flex()
8215 .flex_col()
8216 .flex_1()
8217 .overflow_hidden()
8218 .child(
8219 h_flex()
8220 .flex_1()
8221 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8222 .child(self.center.render(
8223 self.zoomed.as_ref(),
8224 &PaneRenderContext {
8225 follower_states:
8226 &self.follower_states,
8227 active_call: self.active_call(),
8228 active_pane: &self.active_pane,
8229 app_state: &self.app_state,
8230 project: &self.project,
8231 workspace: &self.weak_self,
8232 },
8233 window,
8234 cx,
8235 ))
8236 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8237 )
8238 )
8239
8240 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8241 )
8242 .child(
8243 div()
8244 .w_full()
8245 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8246 ),
8247 ),
8248 BottomDockLayout::Contained => div()
8249 .flex()
8250 .flex_row()
8251 .h_full()
8252 .children(self.render_dock(
8253 DockPosition::Left,
8254 &self.left_dock,
8255 window,
8256 cx,
8257 ))
8258
8259 .child(
8260 div()
8261 .flex()
8262 .flex_col()
8263 .flex_1()
8264 .overflow_hidden()
8265 .child(
8266 h_flex()
8267 .flex_1()
8268 .when_some(paddings.0, |this, p| {
8269 this.child(p.border_r_1())
8270 })
8271 .child(self.center.render(
8272 self.zoomed.as_ref(),
8273 &PaneRenderContext {
8274 follower_states:
8275 &self.follower_states,
8276 active_call: self.active_call(),
8277 active_pane: &self.active_pane,
8278 app_state: &self.app_state,
8279 project: &self.project,
8280 workspace: &self.weak_self,
8281 },
8282 window,
8283 cx,
8284 ))
8285 .when_some(paddings.1, |this, p| {
8286 this.child(p.border_l_1())
8287 }),
8288 )
8289 .children(self.render_dock(
8290 DockPosition::Bottom,
8291 &self.bottom_dock,
8292 window,
8293 cx,
8294 )),
8295 )
8296
8297 .children(self.render_dock(
8298 DockPosition::Right,
8299 &self.right_dock,
8300 window,
8301 cx,
8302 )),
8303 }
8304 })
8305 .children(self.zoomed.as_ref().and_then(|view| {
8306 let zoomed_view = view.upgrade()?;
8307 let div = div()
8308 .occlude()
8309 .absolute()
8310 .overflow_hidden()
8311 .border_color(colors.border)
8312 .bg(colors.background)
8313 .child(zoomed_view)
8314 .inset_0()
8315 .shadow_lg();
8316
8317 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8318 return Some(div);
8319 }
8320
8321 Some(match self.zoomed_position {
8322 Some(DockPosition::Left) => div.right_2().border_r_1(),
8323 Some(DockPosition::Right) => div.left_2().border_l_1(),
8324 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8325 None => {
8326 div.top_2().bottom_2().left_2().right_2().border_1()
8327 }
8328 })
8329 }))
8330 .children(self.render_notifications(window, cx)),
8331 )
8332 .when(self.status_bar_visible(cx), |parent| {
8333 parent.child(self.status_bar.clone())
8334 })
8335 .child(self.toast_layer.clone()),
8336 )
8337 }
8338}
8339
8340impl WorkspaceStore {
8341 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8342 Self {
8343 workspaces: Default::default(),
8344 _subscriptions: vec![
8345 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8346 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8347 ],
8348 client,
8349 }
8350 }
8351
8352 pub fn update_followers(
8353 &self,
8354 project_id: Option<u64>,
8355 update: proto::update_followers::Variant,
8356 cx: &App,
8357 ) -> Option<()> {
8358 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8359 let room_id = active_call.0.room_id(cx)?;
8360 self.client
8361 .send(proto::UpdateFollowers {
8362 room_id,
8363 project_id,
8364 variant: Some(update),
8365 })
8366 .log_err()
8367 }
8368
8369 pub async fn handle_follow(
8370 this: Entity<Self>,
8371 envelope: TypedEnvelope<proto::Follow>,
8372 mut cx: AsyncApp,
8373 ) -> Result<proto::FollowResponse> {
8374 this.update(&mut cx, |this, cx| {
8375 let follower = Follower {
8376 project_id: envelope.payload.project_id,
8377 peer_id: envelope.original_sender_id()?,
8378 };
8379
8380 let mut response = proto::FollowResponse::default();
8381
8382 this.workspaces.retain(|(window_handle, weak_workspace)| {
8383 let Some(workspace) = weak_workspace.upgrade() else {
8384 return false;
8385 };
8386 window_handle
8387 .update(cx, |_, window, cx| {
8388 workspace.update(cx, |workspace, cx| {
8389 let handler_response =
8390 workspace.handle_follow(follower.project_id, window, cx);
8391 if let Some(active_view) = handler_response.active_view
8392 && workspace.project.read(cx).remote_id() == follower.project_id
8393 {
8394 response.active_view = Some(active_view)
8395 }
8396 });
8397 })
8398 .is_ok()
8399 });
8400
8401 Ok(response)
8402 })
8403 }
8404
8405 async fn handle_update_followers(
8406 this: Entity<Self>,
8407 envelope: TypedEnvelope<proto::UpdateFollowers>,
8408 mut cx: AsyncApp,
8409 ) -> Result<()> {
8410 let leader_id = envelope.original_sender_id()?;
8411 let update = envelope.payload;
8412
8413 this.update(&mut cx, |this, cx| {
8414 this.workspaces.retain(|(window_handle, weak_workspace)| {
8415 let Some(workspace) = weak_workspace.upgrade() else {
8416 return false;
8417 };
8418 window_handle
8419 .update(cx, |_, window, cx| {
8420 workspace.update(cx, |workspace, cx| {
8421 let project_id = workspace.project.read(cx).remote_id();
8422 if update.project_id != project_id && update.project_id.is_some() {
8423 return;
8424 }
8425 workspace.handle_update_followers(
8426 leader_id,
8427 update.clone(),
8428 window,
8429 cx,
8430 );
8431 });
8432 })
8433 .is_ok()
8434 });
8435 Ok(())
8436 })
8437 }
8438
8439 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8440 self.workspaces.iter().map(|(_, weak)| weak)
8441 }
8442
8443 pub fn workspaces_with_windows(
8444 &self,
8445 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8446 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8447 }
8448}
8449
8450impl ViewId {
8451 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8452 Ok(Self {
8453 creator: message
8454 .creator
8455 .map(CollaboratorId::PeerId)
8456 .context("creator is missing")?,
8457 id: message.id,
8458 })
8459 }
8460
8461 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8462 if let CollaboratorId::PeerId(peer_id) = self.creator {
8463 Some(proto::ViewId {
8464 creator: Some(peer_id),
8465 id: self.id,
8466 })
8467 } else {
8468 None
8469 }
8470 }
8471}
8472
8473impl FollowerState {
8474 fn pane(&self) -> &Entity<Pane> {
8475 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8476 }
8477}
8478
8479pub trait WorkspaceHandle {
8480 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8481}
8482
8483impl WorkspaceHandle for Entity<Workspace> {
8484 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8485 self.read(cx)
8486 .worktrees(cx)
8487 .flat_map(|worktree| {
8488 let worktree_id = worktree.read(cx).id();
8489 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8490 worktree_id,
8491 path: f.path.clone(),
8492 })
8493 })
8494 .collect::<Vec<_>>()
8495 }
8496}
8497
8498pub async fn last_opened_workspace_location(
8499 db: &WorkspaceDb,
8500 fs: &dyn fs::Fs,
8501) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8502 db.last_workspace(fs)
8503 .await
8504 .log_err()
8505 .flatten()
8506 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8507}
8508
8509pub async fn last_session_workspace_locations(
8510 db: &WorkspaceDb,
8511 last_session_id: &str,
8512 last_session_window_stack: Option<Vec<WindowId>>,
8513 fs: &dyn fs::Fs,
8514) -> Option<Vec<SessionWorkspace>> {
8515 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8516 .await
8517 .log_err()
8518}
8519
8520pub struct MultiWorkspaceRestoreResult {
8521 pub window_handle: WindowHandle<MultiWorkspace>,
8522 pub errors: Vec<anyhow::Error>,
8523}
8524
8525pub async fn restore_multiworkspace(
8526 multi_workspace: SerializedMultiWorkspace,
8527 app_state: Arc<AppState>,
8528 cx: &mut AsyncApp,
8529) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8530 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
8531 let mut group_iter = workspaces.into_iter();
8532 let first = group_iter
8533 .next()
8534 .context("window group must not be empty")?;
8535
8536 let window_handle = if first.paths.is_empty() {
8537 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8538 .await?
8539 } else {
8540 let OpenResult { window, .. } = cx
8541 .update(|cx| {
8542 Workspace::new_local(
8543 first.paths.paths().to_vec(),
8544 app_state.clone(),
8545 None,
8546 None,
8547 None,
8548 true,
8549 cx,
8550 )
8551 })
8552 .await?;
8553 window
8554 };
8555
8556 let mut errors = Vec::new();
8557
8558 for session_workspace in group_iter {
8559 let error = if session_workspace.paths.is_empty() {
8560 cx.update(|cx| {
8561 open_workspace_by_id(
8562 session_workspace.workspace_id,
8563 app_state.clone(),
8564 Some(window_handle),
8565 cx,
8566 )
8567 })
8568 .await
8569 .err()
8570 } else {
8571 cx.update(|cx| {
8572 Workspace::new_local(
8573 session_workspace.paths.paths().to_vec(),
8574 app_state.clone(),
8575 Some(window_handle),
8576 None,
8577 None,
8578 false,
8579 cx,
8580 )
8581 })
8582 .await
8583 .err()
8584 };
8585
8586 if let Some(error) = error {
8587 errors.push(error);
8588 }
8589 }
8590
8591 if let Some(target_id) = state.active_workspace_id {
8592 window_handle
8593 .update(cx, |multi_workspace, window, cx| {
8594 let target_index = multi_workspace
8595 .workspaces()
8596 .iter()
8597 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8598 if let Some(index) = target_index {
8599 multi_workspace.activate_index(index, window, cx);
8600 } else if !multi_workspace.workspaces().is_empty() {
8601 multi_workspace.activate_index(0, window, cx);
8602 }
8603 })
8604 .ok();
8605 } else {
8606 window_handle
8607 .update(cx, |multi_workspace, window, cx| {
8608 if !multi_workspace.workspaces().is_empty() {
8609 multi_workspace.activate_index(0, window, cx);
8610 }
8611 })
8612 .ok();
8613 }
8614
8615 if state.sidebar_open {
8616 window_handle
8617 .update(cx, |multi_workspace, _, cx| {
8618 multi_workspace.open_sidebar(cx);
8619 })
8620 .ok();
8621 }
8622
8623 window_handle
8624 .update(cx, |_, window, _cx| {
8625 window.activate_window();
8626 })
8627 .ok();
8628
8629 Ok(MultiWorkspaceRestoreResult {
8630 window_handle,
8631 errors,
8632 })
8633}
8634
8635actions!(
8636 collab,
8637 [
8638 /// Opens the channel notes for the current call.
8639 ///
8640 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8641 /// channel in the collab panel.
8642 ///
8643 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8644 /// can be copied via "Copy link to section" in the context menu of the channel notes
8645 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8646 OpenChannelNotes,
8647 /// Mutes your microphone.
8648 Mute,
8649 /// Deafens yourself (mute both microphone and speakers).
8650 Deafen,
8651 /// Leaves the current call.
8652 LeaveCall,
8653 /// Shares the current project with collaborators.
8654 ShareProject,
8655 /// Shares your screen with collaborators.
8656 ScreenShare,
8657 /// Copies the current room name and session id for debugging purposes.
8658 CopyRoomId,
8659 ]
8660);
8661
8662/// Opens the channel notes for a specific channel by its ID.
8663#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8664#[action(namespace = collab)]
8665#[serde(deny_unknown_fields)]
8666pub struct OpenChannelNotesById {
8667 pub channel_id: u64,
8668}
8669
8670actions!(
8671 zed,
8672 [
8673 /// Opens the Zed log file.
8674 OpenLog,
8675 /// Reveals the Zed log file in the system file manager.
8676 RevealLogInFileManager
8677 ]
8678);
8679
8680async fn join_channel_internal(
8681 channel_id: ChannelId,
8682 app_state: &Arc<AppState>,
8683 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8684 requesting_workspace: Option<WeakEntity<Workspace>>,
8685 active_call: &dyn AnyActiveCall,
8686 cx: &mut AsyncApp,
8687) -> Result<bool> {
8688 let (should_prompt, already_in_channel) = cx.update(|cx| {
8689 if !active_call.is_in_room(cx) {
8690 return (false, false);
8691 }
8692
8693 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8694 let should_prompt = active_call.is_sharing_project(cx)
8695 && active_call.has_remote_participants(cx)
8696 && !already_in_channel;
8697 (should_prompt, already_in_channel)
8698 });
8699
8700 if already_in_channel {
8701 let task = cx.update(|cx| {
8702 if let Some((project, host)) = active_call.most_active_project(cx) {
8703 Some(join_in_room_project(project, host, app_state.clone(), cx))
8704 } else {
8705 None
8706 }
8707 });
8708 if let Some(task) = task {
8709 task.await?;
8710 }
8711 return anyhow::Ok(true);
8712 }
8713
8714 if should_prompt {
8715 if let Some(multi_workspace) = requesting_window {
8716 let answer = multi_workspace
8717 .update(cx, |_, window, cx| {
8718 window.prompt(
8719 PromptLevel::Warning,
8720 "Do you want to switch channels?",
8721 Some("Leaving this call will unshare your current project."),
8722 &["Yes, Join Channel", "Cancel"],
8723 cx,
8724 )
8725 })?
8726 .await;
8727
8728 if answer == Ok(1) {
8729 return Ok(false);
8730 }
8731 } else {
8732 return Ok(false);
8733 }
8734 }
8735
8736 let client = cx.update(|cx| active_call.client(cx));
8737
8738 let mut client_status = client.status();
8739
8740 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8741 'outer: loop {
8742 let Some(status) = client_status.recv().await else {
8743 anyhow::bail!("error connecting");
8744 };
8745
8746 match status {
8747 Status::Connecting
8748 | Status::Authenticating
8749 | Status::Authenticated
8750 | Status::Reconnecting
8751 | Status::Reauthenticating
8752 | Status::Reauthenticated => continue,
8753 Status::Connected { .. } => break 'outer,
8754 Status::SignedOut | Status::AuthenticationError => {
8755 return Err(ErrorCode::SignedOut.into());
8756 }
8757 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8758 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8759 return Err(ErrorCode::Disconnected.into());
8760 }
8761 }
8762 }
8763
8764 let joined = cx
8765 .update(|cx| active_call.join_channel(channel_id, cx))
8766 .await?;
8767
8768 if !joined {
8769 return anyhow::Ok(true);
8770 }
8771
8772 cx.update(|cx| active_call.room_update_completed(cx)).await;
8773
8774 let task = cx.update(|cx| {
8775 if let Some((project, host)) = active_call.most_active_project(cx) {
8776 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8777 }
8778
8779 // If you are the first to join a channel, see if you should share your project.
8780 if !active_call.has_remote_participants(cx)
8781 && !active_call.local_participant_is_guest(cx)
8782 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8783 {
8784 let project = workspace.update(cx, |workspace, cx| {
8785 let project = workspace.project.read(cx);
8786
8787 if !active_call.share_on_join(cx) {
8788 return None;
8789 }
8790
8791 if (project.is_local() || project.is_via_remote_server())
8792 && project.visible_worktrees(cx).any(|tree| {
8793 tree.read(cx)
8794 .root_entry()
8795 .is_some_and(|entry| entry.is_dir())
8796 })
8797 {
8798 Some(workspace.project.clone())
8799 } else {
8800 None
8801 }
8802 });
8803 if let Some(project) = project {
8804 let share_task = active_call.share_project(project, cx);
8805 return Some(cx.spawn(async move |_cx| -> Result<()> {
8806 share_task.await?;
8807 Ok(())
8808 }));
8809 }
8810 }
8811
8812 None
8813 });
8814 if let Some(task) = task {
8815 task.await?;
8816 return anyhow::Ok(true);
8817 }
8818 anyhow::Ok(false)
8819}
8820
8821pub fn join_channel(
8822 channel_id: ChannelId,
8823 app_state: Arc<AppState>,
8824 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8825 requesting_workspace: Option<WeakEntity<Workspace>>,
8826 cx: &mut App,
8827) -> Task<Result<()>> {
8828 let active_call = GlobalAnyActiveCall::global(cx).clone();
8829 cx.spawn(async move |cx| {
8830 let result = join_channel_internal(
8831 channel_id,
8832 &app_state,
8833 requesting_window,
8834 requesting_workspace,
8835 &*active_call.0,
8836 cx,
8837 )
8838 .await;
8839
8840 // join channel succeeded, and opened a window
8841 if matches!(result, Ok(true)) {
8842 return anyhow::Ok(());
8843 }
8844
8845 // find an existing workspace to focus and show call controls
8846 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8847 if active_window.is_none() {
8848 // no open workspaces, make one to show the error in (blergh)
8849 let OpenResult {
8850 window: window_handle,
8851 ..
8852 } = cx
8853 .update(|cx| {
8854 Workspace::new_local(
8855 vec![],
8856 app_state.clone(),
8857 requesting_window,
8858 None,
8859 None,
8860 true,
8861 cx,
8862 )
8863 })
8864 .await?;
8865
8866 window_handle
8867 .update(cx, |_, window, _cx| {
8868 window.activate_window();
8869 })
8870 .ok();
8871
8872 if result.is_ok() {
8873 cx.update(|cx| {
8874 cx.dispatch_action(&OpenChannelNotes);
8875 });
8876 }
8877
8878 active_window = Some(window_handle);
8879 }
8880
8881 if let Err(err) = result {
8882 log::error!("failed to join channel: {}", err);
8883 if let Some(active_window) = active_window {
8884 active_window
8885 .update(cx, |_, window, cx| {
8886 let detail: SharedString = match err.error_code() {
8887 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8888 ErrorCode::UpgradeRequired => concat!(
8889 "Your are running an unsupported version of Zed. ",
8890 "Please update to continue."
8891 )
8892 .into(),
8893 ErrorCode::NoSuchChannel => concat!(
8894 "No matching channel was found. ",
8895 "Please check the link and try again."
8896 )
8897 .into(),
8898 ErrorCode::Forbidden => concat!(
8899 "This channel is private, and you do not have access. ",
8900 "Please ask someone to add you and try again."
8901 )
8902 .into(),
8903 ErrorCode::Disconnected => {
8904 "Please check your internet connection and try again.".into()
8905 }
8906 _ => format!("{}\n\nPlease try again.", err).into(),
8907 };
8908 window.prompt(
8909 PromptLevel::Critical,
8910 "Failed to join channel",
8911 Some(&detail),
8912 &["Ok"],
8913 cx,
8914 )
8915 })?
8916 .await
8917 .ok();
8918 }
8919 }
8920
8921 // return ok, we showed the error to the user.
8922 anyhow::Ok(())
8923 })
8924}
8925
8926pub async fn get_any_active_multi_workspace(
8927 app_state: Arc<AppState>,
8928 mut cx: AsyncApp,
8929) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8930 // find an existing workspace to focus and show call controls
8931 let active_window = activate_any_workspace_window(&mut cx);
8932 if active_window.is_none() {
8933 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
8934 .await?;
8935 }
8936 activate_any_workspace_window(&mut cx).context("could not open zed")
8937}
8938
8939fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8940 cx.update(|cx| {
8941 if let Some(workspace_window) = cx
8942 .active_window()
8943 .and_then(|window| window.downcast::<MultiWorkspace>())
8944 {
8945 return Some(workspace_window);
8946 }
8947
8948 for window in cx.windows() {
8949 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8950 workspace_window
8951 .update(cx, |_, window, _| window.activate_window())
8952 .ok();
8953 return Some(workspace_window);
8954 }
8955 }
8956 None
8957 })
8958}
8959
8960pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8961 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
8962}
8963
8964pub fn workspace_windows_for_location(
8965 serialized_location: &SerializedWorkspaceLocation,
8966 cx: &App,
8967) -> Vec<WindowHandle<MultiWorkspace>> {
8968 cx.windows()
8969 .into_iter()
8970 .filter_map(|window| window.downcast::<MultiWorkspace>())
8971 .filter(|multi_workspace| {
8972 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
8973 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
8974 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
8975 }
8976 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
8977 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
8978 a.distro_name == b.distro_name
8979 }
8980 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
8981 a.container_id == b.container_id
8982 }
8983 #[cfg(any(test, feature = "test-support"))]
8984 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
8985 a.id == b.id
8986 }
8987 _ => false,
8988 };
8989
8990 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8991 multi_workspace.workspaces().iter().any(|workspace| {
8992 match workspace.read(cx).workspace_location(cx) {
8993 WorkspaceLocation::Location(location, _) => {
8994 match (&location, serialized_location) {
8995 (
8996 SerializedWorkspaceLocation::Local,
8997 SerializedWorkspaceLocation::Local,
8998 ) => true,
8999 (
9000 SerializedWorkspaceLocation::Remote(a),
9001 SerializedWorkspaceLocation::Remote(b),
9002 ) => same_host(a, b),
9003 _ => false,
9004 }
9005 }
9006 _ => false,
9007 }
9008 })
9009 })
9010 })
9011 .collect()
9012}
9013
9014pub async fn find_existing_workspace(
9015 abs_paths: &[PathBuf],
9016 open_options: &OpenOptions,
9017 location: &SerializedWorkspaceLocation,
9018 cx: &mut AsyncApp,
9019) -> (
9020 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
9021 OpenVisible,
9022) {
9023 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
9024 let mut open_visible = OpenVisible::All;
9025 let mut best_match = None;
9026
9027 if open_options.open_new_workspace != Some(true) {
9028 cx.update(|cx| {
9029 for window in workspace_windows_for_location(location, cx) {
9030 if let Ok(multi_workspace) = window.read(cx) {
9031 for workspace in multi_workspace.workspaces() {
9032 let project = workspace.read(cx).project.read(cx);
9033 let m = project.visibility_for_paths(
9034 abs_paths,
9035 open_options.open_new_workspace == None,
9036 cx,
9037 );
9038 if m > best_match {
9039 existing = Some((window, workspace.clone()));
9040 best_match = m;
9041 } else if best_match.is_none()
9042 && open_options.open_new_workspace == Some(false)
9043 {
9044 existing = Some((window, workspace.clone()))
9045 }
9046 }
9047 }
9048 }
9049 });
9050
9051 let all_paths_are_files = existing
9052 .as_ref()
9053 .and_then(|(_, target_workspace)| {
9054 cx.update(|cx| {
9055 let workspace = target_workspace.read(cx);
9056 let project = workspace.project.read(cx);
9057 let path_style = workspace.path_style(cx);
9058 Some(!abs_paths.iter().any(|path| {
9059 let path = util::paths::SanitizedPath::new(path);
9060 project.worktrees(cx).any(|worktree| {
9061 let worktree = worktree.read(cx);
9062 let abs_path = worktree.abs_path();
9063 path_style
9064 .strip_prefix(path.as_ref(), abs_path.as_ref())
9065 .and_then(|rel| worktree.entry_for_path(&rel))
9066 .is_some_and(|e| e.is_dir())
9067 })
9068 }))
9069 })
9070 })
9071 .unwrap_or(false);
9072
9073 if open_options.open_new_workspace.is_none()
9074 && existing.is_some()
9075 && open_options.wait
9076 && all_paths_are_files
9077 {
9078 cx.update(|cx| {
9079 let windows = workspace_windows_for_location(location, cx);
9080 let window = cx
9081 .active_window()
9082 .and_then(|window| window.downcast::<MultiWorkspace>())
9083 .filter(|window| windows.contains(window))
9084 .or_else(|| windows.into_iter().next());
9085 if let Some(window) = window {
9086 if let Ok(multi_workspace) = window.read(cx) {
9087 let active_workspace = multi_workspace.workspace().clone();
9088 existing = Some((window, active_workspace));
9089 open_visible = OpenVisible::None;
9090 }
9091 }
9092 });
9093 }
9094 }
9095 (existing, open_visible)
9096}
9097
9098#[derive(Default, Clone)]
9099pub struct OpenOptions {
9100 pub visible: Option<OpenVisible>,
9101 pub focus: Option<bool>,
9102 pub open_new_workspace: Option<bool>,
9103 pub wait: bool,
9104 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
9105 pub env: Option<HashMap<String, String>>,
9106}
9107
9108/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
9109/// or [`Workspace::open_workspace_for_paths`].
9110pub struct OpenResult {
9111 pub window: WindowHandle<MultiWorkspace>,
9112 pub workspace: Entity<Workspace>,
9113 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
9114}
9115
9116/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
9117pub fn open_workspace_by_id(
9118 workspace_id: WorkspaceId,
9119 app_state: Arc<AppState>,
9120 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9121 cx: &mut App,
9122) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
9123 let project_handle = Project::local(
9124 app_state.client.clone(),
9125 app_state.node_runtime.clone(),
9126 app_state.user_store.clone(),
9127 app_state.languages.clone(),
9128 app_state.fs.clone(),
9129 None,
9130 project::LocalProjectFlags {
9131 init_worktree_trust: true,
9132 ..project::LocalProjectFlags::default()
9133 },
9134 cx,
9135 );
9136
9137 let db = WorkspaceDb::global(cx);
9138 let kvp = db::kvp::KeyValueStore::global(cx);
9139 cx.spawn(async move |cx| {
9140 let serialized_workspace = db
9141 .workspace_for_id(workspace_id)
9142 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
9143
9144 let centered_layout = serialized_workspace.centered_layout;
9145
9146 let (window, workspace) = if let Some(window) = requesting_window {
9147 let workspace = window.update(cx, |multi_workspace, window, cx| {
9148 let workspace = cx.new(|cx| {
9149 let mut workspace = Workspace::new(
9150 Some(workspace_id),
9151 project_handle.clone(),
9152 app_state.clone(),
9153 window,
9154 cx,
9155 );
9156 workspace.centered_layout = centered_layout;
9157 workspace
9158 });
9159 multi_workspace.add_workspace(workspace.clone(), cx);
9160 workspace
9161 })?;
9162 (window, workspace)
9163 } else {
9164 let window_bounds_override = window_bounds_env_override();
9165
9166 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
9167 (Some(WindowBounds::Windowed(bounds)), None)
9168 } else if let Some(display) = serialized_workspace.display
9169 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
9170 {
9171 (Some(bounds.0), Some(display))
9172 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
9173 (Some(bounds), Some(display))
9174 } else {
9175 (None, None)
9176 };
9177
9178 let options = cx.update(|cx| {
9179 let mut options = (app_state.build_window_options)(display, cx);
9180 options.window_bounds = window_bounds;
9181 options
9182 });
9183
9184 let window = cx.open_window(options, {
9185 let app_state = app_state.clone();
9186 let project_handle = project_handle.clone();
9187 move |window, cx| {
9188 let workspace = cx.new(|cx| {
9189 let mut workspace = Workspace::new(
9190 Some(workspace_id),
9191 project_handle,
9192 app_state,
9193 window,
9194 cx,
9195 );
9196 workspace.centered_layout = centered_layout;
9197 workspace
9198 });
9199 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9200 }
9201 })?;
9202
9203 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9204 multi_workspace.workspace().clone()
9205 })?;
9206
9207 (window, workspace)
9208 };
9209
9210 notify_if_database_failed(window, cx);
9211
9212 // Restore items from the serialized workspace
9213 window
9214 .update(cx, |_, window, cx| {
9215 workspace.update(cx, |_workspace, cx| {
9216 open_items(Some(serialized_workspace), vec![], window, cx)
9217 })
9218 })?
9219 .await?;
9220
9221 window.update(cx, |_, window, cx| {
9222 workspace.update(cx, |workspace, cx| {
9223 workspace.serialize_workspace(window, cx);
9224 });
9225 })?;
9226
9227 Ok(window)
9228 })
9229}
9230
9231#[allow(clippy::type_complexity)]
9232pub fn open_paths(
9233 abs_paths: &[PathBuf],
9234 app_state: Arc<AppState>,
9235 open_options: OpenOptions,
9236 cx: &mut App,
9237) -> Task<anyhow::Result<OpenResult>> {
9238 let abs_paths = abs_paths.to_vec();
9239 #[cfg(target_os = "windows")]
9240 let wsl_path = abs_paths
9241 .iter()
9242 .find_map(|p| util::paths::WslPath::from_path(p));
9243
9244 cx.spawn(async move |cx| {
9245 let (mut existing, mut open_visible) = find_existing_workspace(
9246 &abs_paths,
9247 &open_options,
9248 &SerializedWorkspaceLocation::Local,
9249 cx,
9250 )
9251 .await;
9252
9253 // Fallback: if no workspace contains the paths and all paths are files,
9254 // prefer an existing local workspace window (active window first).
9255 if open_options.open_new_workspace.is_none() && existing.is_none() {
9256 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9257 let all_metadatas = futures::future::join_all(all_paths)
9258 .await
9259 .into_iter()
9260 .filter_map(|result| result.ok().flatten())
9261 .collect::<Vec<_>>();
9262
9263 if all_metadatas.iter().all(|file| !file.is_dir) {
9264 cx.update(|cx| {
9265 let windows = workspace_windows_for_location(
9266 &SerializedWorkspaceLocation::Local,
9267 cx,
9268 );
9269 let window = cx
9270 .active_window()
9271 .and_then(|window| window.downcast::<MultiWorkspace>())
9272 .filter(|window| windows.contains(window))
9273 .or_else(|| windows.into_iter().next());
9274 if let Some(window) = window {
9275 if let Ok(multi_workspace) = window.read(cx) {
9276 let active_workspace = multi_workspace.workspace().clone();
9277 existing = Some((window, active_workspace));
9278 open_visible = OpenVisible::None;
9279 }
9280 }
9281 });
9282 }
9283 }
9284
9285 let result = if let Some((existing, target_workspace)) = existing {
9286 let open_task = existing
9287 .update(cx, |multi_workspace, window, cx| {
9288 window.activate_window();
9289 multi_workspace.activate(target_workspace.clone(), cx);
9290 target_workspace.update(cx, |workspace, cx| {
9291 workspace.open_paths(
9292 abs_paths,
9293 OpenOptions {
9294 visible: Some(open_visible),
9295 ..Default::default()
9296 },
9297 None,
9298 window,
9299 cx,
9300 )
9301 })
9302 })?
9303 .await;
9304
9305 _ = existing.update(cx, |multi_workspace, _, cx| {
9306 let workspace = multi_workspace.workspace().clone();
9307 workspace.update(cx, |workspace, cx| {
9308 for item in open_task.iter().flatten() {
9309 if let Err(e) = item {
9310 workspace.show_error(&e, cx);
9311 }
9312 }
9313 });
9314 });
9315
9316 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9317 } else {
9318 let result = cx
9319 .update(move |cx| {
9320 Workspace::new_local(
9321 abs_paths,
9322 app_state.clone(),
9323 open_options.replace_window,
9324 open_options.env,
9325 None,
9326 true,
9327 cx,
9328 )
9329 })
9330 .await;
9331
9332 if let Ok(ref result) = result {
9333 result.window
9334 .update(cx, |_, window, _cx| {
9335 window.activate_window();
9336 })
9337 .log_err();
9338 }
9339
9340 result
9341 };
9342
9343 #[cfg(target_os = "windows")]
9344 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9345 && let Ok(ref result) = result
9346 {
9347 result.window
9348 .update(cx, move |multi_workspace, _window, cx| {
9349 struct OpenInWsl;
9350 let workspace = multi_workspace.workspace().clone();
9351 workspace.update(cx, |workspace, cx| {
9352 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9353 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9354 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9355 cx.new(move |cx| {
9356 MessageNotification::new(msg, cx)
9357 .primary_message("Open in WSL")
9358 .primary_icon(IconName::FolderOpen)
9359 .primary_on_click(move |window, cx| {
9360 window.dispatch_action(Box::new(remote::OpenWslPath {
9361 distro: remote::WslConnectionOptions {
9362 distro_name: distro.clone(),
9363 user: None,
9364 },
9365 paths: vec![path.clone().into()],
9366 }), cx)
9367 })
9368 })
9369 });
9370 });
9371 })
9372 .unwrap();
9373 };
9374 result
9375 })
9376}
9377
9378pub fn open_new(
9379 open_options: OpenOptions,
9380 app_state: Arc<AppState>,
9381 cx: &mut App,
9382 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9383) -> Task<anyhow::Result<()>> {
9384 let task = Workspace::new_local(
9385 Vec::new(),
9386 app_state,
9387 open_options.replace_window,
9388 open_options.env,
9389 Some(Box::new(init)),
9390 true,
9391 cx,
9392 );
9393 cx.spawn(async move |cx| {
9394 let OpenResult { window, .. } = task.await?;
9395 window
9396 .update(cx, |_, window, _cx| {
9397 window.activate_window();
9398 })
9399 .ok();
9400 Ok(())
9401 })
9402}
9403
9404pub fn create_and_open_local_file(
9405 path: &'static Path,
9406 window: &mut Window,
9407 cx: &mut Context<Workspace>,
9408 default_content: impl 'static + Send + FnOnce() -> Rope,
9409) -> Task<Result<Box<dyn ItemHandle>>> {
9410 cx.spawn_in(window, async move |workspace, cx| {
9411 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9412 if !fs.is_file(path).await {
9413 fs.create_file(path, Default::default()).await?;
9414 fs.save(path, &default_content(), Default::default())
9415 .await?;
9416 }
9417
9418 workspace
9419 .update_in(cx, |workspace, window, cx| {
9420 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9421 let path = workspace
9422 .project
9423 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9424 cx.spawn_in(window, async move |workspace, cx| {
9425 let path = path.await?;
9426
9427 let path = fs.canonicalize(&path).await.unwrap_or(path);
9428
9429 let mut items = workspace
9430 .update_in(cx, |workspace, window, cx| {
9431 workspace.open_paths(
9432 vec![path.to_path_buf()],
9433 OpenOptions {
9434 visible: Some(OpenVisible::None),
9435 ..Default::default()
9436 },
9437 None,
9438 window,
9439 cx,
9440 )
9441 })?
9442 .await;
9443 let item = items.pop().flatten();
9444 item.with_context(|| format!("path {path:?} is not a file"))?
9445 })
9446 })
9447 })?
9448 .await?
9449 .await
9450 })
9451}
9452
9453pub fn open_remote_project_with_new_connection(
9454 window: WindowHandle<MultiWorkspace>,
9455 remote_connection: Arc<dyn RemoteConnection>,
9456 cancel_rx: oneshot::Receiver<()>,
9457 delegate: Arc<dyn RemoteClientDelegate>,
9458 app_state: Arc<AppState>,
9459 paths: Vec<PathBuf>,
9460 cx: &mut App,
9461) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9462 cx.spawn(async move |cx| {
9463 let (workspace_id, serialized_workspace) =
9464 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9465 .await?;
9466
9467 let session = match cx
9468 .update(|cx| {
9469 remote::RemoteClient::new(
9470 ConnectionIdentifier::Workspace(workspace_id.0),
9471 remote_connection,
9472 cancel_rx,
9473 delegate,
9474 cx,
9475 )
9476 })
9477 .await?
9478 {
9479 Some(result) => result,
9480 None => return Ok(Vec::new()),
9481 };
9482
9483 let project = cx.update(|cx| {
9484 project::Project::remote(
9485 session,
9486 app_state.client.clone(),
9487 app_state.node_runtime.clone(),
9488 app_state.user_store.clone(),
9489 app_state.languages.clone(),
9490 app_state.fs.clone(),
9491 true,
9492 cx,
9493 )
9494 });
9495
9496 open_remote_project_inner(
9497 project,
9498 paths,
9499 workspace_id,
9500 serialized_workspace,
9501 app_state,
9502 window,
9503 cx,
9504 )
9505 .await
9506 })
9507}
9508
9509pub fn open_remote_project_with_existing_connection(
9510 connection_options: RemoteConnectionOptions,
9511 project: Entity<Project>,
9512 paths: Vec<PathBuf>,
9513 app_state: Arc<AppState>,
9514 window: WindowHandle<MultiWorkspace>,
9515 cx: &mut AsyncApp,
9516) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9517 cx.spawn(async move |cx| {
9518 let (workspace_id, serialized_workspace) =
9519 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9520
9521 open_remote_project_inner(
9522 project,
9523 paths,
9524 workspace_id,
9525 serialized_workspace,
9526 app_state,
9527 window,
9528 cx,
9529 )
9530 .await
9531 })
9532}
9533
9534async fn open_remote_project_inner(
9535 project: Entity<Project>,
9536 paths: Vec<PathBuf>,
9537 workspace_id: WorkspaceId,
9538 serialized_workspace: Option<SerializedWorkspace>,
9539 app_state: Arc<AppState>,
9540 window: WindowHandle<MultiWorkspace>,
9541 cx: &mut AsyncApp,
9542) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9543 let db = cx.update(|cx| WorkspaceDb::global(cx));
9544 let toolchains = db.toolchains(workspace_id).await?;
9545 for (toolchain, worktree_path, path) in toolchains {
9546 project
9547 .update(cx, |this, cx| {
9548 let Some(worktree_id) =
9549 this.find_worktree(&worktree_path, cx)
9550 .and_then(|(worktree, rel_path)| {
9551 if rel_path.is_empty() {
9552 Some(worktree.read(cx).id())
9553 } else {
9554 None
9555 }
9556 })
9557 else {
9558 return Task::ready(None);
9559 };
9560
9561 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9562 })
9563 .await;
9564 }
9565 let mut project_paths_to_open = vec![];
9566 let mut project_path_errors = vec![];
9567
9568 for path in paths {
9569 let result = cx
9570 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9571 .await;
9572 match result {
9573 Ok((_, project_path)) => {
9574 project_paths_to_open.push((path.clone(), Some(project_path)));
9575 }
9576 Err(error) => {
9577 project_path_errors.push(error);
9578 }
9579 };
9580 }
9581
9582 if project_paths_to_open.is_empty() {
9583 return Err(project_path_errors.pop().context("no paths given")?);
9584 }
9585
9586 let workspace = window.update(cx, |multi_workspace, window, cx| {
9587 telemetry::event!("SSH Project Opened");
9588
9589 let new_workspace = cx.new(|cx| {
9590 let mut workspace =
9591 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9592 workspace.update_history(cx);
9593
9594 if let Some(ref serialized) = serialized_workspace {
9595 workspace.centered_layout = serialized.centered_layout;
9596 }
9597
9598 workspace
9599 });
9600
9601 multi_workspace.activate(new_workspace.clone(), cx);
9602 new_workspace
9603 })?;
9604
9605 let items = window
9606 .update(cx, |_, window, cx| {
9607 window.activate_window();
9608 workspace.update(cx, |_workspace, cx| {
9609 open_items(serialized_workspace, project_paths_to_open, window, cx)
9610 })
9611 })?
9612 .await?;
9613
9614 workspace.update(cx, |workspace, cx| {
9615 for error in project_path_errors {
9616 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9617 if let Some(path) = error.error_tag("path") {
9618 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9619 }
9620 } else {
9621 workspace.show_error(&error, cx)
9622 }
9623 }
9624 });
9625
9626 Ok(items.into_iter().map(|item| item?.ok()).collect())
9627}
9628
9629fn deserialize_remote_project(
9630 connection_options: RemoteConnectionOptions,
9631 paths: Vec<PathBuf>,
9632 cx: &AsyncApp,
9633) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9634 let db = cx.update(|cx| WorkspaceDb::global(cx));
9635 cx.background_spawn(async move {
9636 let remote_connection_id = db
9637 .get_or_create_remote_connection(connection_options)
9638 .await?;
9639
9640 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9641
9642 let workspace_id = if let Some(workspace_id) =
9643 serialized_workspace.as_ref().map(|workspace| workspace.id)
9644 {
9645 workspace_id
9646 } else {
9647 db.next_id().await?
9648 };
9649
9650 Ok((workspace_id, serialized_workspace))
9651 })
9652}
9653
9654pub fn join_in_room_project(
9655 project_id: u64,
9656 follow_user_id: u64,
9657 app_state: Arc<AppState>,
9658 cx: &mut App,
9659) -> Task<Result<()>> {
9660 let windows = cx.windows();
9661 cx.spawn(async move |cx| {
9662 let existing_window_and_workspace: Option<(
9663 WindowHandle<MultiWorkspace>,
9664 Entity<Workspace>,
9665 )> = windows.into_iter().find_map(|window_handle| {
9666 window_handle
9667 .downcast::<MultiWorkspace>()
9668 .and_then(|window_handle| {
9669 window_handle
9670 .update(cx, |multi_workspace, _window, cx| {
9671 for workspace in multi_workspace.workspaces() {
9672 if workspace.read(cx).project().read(cx).remote_id()
9673 == Some(project_id)
9674 {
9675 return Some((window_handle, workspace.clone()));
9676 }
9677 }
9678 None
9679 })
9680 .unwrap_or(None)
9681 })
9682 });
9683
9684 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9685 existing_window_and_workspace
9686 {
9687 existing_window
9688 .update(cx, |multi_workspace, _, cx| {
9689 multi_workspace.activate(target_workspace, cx);
9690 })
9691 .ok();
9692 existing_window
9693 } else {
9694 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9695 let project = cx
9696 .update(|cx| {
9697 active_call.0.join_project(
9698 project_id,
9699 app_state.languages.clone(),
9700 app_state.fs.clone(),
9701 cx,
9702 )
9703 })
9704 .await?;
9705
9706 let window_bounds_override = window_bounds_env_override();
9707 cx.update(|cx| {
9708 let mut options = (app_state.build_window_options)(None, cx);
9709 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9710 cx.open_window(options, |window, cx| {
9711 let workspace = cx.new(|cx| {
9712 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9713 });
9714 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9715 })
9716 })?
9717 };
9718
9719 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9720 cx.activate(true);
9721 window.activate_window();
9722
9723 // We set the active workspace above, so this is the correct workspace.
9724 let workspace = multi_workspace.workspace().clone();
9725 workspace.update(cx, |workspace, cx| {
9726 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9727 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9728 .or_else(|| {
9729 // If we couldn't follow the given user, follow the host instead.
9730 let collaborator = workspace
9731 .project()
9732 .read(cx)
9733 .collaborators()
9734 .values()
9735 .find(|collaborator| collaborator.is_host)?;
9736 Some(collaborator.peer_id)
9737 });
9738
9739 if let Some(follow_peer_id) = follow_peer_id {
9740 workspace.follow(follow_peer_id, window, cx);
9741 }
9742 });
9743 })?;
9744
9745 anyhow::Ok(())
9746 })
9747}
9748
9749pub fn reload(cx: &mut App) {
9750 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9751 let mut workspace_windows = cx
9752 .windows()
9753 .into_iter()
9754 .filter_map(|window| window.downcast::<MultiWorkspace>())
9755 .collect::<Vec<_>>();
9756
9757 // If multiple windows have unsaved changes, and need a save prompt,
9758 // prompt in the active window before switching to a different window.
9759 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9760
9761 let mut prompt = None;
9762 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9763 prompt = window
9764 .update(cx, |_, window, cx| {
9765 window.prompt(
9766 PromptLevel::Info,
9767 "Are you sure you want to restart?",
9768 None,
9769 &["Restart", "Cancel"],
9770 cx,
9771 )
9772 })
9773 .ok();
9774 }
9775
9776 cx.spawn(async move |cx| {
9777 if let Some(prompt) = prompt {
9778 let answer = prompt.await?;
9779 if answer != 0 {
9780 return anyhow::Ok(());
9781 }
9782 }
9783
9784 // If the user cancels any save prompt, then keep the app open.
9785 for window in workspace_windows {
9786 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9787 let workspace = multi_workspace.workspace().clone();
9788 workspace.update(cx, |workspace, cx| {
9789 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9790 })
9791 }) && !should_close.await?
9792 {
9793 return anyhow::Ok(());
9794 }
9795 }
9796 cx.update(|cx| cx.restart());
9797 anyhow::Ok(())
9798 })
9799 .detach_and_log_err(cx);
9800}
9801
9802fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9803 let mut parts = value.split(',');
9804 let x: usize = parts.next()?.parse().ok()?;
9805 let y: usize = parts.next()?.parse().ok()?;
9806 Some(point(px(x as f32), px(y as f32)))
9807}
9808
9809fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9810 let mut parts = value.split(',');
9811 let width: usize = parts.next()?.parse().ok()?;
9812 let height: usize = parts.next()?.parse().ok()?;
9813 Some(size(px(width as f32), px(height as f32)))
9814}
9815
9816/// Add client-side decorations (rounded corners, shadows, resize handling) when
9817/// appropriate.
9818///
9819/// The `border_radius_tiling` parameter allows overriding which corners get
9820/// rounded, independently of the actual window tiling state. This is used
9821/// specifically for the workspace switcher sidebar: when the sidebar is open,
9822/// we want square corners on the left (so the sidebar appears flush with the
9823/// window edge) but we still need the shadow padding for proper visual
9824/// appearance. Unlike actual window tiling, this only affects border radius -
9825/// not padding or shadows.
9826pub fn client_side_decorations(
9827 element: impl IntoElement,
9828 window: &mut Window,
9829 cx: &mut App,
9830 border_radius_tiling: Tiling,
9831) -> Stateful<Div> {
9832 const BORDER_SIZE: Pixels = px(1.0);
9833 let decorations = window.window_decorations();
9834 let tiling = match decorations {
9835 Decorations::Server => Tiling::default(),
9836 Decorations::Client { tiling } => tiling,
9837 };
9838
9839 match decorations {
9840 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9841 Decorations::Server => window.set_client_inset(px(0.0)),
9842 }
9843
9844 struct GlobalResizeEdge(ResizeEdge);
9845 impl Global for GlobalResizeEdge {}
9846
9847 div()
9848 .id("window-backdrop")
9849 .bg(transparent_black())
9850 .map(|div| match decorations {
9851 Decorations::Server => div,
9852 Decorations::Client { .. } => div
9853 .when(
9854 !(tiling.top
9855 || tiling.right
9856 || border_radius_tiling.top
9857 || border_radius_tiling.right),
9858 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9859 )
9860 .when(
9861 !(tiling.top
9862 || tiling.left
9863 || border_radius_tiling.top
9864 || border_radius_tiling.left),
9865 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9866 )
9867 .when(
9868 !(tiling.bottom
9869 || tiling.right
9870 || border_radius_tiling.bottom
9871 || border_radius_tiling.right),
9872 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9873 )
9874 .when(
9875 !(tiling.bottom
9876 || tiling.left
9877 || border_radius_tiling.bottom
9878 || border_radius_tiling.left),
9879 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9880 )
9881 .when(!tiling.top, |div| {
9882 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9883 })
9884 .when(!tiling.bottom, |div| {
9885 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9886 })
9887 .when(!tiling.left, |div| {
9888 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9889 })
9890 .when(!tiling.right, |div| {
9891 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9892 })
9893 .on_mouse_move(move |e, window, cx| {
9894 let size = window.window_bounds().get_bounds().size;
9895 let pos = e.position;
9896
9897 let new_edge =
9898 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9899
9900 let edge = cx.try_global::<GlobalResizeEdge>();
9901 if new_edge != edge.map(|edge| edge.0) {
9902 window
9903 .window_handle()
9904 .update(cx, |workspace, _, cx| {
9905 cx.notify(workspace.entity_id());
9906 })
9907 .ok();
9908 }
9909 })
9910 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9911 let size = window.window_bounds().get_bounds().size;
9912 let pos = e.position;
9913
9914 let edge = match resize_edge(
9915 pos,
9916 theme::CLIENT_SIDE_DECORATION_SHADOW,
9917 size,
9918 tiling,
9919 ) {
9920 Some(value) => value,
9921 None => return,
9922 };
9923
9924 window.start_window_resize(edge);
9925 }),
9926 })
9927 .size_full()
9928 .child(
9929 div()
9930 .cursor(CursorStyle::Arrow)
9931 .map(|div| match decorations {
9932 Decorations::Server => div,
9933 Decorations::Client { .. } => div
9934 .border_color(cx.theme().colors().border)
9935 .when(
9936 !(tiling.top
9937 || tiling.right
9938 || border_radius_tiling.top
9939 || border_radius_tiling.right),
9940 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9941 )
9942 .when(
9943 !(tiling.top
9944 || tiling.left
9945 || border_radius_tiling.top
9946 || border_radius_tiling.left),
9947 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9948 )
9949 .when(
9950 !(tiling.bottom
9951 || tiling.right
9952 || border_radius_tiling.bottom
9953 || border_radius_tiling.right),
9954 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9955 )
9956 .when(
9957 !(tiling.bottom
9958 || tiling.left
9959 || border_radius_tiling.bottom
9960 || border_radius_tiling.left),
9961 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9962 )
9963 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9964 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9965 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9966 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9967 .when(!tiling.is_tiled(), |div| {
9968 div.shadow(vec![gpui::BoxShadow {
9969 color: Hsla {
9970 h: 0.,
9971 s: 0.,
9972 l: 0.,
9973 a: 0.4,
9974 },
9975 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9976 spread_radius: px(0.),
9977 offset: point(px(0.0), px(0.0)),
9978 }])
9979 }),
9980 })
9981 .on_mouse_move(|_e, _, cx| {
9982 cx.stop_propagation();
9983 })
9984 .size_full()
9985 .child(element),
9986 )
9987 .map(|div| match decorations {
9988 Decorations::Server => div,
9989 Decorations::Client { tiling, .. } => div.child(
9990 canvas(
9991 |_bounds, window, _| {
9992 window.insert_hitbox(
9993 Bounds::new(
9994 point(px(0.0), px(0.0)),
9995 window.window_bounds().get_bounds().size,
9996 ),
9997 HitboxBehavior::Normal,
9998 )
9999 },
10000 move |_bounds, hitbox, window, cx| {
10001 let mouse = window.mouse_position();
10002 let size = window.window_bounds().get_bounds().size;
10003 let Some(edge) =
10004 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10005 else {
10006 return;
10007 };
10008 cx.set_global(GlobalResizeEdge(edge));
10009 window.set_cursor_style(
10010 match edge {
10011 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10012 ResizeEdge::Left | ResizeEdge::Right => {
10013 CursorStyle::ResizeLeftRight
10014 }
10015 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10016 CursorStyle::ResizeUpLeftDownRight
10017 }
10018 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10019 CursorStyle::ResizeUpRightDownLeft
10020 }
10021 },
10022 &hitbox,
10023 );
10024 },
10025 )
10026 .size_full()
10027 .absolute(),
10028 ),
10029 })
10030}
10031
10032fn resize_edge(
10033 pos: Point<Pixels>,
10034 shadow_size: Pixels,
10035 window_size: Size<Pixels>,
10036 tiling: Tiling,
10037) -> Option<ResizeEdge> {
10038 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10039 if bounds.contains(&pos) {
10040 return None;
10041 }
10042
10043 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10044 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10045 if !tiling.top && top_left_bounds.contains(&pos) {
10046 return Some(ResizeEdge::TopLeft);
10047 }
10048
10049 let top_right_bounds = Bounds::new(
10050 Point::new(window_size.width - corner_size.width, px(0.)),
10051 corner_size,
10052 );
10053 if !tiling.top && top_right_bounds.contains(&pos) {
10054 return Some(ResizeEdge::TopRight);
10055 }
10056
10057 let bottom_left_bounds = Bounds::new(
10058 Point::new(px(0.), window_size.height - corner_size.height),
10059 corner_size,
10060 );
10061 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10062 return Some(ResizeEdge::BottomLeft);
10063 }
10064
10065 let bottom_right_bounds = Bounds::new(
10066 Point::new(
10067 window_size.width - corner_size.width,
10068 window_size.height - corner_size.height,
10069 ),
10070 corner_size,
10071 );
10072 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10073 return Some(ResizeEdge::BottomRight);
10074 }
10075
10076 if !tiling.top && pos.y < shadow_size {
10077 Some(ResizeEdge::Top)
10078 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10079 Some(ResizeEdge::Bottom)
10080 } else if !tiling.left && pos.x < shadow_size {
10081 Some(ResizeEdge::Left)
10082 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10083 Some(ResizeEdge::Right)
10084 } else {
10085 None
10086 }
10087}
10088
10089fn join_pane_into_active(
10090 active_pane: &Entity<Pane>,
10091 pane: &Entity<Pane>,
10092 window: &mut Window,
10093 cx: &mut App,
10094) {
10095 if pane == active_pane {
10096 } else if pane.read(cx).items_len() == 0 {
10097 pane.update(cx, |_, cx| {
10098 cx.emit(pane::Event::Remove {
10099 focus_on_pane: None,
10100 });
10101 })
10102 } else {
10103 move_all_items(pane, active_pane, window, cx);
10104 }
10105}
10106
10107fn move_all_items(
10108 from_pane: &Entity<Pane>,
10109 to_pane: &Entity<Pane>,
10110 window: &mut Window,
10111 cx: &mut App,
10112) {
10113 let destination_is_different = from_pane != to_pane;
10114 let mut moved_items = 0;
10115 for (item_ix, item_handle) in from_pane
10116 .read(cx)
10117 .items()
10118 .enumerate()
10119 .map(|(ix, item)| (ix, item.clone()))
10120 .collect::<Vec<_>>()
10121 {
10122 let ix = item_ix - moved_items;
10123 if destination_is_different {
10124 // Close item from previous pane
10125 from_pane.update(cx, |source, cx| {
10126 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10127 });
10128 moved_items += 1;
10129 }
10130
10131 // This automatically removes duplicate items in the pane
10132 to_pane.update(cx, |destination, cx| {
10133 destination.add_item(item_handle, true, true, None, window, cx);
10134 window.focus(&destination.focus_handle(cx), cx)
10135 });
10136 }
10137}
10138
10139pub fn move_item(
10140 source: &Entity<Pane>,
10141 destination: &Entity<Pane>,
10142 item_id_to_move: EntityId,
10143 destination_index: usize,
10144 activate: bool,
10145 window: &mut Window,
10146 cx: &mut App,
10147) {
10148 let Some((item_ix, item_handle)) = source
10149 .read(cx)
10150 .items()
10151 .enumerate()
10152 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10153 .map(|(ix, item)| (ix, item.clone()))
10154 else {
10155 // Tab was closed during drag
10156 return;
10157 };
10158
10159 if source != destination {
10160 // Close item from previous pane
10161 source.update(cx, |source, cx| {
10162 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10163 });
10164 }
10165
10166 // This automatically removes duplicate items in the pane
10167 destination.update(cx, |destination, cx| {
10168 destination.add_item_inner(
10169 item_handle,
10170 activate,
10171 activate,
10172 activate,
10173 Some(destination_index),
10174 window,
10175 cx,
10176 );
10177 if activate {
10178 window.focus(&destination.focus_handle(cx), cx)
10179 }
10180 });
10181}
10182
10183pub fn move_active_item(
10184 source: &Entity<Pane>,
10185 destination: &Entity<Pane>,
10186 focus_destination: bool,
10187 close_if_empty: bool,
10188 window: &mut Window,
10189 cx: &mut App,
10190) {
10191 if source == destination {
10192 return;
10193 }
10194 let Some(active_item) = source.read(cx).active_item() else {
10195 return;
10196 };
10197 source.update(cx, |source_pane, cx| {
10198 let item_id = active_item.item_id();
10199 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10200 destination.update(cx, |target_pane, cx| {
10201 target_pane.add_item(
10202 active_item,
10203 focus_destination,
10204 focus_destination,
10205 Some(target_pane.items_len()),
10206 window,
10207 cx,
10208 );
10209 });
10210 });
10211}
10212
10213pub fn clone_active_item(
10214 workspace_id: Option<WorkspaceId>,
10215 source: &Entity<Pane>,
10216 destination: &Entity<Pane>,
10217 focus_destination: bool,
10218 window: &mut Window,
10219 cx: &mut App,
10220) {
10221 if source == destination {
10222 return;
10223 }
10224 let Some(active_item) = source.read(cx).active_item() else {
10225 return;
10226 };
10227 if !active_item.can_split(cx) {
10228 return;
10229 }
10230 let destination = destination.downgrade();
10231 let task = active_item.clone_on_split(workspace_id, window, cx);
10232 window
10233 .spawn(cx, async move |cx| {
10234 let Some(clone) = task.await else {
10235 return;
10236 };
10237 destination
10238 .update_in(cx, |target_pane, window, cx| {
10239 target_pane.add_item(
10240 clone,
10241 focus_destination,
10242 focus_destination,
10243 Some(target_pane.items_len()),
10244 window,
10245 cx,
10246 );
10247 })
10248 .log_err();
10249 })
10250 .detach();
10251}
10252
10253#[derive(Debug)]
10254pub struct WorkspacePosition {
10255 pub window_bounds: Option<WindowBounds>,
10256 pub display: Option<Uuid>,
10257 pub centered_layout: bool,
10258}
10259
10260pub fn remote_workspace_position_from_db(
10261 connection_options: RemoteConnectionOptions,
10262 paths_to_open: &[PathBuf],
10263 cx: &App,
10264) -> Task<Result<WorkspacePosition>> {
10265 let paths = paths_to_open.to_vec();
10266 let db = WorkspaceDb::global(cx);
10267 let kvp = db::kvp::KeyValueStore::global(cx);
10268
10269 cx.background_spawn(async move {
10270 let remote_connection_id = db
10271 .get_or_create_remote_connection(connection_options)
10272 .await
10273 .context("fetching serialized ssh project")?;
10274 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10275
10276 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10277 (Some(WindowBounds::Windowed(bounds)), None)
10278 } else {
10279 let restorable_bounds = serialized_workspace
10280 .as_ref()
10281 .and_then(|workspace| {
10282 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10283 })
10284 .or_else(|| persistence::read_default_window_bounds(&kvp));
10285
10286 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10287 (Some(serialized_bounds), Some(serialized_display))
10288 } else {
10289 (None, None)
10290 }
10291 };
10292
10293 let centered_layout = serialized_workspace
10294 .as_ref()
10295 .map(|w| w.centered_layout)
10296 .unwrap_or(false);
10297
10298 Ok(WorkspacePosition {
10299 window_bounds,
10300 display,
10301 centered_layout,
10302 })
10303 })
10304}
10305
10306pub fn with_active_or_new_workspace(
10307 cx: &mut App,
10308 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10309) {
10310 match cx
10311 .active_window()
10312 .and_then(|w| w.downcast::<MultiWorkspace>())
10313 {
10314 Some(multi_workspace) => {
10315 cx.defer(move |cx| {
10316 multi_workspace
10317 .update(cx, |multi_workspace, window, cx| {
10318 let workspace = multi_workspace.workspace().clone();
10319 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10320 })
10321 .log_err();
10322 });
10323 }
10324 None => {
10325 let app_state = AppState::global(cx);
10326 if let Some(app_state) = app_state.upgrade() {
10327 open_new(
10328 OpenOptions::default(),
10329 app_state,
10330 cx,
10331 move |workspace, window, cx| f(workspace, window, cx),
10332 )
10333 .detach_and_log_err(cx);
10334 }
10335 }
10336 }
10337}
10338
10339/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10340/// key. This migration path only runs once per panel per workspace.
10341fn load_legacy_panel_size(
10342 panel_key: &str,
10343 dock_position: DockPosition,
10344 workspace: &Workspace,
10345 cx: &mut App,
10346) -> Option<Pixels> {
10347 #[derive(Deserialize)]
10348 struct LegacyPanelState {
10349 #[serde(default)]
10350 width: Option<Pixels>,
10351 #[serde(default)]
10352 height: Option<Pixels>,
10353 }
10354
10355 let workspace_id = workspace
10356 .database_id()
10357 .map(|id| i64::from(id).to_string())
10358 .or_else(|| workspace.session_id())?;
10359
10360 let legacy_key = match panel_key {
10361 "ProjectPanel" => {
10362 format!("{}-{:?}", "ProjectPanel", workspace_id)
10363 }
10364 "OutlinePanel" => {
10365 format!("{}-{:?}", "OutlinePanel", workspace_id)
10366 }
10367 "GitPanel" => {
10368 format!("{}-{:?}", "GitPanel", workspace_id)
10369 }
10370 "TerminalPanel" => {
10371 format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10372 }
10373 _ => return None,
10374 };
10375
10376 let kvp = db::kvp::KeyValueStore::global(cx);
10377 let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10378 let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10379 let size = match dock_position {
10380 DockPosition::Bottom => state.height,
10381 DockPosition::Left | DockPosition::Right => state.width,
10382 }?;
10383
10384 cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10385 .detach_and_log_err(cx);
10386
10387 Some(size)
10388}
10389
10390#[cfg(test)]
10391mod tests {
10392 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10393
10394 use super::*;
10395 use crate::{
10396 dock::{PanelEvent, test::TestPanel},
10397 item::{
10398 ItemBufferKind, ItemEvent,
10399 test::{TestItem, TestProjectItem},
10400 },
10401 };
10402 use fs::FakeFs;
10403 use gpui::{
10404 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10405 UpdateGlobal, VisualTestContext, px,
10406 };
10407 use project::{Project, ProjectEntryId};
10408 use serde_json::json;
10409 use settings::SettingsStore;
10410 use util::path;
10411 use util::rel_path::rel_path;
10412
10413 #[gpui::test]
10414 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10415 init_test(cx);
10416
10417 let fs = FakeFs::new(cx.executor());
10418 let project = Project::test(fs, [], cx).await;
10419 let (workspace, cx) =
10420 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10421
10422 // Adding an item with no ambiguity renders the tab without detail.
10423 let item1 = cx.new(|cx| {
10424 let mut item = TestItem::new(cx);
10425 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10426 item
10427 });
10428 workspace.update_in(cx, |workspace, window, cx| {
10429 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10430 });
10431 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10432
10433 // Adding an item that creates ambiguity increases the level of detail on
10434 // both tabs.
10435 let item2 = cx.new_window_entity(|_window, cx| {
10436 let mut item = TestItem::new(cx);
10437 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10438 item
10439 });
10440 workspace.update_in(cx, |workspace, window, cx| {
10441 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10442 });
10443 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10444 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10445
10446 // Adding an item that creates ambiguity increases the level of detail only
10447 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10448 // we stop at the highest detail available.
10449 let item3 = cx.new(|cx| {
10450 let mut item = TestItem::new(cx);
10451 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10452 item
10453 });
10454 workspace.update_in(cx, |workspace, window, cx| {
10455 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10456 });
10457 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10458 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10459 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10460 }
10461
10462 #[gpui::test]
10463 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10464 init_test(cx);
10465
10466 let fs = FakeFs::new(cx.executor());
10467 fs.insert_tree(
10468 "/root1",
10469 json!({
10470 "one.txt": "",
10471 "two.txt": "",
10472 }),
10473 )
10474 .await;
10475 fs.insert_tree(
10476 "/root2",
10477 json!({
10478 "three.txt": "",
10479 }),
10480 )
10481 .await;
10482
10483 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10484 let (workspace, cx) =
10485 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10486 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10487 let worktree_id = project.update(cx, |project, cx| {
10488 project.worktrees(cx).next().unwrap().read(cx).id()
10489 });
10490
10491 let item1 = cx.new(|cx| {
10492 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10493 });
10494 let item2 = cx.new(|cx| {
10495 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10496 });
10497
10498 // Add an item to an empty pane
10499 workspace.update_in(cx, |workspace, window, cx| {
10500 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10501 });
10502 project.update(cx, |project, cx| {
10503 assert_eq!(
10504 project.active_entry(),
10505 project
10506 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10507 .map(|e| e.id)
10508 );
10509 });
10510 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10511
10512 // Add a second item to a non-empty pane
10513 workspace.update_in(cx, |workspace, window, cx| {
10514 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10515 });
10516 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10517 project.update(cx, |project, cx| {
10518 assert_eq!(
10519 project.active_entry(),
10520 project
10521 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10522 .map(|e| e.id)
10523 );
10524 });
10525
10526 // Close the active item
10527 pane.update_in(cx, |pane, window, cx| {
10528 pane.close_active_item(&Default::default(), window, cx)
10529 })
10530 .await
10531 .unwrap();
10532 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10533 project.update(cx, |project, cx| {
10534 assert_eq!(
10535 project.active_entry(),
10536 project
10537 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10538 .map(|e| e.id)
10539 );
10540 });
10541
10542 // Add a project folder
10543 project
10544 .update(cx, |project, cx| {
10545 project.find_or_create_worktree("root2", true, cx)
10546 })
10547 .await
10548 .unwrap();
10549 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10550
10551 // Remove a project folder
10552 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10553 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10554 }
10555
10556 #[gpui::test]
10557 async fn test_close_window(cx: &mut TestAppContext) {
10558 init_test(cx);
10559
10560 let fs = FakeFs::new(cx.executor());
10561 fs.insert_tree("/root", json!({ "one": "" })).await;
10562
10563 let project = Project::test(fs, ["root".as_ref()], cx).await;
10564 let (workspace, cx) =
10565 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10566
10567 // When there are no dirty items, there's nothing to do.
10568 let item1 = cx.new(TestItem::new);
10569 workspace.update_in(cx, |w, window, cx| {
10570 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10571 });
10572 let task = workspace.update_in(cx, |w, window, cx| {
10573 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10574 });
10575 assert!(task.await.unwrap());
10576
10577 // When there are dirty untitled items, prompt to save each one. If the user
10578 // cancels any prompt, then abort.
10579 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10580 let item3 = cx.new(|cx| {
10581 TestItem::new(cx)
10582 .with_dirty(true)
10583 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10584 });
10585 workspace.update_in(cx, |w, window, cx| {
10586 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10587 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10588 });
10589 let task = workspace.update_in(cx, |w, window, cx| {
10590 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10591 });
10592 cx.executor().run_until_parked();
10593 cx.simulate_prompt_answer("Cancel"); // cancel save all
10594 cx.executor().run_until_parked();
10595 assert!(!cx.has_pending_prompt());
10596 assert!(!task.await.unwrap());
10597 }
10598
10599 #[gpui::test]
10600 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10601 init_test(cx);
10602
10603 let fs = FakeFs::new(cx.executor());
10604 fs.insert_tree("/root", json!({ "one": "" })).await;
10605
10606 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10607 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10608 let multi_workspace_handle =
10609 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10610 cx.run_until_parked();
10611
10612 let workspace_a = multi_workspace_handle
10613 .read_with(cx, |mw, _| mw.workspace().clone())
10614 .unwrap();
10615
10616 let workspace_b = multi_workspace_handle
10617 .update(cx, |mw, window, cx| {
10618 mw.test_add_workspace(project_b, window, cx)
10619 })
10620 .unwrap();
10621
10622 // Activate workspace A
10623 multi_workspace_handle
10624 .update(cx, |mw, window, cx| {
10625 mw.activate_index(0, window, cx);
10626 })
10627 .unwrap();
10628
10629 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10630
10631 // Workspace A has a clean item
10632 let item_a = cx.new(TestItem::new);
10633 workspace_a.update_in(cx, |w, window, cx| {
10634 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10635 });
10636
10637 // Workspace B has a dirty item
10638 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10639 workspace_b.update_in(cx, |w, window, cx| {
10640 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10641 });
10642
10643 // Verify workspace A is active
10644 multi_workspace_handle
10645 .read_with(cx, |mw, _| {
10646 assert_eq!(mw.active_workspace_index(), 0);
10647 })
10648 .unwrap();
10649
10650 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10651 multi_workspace_handle
10652 .update(cx, |mw, window, cx| {
10653 mw.close_window(&CloseWindow, window, cx);
10654 })
10655 .unwrap();
10656 cx.run_until_parked();
10657
10658 // Workspace B should now be active since it has dirty items that need attention
10659 multi_workspace_handle
10660 .read_with(cx, |mw, _| {
10661 assert_eq!(
10662 mw.active_workspace_index(),
10663 1,
10664 "workspace B should be activated when it prompts"
10665 );
10666 })
10667 .unwrap();
10668
10669 // User cancels the save prompt from workspace B
10670 cx.simulate_prompt_answer("Cancel");
10671 cx.run_until_parked();
10672
10673 // Window should still exist because workspace B's close was cancelled
10674 assert!(
10675 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10676 "window should still exist after cancelling one workspace's close"
10677 );
10678 }
10679
10680 #[gpui::test]
10681 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10682 init_test(cx);
10683
10684 // Register TestItem as a serializable item
10685 cx.update(|cx| {
10686 register_serializable_item::<TestItem>(cx);
10687 });
10688
10689 let fs = FakeFs::new(cx.executor());
10690 fs.insert_tree("/root", json!({ "one": "" })).await;
10691
10692 let project = Project::test(fs, ["root".as_ref()], cx).await;
10693 let (workspace, cx) =
10694 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10695
10696 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10697 let item1 = cx.new(|cx| {
10698 TestItem::new(cx)
10699 .with_dirty(true)
10700 .with_serialize(|| Some(Task::ready(Ok(()))))
10701 });
10702 let item2 = cx.new(|cx| {
10703 TestItem::new(cx)
10704 .with_dirty(true)
10705 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10706 .with_serialize(|| Some(Task::ready(Ok(()))))
10707 });
10708 workspace.update_in(cx, |w, window, cx| {
10709 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10710 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10711 });
10712 let task = workspace.update_in(cx, |w, window, cx| {
10713 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10714 });
10715 assert!(task.await.unwrap());
10716 }
10717
10718 #[gpui::test]
10719 async fn test_close_pane_items(cx: &mut TestAppContext) {
10720 init_test(cx);
10721
10722 let fs = FakeFs::new(cx.executor());
10723
10724 let project = Project::test(fs, None, cx).await;
10725 let (workspace, cx) =
10726 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10727
10728 let item1 = cx.new(|cx| {
10729 TestItem::new(cx)
10730 .with_dirty(true)
10731 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10732 });
10733 let item2 = cx.new(|cx| {
10734 TestItem::new(cx)
10735 .with_dirty(true)
10736 .with_conflict(true)
10737 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10738 });
10739 let item3 = cx.new(|cx| {
10740 TestItem::new(cx)
10741 .with_dirty(true)
10742 .with_conflict(true)
10743 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10744 });
10745 let item4 = cx.new(|cx| {
10746 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10747 let project_item = TestProjectItem::new_untitled(cx);
10748 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10749 project_item
10750 }])
10751 });
10752 let pane = workspace.update_in(cx, |workspace, window, cx| {
10753 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10754 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10755 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10756 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10757 workspace.active_pane().clone()
10758 });
10759
10760 let close_items = pane.update_in(cx, |pane, window, cx| {
10761 pane.activate_item(1, true, true, window, cx);
10762 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10763 let item1_id = item1.item_id();
10764 let item3_id = item3.item_id();
10765 let item4_id = item4.item_id();
10766 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10767 [item1_id, item3_id, item4_id].contains(&id)
10768 })
10769 });
10770 cx.executor().run_until_parked();
10771
10772 assert!(cx.has_pending_prompt());
10773 cx.simulate_prompt_answer("Save all");
10774
10775 cx.executor().run_until_parked();
10776
10777 // Item 1 is saved. There's a prompt to save item 3.
10778 pane.update(cx, |pane, cx| {
10779 assert_eq!(item1.read(cx).save_count, 1);
10780 assert_eq!(item1.read(cx).save_as_count, 0);
10781 assert_eq!(item1.read(cx).reload_count, 0);
10782 assert_eq!(pane.items_len(), 3);
10783 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10784 });
10785 assert!(cx.has_pending_prompt());
10786
10787 // Cancel saving item 3.
10788 cx.simulate_prompt_answer("Discard");
10789 cx.executor().run_until_parked();
10790
10791 // Item 3 is reloaded. There's a prompt to save item 4.
10792 pane.update(cx, |pane, cx| {
10793 assert_eq!(item3.read(cx).save_count, 0);
10794 assert_eq!(item3.read(cx).save_as_count, 0);
10795 assert_eq!(item3.read(cx).reload_count, 1);
10796 assert_eq!(pane.items_len(), 2);
10797 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10798 });
10799
10800 // There's a prompt for a path for item 4.
10801 cx.simulate_new_path_selection(|_| Some(Default::default()));
10802 close_items.await.unwrap();
10803
10804 // The requested items are closed.
10805 pane.update(cx, |pane, cx| {
10806 assert_eq!(item4.read(cx).save_count, 0);
10807 assert_eq!(item4.read(cx).save_as_count, 1);
10808 assert_eq!(item4.read(cx).reload_count, 0);
10809 assert_eq!(pane.items_len(), 1);
10810 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10811 });
10812 }
10813
10814 #[gpui::test]
10815 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10816 init_test(cx);
10817
10818 let fs = FakeFs::new(cx.executor());
10819 let project = Project::test(fs, [], cx).await;
10820 let (workspace, cx) =
10821 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10822
10823 // Create several workspace items with single project entries, and two
10824 // workspace items with multiple project entries.
10825 let single_entry_items = (0..=4)
10826 .map(|project_entry_id| {
10827 cx.new(|cx| {
10828 TestItem::new(cx)
10829 .with_dirty(true)
10830 .with_project_items(&[dirty_project_item(
10831 project_entry_id,
10832 &format!("{project_entry_id}.txt"),
10833 cx,
10834 )])
10835 })
10836 })
10837 .collect::<Vec<_>>();
10838 let item_2_3 = cx.new(|cx| {
10839 TestItem::new(cx)
10840 .with_dirty(true)
10841 .with_buffer_kind(ItemBufferKind::Multibuffer)
10842 .with_project_items(&[
10843 single_entry_items[2].read(cx).project_items[0].clone(),
10844 single_entry_items[3].read(cx).project_items[0].clone(),
10845 ])
10846 });
10847 let item_3_4 = cx.new(|cx| {
10848 TestItem::new(cx)
10849 .with_dirty(true)
10850 .with_buffer_kind(ItemBufferKind::Multibuffer)
10851 .with_project_items(&[
10852 single_entry_items[3].read(cx).project_items[0].clone(),
10853 single_entry_items[4].read(cx).project_items[0].clone(),
10854 ])
10855 });
10856
10857 // Create two panes that contain the following project entries:
10858 // left pane:
10859 // multi-entry items: (2, 3)
10860 // single-entry items: 0, 2, 3, 4
10861 // right pane:
10862 // single-entry items: 4, 1
10863 // multi-entry items: (3, 4)
10864 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10865 let left_pane = workspace.active_pane().clone();
10866 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10867 workspace.add_item_to_active_pane(
10868 single_entry_items[0].boxed_clone(),
10869 None,
10870 true,
10871 window,
10872 cx,
10873 );
10874 workspace.add_item_to_active_pane(
10875 single_entry_items[2].boxed_clone(),
10876 None,
10877 true,
10878 window,
10879 cx,
10880 );
10881 workspace.add_item_to_active_pane(
10882 single_entry_items[3].boxed_clone(),
10883 None,
10884 true,
10885 window,
10886 cx,
10887 );
10888 workspace.add_item_to_active_pane(
10889 single_entry_items[4].boxed_clone(),
10890 None,
10891 true,
10892 window,
10893 cx,
10894 );
10895
10896 let right_pane =
10897 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10898
10899 let boxed_clone = single_entry_items[1].boxed_clone();
10900 let right_pane = window.spawn(cx, async move |cx| {
10901 right_pane.await.inspect(|right_pane| {
10902 right_pane
10903 .update_in(cx, |pane, window, cx| {
10904 pane.add_item(boxed_clone, true, true, None, window, cx);
10905 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10906 })
10907 .unwrap();
10908 })
10909 });
10910
10911 (left_pane, right_pane)
10912 });
10913 let right_pane = right_pane.await.unwrap();
10914 cx.focus(&right_pane);
10915
10916 let close = right_pane.update_in(cx, |pane, window, cx| {
10917 pane.close_all_items(&CloseAllItems::default(), window, cx)
10918 .unwrap()
10919 });
10920 cx.executor().run_until_parked();
10921
10922 let msg = cx.pending_prompt().unwrap().0;
10923 assert!(msg.contains("1.txt"));
10924 assert!(!msg.contains("2.txt"));
10925 assert!(!msg.contains("3.txt"));
10926 assert!(!msg.contains("4.txt"));
10927
10928 // With best-effort close, cancelling item 1 keeps it open but items 4
10929 // and (3,4) still close since their entries exist in left pane.
10930 cx.simulate_prompt_answer("Cancel");
10931 close.await;
10932
10933 right_pane.read_with(cx, |pane, _| {
10934 assert_eq!(pane.items_len(), 1);
10935 });
10936
10937 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10938 left_pane
10939 .update_in(cx, |left_pane, window, cx| {
10940 left_pane.close_item_by_id(
10941 single_entry_items[3].entity_id(),
10942 SaveIntent::Skip,
10943 window,
10944 cx,
10945 )
10946 })
10947 .await
10948 .unwrap();
10949
10950 let close = left_pane.update_in(cx, |pane, window, cx| {
10951 pane.close_all_items(&CloseAllItems::default(), window, cx)
10952 .unwrap()
10953 });
10954 cx.executor().run_until_parked();
10955
10956 let details = cx.pending_prompt().unwrap().1;
10957 assert!(details.contains("0.txt"));
10958 assert!(details.contains("3.txt"));
10959 assert!(details.contains("4.txt"));
10960 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10961 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10962 // assert!(!details.contains("2.txt"));
10963
10964 cx.simulate_prompt_answer("Save all");
10965 cx.executor().run_until_parked();
10966 close.await;
10967
10968 left_pane.read_with(cx, |pane, _| {
10969 assert_eq!(pane.items_len(), 0);
10970 });
10971 }
10972
10973 #[gpui::test]
10974 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10975 init_test(cx);
10976
10977 let fs = FakeFs::new(cx.executor());
10978 let project = Project::test(fs, [], cx).await;
10979 let (workspace, cx) =
10980 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10981 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10982
10983 let item = cx.new(|cx| {
10984 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10985 });
10986 let item_id = item.entity_id();
10987 workspace.update_in(cx, |workspace, window, cx| {
10988 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10989 });
10990
10991 // Autosave on window change.
10992 item.update(cx, |item, cx| {
10993 SettingsStore::update_global(cx, |settings, cx| {
10994 settings.update_user_settings(cx, |settings| {
10995 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10996 })
10997 });
10998 item.is_dirty = true;
10999 });
11000
11001 // Deactivating the window saves the file.
11002 cx.deactivate_window();
11003 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11004
11005 // Re-activating the window doesn't save the file.
11006 cx.update(|window, _| window.activate_window());
11007 cx.executor().run_until_parked();
11008 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11009
11010 // Autosave on focus change.
11011 item.update_in(cx, |item, window, cx| {
11012 cx.focus_self(window);
11013 SettingsStore::update_global(cx, |settings, cx| {
11014 settings.update_user_settings(cx, |settings| {
11015 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11016 })
11017 });
11018 item.is_dirty = true;
11019 });
11020 // Blurring the item saves the file.
11021 item.update_in(cx, |_, window, _| window.blur());
11022 cx.executor().run_until_parked();
11023 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11024
11025 // Deactivating the window still saves the file.
11026 item.update_in(cx, |item, window, cx| {
11027 cx.focus_self(window);
11028 item.is_dirty = true;
11029 });
11030 cx.deactivate_window();
11031 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11032
11033 // Autosave after delay.
11034 item.update(cx, |item, cx| {
11035 SettingsStore::update_global(cx, |settings, cx| {
11036 settings.update_user_settings(cx, |settings| {
11037 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11038 milliseconds: 500.into(),
11039 });
11040 })
11041 });
11042 item.is_dirty = true;
11043 cx.emit(ItemEvent::Edit);
11044 });
11045
11046 // Delay hasn't fully expired, so the file is still dirty and unsaved.
11047 cx.executor().advance_clock(Duration::from_millis(250));
11048 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11049
11050 // After delay expires, the file is saved.
11051 cx.executor().advance_clock(Duration::from_millis(250));
11052 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11053
11054 // Autosave after delay, should save earlier than delay if tab is closed
11055 item.update(cx, |item, cx| {
11056 item.is_dirty = true;
11057 cx.emit(ItemEvent::Edit);
11058 });
11059 cx.executor().advance_clock(Duration::from_millis(250));
11060 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11061
11062 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11063 pane.update_in(cx, |pane, window, cx| {
11064 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11065 })
11066 .await
11067 .unwrap();
11068 assert!(!cx.has_pending_prompt());
11069 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11070
11071 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11072 workspace.update_in(cx, |workspace, window, cx| {
11073 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11074 });
11075 item.update_in(cx, |item, _window, cx| {
11076 item.is_dirty = true;
11077 for project_item in &mut item.project_items {
11078 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11079 }
11080 });
11081 cx.run_until_parked();
11082 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11083
11084 // Autosave on focus change, ensuring closing the tab counts as such.
11085 item.update(cx, |item, cx| {
11086 SettingsStore::update_global(cx, |settings, cx| {
11087 settings.update_user_settings(cx, |settings| {
11088 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11089 })
11090 });
11091 item.is_dirty = true;
11092 for project_item in &mut item.project_items {
11093 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11094 }
11095 });
11096
11097 pane.update_in(cx, |pane, window, cx| {
11098 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11099 })
11100 .await
11101 .unwrap();
11102 assert!(!cx.has_pending_prompt());
11103 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11104
11105 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11106 workspace.update_in(cx, |workspace, window, cx| {
11107 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11108 });
11109 item.update_in(cx, |item, window, cx| {
11110 item.project_items[0].update(cx, |item, _| {
11111 item.entry_id = None;
11112 });
11113 item.is_dirty = true;
11114 window.blur();
11115 });
11116 cx.run_until_parked();
11117 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11118
11119 // Ensure autosave is prevented for deleted files also when closing the buffer.
11120 let _close_items = pane.update_in(cx, |pane, window, cx| {
11121 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11122 });
11123 cx.run_until_parked();
11124 assert!(cx.has_pending_prompt());
11125 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11126 }
11127
11128 #[gpui::test]
11129 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11130 init_test(cx);
11131
11132 let fs = FakeFs::new(cx.executor());
11133 let project = Project::test(fs, [], cx).await;
11134 let (workspace, cx) =
11135 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11136
11137 // Create a multibuffer-like item with two child focus handles,
11138 // simulating individual buffer editors within a multibuffer.
11139 let item = cx.new(|cx| {
11140 TestItem::new(cx)
11141 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11142 .with_child_focus_handles(2, cx)
11143 });
11144 workspace.update_in(cx, |workspace, window, cx| {
11145 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11146 });
11147
11148 // Set autosave to OnFocusChange and focus the first child handle,
11149 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11150 item.update_in(cx, |item, window, cx| {
11151 SettingsStore::update_global(cx, |settings, cx| {
11152 settings.update_user_settings(cx, |settings| {
11153 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11154 })
11155 });
11156 item.is_dirty = true;
11157 window.focus(&item.child_focus_handles[0], cx);
11158 });
11159 cx.executor().run_until_parked();
11160 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11161
11162 // Moving focus from one child to another within the same item should
11163 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11164 item.update_in(cx, |item, window, cx| {
11165 window.focus(&item.child_focus_handles[1], cx);
11166 });
11167 cx.executor().run_until_parked();
11168 item.read_with(cx, |item, _| {
11169 assert_eq!(
11170 item.save_count, 0,
11171 "Switching focus between children within the same item should not autosave"
11172 );
11173 });
11174
11175 // Blurring the item saves the file. This is the core regression scenario:
11176 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11177 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11178 // the leaf is always a child focus handle, so `on_blur` never detected
11179 // focus leaving the item.
11180 item.update_in(cx, |_, window, _| window.blur());
11181 cx.executor().run_until_parked();
11182 item.read_with(cx, |item, _| {
11183 assert_eq!(
11184 item.save_count, 1,
11185 "Blurring should trigger autosave when focus was on a child of the item"
11186 );
11187 });
11188
11189 // Deactivating the window should also trigger autosave when a child of
11190 // the multibuffer item currently owns focus.
11191 item.update_in(cx, |item, window, cx| {
11192 item.is_dirty = true;
11193 window.focus(&item.child_focus_handles[0], cx);
11194 });
11195 cx.executor().run_until_parked();
11196 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11197
11198 cx.deactivate_window();
11199 item.read_with(cx, |item, _| {
11200 assert_eq!(
11201 item.save_count, 2,
11202 "Deactivating window should trigger autosave when focus was on a child"
11203 );
11204 });
11205 }
11206
11207 #[gpui::test]
11208 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11209 init_test(cx);
11210
11211 let fs = FakeFs::new(cx.executor());
11212
11213 let project = Project::test(fs, [], cx).await;
11214 let (workspace, cx) =
11215 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11216
11217 let item = cx.new(|cx| {
11218 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11219 });
11220 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11221 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11222 let toolbar_notify_count = Rc::new(RefCell::new(0));
11223
11224 workspace.update_in(cx, |workspace, window, cx| {
11225 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11226 let toolbar_notification_count = toolbar_notify_count.clone();
11227 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11228 *toolbar_notification_count.borrow_mut() += 1
11229 })
11230 .detach();
11231 });
11232
11233 pane.read_with(cx, |pane, _| {
11234 assert!(!pane.can_navigate_backward());
11235 assert!(!pane.can_navigate_forward());
11236 });
11237
11238 item.update_in(cx, |item, _, cx| {
11239 item.set_state("one".to_string(), cx);
11240 });
11241
11242 // Toolbar must be notified to re-render the navigation buttons
11243 assert_eq!(*toolbar_notify_count.borrow(), 1);
11244
11245 pane.read_with(cx, |pane, _| {
11246 assert!(pane.can_navigate_backward());
11247 assert!(!pane.can_navigate_forward());
11248 });
11249
11250 workspace
11251 .update_in(cx, |workspace, window, cx| {
11252 workspace.go_back(pane.downgrade(), window, cx)
11253 })
11254 .await
11255 .unwrap();
11256
11257 assert_eq!(*toolbar_notify_count.borrow(), 2);
11258 pane.read_with(cx, |pane, _| {
11259 assert!(!pane.can_navigate_backward());
11260 assert!(pane.can_navigate_forward());
11261 });
11262 }
11263
11264 /// Tests that the navigation history deduplicates entries for the same item.
11265 ///
11266 /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11267 /// the navigation history deduplicates by keeping only the most recent visit to each item,
11268 /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11269 /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11270 /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11271 ///
11272 /// This behavior prevents the navigation history from growing unnecessarily large and provides
11273 /// a better user experience by eliminating redundant navigation steps when jumping between files.
11274 #[gpui::test]
11275 async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11276 init_test(cx);
11277
11278 let fs = FakeFs::new(cx.executor());
11279 let project = Project::test(fs, [], cx).await;
11280 let (workspace, cx) =
11281 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11282
11283 let item_a = cx.new(|cx| {
11284 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11285 });
11286 let item_b = cx.new(|cx| {
11287 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11288 });
11289 let item_c = cx.new(|cx| {
11290 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11291 });
11292
11293 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11294
11295 workspace.update_in(cx, |workspace, window, cx| {
11296 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11297 workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11298 workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11299 });
11300
11301 workspace.update_in(cx, |workspace, window, cx| {
11302 workspace.activate_item(&item_a, false, false, window, cx);
11303 });
11304 cx.run_until_parked();
11305
11306 workspace.update_in(cx, |workspace, window, cx| {
11307 workspace.activate_item(&item_b, false, false, window, cx);
11308 });
11309 cx.run_until_parked();
11310
11311 workspace.update_in(cx, |workspace, window, cx| {
11312 workspace.activate_item(&item_a, false, false, window, cx);
11313 });
11314 cx.run_until_parked();
11315
11316 workspace.update_in(cx, |workspace, window, cx| {
11317 workspace.activate_item(&item_b, false, false, window, cx);
11318 });
11319 cx.run_until_parked();
11320
11321 workspace.update_in(cx, |workspace, window, cx| {
11322 workspace.activate_item(&item_a, false, false, window, cx);
11323 });
11324 cx.run_until_parked();
11325
11326 workspace.update_in(cx, |workspace, window, cx| {
11327 workspace.activate_item(&item_b, false, false, window, cx);
11328 });
11329 cx.run_until_parked();
11330
11331 workspace.update_in(cx, |workspace, window, cx| {
11332 workspace.activate_item(&item_c, false, false, window, cx);
11333 });
11334 cx.run_until_parked();
11335
11336 let backward_count = pane.read_with(cx, |pane, cx| {
11337 let mut count = 0;
11338 pane.nav_history().for_each_entry(cx, &mut |_, _| {
11339 count += 1;
11340 });
11341 count
11342 });
11343 assert!(
11344 backward_count <= 4,
11345 "Should have at most 4 entries, got {}",
11346 backward_count
11347 );
11348
11349 workspace
11350 .update_in(cx, |workspace, window, cx| {
11351 workspace.go_back(pane.downgrade(), window, cx)
11352 })
11353 .await
11354 .unwrap();
11355
11356 let active_item = workspace.read_with(cx, |workspace, cx| {
11357 workspace.active_item(cx).unwrap().item_id()
11358 });
11359 assert_eq!(
11360 active_item,
11361 item_b.entity_id(),
11362 "After first go_back, should be at item B"
11363 );
11364
11365 workspace
11366 .update_in(cx, |workspace, window, cx| {
11367 workspace.go_back(pane.downgrade(), window, cx)
11368 })
11369 .await
11370 .unwrap();
11371
11372 let active_item = workspace.read_with(cx, |workspace, cx| {
11373 workspace.active_item(cx).unwrap().item_id()
11374 });
11375 assert_eq!(
11376 active_item,
11377 item_a.entity_id(),
11378 "After second go_back, should be at item A"
11379 );
11380
11381 pane.read_with(cx, |pane, _| {
11382 assert!(pane.can_navigate_forward(), "Should be able to go forward");
11383 });
11384 }
11385
11386 #[gpui::test]
11387 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11388 init_test(cx);
11389 let fs = FakeFs::new(cx.executor());
11390 let project = Project::test(fs, [], cx).await;
11391 let (multi_workspace, cx) =
11392 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11393 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11394
11395 workspace.update_in(cx, |workspace, window, cx| {
11396 let first_item = cx.new(|cx| {
11397 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11398 });
11399 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11400 workspace.split_pane(
11401 workspace.active_pane().clone(),
11402 SplitDirection::Right,
11403 window,
11404 cx,
11405 );
11406 workspace.split_pane(
11407 workspace.active_pane().clone(),
11408 SplitDirection::Right,
11409 window,
11410 cx,
11411 );
11412 });
11413
11414 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11415 let panes = workspace.center.panes();
11416 assert!(panes.len() >= 2);
11417 (
11418 panes.first().expect("at least one pane").entity_id(),
11419 panes.last().expect("at least one pane").entity_id(),
11420 )
11421 });
11422
11423 workspace.update_in(cx, |workspace, window, cx| {
11424 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11425 });
11426 workspace.update(cx, |workspace, _| {
11427 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11428 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11429 });
11430
11431 cx.dispatch_action(ActivateLastPane);
11432
11433 workspace.update(cx, |workspace, _| {
11434 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11435 });
11436 }
11437
11438 #[gpui::test]
11439 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11440 init_test(cx);
11441 let fs = FakeFs::new(cx.executor());
11442
11443 let project = Project::test(fs, [], cx).await;
11444 let (workspace, cx) =
11445 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11446
11447 let panel = workspace.update_in(cx, |workspace, window, cx| {
11448 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11449 workspace.add_panel(panel.clone(), window, cx);
11450
11451 workspace
11452 .right_dock()
11453 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11454
11455 panel
11456 });
11457
11458 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11459 pane.update_in(cx, |pane, window, cx| {
11460 let item = cx.new(TestItem::new);
11461 pane.add_item(Box::new(item), true, true, None, window, cx);
11462 });
11463
11464 // Transfer focus from center to panel
11465 workspace.update_in(cx, |workspace, window, cx| {
11466 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11467 });
11468
11469 workspace.update_in(cx, |workspace, window, cx| {
11470 assert!(workspace.right_dock().read(cx).is_open());
11471 assert!(!panel.is_zoomed(window, cx));
11472 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11473 });
11474
11475 // Transfer focus from panel to center
11476 workspace.update_in(cx, |workspace, window, cx| {
11477 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11478 });
11479
11480 workspace.update_in(cx, |workspace, window, cx| {
11481 assert!(workspace.right_dock().read(cx).is_open());
11482 assert!(!panel.is_zoomed(window, cx));
11483 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11484 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11485 });
11486
11487 // Close the dock
11488 workspace.update_in(cx, |workspace, window, cx| {
11489 workspace.toggle_dock(DockPosition::Right, window, cx);
11490 });
11491
11492 workspace.update_in(cx, |workspace, window, cx| {
11493 assert!(!workspace.right_dock().read(cx).is_open());
11494 assert!(!panel.is_zoomed(window, cx));
11495 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11496 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11497 });
11498
11499 // Open the dock
11500 workspace.update_in(cx, |workspace, window, cx| {
11501 workspace.toggle_dock(DockPosition::Right, window, cx);
11502 });
11503
11504 workspace.update_in(cx, |workspace, window, cx| {
11505 assert!(workspace.right_dock().read(cx).is_open());
11506 assert!(!panel.is_zoomed(window, cx));
11507 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11508 });
11509
11510 // Focus and zoom panel
11511 panel.update_in(cx, |panel, window, cx| {
11512 cx.focus_self(window);
11513 panel.set_zoomed(true, window, cx)
11514 });
11515
11516 workspace.update_in(cx, |workspace, window, cx| {
11517 assert!(workspace.right_dock().read(cx).is_open());
11518 assert!(panel.is_zoomed(window, cx));
11519 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11520 });
11521
11522 // Transfer focus to the center closes the dock
11523 workspace.update_in(cx, |workspace, window, cx| {
11524 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11525 });
11526
11527 workspace.update_in(cx, |workspace, window, cx| {
11528 assert!(!workspace.right_dock().read(cx).is_open());
11529 assert!(panel.is_zoomed(window, cx));
11530 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11531 });
11532
11533 // Transferring focus back to the panel keeps it zoomed
11534 workspace.update_in(cx, |workspace, window, cx| {
11535 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11536 });
11537
11538 workspace.update_in(cx, |workspace, window, cx| {
11539 assert!(workspace.right_dock().read(cx).is_open());
11540 assert!(panel.is_zoomed(window, cx));
11541 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11542 });
11543
11544 // Close the dock while it is zoomed
11545 workspace.update_in(cx, |workspace, window, cx| {
11546 workspace.toggle_dock(DockPosition::Right, window, cx)
11547 });
11548
11549 workspace.update_in(cx, |workspace, window, cx| {
11550 assert!(!workspace.right_dock().read(cx).is_open());
11551 assert!(panel.is_zoomed(window, cx));
11552 assert!(workspace.zoomed.is_none());
11553 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11554 });
11555
11556 // Opening the dock, when it's zoomed, retains focus
11557 workspace.update_in(cx, |workspace, window, cx| {
11558 workspace.toggle_dock(DockPosition::Right, window, cx)
11559 });
11560
11561 workspace.update_in(cx, |workspace, window, cx| {
11562 assert!(workspace.right_dock().read(cx).is_open());
11563 assert!(panel.is_zoomed(window, cx));
11564 assert!(workspace.zoomed.is_some());
11565 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11566 });
11567
11568 // Unzoom and close the panel, zoom the active pane.
11569 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11570 workspace.update_in(cx, |workspace, window, cx| {
11571 workspace.toggle_dock(DockPosition::Right, window, cx)
11572 });
11573 pane.update_in(cx, |pane, window, cx| {
11574 pane.toggle_zoom(&Default::default(), window, cx)
11575 });
11576
11577 // Opening a dock unzooms the pane.
11578 workspace.update_in(cx, |workspace, window, cx| {
11579 workspace.toggle_dock(DockPosition::Right, window, cx)
11580 });
11581 workspace.update_in(cx, |workspace, window, cx| {
11582 let pane = pane.read(cx);
11583 assert!(!pane.is_zoomed());
11584 assert!(!pane.focus_handle(cx).is_focused(window));
11585 assert!(workspace.right_dock().read(cx).is_open());
11586 assert!(workspace.zoomed.is_none());
11587 });
11588 }
11589
11590 #[gpui::test]
11591 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11592 init_test(cx);
11593 let fs = FakeFs::new(cx.executor());
11594
11595 let project = Project::test(fs, [], cx).await;
11596 let (workspace, cx) =
11597 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11598
11599 let panel = workspace.update_in(cx, |workspace, window, cx| {
11600 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11601 workspace.add_panel(panel.clone(), window, cx);
11602 panel
11603 });
11604
11605 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11606 pane.update_in(cx, |pane, window, cx| {
11607 let item = cx.new(TestItem::new);
11608 pane.add_item(Box::new(item), true, true, None, window, cx);
11609 });
11610
11611 // Enable close_panel_on_toggle
11612 cx.update_global(|store: &mut SettingsStore, cx| {
11613 store.update_user_settings(cx, |settings| {
11614 settings.workspace.close_panel_on_toggle = Some(true);
11615 });
11616 });
11617
11618 // Panel starts closed. Toggling should open and focus it.
11619 workspace.update_in(cx, |workspace, window, cx| {
11620 assert!(!workspace.right_dock().read(cx).is_open());
11621 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11622 });
11623
11624 workspace.update_in(cx, |workspace, window, cx| {
11625 assert!(
11626 workspace.right_dock().read(cx).is_open(),
11627 "Dock should be open after toggling from center"
11628 );
11629 assert!(
11630 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11631 "Panel should be focused after toggling from center"
11632 );
11633 });
11634
11635 // Panel is open and focused. Toggling should close the panel and
11636 // return focus to the center.
11637 workspace.update_in(cx, |workspace, window, cx| {
11638 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11639 });
11640
11641 workspace.update_in(cx, |workspace, window, cx| {
11642 assert!(
11643 !workspace.right_dock().read(cx).is_open(),
11644 "Dock should be closed after toggling from focused panel"
11645 );
11646 assert!(
11647 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11648 "Panel should not be focused after toggling from focused panel"
11649 );
11650 });
11651
11652 // Open the dock and focus something else so the panel is open but not
11653 // focused. Toggling should focus the panel (not close it).
11654 workspace.update_in(cx, |workspace, window, cx| {
11655 workspace
11656 .right_dock()
11657 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11658 window.focus(&pane.read(cx).focus_handle(cx), cx);
11659 });
11660
11661 workspace.update_in(cx, |workspace, window, cx| {
11662 assert!(workspace.right_dock().read(cx).is_open());
11663 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11664 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11665 });
11666
11667 workspace.update_in(cx, |workspace, window, cx| {
11668 assert!(
11669 workspace.right_dock().read(cx).is_open(),
11670 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11671 );
11672 assert!(
11673 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11674 "Panel should be focused after toggling an open-but-unfocused panel"
11675 );
11676 });
11677
11678 // Now disable the setting and verify the original behavior: toggling
11679 // from a focused panel moves focus to center but leaves the dock open.
11680 cx.update_global(|store: &mut SettingsStore, cx| {
11681 store.update_user_settings(cx, |settings| {
11682 settings.workspace.close_panel_on_toggle = Some(false);
11683 });
11684 });
11685
11686 workspace.update_in(cx, |workspace, window, cx| {
11687 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11688 });
11689
11690 workspace.update_in(cx, |workspace, window, cx| {
11691 assert!(
11692 workspace.right_dock().read(cx).is_open(),
11693 "Dock should remain open when setting is disabled"
11694 );
11695 assert!(
11696 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11697 "Panel should not be focused after toggling with setting disabled"
11698 );
11699 });
11700 }
11701
11702 #[gpui::test]
11703 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11704 init_test(cx);
11705 let fs = FakeFs::new(cx.executor());
11706
11707 let project = Project::test(fs, [], cx).await;
11708 let (workspace, cx) =
11709 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11710
11711 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11712 workspace.active_pane().clone()
11713 });
11714
11715 // Add an item to the pane so it can be zoomed
11716 workspace.update_in(cx, |workspace, window, cx| {
11717 let item = cx.new(TestItem::new);
11718 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11719 });
11720
11721 // Initially not zoomed
11722 workspace.update_in(cx, |workspace, _window, cx| {
11723 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11724 assert!(
11725 workspace.zoomed.is_none(),
11726 "Workspace should track no zoomed pane"
11727 );
11728 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11729 });
11730
11731 // Zoom In
11732 pane.update_in(cx, |pane, window, cx| {
11733 pane.zoom_in(&crate::ZoomIn, window, cx);
11734 });
11735
11736 workspace.update_in(cx, |workspace, window, cx| {
11737 assert!(
11738 pane.read(cx).is_zoomed(),
11739 "Pane should be zoomed after ZoomIn"
11740 );
11741 assert!(
11742 workspace.zoomed.is_some(),
11743 "Workspace should track the zoomed pane"
11744 );
11745 assert!(
11746 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11747 "ZoomIn should focus the pane"
11748 );
11749 });
11750
11751 // Zoom In again is a no-op
11752 pane.update_in(cx, |pane, window, cx| {
11753 pane.zoom_in(&crate::ZoomIn, window, cx);
11754 });
11755
11756 workspace.update_in(cx, |workspace, window, cx| {
11757 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11758 assert!(
11759 workspace.zoomed.is_some(),
11760 "Workspace still tracks zoomed pane"
11761 );
11762 assert!(
11763 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11764 "Pane remains focused after repeated ZoomIn"
11765 );
11766 });
11767
11768 // Zoom Out
11769 pane.update_in(cx, |pane, window, cx| {
11770 pane.zoom_out(&crate::ZoomOut, window, cx);
11771 });
11772
11773 workspace.update_in(cx, |workspace, _window, cx| {
11774 assert!(
11775 !pane.read(cx).is_zoomed(),
11776 "Pane should unzoom after ZoomOut"
11777 );
11778 assert!(
11779 workspace.zoomed.is_none(),
11780 "Workspace clears zoom tracking after ZoomOut"
11781 );
11782 });
11783
11784 // Zoom Out again is a no-op
11785 pane.update_in(cx, |pane, window, cx| {
11786 pane.zoom_out(&crate::ZoomOut, window, cx);
11787 });
11788
11789 workspace.update_in(cx, |workspace, _window, cx| {
11790 assert!(
11791 !pane.read(cx).is_zoomed(),
11792 "Second ZoomOut keeps pane unzoomed"
11793 );
11794 assert!(
11795 workspace.zoomed.is_none(),
11796 "Workspace remains without zoomed pane"
11797 );
11798 });
11799 }
11800
11801 #[gpui::test]
11802 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11803 init_test(cx);
11804 let fs = FakeFs::new(cx.executor());
11805
11806 let project = Project::test(fs, [], cx).await;
11807 let (workspace, cx) =
11808 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11809 workspace.update_in(cx, |workspace, window, cx| {
11810 // Open two docks
11811 let left_dock = workspace.dock_at_position(DockPosition::Left);
11812 let right_dock = workspace.dock_at_position(DockPosition::Right);
11813
11814 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11815 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11816
11817 assert!(left_dock.read(cx).is_open());
11818 assert!(right_dock.read(cx).is_open());
11819 });
11820
11821 workspace.update_in(cx, |workspace, window, cx| {
11822 // Toggle all docks - should close both
11823 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11824
11825 let left_dock = workspace.dock_at_position(DockPosition::Left);
11826 let right_dock = workspace.dock_at_position(DockPosition::Right);
11827 assert!(!left_dock.read(cx).is_open());
11828 assert!(!right_dock.read(cx).is_open());
11829 });
11830
11831 workspace.update_in(cx, |workspace, window, cx| {
11832 // Toggle again - should reopen both
11833 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11834
11835 let left_dock = workspace.dock_at_position(DockPosition::Left);
11836 let right_dock = workspace.dock_at_position(DockPosition::Right);
11837 assert!(left_dock.read(cx).is_open());
11838 assert!(right_dock.read(cx).is_open());
11839 });
11840 }
11841
11842 #[gpui::test]
11843 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11844 init_test(cx);
11845 let fs = FakeFs::new(cx.executor());
11846
11847 let project = Project::test(fs, [], cx).await;
11848 let (workspace, cx) =
11849 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11850 workspace.update_in(cx, |workspace, window, cx| {
11851 // Open two docks
11852 let left_dock = workspace.dock_at_position(DockPosition::Left);
11853 let right_dock = workspace.dock_at_position(DockPosition::Right);
11854
11855 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11856 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11857
11858 assert!(left_dock.read(cx).is_open());
11859 assert!(right_dock.read(cx).is_open());
11860 });
11861
11862 workspace.update_in(cx, |workspace, window, cx| {
11863 // Close them manually
11864 workspace.toggle_dock(DockPosition::Left, window, cx);
11865 workspace.toggle_dock(DockPosition::Right, window, cx);
11866
11867 let left_dock = workspace.dock_at_position(DockPosition::Left);
11868 let right_dock = workspace.dock_at_position(DockPosition::Right);
11869 assert!(!left_dock.read(cx).is_open());
11870 assert!(!right_dock.read(cx).is_open());
11871 });
11872
11873 workspace.update_in(cx, |workspace, window, cx| {
11874 // Toggle all docks - only last closed (right dock) should reopen
11875 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11876
11877 let left_dock = workspace.dock_at_position(DockPosition::Left);
11878 let right_dock = workspace.dock_at_position(DockPosition::Right);
11879 assert!(!left_dock.read(cx).is_open());
11880 assert!(right_dock.read(cx).is_open());
11881 });
11882 }
11883
11884 #[gpui::test]
11885 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11886 init_test(cx);
11887 let fs = FakeFs::new(cx.executor());
11888 let project = Project::test(fs, [], cx).await;
11889 let (multi_workspace, cx) =
11890 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11891 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11892
11893 // Open two docks (left and right) with one panel each
11894 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11895 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11896 workspace.add_panel(left_panel.clone(), window, cx);
11897
11898 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11899 workspace.add_panel(right_panel.clone(), window, cx);
11900
11901 workspace.toggle_dock(DockPosition::Left, window, cx);
11902 workspace.toggle_dock(DockPosition::Right, window, cx);
11903
11904 // Verify initial state
11905 assert!(
11906 workspace.left_dock().read(cx).is_open(),
11907 "Left dock should be open"
11908 );
11909 assert_eq!(
11910 workspace
11911 .left_dock()
11912 .read(cx)
11913 .visible_panel()
11914 .unwrap()
11915 .panel_id(),
11916 left_panel.panel_id(),
11917 "Left panel should be visible in left dock"
11918 );
11919 assert!(
11920 workspace.right_dock().read(cx).is_open(),
11921 "Right dock should be open"
11922 );
11923 assert_eq!(
11924 workspace
11925 .right_dock()
11926 .read(cx)
11927 .visible_panel()
11928 .unwrap()
11929 .panel_id(),
11930 right_panel.panel_id(),
11931 "Right panel should be visible in right dock"
11932 );
11933 assert!(
11934 !workspace.bottom_dock().read(cx).is_open(),
11935 "Bottom dock should be closed"
11936 );
11937
11938 (left_panel, right_panel)
11939 });
11940
11941 // Focus the left panel and move it to the next position (bottom dock)
11942 workspace.update_in(cx, |workspace, window, cx| {
11943 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11944 assert!(
11945 left_panel.read(cx).focus_handle(cx).is_focused(window),
11946 "Left panel should be focused"
11947 );
11948 });
11949
11950 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11951
11952 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11953 workspace.update(cx, |workspace, cx| {
11954 assert!(
11955 !workspace.left_dock().read(cx).is_open(),
11956 "Left dock should be closed"
11957 );
11958 assert!(
11959 workspace.bottom_dock().read(cx).is_open(),
11960 "Bottom dock should now be open"
11961 );
11962 assert_eq!(
11963 left_panel.read(cx).position,
11964 DockPosition::Bottom,
11965 "Left panel should now be in the bottom dock"
11966 );
11967 assert_eq!(
11968 workspace
11969 .bottom_dock()
11970 .read(cx)
11971 .visible_panel()
11972 .unwrap()
11973 .panel_id(),
11974 left_panel.panel_id(),
11975 "Left panel should be the visible panel in the bottom dock"
11976 );
11977 });
11978
11979 // Toggle all docks off
11980 workspace.update_in(cx, |workspace, window, cx| {
11981 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11982 assert!(
11983 !workspace.left_dock().read(cx).is_open(),
11984 "Left dock should be closed"
11985 );
11986 assert!(
11987 !workspace.right_dock().read(cx).is_open(),
11988 "Right dock should be closed"
11989 );
11990 assert!(
11991 !workspace.bottom_dock().read(cx).is_open(),
11992 "Bottom dock should be closed"
11993 );
11994 });
11995
11996 // Toggle all docks back on and verify positions are restored
11997 workspace.update_in(cx, |workspace, window, cx| {
11998 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11999 assert!(
12000 !workspace.left_dock().read(cx).is_open(),
12001 "Left dock should remain closed"
12002 );
12003 assert!(
12004 workspace.right_dock().read(cx).is_open(),
12005 "Right dock should remain open"
12006 );
12007 assert!(
12008 workspace.bottom_dock().read(cx).is_open(),
12009 "Bottom dock should remain open"
12010 );
12011 assert_eq!(
12012 left_panel.read(cx).position,
12013 DockPosition::Bottom,
12014 "Left panel should remain in the bottom dock"
12015 );
12016 assert_eq!(
12017 right_panel.read(cx).position,
12018 DockPosition::Right,
12019 "Right panel should remain in the right dock"
12020 );
12021 assert_eq!(
12022 workspace
12023 .bottom_dock()
12024 .read(cx)
12025 .visible_panel()
12026 .unwrap()
12027 .panel_id(),
12028 left_panel.panel_id(),
12029 "Left panel should be the visible panel in the right dock"
12030 );
12031 });
12032 }
12033
12034 #[gpui::test]
12035 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12036 init_test(cx);
12037
12038 let fs = FakeFs::new(cx.executor());
12039
12040 let project = Project::test(fs, None, cx).await;
12041 let (workspace, cx) =
12042 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12043
12044 // Let's arrange the panes like this:
12045 //
12046 // +-----------------------+
12047 // | top |
12048 // +------+--------+-------+
12049 // | left | center | right |
12050 // +------+--------+-------+
12051 // | bottom |
12052 // +-----------------------+
12053
12054 let top_item = cx.new(|cx| {
12055 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12056 });
12057 let bottom_item = cx.new(|cx| {
12058 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12059 });
12060 let left_item = cx.new(|cx| {
12061 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12062 });
12063 let right_item = cx.new(|cx| {
12064 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12065 });
12066 let center_item = cx.new(|cx| {
12067 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12068 });
12069
12070 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12071 let top_pane_id = workspace.active_pane().entity_id();
12072 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12073 workspace.split_pane(
12074 workspace.active_pane().clone(),
12075 SplitDirection::Down,
12076 window,
12077 cx,
12078 );
12079 top_pane_id
12080 });
12081 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12082 let bottom_pane_id = workspace.active_pane().entity_id();
12083 workspace.add_item_to_active_pane(
12084 Box::new(bottom_item.clone()),
12085 None,
12086 false,
12087 window,
12088 cx,
12089 );
12090 workspace.split_pane(
12091 workspace.active_pane().clone(),
12092 SplitDirection::Up,
12093 window,
12094 cx,
12095 );
12096 bottom_pane_id
12097 });
12098 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12099 let left_pane_id = workspace.active_pane().entity_id();
12100 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12101 workspace.split_pane(
12102 workspace.active_pane().clone(),
12103 SplitDirection::Right,
12104 window,
12105 cx,
12106 );
12107 left_pane_id
12108 });
12109 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12110 let right_pane_id = workspace.active_pane().entity_id();
12111 workspace.add_item_to_active_pane(
12112 Box::new(right_item.clone()),
12113 None,
12114 false,
12115 window,
12116 cx,
12117 );
12118 workspace.split_pane(
12119 workspace.active_pane().clone(),
12120 SplitDirection::Left,
12121 window,
12122 cx,
12123 );
12124 right_pane_id
12125 });
12126 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12127 let center_pane_id = workspace.active_pane().entity_id();
12128 workspace.add_item_to_active_pane(
12129 Box::new(center_item.clone()),
12130 None,
12131 false,
12132 window,
12133 cx,
12134 );
12135 center_pane_id
12136 });
12137 cx.executor().run_until_parked();
12138
12139 workspace.update_in(cx, |workspace, window, cx| {
12140 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12141
12142 // Join into next from center pane into right
12143 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12144 });
12145
12146 workspace.update_in(cx, |workspace, window, cx| {
12147 let active_pane = workspace.active_pane();
12148 assert_eq!(right_pane_id, active_pane.entity_id());
12149 assert_eq!(2, active_pane.read(cx).items_len());
12150 let item_ids_in_pane =
12151 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12152 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12153 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12154
12155 // Join into next from right pane into bottom
12156 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12157 });
12158
12159 workspace.update_in(cx, |workspace, window, cx| {
12160 let active_pane = workspace.active_pane();
12161 assert_eq!(bottom_pane_id, active_pane.entity_id());
12162 assert_eq!(3, active_pane.read(cx).items_len());
12163 let item_ids_in_pane =
12164 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12165 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12166 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12167 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12168
12169 // Join into next from bottom pane into left
12170 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12171 });
12172
12173 workspace.update_in(cx, |workspace, window, cx| {
12174 let active_pane = workspace.active_pane();
12175 assert_eq!(left_pane_id, active_pane.entity_id());
12176 assert_eq!(4, active_pane.read(cx).items_len());
12177 let item_ids_in_pane =
12178 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12179 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12180 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12181 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12182 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12183
12184 // Join into next from left pane into top
12185 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12186 });
12187
12188 workspace.update_in(cx, |workspace, window, cx| {
12189 let active_pane = workspace.active_pane();
12190 assert_eq!(top_pane_id, active_pane.entity_id());
12191 assert_eq!(5, active_pane.read(cx).items_len());
12192 let item_ids_in_pane =
12193 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12194 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12195 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12196 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12197 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12198 assert!(item_ids_in_pane.contains(&top_item.item_id()));
12199
12200 // Single pane left: no-op
12201 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12202 });
12203
12204 workspace.update(cx, |workspace, _cx| {
12205 let active_pane = workspace.active_pane();
12206 assert_eq!(top_pane_id, active_pane.entity_id());
12207 });
12208 }
12209
12210 fn add_an_item_to_active_pane(
12211 cx: &mut VisualTestContext,
12212 workspace: &Entity<Workspace>,
12213 item_id: u64,
12214 ) -> Entity<TestItem> {
12215 let item = cx.new(|cx| {
12216 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12217 item_id,
12218 "item{item_id}.txt",
12219 cx,
12220 )])
12221 });
12222 workspace.update_in(cx, |workspace, window, cx| {
12223 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12224 });
12225 item
12226 }
12227
12228 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12229 workspace.update_in(cx, |workspace, window, cx| {
12230 workspace.split_pane(
12231 workspace.active_pane().clone(),
12232 SplitDirection::Right,
12233 window,
12234 cx,
12235 )
12236 })
12237 }
12238
12239 #[gpui::test]
12240 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12241 init_test(cx);
12242 let fs = FakeFs::new(cx.executor());
12243 let project = Project::test(fs, None, cx).await;
12244 let (workspace, cx) =
12245 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12246
12247 add_an_item_to_active_pane(cx, &workspace, 1);
12248 split_pane(cx, &workspace);
12249 add_an_item_to_active_pane(cx, &workspace, 2);
12250 split_pane(cx, &workspace); // empty pane
12251 split_pane(cx, &workspace);
12252 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12253
12254 cx.executor().run_until_parked();
12255
12256 workspace.update(cx, |workspace, cx| {
12257 let num_panes = workspace.panes().len();
12258 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12259 let active_item = workspace
12260 .active_pane()
12261 .read(cx)
12262 .active_item()
12263 .expect("item is in focus");
12264
12265 assert_eq!(num_panes, 4);
12266 assert_eq!(num_items_in_current_pane, 1);
12267 assert_eq!(active_item.item_id(), last_item.item_id());
12268 });
12269
12270 workspace.update_in(cx, |workspace, window, cx| {
12271 workspace.join_all_panes(window, cx);
12272 });
12273
12274 workspace.update(cx, |workspace, cx| {
12275 let num_panes = workspace.panes().len();
12276 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12277 let active_item = workspace
12278 .active_pane()
12279 .read(cx)
12280 .active_item()
12281 .expect("item is in focus");
12282
12283 assert_eq!(num_panes, 1);
12284 assert_eq!(num_items_in_current_pane, 3);
12285 assert_eq!(active_item.item_id(), last_item.item_id());
12286 });
12287 }
12288
12289 #[gpui::test]
12290 async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12291 init_test(cx);
12292 let fs = FakeFs::new(cx.executor());
12293
12294 let project = Project::test(fs, [], cx).await;
12295 let (multi_workspace, cx) =
12296 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12297 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12298
12299 workspace.update(cx, |workspace, _cx| {
12300 workspace.bounds.size.width = px(800.);
12301 });
12302
12303 workspace.update_in(cx, |workspace, window, cx| {
12304 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12305 workspace.add_panel(panel, window, cx);
12306 workspace.toggle_dock(DockPosition::Right, window, cx);
12307 });
12308
12309 let (panel, resized_width, ratio_basis_width) =
12310 workspace.update_in(cx, |workspace, window, cx| {
12311 let item = cx.new(|cx| {
12312 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12313 });
12314 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12315
12316 let dock = workspace.right_dock().read(cx);
12317 let workspace_width = workspace.bounds.size.width;
12318 let initial_width = dock
12319 .active_panel()
12320 .map(|panel| {
12321 workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx)
12322 })
12323 .expect("flexible dock should have an initial width");
12324
12325 assert_eq!(initial_width, workspace_width / 2.);
12326
12327 workspace.resize_right_dock(px(300.), window, cx);
12328
12329 let dock = workspace.right_dock().read(cx);
12330 let resized_width = dock
12331 .active_panel()
12332 .map(|panel| {
12333 workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx)
12334 })
12335 .expect("flexible dock should keep its resized width");
12336
12337 assert_eq!(resized_width, px(300.));
12338
12339 let panel = workspace
12340 .right_dock()
12341 .read(cx)
12342 .visible_panel()
12343 .expect("flexible dock should have a visible panel")
12344 .panel_id();
12345
12346 (panel, resized_width, workspace_width)
12347 });
12348
12349 workspace.update_in(cx, |workspace, window, cx| {
12350 workspace.toggle_dock(DockPosition::Right, window, cx);
12351 workspace.toggle_dock(DockPosition::Right, window, cx);
12352
12353 let dock = workspace.right_dock().read(cx);
12354 let reopened_width = dock
12355 .active_panel()
12356 .map(|panel| workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx))
12357 .expect("flexible dock should restore when reopened");
12358
12359 assert_eq!(reopened_width, resized_width);
12360
12361 let right_dock = workspace.right_dock().read(cx);
12362 let flexible_panel = right_dock
12363 .visible_panel()
12364 .expect("flexible dock should still have a visible panel");
12365 assert_eq!(flexible_panel.panel_id(), panel);
12366 assert_eq!(
12367 right_dock
12368 .stored_panel_size_state(flexible_panel.as_ref())
12369 .and_then(|size_state| size_state.flexible_size_ratio),
12370 Some(resized_width.to_f64() as f32 / workspace.bounds.size.width.to_f64() as f32)
12371 );
12372 });
12373
12374 workspace.update_in(cx, |workspace, window, cx| {
12375 workspace.split_pane(
12376 workspace.active_pane().clone(),
12377 SplitDirection::Right,
12378 window,
12379 cx,
12380 );
12381
12382 let dock = workspace.right_dock().read(cx);
12383 let split_width = dock
12384 .active_panel()
12385 .map(|panel| workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx))
12386 .expect("flexible dock should keep its user-resized proportion");
12387
12388 assert_eq!(split_width, px(300.));
12389
12390 workspace.bounds.size.width = px(1600.);
12391
12392 let dock = workspace.right_dock().read(cx);
12393 let resized_window_width = dock
12394 .active_panel()
12395 .map(|panel| workspace.resolved_dock_panel_size(&dock, panel.as_ref(), window, cx))
12396 .expect("flexible dock should preserve proportional size on window resize");
12397
12398 assert_eq!(
12399 resized_window_width,
12400 workspace.bounds.size.width
12401 * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12402 );
12403 });
12404 }
12405
12406 #[gpui::test]
12407 async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12408 init_test(cx);
12409 let fs = FakeFs::new(cx.executor());
12410
12411 // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12412 {
12413 let project = Project::test(fs.clone(), [], cx).await;
12414 let (multi_workspace, cx) =
12415 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12416 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12417
12418 workspace.update(cx, |workspace, _cx| {
12419 workspace.set_random_database_id();
12420 workspace.bounds.size.width = px(800.);
12421 });
12422
12423 let panel = workspace.update_in(cx, |workspace, window, cx| {
12424 let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12425 workspace.add_panel(panel.clone(), window, cx);
12426 workspace.toggle_dock(DockPosition::Left, window, cx);
12427 panel
12428 });
12429
12430 workspace.update_in(cx, |workspace, window, cx| {
12431 workspace.resize_left_dock(px(350.), window, cx);
12432 });
12433
12434 cx.run_until_parked();
12435
12436 let persisted = workspace.read_with(cx, |workspace, cx| {
12437 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12438 });
12439 assert_eq!(
12440 persisted.and_then(|s| s.size),
12441 Some(px(350.)),
12442 "fixed-width panel size should be persisted to KVP"
12443 );
12444
12445 // Remove the panel and re-add a fresh instance with the same key.
12446 // The new instance should have its size state restored from KVP.
12447 workspace.update_in(cx, |workspace, window, cx| {
12448 workspace.remove_panel(&panel, window, cx);
12449 });
12450
12451 workspace.update_in(cx, |workspace, window, cx| {
12452 let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12453 workspace.add_panel(new_panel, window, cx);
12454
12455 let left_dock = workspace.left_dock().read(cx);
12456 let size_state = left_dock
12457 .panel::<TestPanel>()
12458 .and_then(|p| left_dock.stored_panel_size_state(&p));
12459 assert_eq!(
12460 size_state.and_then(|s| s.size),
12461 Some(px(350.)),
12462 "re-added fixed-width panel should restore persisted size from KVP"
12463 );
12464 });
12465 }
12466
12467 // Flexible panel: both pixel size and ratio are persisted and restored.
12468 {
12469 let project = Project::test(fs.clone(), [], cx).await;
12470 let (multi_workspace, cx) =
12471 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12472 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12473
12474 workspace.update(cx, |workspace, _cx| {
12475 workspace.set_random_database_id();
12476 workspace.bounds.size.width = px(800.);
12477 });
12478
12479 let panel = workspace.update_in(cx, |workspace, window, cx| {
12480 let item = cx.new(|cx| {
12481 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12482 });
12483 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12484
12485 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12486 workspace.add_panel(panel.clone(), window, cx);
12487 workspace.toggle_dock(DockPosition::Right, window, cx);
12488 panel
12489 });
12490
12491 workspace.update_in(cx, |workspace, window, cx| {
12492 workspace.resize_right_dock(px(300.), window, cx);
12493 });
12494
12495 cx.run_until_parked();
12496
12497 let persisted = workspace
12498 .read_with(cx, |workspace, cx| {
12499 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12500 })
12501 .expect("flexible panel state should be persisted to KVP");
12502 assert_eq!(
12503 persisted.size, None,
12504 "flexible panel should not persist a redundant pixel size"
12505 );
12506 let original_ratio = persisted
12507 .flexible_size_ratio
12508 .expect("flexible panel ratio should be persisted");
12509
12510 // Remove the panel and re-add: both size and ratio should be restored.
12511 workspace.update_in(cx, |workspace, window, cx| {
12512 workspace.remove_panel(&panel, window, cx);
12513 });
12514
12515 workspace.update_in(cx, |workspace, window, cx| {
12516 let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12517 workspace.add_panel(new_panel, window, cx);
12518
12519 let right_dock = workspace.right_dock().read(cx);
12520 let size_state = right_dock
12521 .panel::<TestPanel>()
12522 .and_then(|p| right_dock.stored_panel_size_state(&p))
12523 .expect("re-added flexible panel should have restored size state from KVP");
12524 assert_eq!(
12525 size_state.size, None,
12526 "re-added flexible panel should not have a persisted pixel size"
12527 );
12528 assert_eq!(
12529 size_state.flexible_size_ratio,
12530 Some(original_ratio),
12531 "re-added flexible panel should restore persisted ratio"
12532 );
12533 });
12534 }
12535 }
12536
12537 #[gpui::test]
12538 async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12539 init_test(cx);
12540 let fs = FakeFs::new(cx.executor());
12541
12542 let project = Project::test(fs, [], cx).await;
12543 let (multi_workspace, cx) =
12544 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12545 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12546
12547 workspace.update(cx, |workspace, _cx| {
12548 workspace.bounds.size.width = px(900.);
12549 });
12550
12551 // Step 1: Add a tab to the center pane then open a flexible panel in the left
12552 // dock. With one full-width center pane the default ratio is 0.5, so the panel
12553 // and the center pane each take half the workspace width.
12554 workspace.update_in(cx, |workspace, window, cx| {
12555 let item = cx.new(|cx| {
12556 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12557 });
12558 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12559
12560 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12561 workspace.add_panel(panel, window, cx);
12562 workspace.toggle_dock(DockPosition::Left, window, cx);
12563
12564 let left_dock = workspace.left_dock().read(cx);
12565 let left_width = left_dock
12566 .active_panel()
12567 .map(|p| workspace.resolved_dock_panel_size(&left_dock, p.as_ref(), window, cx))
12568 .expect("left dock should have an active panel");
12569
12570 assert_eq!(
12571 left_width,
12572 workspace.bounds.size.width / 2.,
12573 "flexible left panel should split evenly with the center pane"
12574 );
12575 });
12576
12577 // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12578 // change horizontal width fractions, so the flexible panel stays at the same
12579 // width as each half of the split.
12580 workspace.update_in(cx, |workspace, window, cx| {
12581 workspace.split_pane(
12582 workspace.active_pane().clone(),
12583 SplitDirection::Down,
12584 window,
12585 cx,
12586 );
12587
12588 let left_dock = workspace.left_dock().read(cx);
12589 let left_width = left_dock
12590 .active_panel()
12591 .map(|p| workspace.resolved_dock_panel_size(&left_dock, p.as_ref(), window, cx))
12592 .expect("left dock should still have an active panel after vertical split");
12593
12594 assert_eq!(
12595 left_width,
12596 workspace.bounds.size.width / 2.,
12597 "flexible left panel width should match each vertically-split pane"
12598 );
12599 });
12600
12601 // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12602 // size reduces the available width, so the flexible left panel and the center
12603 // panes all shrink proportionally to accommodate it.
12604 workspace.update_in(cx, |workspace, window, cx| {
12605 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12606 workspace.add_panel(panel, window, cx);
12607 workspace.toggle_dock(DockPosition::Right, window, cx);
12608
12609 let right_dock = workspace.right_dock().read(cx);
12610 let right_width = right_dock
12611 .active_panel()
12612 .map(|p| workspace.resolved_dock_panel_size(&right_dock, p.as_ref(), window, cx))
12613 .expect("right dock should have an active panel");
12614
12615 let left_dock = workspace.left_dock().read(cx);
12616 let left_width = left_dock
12617 .active_panel()
12618 .map(|p| workspace.resolved_dock_panel_size(&left_dock, p.as_ref(), window, cx))
12619 .expect("left dock should still have an active panel");
12620
12621 let available_width = workspace.bounds.size.width - right_width;
12622 assert_eq!(
12623 left_width,
12624 available_width / 2.,
12625 "flexible left panel should shrink proportionally as the right dock takes space"
12626 );
12627 });
12628 }
12629
12630 struct TestModal(FocusHandle);
12631
12632 impl TestModal {
12633 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12634 Self(cx.focus_handle())
12635 }
12636 }
12637
12638 impl EventEmitter<DismissEvent> for TestModal {}
12639
12640 impl Focusable for TestModal {
12641 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12642 self.0.clone()
12643 }
12644 }
12645
12646 impl ModalView for TestModal {}
12647
12648 impl Render for TestModal {
12649 fn render(
12650 &mut self,
12651 _window: &mut Window,
12652 _cx: &mut Context<TestModal>,
12653 ) -> impl IntoElement {
12654 div().track_focus(&self.0)
12655 }
12656 }
12657
12658 #[gpui::test]
12659 async fn test_panels(cx: &mut gpui::TestAppContext) {
12660 init_test(cx);
12661 let fs = FakeFs::new(cx.executor());
12662
12663 let project = Project::test(fs, [], cx).await;
12664 let (multi_workspace, cx) =
12665 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12666 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12667
12668 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12669 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12670 workspace.add_panel(panel_1.clone(), window, cx);
12671 workspace.toggle_dock(DockPosition::Left, window, cx);
12672 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12673 workspace.add_panel(panel_2.clone(), window, cx);
12674 workspace.toggle_dock(DockPosition::Right, window, cx);
12675
12676 let left_dock = workspace.left_dock();
12677 assert_eq!(
12678 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12679 panel_1.panel_id()
12680 );
12681 assert_eq!(
12682 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
12683 px(300.)
12684 );
12685
12686 workspace.resize_left_dock(px(1337.), window, cx);
12687 assert_eq!(
12688 workspace
12689 .right_dock()
12690 .read(cx)
12691 .visible_panel()
12692 .unwrap()
12693 .panel_id(),
12694 panel_2.panel_id(),
12695 );
12696
12697 (panel_1, panel_2)
12698 });
12699
12700 // Move panel_1 to the right
12701 panel_1.update_in(cx, |panel_1, window, cx| {
12702 panel_1.set_position(DockPosition::Right, window, cx)
12703 });
12704
12705 workspace.update_in(cx, |workspace, window, cx| {
12706 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12707 // Since it was the only panel on the left, the left dock should now be closed.
12708 assert!(!workspace.left_dock().read(cx).is_open());
12709 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12710 let right_dock = workspace.right_dock();
12711 assert_eq!(
12712 right_dock.read(cx).visible_panel().unwrap().panel_id(),
12713 panel_1.panel_id()
12714 );
12715 assert_eq!(
12716 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
12717 px(1337.)
12718 );
12719
12720 // Now we move panel_2 to the left
12721 panel_2.set_position(DockPosition::Left, window, cx);
12722 });
12723
12724 workspace.update(cx, |workspace, cx| {
12725 // Since panel_2 was not visible on the right, we don't open the left dock.
12726 assert!(!workspace.left_dock().read(cx).is_open());
12727 // And the right dock is unaffected in its displaying of panel_1
12728 assert!(workspace.right_dock().read(cx).is_open());
12729 assert_eq!(
12730 workspace
12731 .right_dock()
12732 .read(cx)
12733 .visible_panel()
12734 .unwrap()
12735 .panel_id(),
12736 panel_1.panel_id(),
12737 );
12738 });
12739
12740 // Move panel_1 back to the left
12741 panel_1.update_in(cx, |panel_1, window, cx| {
12742 panel_1.set_position(DockPosition::Left, window, cx)
12743 });
12744
12745 workspace.update_in(cx, |workspace, window, cx| {
12746 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12747 let left_dock = workspace.left_dock();
12748 assert!(left_dock.read(cx).is_open());
12749 assert_eq!(
12750 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12751 panel_1.panel_id()
12752 );
12753 assert_eq!(
12754 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
12755 px(1337.)
12756 );
12757 // And the right dock should be closed as it no longer has any panels.
12758 assert!(!workspace.right_dock().read(cx).is_open());
12759
12760 // Now we move panel_1 to the bottom
12761 panel_1.set_position(DockPosition::Bottom, window, cx);
12762 });
12763
12764 workspace.update_in(cx, |workspace, window, cx| {
12765 // Since panel_1 was visible on the left, we close the left dock.
12766 assert!(!workspace.left_dock().read(cx).is_open());
12767 // The bottom dock is sized based on the panel's default size,
12768 // since the panel orientation changed from vertical to horizontal.
12769 let bottom_dock = workspace.bottom_dock();
12770 assert_eq!(
12771 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
12772 px(300.),
12773 );
12774 // Close bottom dock and move panel_1 back to the left.
12775 bottom_dock.update(cx, |bottom_dock, cx| {
12776 bottom_dock.set_open(false, window, cx)
12777 });
12778 panel_1.set_position(DockPosition::Left, window, cx);
12779 });
12780
12781 // Emit activated event on panel 1
12782 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12783
12784 // Now the left dock is open and panel_1 is active and focused.
12785 workspace.update_in(cx, |workspace, window, cx| {
12786 let left_dock = workspace.left_dock();
12787 assert!(left_dock.read(cx).is_open());
12788 assert_eq!(
12789 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12790 panel_1.panel_id(),
12791 );
12792 assert!(panel_1.focus_handle(cx).is_focused(window));
12793 });
12794
12795 // Emit closed event on panel 2, which is not active
12796 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12797
12798 // Wo don't close the left dock, because panel_2 wasn't the active panel
12799 workspace.update(cx, |workspace, cx| {
12800 let left_dock = workspace.left_dock();
12801 assert!(left_dock.read(cx).is_open());
12802 assert_eq!(
12803 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12804 panel_1.panel_id(),
12805 );
12806 });
12807
12808 // Emitting a ZoomIn event shows the panel as zoomed.
12809 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12810 workspace.read_with(cx, |workspace, _| {
12811 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12812 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12813 });
12814
12815 // Move panel to another dock while it is zoomed
12816 panel_1.update_in(cx, |panel, window, cx| {
12817 panel.set_position(DockPosition::Right, window, cx)
12818 });
12819 workspace.read_with(cx, |workspace, _| {
12820 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12821
12822 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12823 });
12824
12825 // This is a helper for getting a:
12826 // - valid focus on an element,
12827 // - that isn't a part of the panes and panels system of the Workspace,
12828 // - and doesn't trigger the 'on_focus_lost' API.
12829 let focus_other_view = {
12830 let workspace = workspace.clone();
12831 move |cx: &mut VisualTestContext| {
12832 workspace.update_in(cx, |workspace, window, cx| {
12833 if workspace.active_modal::<TestModal>(cx).is_some() {
12834 workspace.toggle_modal(window, cx, TestModal::new);
12835 workspace.toggle_modal(window, cx, TestModal::new);
12836 } else {
12837 workspace.toggle_modal(window, cx, TestModal::new);
12838 }
12839 })
12840 }
12841 };
12842
12843 // If focus is transferred to another view that's not a panel or another pane, we still show
12844 // the panel as zoomed.
12845 focus_other_view(cx);
12846 workspace.read_with(cx, |workspace, _| {
12847 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12848 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12849 });
12850
12851 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12852 workspace.update_in(cx, |_workspace, window, cx| {
12853 cx.focus_self(window);
12854 });
12855 workspace.read_with(cx, |workspace, _| {
12856 assert_eq!(workspace.zoomed, None);
12857 assert_eq!(workspace.zoomed_position, None);
12858 });
12859
12860 // If focus is transferred again to another view that's not a panel or a pane, we won't
12861 // show the panel as zoomed because it wasn't zoomed before.
12862 focus_other_view(cx);
12863 workspace.read_with(cx, |workspace, _| {
12864 assert_eq!(workspace.zoomed, None);
12865 assert_eq!(workspace.zoomed_position, None);
12866 });
12867
12868 // When the panel is activated, it is zoomed again.
12869 cx.dispatch_action(ToggleRightDock);
12870 workspace.read_with(cx, |workspace, _| {
12871 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12872 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12873 });
12874
12875 // Emitting a ZoomOut event unzooms the panel.
12876 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12877 workspace.read_with(cx, |workspace, _| {
12878 assert_eq!(workspace.zoomed, None);
12879 assert_eq!(workspace.zoomed_position, None);
12880 });
12881
12882 // Emit closed event on panel 1, which is active
12883 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12884
12885 // Now the left dock is closed, because panel_1 was the active panel
12886 workspace.update(cx, |workspace, cx| {
12887 let right_dock = workspace.right_dock();
12888 assert!(!right_dock.read(cx).is_open());
12889 });
12890 }
12891
12892 #[gpui::test]
12893 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12894 init_test(cx);
12895
12896 let fs = FakeFs::new(cx.background_executor.clone());
12897 let project = Project::test(fs, [], cx).await;
12898 let (workspace, cx) =
12899 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12900 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12901
12902 let dirty_regular_buffer = cx.new(|cx| {
12903 TestItem::new(cx)
12904 .with_dirty(true)
12905 .with_label("1.txt")
12906 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12907 });
12908 let dirty_regular_buffer_2 = cx.new(|cx| {
12909 TestItem::new(cx)
12910 .with_dirty(true)
12911 .with_label("2.txt")
12912 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12913 });
12914 let dirty_multi_buffer_with_both = cx.new(|cx| {
12915 TestItem::new(cx)
12916 .with_dirty(true)
12917 .with_buffer_kind(ItemBufferKind::Multibuffer)
12918 .with_label("Fake Project Search")
12919 .with_project_items(&[
12920 dirty_regular_buffer.read(cx).project_items[0].clone(),
12921 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12922 ])
12923 });
12924 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12925 workspace.update_in(cx, |workspace, window, cx| {
12926 workspace.add_item(
12927 pane.clone(),
12928 Box::new(dirty_regular_buffer.clone()),
12929 None,
12930 false,
12931 false,
12932 window,
12933 cx,
12934 );
12935 workspace.add_item(
12936 pane.clone(),
12937 Box::new(dirty_regular_buffer_2.clone()),
12938 None,
12939 false,
12940 false,
12941 window,
12942 cx,
12943 );
12944 workspace.add_item(
12945 pane.clone(),
12946 Box::new(dirty_multi_buffer_with_both.clone()),
12947 None,
12948 false,
12949 false,
12950 window,
12951 cx,
12952 );
12953 });
12954
12955 pane.update_in(cx, |pane, window, cx| {
12956 pane.activate_item(2, true, true, window, cx);
12957 assert_eq!(
12958 pane.active_item().unwrap().item_id(),
12959 multi_buffer_with_both_files_id,
12960 "Should select the multi buffer in the pane"
12961 );
12962 });
12963 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12964 pane.close_other_items(
12965 &CloseOtherItems {
12966 save_intent: Some(SaveIntent::Save),
12967 close_pinned: true,
12968 },
12969 None,
12970 window,
12971 cx,
12972 )
12973 });
12974 cx.background_executor.run_until_parked();
12975 assert!(!cx.has_pending_prompt());
12976 close_all_but_multi_buffer_task
12977 .await
12978 .expect("Closing all buffers but the multi buffer failed");
12979 pane.update(cx, |pane, cx| {
12980 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12981 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12982 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12983 assert_eq!(pane.items_len(), 1);
12984 assert_eq!(
12985 pane.active_item().unwrap().item_id(),
12986 multi_buffer_with_both_files_id,
12987 "Should have only the multi buffer left in the pane"
12988 );
12989 assert!(
12990 dirty_multi_buffer_with_both.read(cx).is_dirty,
12991 "The multi buffer containing the unsaved buffer should still be dirty"
12992 );
12993 });
12994
12995 dirty_regular_buffer.update(cx, |buffer, cx| {
12996 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12997 });
12998
12999 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13000 pane.close_active_item(
13001 &CloseActiveItem {
13002 save_intent: Some(SaveIntent::Close),
13003 close_pinned: false,
13004 },
13005 window,
13006 cx,
13007 )
13008 });
13009 cx.background_executor.run_until_parked();
13010 assert!(
13011 cx.has_pending_prompt(),
13012 "Dirty multi buffer should prompt a save dialog"
13013 );
13014 cx.simulate_prompt_answer("Save");
13015 cx.background_executor.run_until_parked();
13016 close_multi_buffer_task
13017 .await
13018 .expect("Closing the multi buffer failed");
13019 pane.update(cx, |pane, cx| {
13020 assert_eq!(
13021 dirty_multi_buffer_with_both.read(cx).save_count,
13022 1,
13023 "Multi buffer item should get be saved"
13024 );
13025 // Test impl does not save inner items, so we do not assert them
13026 assert_eq!(
13027 pane.items_len(),
13028 0,
13029 "No more items should be left in the pane"
13030 );
13031 assert!(pane.active_item().is_none());
13032 });
13033 }
13034
13035 #[gpui::test]
13036 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13037 cx: &mut TestAppContext,
13038 ) {
13039 init_test(cx);
13040
13041 let fs = FakeFs::new(cx.background_executor.clone());
13042 let project = Project::test(fs, [], cx).await;
13043 let (workspace, cx) =
13044 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13045 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13046
13047 let dirty_regular_buffer = cx.new(|cx| {
13048 TestItem::new(cx)
13049 .with_dirty(true)
13050 .with_label("1.txt")
13051 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13052 });
13053 let dirty_regular_buffer_2 = cx.new(|cx| {
13054 TestItem::new(cx)
13055 .with_dirty(true)
13056 .with_label("2.txt")
13057 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13058 });
13059 let clear_regular_buffer = cx.new(|cx| {
13060 TestItem::new(cx)
13061 .with_label("3.txt")
13062 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13063 });
13064
13065 let dirty_multi_buffer_with_both = cx.new(|cx| {
13066 TestItem::new(cx)
13067 .with_dirty(true)
13068 .with_buffer_kind(ItemBufferKind::Multibuffer)
13069 .with_label("Fake Project Search")
13070 .with_project_items(&[
13071 dirty_regular_buffer.read(cx).project_items[0].clone(),
13072 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13073 clear_regular_buffer.read(cx).project_items[0].clone(),
13074 ])
13075 });
13076 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13077 workspace.update_in(cx, |workspace, window, cx| {
13078 workspace.add_item(
13079 pane.clone(),
13080 Box::new(dirty_regular_buffer.clone()),
13081 None,
13082 false,
13083 false,
13084 window,
13085 cx,
13086 );
13087 workspace.add_item(
13088 pane.clone(),
13089 Box::new(dirty_multi_buffer_with_both.clone()),
13090 None,
13091 false,
13092 false,
13093 window,
13094 cx,
13095 );
13096 });
13097
13098 pane.update_in(cx, |pane, window, cx| {
13099 pane.activate_item(1, true, true, window, cx);
13100 assert_eq!(
13101 pane.active_item().unwrap().item_id(),
13102 multi_buffer_with_both_files_id,
13103 "Should select the multi buffer in the pane"
13104 );
13105 });
13106 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13107 pane.close_active_item(
13108 &CloseActiveItem {
13109 save_intent: None,
13110 close_pinned: false,
13111 },
13112 window,
13113 cx,
13114 )
13115 });
13116 cx.background_executor.run_until_parked();
13117 assert!(
13118 cx.has_pending_prompt(),
13119 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13120 );
13121 }
13122
13123 /// Tests that when `close_on_file_delete` is enabled, files are automatically
13124 /// closed when they are deleted from disk.
13125 #[gpui::test]
13126 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13127 init_test(cx);
13128
13129 // Enable the close_on_disk_deletion setting
13130 cx.update_global(|store: &mut SettingsStore, cx| {
13131 store.update_user_settings(cx, |settings| {
13132 settings.workspace.close_on_file_delete = Some(true);
13133 });
13134 });
13135
13136 let fs = FakeFs::new(cx.background_executor.clone());
13137 let project = Project::test(fs, [], cx).await;
13138 let (workspace, cx) =
13139 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13140 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13141
13142 // Create a test item that simulates a file
13143 let item = cx.new(|cx| {
13144 TestItem::new(cx)
13145 .with_label("test.txt")
13146 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13147 });
13148
13149 // Add item to workspace
13150 workspace.update_in(cx, |workspace, window, cx| {
13151 workspace.add_item(
13152 pane.clone(),
13153 Box::new(item.clone()),
13154 None,
13155 false,
13156 false,
13157 window,
13158 cx,
13159 );
13160 });
13161
13162 // Verify the item is in the pane
13163 pane.read_with(cx, |pane, _| {
13164 assert_eq!(pane.items().count(), 1);
13165 });
13166
13167 // Simulate file deletion by setting the item's deleted state
13168 item.update(cx, |item, _| {
13169 item.set_has_deleted_file(true);
13170 });
13171
13172 // Emit UpdateTab event to trigger the close behavior
13173 cx.run_until_parked();
13174 item.update(cx, |_, cx| {
13175 cx.emit(ItemEvent::UpdateTab);
13176 });
13177
13178 // Allow the close operation to complete
13179 cx.run_until_parked();
13180
13181 // Verify the item was automatically closed
13182 pane.read_with(cx, |pane, _| {
13183 assert_eq!(
13184 pane.items().count(),
13185 0,
13186 "Item should be automatically closed when file is deleted"
13187 );
13188 });
13189 }
13190
13191 /// Tests that when `close_on_file_delete` is disabled (default), files remain
13192 /// open with a strikethrough when they are deleted from disk.
13193 #[gpui::test]
13194 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13195 init_test(cx);
13196
13197 // Ensure close_on_disk_deletion is disabled (default)
13198 cx.update_global(|store: &mut SettingsStore, cx| {
13199 store.update_user_settings(cx, |settings| {
13200 settings.workspace.close_on_file_delete = Some(false);
13201 });
13202 });
13203
13204 let fs = FakeFs::new(cx.background_executor.clone());
13205 let project = Project::test(fs, [], cx).await;
13206 let (workspace, cx) =
13207 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13208 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13209
13210 // Create a test item that simulates a file
13211 let item = cx.new(|cx| {
13212 TestItem::new(cx)
13213 .with_label("test.txt")
13214 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13215 });
13216
13217 // Add item to workspace
13218 workspace.update_in(cx, |workspace, window, cx| {
13219 workspace.add_item(
13220 pane.clone(),
13221 Box::new(item.clone()),
13222 None,
13223 false,
13224 false,
13225 window,
13226 cx,
13227 );
13228 });
13229
13230 // Verify the item is in the pane
13231 pane.read_with(cx, |pane, _| {
13232 assert_eq!(pane.items().count(), 1);
13233 });
13234
13235 // Simulate file deletion
13236 item.update(cx, |item, _| {
13237 item.set_has_deleted_file(true);
13238 });
13239
13240 // Emit UpdateTab event
13241 cx.run_until_parked();
13242 item.update(cx, |_, cx| {
13243 cx.emit(ItemEvent::UpdateTab);
13244 });
13245
13246 // Allow any potential close operation to complete
13247 cx.run_until_parked();
13248
13249 // Verify the item remains open (with strikethrough)
13250 pane.read_with(cx, |pane, _| {
13251 assert_eq!(
13252 pane.items().count(),
13253 1,
13254 "Item should remain open when close_on_disk_deletion is disabled"
13255 );
13256 });
13257
13258 // Verify the item shows as deleted
13259 item.read_with(cx, |item, _| {
13260 assert!(
13261 item.has_deleted_file,
13262 "Item should be marked as having deleted file"
13263 );
13264 });
13265 }
13266
13267 /// Tests that dirty files are not automatically closed when deleted from disk,
13268 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13269 /// unsaved changes without being prompted.
13270 #[gpui::test]
13271 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13272 init_test(cx);
13273
13274 // Enable the close_on_file_delete setting
13275 cx.update_global(|store: &mut SettingsStore, cx| {
13276 store.update_user_settings(cx, |settings| {
13277 settings.workspace.close_on_file_delete = Some(true);
13278 });
13279 });
13280
13281 let fs = FakeFs::new(cx.background_executor.clone());
13282 let project = Project::test(fs, [], cx).await;
13283 let (workspace, cx) =
13284 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13285 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13286
13287 // Create a dirty test item
13288 let item = cx.new(|cx| {
13289 TestItem::new(cx)
13290 .with_dirty(true)
13291 .with_label("test.txt")
13292 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13293 });
13294
13295 // Add item to workspace
13296 workspace.update_in(cx, |workspace, window, cx| {
13297 workspace.add_item(
13298 pane.clone(),
13299 Box::new(item.clone()),
13300 None,
13301 false,
13302 false,
13303 window,
13304 cx,
13305 );
13306 });
13307
13308 // Simulate file deletion
13309 item.update(cx, |item, _| {
13310 item.set_has_deleted_file(true);
13311 });
13312
13313 // Emit UpdateTab event to trigger the close behavior
13314 cx.run_until_parked();
13315 item.update(cx, |_, cx| {
13316 cx.emit(ItemEvent::UpdateTab);
13317 });
13318
13319 // Allow any potential close operation to complete
13320 cx.run_until_parked();
13321
13322 // Verify the item remains open (dirty files are not auto-closed)
13323 pane.read_with(cx, |pane, _| {
13324 assert_eq!(
13325 pane.items().count(),
13326 1,
13327 "Dirty items should not be automatically closed even when file is deleted"
13328 );
13329 });
13330
13331 // Verify the item is marked as deleted and still dirty
13332 item.read_with(cx, |item, _| {
13333 assert!(
13334 item.has_deleted_file,
13335 "Item should be marked as having deleted file"
13336 );
13337 assert!(item.is_dirty, "Item should still be dirty");
13338 });
13339 }
13340
13341 /// Tests that navigation history is cleaned up when files are auto-closed
13342 /// due to deletion from disk.
13343 #[gpui::test]
13344 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13345 init_test(cx);
13346
13347 // Enable the close_on_file_delete setting
13348 cx.update_global(|store: &mut SettingsStore, cx| {
13349 store.update_user_settings(cx, |settings| {
13350 settings.workspace.close_on_file_delete = Some(true);
13351 });
13352 });
13353
13354 let fs = FakeFs::new(cx.background_executor.clone());
13355 let project = Project::test(fs, [], cx).await;
13356 let (workspace, cx) =
13357 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13358 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13359
13360 // Create test items
13361 let item1 = cx.new(|cx| {
13362 TestItem::new(cx)
13363 .with_label("test1.txt")
13364 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13365 });
13366 let item1_id = item1.item_id();
13367
13368 let item2 = cx.new(|cx| {
13369 TestItem::new(cx)
13370 .with_label("test2.txt")
13371 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13372 });
13373
13374 // Add items to workspace
13375 workspace.update_in(cx, |workspace, window, cx| {
13376 workspace.add_item(
13377 pane.clone(),
13378 Box::new(item1.clone()),
13379 None,
13380 false,
13381 false,
13382 window,
13383 cx,
13384 );
13385 workspace.add_item(
13386 pane.clone(),
13387 Box::new(item2.clone()),
13388 None,
13389 false,
13390 false,
13391 window,
13392 cx,
13393 );
13394 });
13395
13396 // Activate item1 to ensure it gets navigation entries
13397 pane.update_in(cx, |pane, window, cx| {
13398 pane.activate_item(0, true, true, window, cx);
13399 });
13400
13401 // Switch to item2 and back to create navigation history
13402 pane.update_in(cx, |pane, window, cx| {
13403 pane.activate_item(1, true, true, window, cx);
13404 });
13405 cx.run_until_parked();
13406
13407 pane.update_in(cx, |pane, window, cx| {
13408 pane.activate_item(0, true, true, window, cx);
13409 });
13410 cx.run_until_parked();
13411
13412 // Simulate file deletion for item1
13413 item1.update(cx, |item, _| {
13414 item.set_has_deleted_file(true);
13415 });
13416
13417 // Emit UpdateTab event to trigger the close behavior
13418 item1.update(cx, |_, cx| {
13419 cx.emit(ItemEvent::UpdateTab);
13420 });
13421 cx.run_until_parked();
13422
13423 // Verify item1 was closed
13424 pane.read_with(cx, |pane, _| {
13425 assert_eq!(
13426 pane.items().count(),
13427 1,
13428 "Should have 1 item remaining after auto-close"
13429 );
13430 });
13431
13432 // Check navigation history after close
13433 let has_item = pane.read_with(cx, |pane, cx| {
13434 let mut has_item = false;
13435 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13436 if entry.item.id() == item1_id {
13437 has_item = true;
13438 }
13439 });
13440 has_item
13441 });
13442
13443 assert!(
13444 !has_item,
13445 "Navigation history should not contain closed item entries"
13446 );
13447 }
13448
13449 #[gpui::test]
13450 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13451 cx: &mut TestAppContext,
13452 ) {
13453 init_test(cx);
13454
13455 let fs = FakeFs::new(cx.background_executor.clone());
13456 let project = Project::test(fs, [], cx).await;
13457 let (workspace, cx) =
13458 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13459 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13460
13461 let dirty_regular_buffer = cx.new(|cx| {
13462 TestItem::new(cx)
13463 .with_dirty(true)
13464 .with_label("1.txt")
13465 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13466 });
13467 let dirty_regular_buffer_2 = cx.new(|cx| {
13468 TestItem::new(cx)
13469 .with_dirty(true)
13470 .with_label("2.txt")
13471 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13472 });
13473 let clear_regular_buffer = cx.new(|cx| {
13474 TestItem::new(cx)
13475 .with_label("3.txt")
13476 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13477 });
13478
13479 let dirty_multi_buffer = cx.new(|cx| {
13480 TestItem::new(cx)
13481 .with_dirty(true)
13482 .with_buffer_kind(ItemBufferKind::Multibuffer)
13483 .with_label("Fake Project Search")
13484 .with_project_items(&[
13485 dirty_regular_buffer.read(cx).project_items[0].clone(),
13486 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13487 clear_regular_buffer.read(cx).project_items[0].clone(),
13488 ])
13489 });
13490 workspace.update_in(cx, |workspace, window, cx| {
13491 workspace.add_item(
13492 pane.clone(),
13493 Box::new(dirty_regular_buffer.clone()),
13494 None,
13495 false,
13496 false,
13497 window,
13498 cx,
13499 );
13500 workspace.add_item(
13501 pane.clone(),
13502 Box::new(dirty_regular_buffer_2.clone()),
13503 None,
13504 false,
13505 false,
13506 window,
13507 cx,
13508 );
13509 workspace.add_item(
13510 pane.clone(),
13511 Box::new(dirty_multi_buffer.clone()),
13512 None,
13513 false,
13514 false,
13515 window,
13516 cx,
13517 );
13518 });
13519
13520 pane.update_in(cx, |pane, window, cx| {
13521 pane.activate_item(2, true, true, window, cx);
13522 assert_eq!(
13523 pane.active_item().unwrap().item_id(),
13524 dirty_multi_buffer.item_id(),
13525 "Should select the multi buffer in the pane"
13526 );
13527 });
13528 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13529 pane.close_active_item(
13530 &CloseActiveItem {
13531 save_intent: None,
13532 close_pinned: false,
13533 },
13534 window,
13535 cx,
13536 )
13537 });
13538 cx.background_executor.run_until_parked();
13539 assert!(
13540 !cx.has_pending_prompt(),
13541 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13542 );
13543 close_multi_buffer_task
13544 .await
13545 .expect("Closing multi buffer failed");
13546 pane.update(cx, |pane, cx| {
13547 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13548 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13549 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13550 assert_eq!(
13551 pane.items()
13552 .map(|item| item.item_id())
13553 .sorted()
13554 .collect::<Vec<_>>(),
13555 vec![
13556 dirty_regular_buffer.item_id(),
13557 dirty_regular_buffer_2.item_id(),
13558 ],
13559 "Should have no multi buffer left in the pane"
13560 );
13561 assert!(dirty_regular_buffer.read(cx).is_dirty);
13562 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13563 });
13564 }
13565
13566 #[gpui::test]
13567 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13568 init_test(cx);
13569 let fs = FakeFs::new(cx.executor());
13570 let project = Project::test(fs, [], cx).await;
13571 let (multi_workspace, cx) =
13572 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13573 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13574
13575 // Add a new panel to the right dock, opening the dock and setting the
13576 // focus to the new panel.
13577 let panel = workspace.update_in(cx, |workspace, window, cx| {
13578 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13579 workspace.add_panel(panel.clone(), window, cx);
13580
13581 workspace
13582 .right_dock()
13583 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13584
13585 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13586
13587 panel
13588 });
13589
13590 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13591 // panel to the next valid position which, in this case, is the left
13592 // dock.
13593 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13594 workspace.update(cx, |workspace, cx| {
13595 assert!(workspace.left_dock().read(cx).is_open());
13596 assert_eq!(panel.read(cx).position, DockPosition::Left);
13597 });
13598
13599 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13600 // panel to the next valid position which, in this case, is the bottom
13601 // dock.
13602 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13603 workspace.update(cx, |workspace, cx| {
13604 assert!(workspace.bottom_dock().read(cx).is_open());
13605 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13606 });
13607
13608 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13609 // around moving the panel to its initial position, the right dock.
13610 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13611 workspace.update(cx, |workspace, cx| {
13612 assert!(workspace.right_dock().read(cx).is_open());
13613 assert_eq!(panel.read(cx).position, DockPosition::Right);
13614 });
13615
13616 // Remove focus from the panel, ensuring that, if the panel is not
13617 // focused, the `MoveFocusedPanelToNextPosition` action does not update
13618 // the panel's position, so the panel is still in the right dock.
13619 workspace.update_in(cx, |workspace, window, cx| {
13620 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13621 });
13622
13623 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13624 workspace.update(cx, |workspace, cx| {
13625 assert!(workspace.right_dock().read(cx).is_open());
13626 assert_eq!(panel.read(cx).position, DockPosition::Right);
13627 });
13628 }
13629
13630 #[gpui::test]
13631 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13632 init_test(cx);
13633
13634 let fs = FakeFs::new(cx.executor());
13635 let project = Project::test(fs, [], cx).await;
13636 let (workspace, cx) =
13637 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13638
13639 let item_1 = cx.new(|cx| {
13640 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13641 });
13642 workspace.update_in(cx, |workspace, window, cx| {
13643 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13644 workspace.move_item_to_pane_in_direction(
13645 &MoveItemToPaneInDirection {
13646 direction: SplitDirection::Right,
13647 focus: true,
13648 clone: false,
13649 },
13650 window,
13651 cx,
13652 );
13653 workspace.move_item_to_pane_at_index(
13654 &MoveItemToPane {
13655 destination: 3,
13656 focus: true,
13657 clone: false,
13658 },
13659 window,
13660 cx,
13661 );
13662
13663 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13664 assert_eq!(
13665 pane_items_paths(&workspace.active_pane, cx),
13666 vec!["first.txt".to_string()],
13667 "Single item was not moved anywhere"
13668 );
13669 });
13670
13671 let item_2 = cx.new(|cx| {
13672 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13673 });
13674 workspace.update_in(cx, |workspace, window, cx| {
13675 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13676 assert_eq!(
13677 pane_items_paths(&workspace.panes[0], cx),
13678 vec!["first.txt".to_string(), "second.txt".to_string()],
13679 );
13680 workspace.move_item_to_pane_in_direction(
13681 &MoveItemToPaneInDirection {
13682 direction: SplitDirection::Right,
13683 focus: true,
13684 clone: false,
13685 },
13686 window,
13687 cx,
13688 );
13689
13690 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13691 assert_eq!(
13692 pane_items_paths(&workspace.panes[0], cx),
13693 vec!["first.txt".to_string()],
13694 "After moving, one item should be left in the original pane"
13695 );
13696 assert_eq!(
13697 pane_items_paths(&workspace.panes[1], cx),
13698 vec!["second.txt".to_string()],
13699 "New item should have been moved to the new pane"
13700 );
13701 });
13702
13703 let item_3 = cx.new(|cx| {
13704 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13705 });
13706 workspace.update_in(cx, |workspace, window, cx| {
13707 let original_pane = workspace.panes[0].clone();
13708 workspace.set_active_pane(&original_pane, window, cx);
13709 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13710 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13711 assert_eq!(
13712 pane_items_paths(&workspace.active_pane, cx),
13713 vec!["first.txt".to_string(), "third.txt".to_string()],
13714 "New pane should be ready to move one item out"
13715 );
13716
13717 workspace.move_item_to_pane_at_index(
13718 &MoveItemToPane {
13719 destination: 3,
13720 focus: true,
13721 clone: false,
13722 },
13723 window,
13724 cx,
13725 );
13726 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13727 assert_eq!(
13728 pane_items_paths(&workspace.active_pane, cx),
13729 vec!["first.txt".to_string()],
13730 "After moving, one item should be left in the original pane"
13731 );
13732 assert_eq!(
13733 pane_items_paths(&workspace.panes[1], cx),
13734 vec!["second.txt".to_string()],
13735 "Previously created pane should be unchanged"
13736 );
13737 assert_eq!(
13738 pane_items_paths(&workspace.panes[2], cx),
13739 vec!["third.txt".to_string()],
13740 "New item should have been moved to the new pane"
13741 );
13742 });
13743 }
13744
13745 #[gpui::test]
13746 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13747 init_test(cx);
13748
13749 let fs = FakeFs::new(cx.executor());
13750 let project = Project::test(fs, [], cx).await;
13751 let (workspace, cx) =
13752 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13753
13754 let item_1 = cx.new(|cx| {
13755 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13756 });
13757 workspace.update_in(cx, |workspace, window, cx| {
13758 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13759 workspace.move_item_to_pane_in_direction(
13760 &MoveItemToPaneInDirection {
13761 direction: SplitDirection::Right,
13762 focus: true,
13763 clone: true,
13764 },
13765 window,
13766 cx,
13767 );
13768 });
13769 cx.run_until_parked();
13770 workspace.update_in(cx, |workspace, window, cx| {
13771 workspace.move_item_to_pane_at_index(
13772 &MoveItemToPane {
13773 destination: 3,
13774 focus: true,
13775 clone: true,
13776 },
13777 window,
13778 cx,
13779 );
13780 });
13781 cx.run_until_parked();
13782
13783 workspace.update(cx, |workspace, cx| {
13784 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13785 for pane in workspace.panes() {
13786 assert_eq!(
13787 pane_items_paths(pane, cx),
13788 vec!["first.txt".to_string()],
13789 "Single item exists in all panes"
13790 );
13791 }
13792 });
13793
13794 // verify that the active pane has been updated after waiting for the
13795 // pane focus event to fire and resolve
13796 workspace.read_with(cx, |workspace, _app| {
13797 assert_eq!(
13798 workspace.active_pane(),
13799 &workspace.panes[2],
13800 "The third pane should be the active one: {:?}",
13801 workspace.panes
13802 );
13803 })
13804 }
13805
13806 #[gpui::test]
13807 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13808 init_test(cx);
13809
13810 let fs = FakeFs::new(cx.executor());
13811 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13812
13813 let project = Project::test(fs, ["root".as_ref()], cx).await;
13814 let (workspace, cx) =
13815 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13816
13817 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13818 // Add item to pane A with project path
13819 let item_a = cx.new(|cx| {
13820 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13821 });
13822 workspace.update_in(cx, |workspace, window, cx| {
13823 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13824 });
13825
13826 // Split to create pane B
13827 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13828 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13829 });
13830
13831 // Add item with SAME project path to pane B, and pin it
13832 let item_b = cx.new(|cx| {
13833 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13834 });
13835 pane_b.update_in(cx, |pane, window, cx| {
13836 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13837 pane.set_pinned_count(1);
13838 });
13839
13840 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13841 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13842
13843 // close_pinned: false should only close the unpinned copy
13844 workspace.update_in(cx, |workspace, window, cx| {
13845 workspace.close_item_in_all_panes(
13846 &CloseItemInAllPanes {
13847 save_intent: Some(SaveIntent::Close),
13848 close_pinned: false,
13849 },
13850 window,
13851 cx,
13852 )
13853 });
13854 cx.executor().run_until_parked();
13855
13856 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13857 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13858 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13859 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13860
13861 // Split again, seeing as closing the previous item also closed its
13862 // pane, so only pane remains, which does not allow us to properly test
13863 // that both items close when `close_pinned: true`.
13864 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13865 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13866 });
13867
13868 // Add an item with the same project path to pane C so that
13869 // close_item_in_all_panes can determine what to close across all panes
13870 // (it reads the active item from the active pane, and split_pane
13871 // creates an empty pane).
13872 let item_c = cx.new(|cx| {
13873 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13874 });
13875 pane_c.update_in(cx, |pane, window, cx| {
13876 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13877 });
13878
13879 // close_pinned: true should close the pinned copy too
13880 workspace.update_in(cx, |workspace, window, cx| {
13881 let panes_count = workspace.panes().len();
13882 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13883
13884 workspace.close_item_in_all_panes(
13885 &CloseItemInAllPanes {
13886 save_intent: Some(SaveIntent::Close),
13887 close_pinned: true,
13888 },
13889 window,
13890 cx,
13891 )
13892 });
13893 cx.executor().run_until_parked();
13894
13895 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13896 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13897 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13898 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13899 }
13900
13901 mod register_project_item_tests {
13902
13903 use super::*;
13904
13905 // View
13906 struct TestPngItemView {
13907 focus_handle: FocusHandle,
13908 }
13909 // Model
13910 struct TestPngItem {}
13911
13912 impl project::ProjectItem for TestPngItem {
13913 fn try_open(
13914 _project: &Entity<Project>,
13915 path: &ProjectPath,
13916 cx: &mut App,
13917 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13918 if path.path.extension().unwrap() == "png" {
13919 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13920 } else {
13921 None
13922 }
13923 }
13924
13925 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13926 None
13927 }
13928
13929 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13930 None
13931 }
13932
13933 fn is_dirty(&self) -> bool {
13934 false
13935 }
13936 }
13937
13938 impl Item for TestPngItemView {
13939 type Event = ();
13940 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13941 "".into()
13942 }
13943 }
13944 impl EventEmitter<()> for TestPngItemView {}
13945 impl Focusable for TestPngItemView {
13946 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13947 self.focus_handle.clone()
13948 }
13949 }
13950
13951 impl Render for TestPngItemView {
13952 fn render(
13953 &mut self,
13954 _window: &mut Window,
13955 _cx: &mut Context<Self>,
13956 ) -> impl IntoElement {
13957 Empty
13958 }
13959 }
13960
13961 impl ProjectItem for TestPngItemView {
13962 type Item = TestPngItem;
13963
13964 fn for_project_item(
13965 _project: Entity<Project>,
13966 _pane: Option<&Pane>,
13967 _item: Entity<Self::Item>,
13968 _: &mut Window,
13969 cx: &mut Context<Self>,
13970 ) -> Self
13971 where
13972 Self: Sized,
13973 {
13974 Self {
13975 focus_handle: cx.focus_handle(),
13976 }
13977 }
13978 }
13979
13980 // View
13981 struct TestIpynbItemView {
13982 focus_handle: FocusHandle,
13983 }
13984 // Model
13985 struct TestIpynbItem {}
13986
13987 impl project::ProjectItem for TestIpynbItem {
13988 fn try_open(
13989 _project: &Entity<Project>,
13990 path: &ProjectPath,
13991 cx: &mut App,
13992 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13993 if path.path.extension().unwrap() == "ipynb" {
13994 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13995 } else {
13996 None
13997 }
13998 }
13999
14000 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14001 None
14002 }
14003
14004 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14005 None
14006 }
14007
14008 fn is_dirty(&self) -> bool {
14009 false
14010 }
14011 }
14012
14013 impl Item for TestIpynbItemView {
14014 type Event = ();
14015 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14016 "".into()
14017 }
14018 }
14019 impl EventEmitter<()> for TestIpynbItemView {}
14020 impl Focusable for TestIpynbItemView {
14021 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14022 self.focus_handle.clone()
14023 }
14024 }
14025
14026 impl Render for TestIpynbItemView {
14027 fn render(
14028 &mut self,
14029 _window: &mut Window,
14030 _cx: &mut Context<Self>,
14031 ) -> impl IntoElement {
14032 Empty
14033 }
14034 }
14035
14036 impl ProjectItem for TestIpynbItemView {
14037 type Item = TestIpynbItem;
14038
14039 fn for_project_item(
14040 _project: Entity<Project>,
14041 _pane: Option<&Pane>,
14042 _item: Entity<Self::Item>,
14043 _: &mut Window,
14044 cx: &mut Context<Self>,
14045 ) -> Self
14046 where
14047 Self: Sized,
14048 {
14049 Self {
14050 focus_handle: cx.focus_handle(),
14051 }
14052 }
14053 }
14054
14055 struct TestAlternatePngItemView {
14056 focus_handle: FocusHandle,
14057 }
14058
14059 impl Item for TestAlternatePngItemView {
14060 type Event = ();
14061 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14062 "".into()
14063 }
14064 }
14065
14066 impl EventEmitter<()> for TestAlternatePngItemView {}
14067 impl Focusable for TestAlternatePngItemView {
14068 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14069 self.focus_handle.clone()
14070 }
14071 }
14072
14073 impl Render for TestAlternatePngItemView {
14074 fn render(
14075 &mut self,
14076 _window: &mut Window,
14077 _cx: &mut Context<Self>,
14078 ) -> impl IntoElement {
14079 Empty
14080 }
14081 }
14082
14083 impl ProjectItem for TestAlternatePngItemView {
14084 type Item = TestPngItem;
14085
14086 fn for_project_item(
14087 _project: Entity<Project>,
14088 _pane: Option<&Pane>,
14089 _item: Entity<Self::Item>,
14090 _: &mut Window,
14091 cx: &mut Context<Self>,
14092 ) -> Self
14093 where
14094 Self: Sized,
14095 {
14096 Self {
14097 focus_handle: cx.focus_handle(),
14098 }
14099 }
14100 }
14101
14102 #[gpui::test]
14103 async fn test_register_project_item(cx: &mut TestAppContext) {
14104 init_test(cx);
14105
14106 cx.update(|cx| {
14107 register_project_item::<TestPngItemView>(cx);
14108 register_project_item::<TestIpynbItemView>(cx);
14109 });
14110
14111 let fs = FakeFs::new(cx.executor());
14112 fs.insert_tree(
14113 "/root1",
14114 json!({
14115 "one.png": "BINARYDATAHERE",
14116 "two.ipynb": "{ totally a notebook }",
14117 "three.txt": "editing text, sure why not?"
14118 }),
14119 )
14120 .await;
14121
14122 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14123 let (workspace, cx) =
14124 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14125
14126 let worktree_id = project.update(cx, |project, cx| {
14127 project.worktrees(cx).next().unwrap().read(cx).id()
14128 });
14129
14130 let handle = workspace
14131 .update_in(cx, |workspace, window, cx| {
14132 let project_path = (worktree_id, rel_path("one.png"));
14133 workspace.open_path(project_path, None, true, window, cx)
14134 })
14135 .await
14136 .unwrap();
14137
14138 // Now we can check if the handle we got back errored or not
14139 assert_eq!(
14140 handle.to_any_view().entity_type(),
14141 TypeId::of::<TestPngItemView>()
14142 );
14143
14144 let handle = workspace
14145 .update_in(cx, |workspace, window, cx| {
14146 let project_path = (worktree_id, rel_path("two.ipynb"));
14147 workspace.open_path(project_path, None, true, window, cx)
14148 })
14149 .await
14150 .unwrap();
14151
14152 assert_eq!(
14153 handle.to_any_view().entity_type(),
14154 TypeId::of::<TestIpynbItemView>()
14155 );
14156
14157 let handle = workspace
14158 .update_in(cx, |workspace, window, cx| {
14159 let project_path = (worktree_id, rel_path("three.txt"));
14160 workspace.open_path(project_path, None, true, window, cx)
14161 })
14162 .await;
14163 assert!(handle.is_err());
14164 }
14165
14166 #[gpui::test]
14167 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14168 init_test(cx);
14169
14170 cx.update(|cx| {
14171 register_project_item::<TestPngItemView>(cx);
14172 register_project_item::<TestAlternatePngItemView>(cx);
14173 });
14174
14175 let fs = FakeFs::new(cx.executor());
14176 fs.insert_tree(
14177 "/root1",
14178 json!({
14179 "one.png": "BINARYDATAHERE",
14180 "two.ipynb": "{ totally a notebook }",
14181 "three.txt": "editing text, sure why not?"
14182 }),
14183 )
14184 .await;
14185 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14186 let (workspace, cx) =
14187 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14188 let worktree_id = project.update(cx, |project, cx| {
14189 project.worktrees(cx).next().unwrap().read(cx).id()
14190 });
14191
14192 let handle = workspace
14193 .update_in(cx, |workspace, window, cx| {
14194 let project_path = (worktree_id, rel_path("one.png"));
14195 workspace.open_path(project_path, None, true, window, cx)
14196 })
14197 .await
14198 .unwrap();
14199
14200 // This _must_ be the second item registered
14201 assert_eq!(
14202 handle.to_any_view().entity_type(),
14203 TypeId::of::<TestAlternatePngItemView>()
14204 );
14205
14206 let handle = workspace
14207 .update_in(cx, |workspace, window, cx| {
14208 let project_path = (worktree_id, rel_path("three.txt"));
14209 workspace.open_path(project_path, None, true, window, cx)
14210 })
14211 .await;
14212 assert!(handle.is_err());
14213 }
14214 }
14215
14216 #[gpui::test]
14217 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14218 init_test(cx);
14219
14220 let fs = FakeFs::new(cx.executor());
14221 let project = Project::test(fs, [], cx).await;
14222 let (workspace, _cx) =
14223 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14224
14225 // Test with status bar shown (default)
14226 workspace.read_with(cx, |workspace, cx| {
14227 let visible = workspace.status_bar_visible(cx);
14228 assert!(visible, "Status bar should be visible by default");
14229 });
14230
14231 // Test with status bar hidden
14232 cx.update_global(|store: &mut SettingsStore, cx| {
14233 store.update_user_settings(cx, |settings| {
14234 settings.status_bar.get_or_insert_default().show = Some(false);
14235 });
14236 });
14237
14238 workspace.read_with(cx, |workspace, cx| {
14239 let visible = workspace.status_bar_visible(cx);
14240 assert!(!visible, "Status bar should be hidden when show is false");
14241 });
14242
14243 // Test with status bar shown explicitly
14244 cx.update_global(|store: &mut SettingsStore, cx| {
14245 store.update_user_settings(cx, |settings| {
14246 settings.status_bar.get_or_insert_default().show = Some(true);
14247 });
14248 });
14249
14250 workspace.read_with(cx, |workspace, cx| {
14251 let visible = workspace.status_bar_visible(cx);
14252 assert!(visible, "Status bar should be visible when show is true");
14253 });
14254 }
14255
14256 #[gpui::test]
14257 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14258 init_test(cx);
14259
14260 let fs = FakeFs::new(cx.executor());
14261 let project = Project::test(fs, [], cx).await;
14262 let (multi_workspace, cx) =
14263 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14264 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14265 let panel = workspace.update_in(cx, |workspace, window, cx| {
14266 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14267 workspace.add_panel(panel.clone(), window, cx);
14268
14269 workspace
14270 .right_dock()
14271 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14272
14273 panel
14274 });
14275
14276 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14277 let item_a = cx.new(TestItem::new);
14278 let item_b = cx.new(TestItem::new);
14279 let item_a_id = item_a.entity_id();
14280 let item_b_id = item_b.entity_id();
14281
14282 pane.update_in(cx, |pane, window, cx| {
14283 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14284 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14285 });
14286
14287 pane.read_with(cx, |pane, _| {
14288 assert_eq!(pane.items_len(), 2);
14289 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14290 });
14291
14292 workspace.update_in(cx, |workspace, window, cx| {
14293 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14294 });
14295
14296 workspace.update_in(cx, |_, window, cx| {
14297 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14298 });
14299
14300 // Assert that the `pane::CloseActiveItem` action is handled at the
14301 // workspace level when one of the dock panels is focused and, in that
14302 // case, the center pane's active item is closed but the focus is not
14303 // moved.
14304 cx.dispatch_action(pane::CloseActiveItem::default());
14305 cx.run_until_parked();
14306
14307 pane.read_with(cx, |pane, _| {
14308 assert_eq!(pane.items_len(), 1);
14309 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14310 });
14311
14312 workspace.update_in(cx, |workspace, window, cx| {
14313 assert!(workspace.right_dock().read(cx).is_open());
14314 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14315 });
14316 }
14317
14318 #[gpui::test]
14319 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14320 init_test(cx);
14321 let fs = FakeFs::new(cx.executor());
14322
14323 let project_a = Project::test(fs.clone(), [], cx).await;
14324 let project_b = Project::test(fs, [], cx).await;
14325
14326 let multi_workspace_handle =
14327 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14328 cx.run_until_parked();
14329
14330 let workspace_a = multi_workspace_handle
14331 .read_with(cx, |mw, _| mw.workspace().clone())
14332 .unwrap();
14333
14334 let _workspace_b = multi_workspace_handle
14335 .update(cx, |mw, window, cx| {
14336 mw.test_add_workspace(project_b, window, cx)
14337 })
14338 .unwrap();
14339
14340 // Switch to workspace A
14341 multi_workspace_handle
14342 .update(cx, |mw, window, cx| {
14343 mw.activate_index(0, window, cx);
14344 })
14345 .unwrap();
14346
14347 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14348
14349 // Add a panel to workspace A's right dock and open the dock
14350 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14351 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14352 workspace.add_panel(panel.clone(), window, cx);
14353 workspace
14354 .right_dock()
14355 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14356 panel
14357 });
14358
14359 // Focus the panel through the workspace (matching existing test pattern)
14360 workspace_a.update_in(cx, |workspace, window, cx| {
14361 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14362 });
14363
14364 // Zoom the panel
14365 panel.update_in(cx, |panel, window, cx| {
14366 panel.set_zoomed(true, window, cx);
14367 });
14368
14369 // Verify the panel is zoomed and the dock is open
14370 workspace_a.update_in(cx, |workspace, window, cx| {
14371 assert!(
14372 workspace.right_dock().read(cx).is_open(),
14373 "dock should be open before switch"
14374 );
14375 assert!(
14376 panel.is_zoomed(window, cx),
14377 "panel should be zoomed before switch"
14378 );
14379 assert!(
14380 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14381 "panel should be focused before switch"
14382 );
14383 });
14384
14385 // Switch to workspace B
14386 multi_workspace_handle
14387 .update(cx, |mw, window, cx| {
14388 mw.activate_index(1, window, cx);
14389 })
14390 .unwrap();
14391 cx.run_until_parked();
14392
14393 // Switch back to workspace A
14394 multi_workspace_handle
14395 .update(cx, |mw, window, cx| {
14396 mw.activate_index(0, window, cx);
14397 })
14398 .unwrap();
14399 cx.run_until_parked();
14400
14401 // Verify the panel is still zoomed and the dock is still open
14402 workspace_a.update_in(cx, |workspace, window, cx| {
14403 assert!(
14404 workspace.right_dock().read(cx).is_open(),
14405 "dock should still be open after switching back"
14406 );
14407 assert!(
14408 panel.is_zoomed(window, cx),
14409 "panel should still be zoomed after switching back"
14410 );
14411 });
14412 }
14413
14414 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14415 pane.read(cx)
14416 .items()
14417 .flat_map(|item| {
14418 item.project_paths(cx)
14419 .into_iter()
14420 .map(|path| path.path.display(PathStyle::local()).into_owned())
14421 })
14422 .collect()
14423 }
14424
14425 pub fn init_test(cx: &mut TestAppContext) {
14426 cx.update(|cx| {
14427 let settings_store = SettingsStore::test(cx);
14428 cx.set_global(settings_store);
14429 cx.set_global(db::AppDatabase::test_new());
14430 theme::init(theme::LoadThemes::JustBase, cx);
14431 });
14432 }
14433
14434 #[gpui::test]
14435 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14436 use settings::{ThemeName, ThemeSelection};
14437 use theme::SystemAppearance;
14438 use zed_actions::theme::ToggleMode;
14439
14440 init_test(cx);
14441
14442 let fs = FakeFs::new(cx.executor());
14443 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14444
14445 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14446 .await;
14447
14448 // Build a test project and workspace view so the test can invoke
14449 // the workspace action handler the same way the UI would.
14450 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14451 let (workspace, cx) =
14452 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14453
14454 // Seed the settings file with a plain static light theme so the
14455 // first toggle always starts from a known persisted state.
14456 workspace.update_in(cx, |_workspace, _window, cx| {
14457 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14458 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14459 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14460 });
14461 });
14462 cx.executor().advance_clock(Duration::from_millis(200));
14463 cx.run_until_parked();
14464
14465 // Confirm the initial persisted settings contain the static theme
14466 // we just wrote before any toggling happens.
14467 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14468 assert!(settings_text.contains(r#""theme": "One Light""#));
14469
14470 // Toggle once. This should migrate the persisted theme settings
14471 // into light/dark slots and enable system mode.
14472 workspace.update_in(cx, |workspace, window, cx| {
14473 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14474 });
14475 cx.executor().advance_clock(Duration::from_millis(200));
14476 cx.run_until_parked();
14477
14478 // 1. Static -> Dynamic
14479 // this assertion checks theme changed from static to dynamic.
14480 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14481 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14482 assert_eq!(
14483 parsed["theme"],
14484 serde_json::json!({
14485 "mode": "system",
14486 "light": "One Light",
14487 "dark": "One Dark"
14488 })
14489 );
14490
14491 // 2. Toggle again, suppose it will change the mode to light
14492 workspace.update_in(cx, |workspace, window, cx| {
14493 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14494 });
14495 cx.executor().advance_clock(Duration::from_millis(200));
14496 cx.run_until_parked();
14497
14498 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14499 assert!(settings_text.contains(r#""mode": "light""#));
14500 }
14501
14502 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14503 let item = TestProjectItem::new(id, path, cx);
14504 item.update(cx, |item, _| {
14505 item.is_dirty = true;
14506 });
14507 item
14508 }
14509
14510 #[gpui::test]
14511 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14512 cx: &mut gpui::TestAppContext,
14513 ) {
14514 init_test(cx);
14515 let fs = FakeFs::new(cx.executor());
14516
14517 let project = Project::test(fs, [], cx).await;
14518 let (workspace, cx) =
14519 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14520
14521 let panel = workspace.update_in(cx, |workspace, window, cx| {
14522 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14523 workspace.add_panel(panel.clone(), window, cx);
14524 workspace
14525 .right_dock()
14526 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14527 panel
14528 });
14529
14530 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14531 pane.update_in(cx, |pane, window, cx| {
14532 let item = cx.new(TestItem::new);
14533 pane.add_item(Box::new(item), true, true, None, window, cx);
14534 });
14535
14536 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14537 // mirrors the real-world flow and avoids side effects from directly
14538 // focusing the panel while the center pane is active.
14539 workspace.update_in(cx, |workspace, window, cx| {
14540 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14541 });
14542
14543 panel.update_in(cx, |panel, window, cx| {
14544 panel.set_zoomed(true, window, cx);
14545 });
14546
14547 workspace.update_in(cx, |workspace, window, cx| {
14548 assert!(workspace.right_dock().read(cx).is_open());
14549 assert!(panel.is_zoomed(window, cx));
14550 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14551 });
14552
14553 // Simulate a spurious pane::Event::Focus on the center pane while the
14554 // panel still has focus. This mirrors what happens during macOS window
14555 // activation: the center pane fires a focus event even though actual
14556 // focus remains on the dock panel.
14557 pane.update_in(cx, |_, _, cx| {
14558 cx.emit(pane::Event::Focus);
14559 });
14560
14561 // The dock must remain open because the panel had focus at the time the
14562 // event was processed. Before the fix, dock_to_preserve was None for
14563 // panels that don't implement pane(), causing the dock to close.
14564 workspace.update_in(cx, |workspace, window, cx| {
14565 assert!(
14566 workspace.right_dock().read(cx).is_open(),
14567 "Dock should stay open when its zoomed panel (without pane()) still has focus"
14568 );
14569 assert!(panel.is_zoomed(window, cx));
14570 });
14571 }
14572
14573 #[gpui::test]
14574 async fn test_panels_stay_open_after_position_change_and_settings_update(
14575 cx: &mut gpui::TestAppContext,
14576 ) {
14577 init_test(cx);
14578 let fs = FakeFs::new(cx.executor());
14579 let project = Project::test(fs, [], cx).await;
14580 let (workspace, cx) =
14581 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14582
14583 // Add two panels to the left dock and open it.
14584 let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14585 let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14586 let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14587 workspace.add_panel(panel_a.clone(), window, cx);
14588 workspace.add_panel(panel_b.clone(), window, cx);
14589 workspace.left_dock().update(cx, |dock, cx| {
14590 dock.set_open(true, window, cx);
14591 dock.activate_panel(0, window, cx);
14592 });
14593 (panel_a, panel_b)
14594 });
14595
14596 workspace.update_in(cx, |workspace, _, cx| {
14597 assert!(workspace.left_dock().read(cx).is_open());
14598 });
14599
14600 // Simulate a feature flag changing default dock positions: both panels
14601 // move from Left to Right.
14602 workspace.update_in(cx, |_workspace, _window, cx| {
14603 panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14604 panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14605 cx.update_global::<SettingsStore, _>(|_, _| {});
14606 });
14607
14608 // Both panels should now be in the right dock.
14609 workspace.update_in(cx, |workspace, _, cx| {
14610 let right_dock = workspace.right_dock().read(cx);
14611 assert_eq!(right_dock.panels_len(), 2);
14612 });
14613
14614 // Open the right dock and activate panel_b (simulating the user
14615 // opening the panel after it moved).
14616 workspace.update_in(cx, |workspace, window, cx| {
14617 workspace.right_dock().update(cx, |dock, cx| {
14618 dock.set_open(true, window, cx);
14619 dock.activate_panel(1, window, cx);
14620 });
14621 });
14622
14623 // Now trigger another SettingsStore change
14624 workspace.update_in(cx, |_workspace, _window, cx| {
14625 cx.update_global::<SettingsStore, _>(|_, _| {});
14626 });
14627
14628 workspace.update_in(cx, |workspace, _, cx| {
14629 assert!(
14630 workspace.right_dock().read(cx).is_open(),
14631 "Right dock should still be open after a settings change"
14632 );
14633 assert_eq!(
14634 workspace.right_dock().read(cx).panels_len(),
14635 2,
14636 "Both panels should still be in the right dock"
14637 );
14638 });
14639 }
14640}