workspace.rs

    1pub mod dock;
    2pub mod history_manager;
    3pub mod invalid_item_view;
    4pub mod item;
    5mod modal_layer;
    6pub mod notifications;
    7pub mod pane;
    8pub mod pane_group;
    9mod path_list;
   10mod persistence;
   11pub mod searchable;
   12pub mod shared_screen;
   13mod status_bar;
   14pub mod tasks;
   15mod theme_preview;
   16mod toast_layer;
   17mod toolbar;
   18pub mod utility_pane;
   19pub mod welcome;
   20mod workspace_settings;
   21
   22pub use crate::notifications::NotificationFrame;
   23pub use dock::Panel;
   24pub use path_list::PathList;
   25pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   26
   27use anyhow::{Context as _, Result, anyhow};
   28use call::{ActiveCall, call_settings::CallSettings};
   29use client::{
   30    ChannelId, Client, ErrorExt, Status, TypedEnvelope, UserStore,
   31    proto::{self, ErrorCode, PanelId, PeerId},
   32};
   33use collections::{HashMap, HashSet, hash_map};
   34use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   35use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt};
   36use futures::{
   37    Future, FutureExt, StreamExt,
   38    channel::{
   39        mpsc::{self, UnboundedReceiver, UnboundedSender},
   40        oneshot,
   41    },
   42    future::{Shared, try_join_all},
   43};
   44use gpui::{
   45    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
   46    CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   47    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   48    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   49    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   50    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   51};
   52pub use history_manager::*;
   53pub use item::{
   54    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   55    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   56};
   57use itertools::Itertools;
   58use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
   59pub use modal_layer::*;
   60use node_runtime::NodeRuntime;
   61use notifications::{
   62    DetachAndPromptErr, Notifications, dismiss_app_notification,
   63    simple_message_notification::MessageNotification,
   64};
   65pub use pane::*;
   66pub use pane_group::{
   67    ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
   68    SplitDirection,
   69};
   70use persistence::{DB, SerializedWindowBounds, model::SerializedWorkspace};
   71pub use persistence::{
   72    DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
   73    model::{ItemId, SerializedWorkspaceLocation},
   74};
   75use postage::stream::Stream;
   76use project::{
   77    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
   78    WorktreeSettings,
   79    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   80    toolchain_store::ToolchainStoreEvent,
   81};
   82use remote::{
   83    RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
   84    remote_client::ConnectionIdentifier,
   85};
   86use schemars::JsonSchema;
   87use serde::Deserialize;
   88use session::AppSession;
   89use settings::{CenteredPaddingSettings, Settings, SettingsLocation, update_settings_file};
   90use shared_screen::SharedScreen;
   91use sqlez::{
   92    bindable::{Bind, Column, StaticColumnCount},
   93    statement::Statement,
   94};
   95use status_bar::StatusBar;
   96pub use status_bar::StatusItemView;
   97use std::{
   98    any::TypeId,
   99    borrow::Cow,
  100    cell::RefCell,
  101    cmp,
  102    collections::{VecDeque, hash_map::DefaultHasher},
  103    env,
  104    hash::{Hash, Hasher},
  105    path::{Path, PathBuf},
  106    process::ExitStatus,
  107    rc::Rc,
  108    sync::{
  109        Arc, LazyLock, Weak,
  110        atomic::{AtomicBool, AtomicUsize},
  111    },
  112    time::Duration,
  113};
  114use task::{DebugScenario, SpawnInTerminal, TaskContext};
  115use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
  116pub use toolbar::{Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView};
  117pub use ui;
  118use ui::{Window, prelude::*};
  119use util::{
  120    ResultExt, TryFutureExt,
  121    paths::{PathStyle, SanitizedPath},
  122    rel_path::RelPath,
  123    serde::default_true,
  124};
  125use uuid::Uuid;
  126pub use workspace_settings::{
  127    AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
  128    WorkspaceSettings,
  129};
  130use zed_actions::{Spawn, feedback::FileBugReport};
  131
  132use crate::{
  133    item::ItemBufferKind,
  134    notifications::NotificationId,
  135    utility_pane::{UTILITY_PANE_MIN_WIDTH, utility_slot_for_dock_position},
  136};
  137use crate::{
  138    persistence::{
  139        SerializedAxis,
  140        model::{DockData, DockStructure, SerializedItem, SerializedPane, SerializedPaneGroup},
  141    },
  142    utility_pane::{DraggedUtilityPane, UtilityPaneFrame, UtilityPaneSlot, UtilityPaneState},
  143};
  144
  145pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
  146
  147static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
  148    env::var("ZED_WINDOW_SIZE")
  149        .ok()
  150        .as_deref()
  151        .and_then(parse_pixel_size_env_var)
  152});
  153
  154static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
  155    env::var("ZED_WINDOW_POSITION")
  156        .ok()
  157        .as_deref()
  158        .and_then(parse_pixel_position_env_var)
  159});
  160
  161pub trait TerminalProvider {
  162    fn spawn(
  163        &self,
  164        task: SpawnInTerminal,
  165        window: &mut Window,
  166        cx: &mut App,
  167    ) -> Task<Option<Result<ExitStatus>>>;
  168}
  169
  170pub trait DebuggerProvider {
  171    // `active_buffer` is used to resolve build task's name against language-specific tasks.
  172    fn start_session(
  173        &self,
  174        definition: DebugScenario,
  175        task_context: TaskContext,
  176        active_buffer: Option<Entity<Buffer>>,
  177        worktree_id: Option<WorktreeId>,
  178        window: &mut Window,
  179        cx: &mut App,
  180    );
  181
  182    fn spawn_task_or_modal(
  183        &self,
  184        workspace: &mut Workspace,
  185        action: &Spawn,
  186        window: &mut Window,
  187        cx: &mut Context<Workspace>,
  188    );
  189
  190    fn task_scheduled(&self, cx: &mut App);
  191    fn debug_scenario_scheduled(&self, cx: &mut App);
  192    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
  193
  194    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
  195}
  196
  197actions!(
  198    workspace,
  199    [
  200        /// Activates the next pane in the workspace.
  201        ActivateNextPane,
  202        /// Activates the previous pane in the workspace.
  203        ActivatePreviousPane,
  204        /// Switches to the next window.
  205        ActivateNextWindow,
  206        /// Switches to the previous window.
  207        ActivatePreviousWindow,
  208        /// Adds a folder to the current project.
  209        AddFolderToProject,
  210        /// Clears all notifications.
  211        ClearAllNotifications,
  212        /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
  213        ClearNavigationHistory,
  214        /// Closes the active dock.
  215        CloseActiveDock,
  216        /// Closes all docks.
  217        CloseAllDocks,
  218        /// Toggles all docks.
  219        ToggleAllDocks,
  220        /// Closes the current window.
  221        CloseWindow,
  222        /// Opens the feedback dialog.
  223        Feedback,
  224        /// Follows the next collaborator in the session.
  225        FollowNextCollaborator,
  226        /// Moves the focused panel to the next position.
  227        MoveFocusedPanelToNextPosition,
  228        /// Opens a new terminal in the center.
  229        NewCenterTerminal,
  230        /// Creates a new file.
  231        NewFile,
  232        /// Creates a new file in a vertical split.
  233        NewFileSplitVertical,
  234        /// Creates a new file in a horizontal split.
  235        NewFileSplitHorizontal,
  236        /// Opens a new search.
  237        NewSearch,
  238        /// Opens a new terminal.
  239        NewTerminal,
  240        /// Opens a new window.
  241        NewWindow,
  242        /// Opens a file or directory.
  243        Open,
  244        /// Opens multiple files.
  245        OpenFiles,
  246        /// Opens the current location in terminal.
  247        OpenInTerminal,
  248        /// Opens the component preview.
  249        OpenComponentPreview,
  250        /// Reloads the active item.
  251        ReloadActiveItem,
  252        /// Resets the active dock to its default size.
  253        ResetActiveDockSize,
  254        /// Resets all open docks to their default sizes.
  255        ResetOpenDocksSize,
  256        /// Reloads the application
  257        Reload,
  258        /// Saves the current file with a new name.
  259        SaveAs,
  260        /// Saves without formatting.
  261        SaveWithoutFormat,
  262        /// Shuts down all debug adapters.
  263        ShutdownDebugAdapters,
  264        /// Suppresses the current notification.
  265        SuppressNotification,
  266        /// Toggles the bottom dock.
  267        ToggleBottomDock,
  268        /// Toggles centered layout mode.
  269        ToggleCenteredLayout,
  270        /// Toggles edit prediction feature globally for all files.
  271        ToggleEditPrediction,
  272        /// Toggles the left dock.
  273        ToggleLeftDock,
  274        /// Toggles the right dock.
  275        ToggleRightDock,
  276        /// Toggles zoom on the active pane.
  277        ToggleZoom,
  278        /// Zooms in on the active pane.
  279        ZoomIn,
  280        /// Zooms out of the active pane.
  281        ZoomOut,
  282        /// Stops following a collaborator.
  283        Unfollow,
  284        /// Restores the banner.
  285        RestoreBanner,
  286        /// Toggles expansion of the selected item.
  287        ToggleExpandItem,
  288    ]
  289);
  290
  291/// Activates a specific pane by its index.
  292#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  293#[action(namespace = workspace)]
  294pub struct ActivatePane(pub usize);
  295
  296/// Moves an item to a specific pane by index.
  297#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  298#[action(namespace = workspace)]
  299#[serde(deny_unknown_fields)]
  300pub struct MoveItemToPane {
  301    #[serde(default = "default_1")]
  302    pub destination: usize,
  303    #[serde(default = "default_true")]
  304    pub focus: bool,
  305    #[serde(default)]
  306    pub clone: bool,
  307}
  308
  309fn default_1() -> usize {
  310    1
  311}
  312
  313/// Moves an item to a pane in the specified direction.
  314#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  315#[action(namespace = workspace)]
  316#[serde(deny_unknown_fields)]
  317pub struct MoveItemToPaneInDirection {
  318    #[serde(default = "default_right")]
  319    pub direction: SplitDirection,
  320    #[serde(default = "default_true")]
  321    pub focus: bool,
  322    #[serde(default)]
  323    pub clone: bool,
  324}
  325
  326/// Creates a new file in a split of the desired direction.
  327#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  328#[action(namespace = workspace)]
  329#[serde(deny_unknown_fields)]
  330pub struct NewFileSplit(pub SplitDirection);
  331
  332fn default_right() -> SplitDirection {
  333    SplitDirection::Right
  334}
  335
  336/// Saves all open files in the workspace.
  337#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  338#[action(namespace = workspace)]
  339#[serde(deny_unknown_fields)]
  340pub struct SaveAll {
  341    #[serde(default)]
  342    pub save_intent: Option<SaveIntent>,
  343}
  344
  345/// Saves the current file with the specified options.
  346#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
  347#[action(namespace = workspace)]
  348#[serde(deny_unknown_fields)]
  349pub struct Save {
  350    #[serde(default)]
  351    pub save_intent: Option<SaveIntent>,
  352}
  353
  354/// Closes all items and panes in the workspace.
  355#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  356#[action(namespace = workspace)]
  357#[serde(deny_unknown_fields)]
  358pub struct CloseAllItemsAndPanes {
  359    #[serde(default)]
  360    pub save_intent: Option<SaveIntent>,
  361}
  362
  363/// Closes all inactive tabs and panes in the workspace.
  364#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
  365#[action(namespace = workspace)]
  366#[serde(deny_unknown_fields)]
  367pub struct CloseInactiveTabsAndPanes {
  368    #[serde(default)]
  369    pub save_intent: Option<SaveIntent>,
  370}
  371
  372/// Sends a sequence of keystrokes to the active element.
  373#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
  374#[action(namespace = workspace)]
  375pub struct SendKeystrokes(pub String);
  376
  377actions!(
  378    project_symbols,
  379    [
  380        /// Toggles the project symbols search.
  381        #[action(name = "Toggle")]
  382        ToggleProjectSymbols
  383    ]
  384);
  385
  386/// Toggles the file finder interface.
  387#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
  388#[action(namespace = file_finder, name = "Toggle")]
  389#[serde(deny_unknown_fields)]
  390pub struct ToggleFileFinder {
  391    #[serde(default)]
  392    pub separate_history: bool,
  393}
  394
  395/// Increases size of a currently focused dock by a given amount of pixels.
  396#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  397#[action(namespace = workspace)]
  398#[serde(deny_unknown_fields)]
  399pub struct IncreaseActiveDockSize {
  400    /// For 0px parameter, uses UI font size value.
  401    #[serde(default)]
  402    pub px: u32,
  403}
  404
  405/// Decreases size of a currently focused dock by a given amount of pixels.
  406#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  407#[action(namespace = workspace)]
  408#[serde(deny_unknown_fields)]
  409pub struct DecreaseActiveDockSize {
  410    /// For 0px parameter, uses UI font size value.
  411    #[serde(default)]
  412    pub px: u32,
  413}
  414
  415/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
  416#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  417#[action(namespace = workspace)]
  418#[serde(deny_unknown_fields)]
  419pub struct IncreaseOpenDocksSize {
  420    /// For 0px parameter, uses UI font size value.
  421    #[serde(default)]
  422    pub px: u32,
  423}
  424
  425/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
  426#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
  427#[action(namespace = workspace)]
  428#[serde(deny_unknown_fields)]
  429pub struct DecreaseOpenDocksSize {
  430    /// For 0px parameter, uses UI font size value.
  431    #[serde(default)]
  432    pub px: u32,
  433}
  434
  435actions!(
  436    workspace,
  437    [
  438        /// Activates the pane to the left.
  439        ActivatePaneLeft,
  440        /// Activates the pane to the right.
  441        ActivatePaneRight,
  442        /// Activates the pane above.
  443        ActivatePaneUp,
  444        /// Activates the pane below.
  445        ActivatePaneDown,
  446        /// Swaps the current pane with the one to the left.
  447        SwapPaneLeft,
  448        /// Swaps the current pane with the one to the right.
  449        SwapPaneRight,
  450        /// Swaps the current pane with the one above.
  451        SwapPaneUp,
  452        /// Swaps the current pane with the one below.
  453        SwapPaneDown,
  454        // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
  455        SwapPaneAdjacent,
  456        /// Move the current pane to be at the far left.
  457        MovePaneLeft,
  458        /// Move the current pane to be at the far right.
  459        MovePaneRight,
  460        /// Move the current pane to be at the very top.
  461        MovePaneUp,
  462        /// Move the current pane to be at the very bottom.
  463        MovePaneDown,
  464    ]
  465);
  466
  467#[derive(PartialEq, Eq, Debug)]
  468pub enum CloseIntent {
  469    /// Quit the program entirely.
  470    Quit,
  471    /// Close a window.
  472    CloseWindow,
  473    /// Replace the workspace in an existing window.
  474    ReplaceWindow,
  475}
  476
  477#[derive(Clone)]
  478pub struct Toast {
  479    id: NotificationId,
  480    msg: Cow<'static, str>,
  481    autohide: bool,
  482    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
  483}
  484
  485impl Toast {
  486    pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
  487        Toast {
  488            id,
  489            msg: msg.into(),
  490            on_click: None,
  491            autohide: false,
  492        }
  493    }
  494
  495    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
  496    where
  497        M: Into<Cow<'static, str>>,
  498        F: Fn(&mut Window, &mut App) + 'static,
  499    {
  500        self.on_click = Some((message.into(), Arc::new(on_click)));
  501        self
  502    }
  503
  504    pub fn autohide(mut self) -> Self {
  505        self.autohide = true;
  506        self
  507    }
  508}
  509
  510impl PartialEq for Toast {
  511    fn eq(&self, other: &Self) -> bool {
  512        self.id == other.id
  513            && self.msg == other.msg
  514            && self.on_click.is_some() == other.on_click.is_some()
  515    }
  516}
  517
  518/// Opens a new terminal with the specified working directory.
  519#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
  520#[action(namespace = workspace)]
  521#[serde(deny_unknown_fields)]
  522pub struct OpenTerminal {
  523    pub working_directory: PathBuf,
  524}
  525
  526#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
  527pub struct WorkspaceId(i64);
  528
  529impl StaticColumnCount for WorkspaceId {}
  530impl Bind for WorkspaceId {
  531    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
  532        self.0.bind(statement, start_index)
  533    }
  534}
  535impl Column for WorkspaceId {
  536    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
  537        i64::column(statement, start_index)
  538            .map(|(i, next_index)| (Self(i), next_index))
  539            .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
  540    }
  541}
  542impl From<WorkspaceId> for i64 {
  543    fn from(val: WorkspaceId) -> Self {
  544        val.0
  545    }
  546}
  547
  548fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
  549    let paths = cx.prompt_for_paths(options);
  550    cx.spawn(
  551        async move |cx| match paths.await.anyhow().and_then(|res| res) {
  552            Ok(Some(paths)) => {
  553                cx.update(|cx| {
  554                    open_paths(&paths, app_state, OpenOptions::default(), cx).detach_and_log_err(cx)
  555                })
  556                .ok();
  557            }
  558            Ok(None) => {}
  559            Err(err) => {
  560                util::log_err(&err);
  561                cx.update(|cx| {
  562                    if let Some(workspace_window) = cx
  563                        .active_window()
  564                        .and_then(|window| window.downcast::<Workspace>())
  565                    {
  566                        workspace_window
  567                            .update(cx, |workspace, _, cx| {
  568                                workspace.show_portal_error(err.to_string(), cx);
  569                            })
  570                            .ok();
  571                    }
  572                })
  573                .ok();
  574            }
  575        },
  576    )
  577    .detach();
  578}
  579
  580pub fn init(app_state: Arc<AppState>, cx: &mut App) {
  581    component::init();
  582    theme_preview::init(cx);
  583    toast_layer::init(cx);
  584    history_manager::init(cx);
  585
  586    cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
  587        .on_action(|_: &Reload, cx| reload(cx))
  588        .on_action({
  589            let app_state = Arc::downgrade(&app_state);
  590            move |_: &Open, cx: &mut App| {
  591                if let Some(app_state) = app_state.upgrade() {
  592                    prompt_and_open_paths(
  593                        app_state,
  594                        PathPromptOptions {
  595                            files: true,
  596                            directories: true,
  597                            multiple: true,
  598                            prompt: None,
  599                        },
  600                        cx,
  601                    );
  602                }
  603            }
  604        })
  605        .on_action({
  606            let app_state = Arc::downgrade(&app_state);
  607            move |_: &OpenFiles, cx: &mut App| {
  608                let directories = cx.can_select_mixed_files_and_dirs();
  609                if let Some(app_state) = app_state.upgrade() {
  610                    prompt_and_open_paths(
  611                        app_state,
  612                        PathPromptOptions {
  613                            files: true,
  614                            directories,
  615                            multiple: true,
  616                            prompt: None,
  617                        },
  618                        cx,
  619                    );
  620                }
  621            }
  622        });
  623}
  624
  625type BuildProjectItemFn =
  626    fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
  627
  628type BuildProjectItemForPathFn =
  629    fn(
  630        &Entity<Project>,
  631        &ProjectPath,
  632        &mut Window,
  633        &mut App,
  634    ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
  635
  636#[derive(Clone, Default)]
  637struct ProjectItemRegistry {
  638    build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
  639    build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
  640}
  641
  642impl ProjectItemRegistry {
  643    fn register<T: ProjectItem>(&mut self) {
  644        self.build_project_item_fns_by_type.insert(
  645            TypeId::of::<T::Item>(),
  646            |item, project, pane, window, cx| {
  647                let item = item.downcast().unwrap();
  648                Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
  649                    as Box<dyn ItemHandle>
  650            },
  651        );
  652        self.build_project_item_for_path_fns
  653            .push(|project, project_path, window, cx| {
  654                let project_path = project_path.clone();
  655                let is_file = project
  656                    .read(cx)
  657                    .entry_for_path(&project_path, cx)
  658                    .is_some_and(|entry| entry.is_file());
  659                let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
  660                let is_local = project.read(cx).is_local();
  661                let project_item =
  662                    <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
  663                let project = project.clone();
  664                Some(window.spawn(cx, async move |cx| {
  665                    match project_item.await.with_context(|| {
  666                        format!(
  667                            "opening project path {:?}",
  668                            entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
  669                        )
  670                    }) {
  671                        Ok(project_item) => {
  672                            let project_item = project_item;
  673                            let project_entry_id: Option<ProjectEntryId> =
  674                                project_item.read_with(cx, project::ProjectItem::entry_id)?;
  675                            let build_workspace_item = Box::new(
  676                                |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
  677                                    Box::new(cx.new(|cx| {
  678                                        T::for_project_item(
  679                                            project,
  680                                            Some(pane),
  681                                            project_item,
  682                                            window,
  683                                            cx,
  684                                        )
  685                                    })) as Box<dyn ItemHandle>
  686                                },
  687                            ) as Box<_>;
  688                            Ok((project_entry_id, build_workspace_item))
  689                        }
  690                        Err(e) => {
  691                            log::warn!("Failed to open a project item: {e:#}");
  692                            if e.error_code() == ErrorCode::Internal {
  693                                if let Some(abs_path) =
  694                                    entry_abs_path.as_deref().filter(|_| is_file)
  695                                {
  696                                    if let Some(broken_project_item_view) =
  697                                        cx.update(|window, cx| {
  698                                            T::for_broken_project_item(
  699                                                abs_path, is_local, &e, window, cx,
  700                                            )
  701                                        })?
  702                                    {
  703                                        let build_workspace_item = Box::new(
  704                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  705                                                cx.new(|_| broken_project_item_view).boxed_clone()
  706                                            },
  707                                        )
  708                                        as Box<_>;
  709                                        return Ok((None, build_workspace_item));
  710                                    }
  711                                }
  712                            }
  713                            Err(e)
  714                        }
  715                    }
  716                }))
  717            });
  718    }
  719
  720    fn open_path(
  721        &self,
  722        project: &Entity<Project>,
  723        path: &ProjectPath,
  724        window: &mut Window,
  725        cx: &mut App,
  726    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  727        let Some(open_project_item) = self
  728            .build_project_item_for_path_fns
  729            .iter()
  730            .rev()
  731            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  732        else {
  733            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  734        };
  735        open_project_item
  736    }
  737
  738    fn build_item<T: project::ProjectItem>(
  739        &self,
  740        item: Entity<T>,
  741        project: Entity<Project>,
  742        pane: Option<&Pane>,
  743        window: &mut Window,
  744        cx: &mut App,
  745    ) -> Option<Box<dyn ItemHandle>> {
  746        let build = self
  747            .build_project_item_fns_by_type
  748            .get(&TypeId::of::<T>())?;
  749        Some(build(item.into_any(), project, pane, window, cx))
  750    }
  751}
  752
  753type WorkspaceItemBuilder =
  754    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  755
  756impl Global for ProjectItemRegistry {}
  757
  758/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  759/// items will get a chance to open the file, starting from the project item that
  760/// was added last.
  761pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  762    cx.default_global::<ProjectItemRegistry>().register::<I>();
  763}
  764
  765#[derive(Default)]
  766pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  767
  768struct FollowableViewDescriptor {
  769    from_state_proto: fn(
  770        Entity<Workspace>,
  771        ViewId,
  772        &mut Option<proto::view::Variant>,
  773        &mut Window,
  774        &mut App,
  775    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  776    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  777}
  778
  779impl Global for FollowableViewRegistry {}
  780
  781impl FollowableViewRegistry {
  782    pub fn register<I: FollowableItem>(cx: &mut App) {
  783        cx.default_global::<Self>().0.insert(
  784            TypeId::of::<I>(),
  785            FollowableViewDescriptor {
  786                from_state_proto: |workspace, id, state, window, cx| {
  787                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  788                        cx.foreground_executor()
  789                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  790                    })
  791                },
  792                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  793            },
  794        );
  795    }
  796
  797    pub fn from_state_proto(
  798        workspace: Entity<Workspace>,
  799        view_id: ViewId,
  800        mut state: Option<proto::view::Variant>,
  801        window: &mut Window,
  802        cx: &mut App,
  803    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  804        cx.update_default_global(|this: &mut Self, cx| {
  805            this.0.values().find_map(|descriptor| {
  806                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  807            })
  808        })
  809    }
  810
  811    pub fn to_followable_view(
  812        view: impl Into<AnyView>,
  813        cx: &App,
  814    ) -> Option<Box<dyn FollowableItemHandle>> {
  815        let this = cx.try_global::<Self>()?;
  816        let view = view.into();
  817        let descriptor = this.0.get(&view.entity_type())?;
  818        Some((descriptor.to_followable_view)(&view))
  819    }
  820}
  821
  822#[derive(Copy, Clone)]
  823struct SerializableItemDescriptor {
  824    deserialize: fn(
  825        Entity<Project>,
  826        WeakEntity<Workspace>,
  827        WorkspaceId,
  828        ItemId,
  829        &mut Window,
  830        &mut Context<Pane>,
  831    ) -> Task<Result<Box<dyn ItemHandle>>>,
  832    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  833    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  834}
  835
  836#[derive(Default)]
  837struct SerializableItemRegistry {
  838    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  839    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  840}
  841
  842impl Global for SerializableItemRegistry {}
  843
  844impl SerializableItemRegistry {
  845    fn deserialize(
  846        item_kind: &str,
  847        project: Entity<Project>,
  848        workspace: WeakEntity<Workspace>,
  849        workspace_id: WorkspaceId,
  850        item_item: ItemId,
  851        window: &mut Window,
  852        cx: &mut Context<Pane>,
  853    ) -> Task<Result<Box<dyn ItemHandle>>> {
  854        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  855            return Task::ready(Err(anyhow!(
  856                "cannot deserialize {}, descriptor not found",
  857                item_kind
  858            )));
  859        };
  860
  861        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
  862    }
  863
  864    fn cleanup(
  865        item_kind: &str,
  866        workspace_id: WorkspaceId,
  867        loaded_items: Vec<ItemId>,
  868        window: &mut Window,
  869        cx: &mut App,
  870    ) -> Task<Result<()>> {
  871        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  872            return Task::ready(Err(anyhow!(
  873                "cannot cleanup {}, descriptor not found",
  874                item_kind
  875            )));
  876        };
  877
  878        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
  879    }
  880
  881    fn view_to_serializable_item_handle(
  882        view: AnyView,
  883        cx: &App,
  884    ) -> Option<Box<dyn SerializableItemHandle>> {
  885        let this = cx.try_global::<Self>()?;
  886        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
  887        Some((descriptor.view_to_serializable_item)(view))
  888    }
  889
  890    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
  891        let this = cx.try_global::<Self>()?;
  892        this.descriptors_by_kind.get(item_kind).copied()
  893    }
  894}
  895
  896pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
  897    let serialized_item_kind = I::serialized_item_kind();
  898
  899    let registry = cx.default_global::<SerializableItemRegistry>();
  900    let descriptor = SerializableItemDescriptor {
  901        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
  902            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
  903            cx.foreground_executor()
  904                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
  905        },
  906        cleanup: |workspace_id, loaded_items, window, cx| {
  907            I::cleanup(workspace_id, loaded_items, window, cx)
  908        },
  909        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
  910    };
  911    registry
  912        .descriptors_by_kind
  913        .insert(Arc::from(serialized_item_kind), descriptor);
  914    registry
  915        .descriptors_by_type
  916        .insert(TypeId::of::<I>(), descriptor);
  917}
  918
  919pub struct AppState {
  920    pub languages: Arc<LanguageRegistry>,
  921    pub client: Arc<Client>,
  922    pub user_store: Entity<UserStore>,
  923    pub workspace_store: Entity<WorkspaceStore>,
  924    pub fs: Arc<dyn fs::Fs>,
  925    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
  926    pub node_runtime: NodeRuntime,
  927    pub session: Entity<AppSession>,
  928}
  929
  930struct GlobalAppState(Weak<AppState>);
  931
  932impl Global for GlobalAppState {}
  933
  934pub struct WorkspaceStore {
  935    workspaces: HashSet<WindowHandle<Workspace>>,
  936    client: Arc<Client>,
  937    _subscriptions: Vec<client::Subscription>,
  938}
  939
  940#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
  941pub enum CollaboratorId {
  942    PeerId(PeerId),
  943    Agent,
  944}
  945
  946impl From<PeerId> for CollaboratorId {
  947    fn from(peer_id: PeerId) -> Self {
  948        CollaboratorId::PeerId(peer_id)
  949    }
  950}
  951
  952impl From<&PeerId> for CollaboratorId {
  953    fn from(peer_id: &PeerId) -> Self {
  954        CollaboratorId::PeerId(*peer_id)
  955    }
  956}
  957
  958#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
  959struct Follower {
  960    project_id: Option<u64>,
  961    peer_id: PeerId,
  962}
  963
  964impl AppState {
  965    #[track_caller]
  966    pub fn global(cx: &App) -> Weak<Self> {
  967        cx.global::<GlobalAppState>().0.clone()
  968    }
  969    pub fn try_global(cx: &App) -> Option<Weak<Self>> {
  970        cx.try_global::<GlobalAppState>()
  971            .map(|state| state.0.clone())
  972    }
  973    pub fn set_global(state: Weak<AppState>, cx: &mut App) {
  974        cx.set_global(GlobalAppState(state));
  975    }
  976
  977    #[cfg(any(test, feature = "test-support"))]
  978    pub fn test(cx: &mut App) -> Arc<Self> {
  979        use fs::Fs;
  980        use node_runtime::NodeRuntime;
  981        use session::Session;
  982        use settings::SettingsStore;
  983
  984        if !cx.has_global::<SettingsStore>() {
  985            let settings_store = SettingsStore::test(cx);
  986            cx.set_global(settings_store);
  987        }
  988
  989        let fs = fs::FakeFs::new(cx.background_executor().clone());
  990        <dyn Fs>::set_global(fs.clone(), cx);
  991        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
  992        let clock = Arc::new(clock::FakeSystemClock::new());
  993        let http_client = http_client::FakeHttpClient::with_404_response();
  994        let client = Client::new(clock, http_client, cx);
  995        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
  996        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
  997        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
  998
  999        theme::init(theme::LoadThemes::JustBase, cx);
 1000        client::init(&client, cx);
 1001
 1002        Arc::new(Self {
 1003            client,
 1004            fs,
 1005            languages,
 1006            user_store,
 1007            workspace_store,
 1008            node_runtime: NodeRuntime::unavailable(),
 1009            build_window_options: |_, _| Default::default(),
 1010            session,
 1011        })
 1012    }
 1013}
 1014
 1015struct DelayedDebouncedEditAction {
 1016    task: Option<Task<()>>,
 1017    cancel_channel: Option<oneshot::Sender<()>>,
 1018}
 1019
 1020impl DelayedDebouncedEditAction {
 1021    fn new() -> DelayedDebouncedEditAction {
 1022        DelayedDebouncedEditAction {
 1023            task: None,
 1024            cancel_channel: None,
 1025        }
 1026    }
 1027
 1028    fn fire_new<F>(
 1029        &mut self,
 1030        delay: Duration,
 1031        window: &mut Window,
 1032        cx: &mut Context<Workspace>,
 1033        func: F,
 1034    ) where
 1035        F: 'static
 1036            + Send
 1037            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
 1038    {
 1039        if let Some(channel) = self.cancel_channel.take() {
 1040            _ = channel.send(());
 1041        }
 1042
 1043        let (sender, mut receiver) = oneshot::channel::<()>();
 1044        self.cancel_channel = Some(sender);
 1045
 1046        let previous_task = self.task.take();
 1047        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1048            let mut timer = cx.background_executor().timer(delay).fuse();
 1049            if let Some(previous_task) = previous_task {
 1050                previous_task.await;
 1051            }
 1052
 1053            futures::select_biased! {
 1054                _ = receiver => return,
 1055                    _ = timer => {}
 1056            }
 1057
 1058            if let Some(result) = workspace
 1059                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1060                .log_err()
 1061            {
 1062                result.await.log_err();
 1063            }
 1064        }));
 1065    }
 1066}
 1067
 1068pub enum Event {
 1069    PaneAdded(Entity<Pane>),
 1070    PaneRemoved,
 1071    ItemAdded {
 1072        item: Box<dyn ItemHandle>,
 1073    },
 1074    ActiveItemChanged,
 1075    ItemRemoved {
 1076        item_id: EntityId,
 1077    },
 1078    UserSavedItem {
 1079        pane: WeakEntity<Pane>,
 1080        item: Box<dyn WeakItemHandle>,
 1081        save_intent: SaveIntent,
 1082    },
 1083    ContactRequestedJoin(u64),
 1084    WorkspaceCreated(WeakEntity<Workspace>),
 1085    OpenBundledFile {
 1086        text: Cow<'static, str>,
 1087        title: &'static str,
 1088        language: &'static str,
 1089    },
 1090    ZoomChanged,
 1091    ModalOpened,
 1092}
 1093
 1094#[derive(Debug)]
 1095pub enum OpenVisible {
 1096    All,
 1097    None,
 1098    OnlyFiles,
 1099    OnlyDirectories,
 1100}
 1101
 1102enum WorkspaceLocation {
 1103    // Valid local paths or SSH project to serialize
 1104    Location(SerializedWorkspaceLocation, PathList),
 1105    // No valid location found hence clear session id
 1106    DetachFromSession,
 1107    // No valid location found to serialize
 1108    None,
 1109}
 1110
 1111type PromptForNewPath = Box<
 1112    dyn Fn(
 1113        &mut Workspace,
 1114        DirectoryLister,
 1115        &mut Window,
 1116        &mut Context<Workspace>,
 1117    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1118>;
 1119
 1120type PromptForOpenPath = Box<
 1121    dyn Fn(
 1122        &mut Workspace,
 1123        DirectoryLister,
 1124        &mut Window,
 1125        &mut Context<Workspace>,
 1126    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1127>;
 1128
 1129#[derive(Default)]
 1130struct DispatchingKeystrokes {
 1131    dispatched: HashSet<Vec<Keystroke>>,
 1132    queue: VecDeque<Keystroke>,
 1133    task: Option<Shared<Task<()>>>,
 1134}
 1135
 1136/// Collects everything project-related for a certain window opened.
 1137/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1138///
 1139/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1140/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1141/// that can be used to register a global action to be triggered from any place in the window.
 1142pub struct Workspace {
 1143    weak_self: WeakEntity<Self>,
 1144    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1145    zoomed: Option<AnyWeakView>,
 1146    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1147    zoomed_position: Option<DockPosition>,
 1148    center: PaneGroup,
 1149    left_dock: Entity<Dock>,
 1150    bottom_dock: Entity<Dock>,
 1151    right_dock: Entity<Dock>,
 1152    panes: Vec<Entity<Pane>>,
 1153    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1154    active_pane: Entity<Pane>,
 1155    last_active_center_pane: Option<WeakEntity<Pane>>,
 1156    last_active_view_id: Option<proto::ViewId>,
 1157    status_bar: Entity<StatusBar>,
 1158    modal_layer: Entity<ModalLayer>,
 1159    toast_layer: Entity<ToastLayer>,
 1160    titlebar_item: Option<AnyView>,
 1161    notifications: Notifications,
 1162    suppressed_notifications: HashSet<NotificationId>,
 1163    project: Entity<Project>,
 1164    follower_states: HashMap<CollaboratorId, FollowerState>,
 1165    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1166    window_edited: bool,
 1167    last_window_title: Option<String>,
 1168    dirty_items: HashMap<EntityId, Subscription>,
 1169    active_call: Option<(Entity<ActiveCall>, Vec<Subscription>)>,
 1170    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1171    database_id: Option<WorkspaceId>,
 1172    app_state: Arc<AppState>,
 1173    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1174    _subscriptions: Vec<Subscription>,
 1175    _apply_leader_updates: Task<Result<()>>,
 1176    _observe_current_user: Task<Result<()>>,
 1177    _schedule_serialize_workspace: Option<Task<()>>,
 1178    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1179    pane_history_timestamp: Arc<AtomicUsize>,
 1180    bounds: Bounds<Pixels>,
 1181    pub centered_layout: bool,
 1182    bounds_save_task_queued: Option<Task<()>>,
 1183    on_prompt_for_new_path: Option<PromptForNewPath>,
 1184    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1185    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1186    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1187    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1188    _items_serializer: Task<Result<()>>,
 1189    session_id: Option<String>,
 1190    scheduled_tasks: Vec<Task<()>>,
 1191    last_open_dock_positions: Vec<DockPosition>,
 1192    removing: bool,
 1193    utility_panes: UtilityPaneState,
 1194}
 1195
 1196impl EventEmitter<Event> for Workspace {}
 1197
 1198#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1199pub struct ViewId {
 1200    pub creator: CollaboratorId,
 1201    pub id: u64,
 1202}
 1203
 1204pub struct FollowerState {
 1205    center_pane: Entity<Pane>,
 1206    dock_pane: Option<Entity<Pane>>,
 1207    active_view_id: Option<ViewId>,
 1208    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1209}
 1210
 1211struct FollowerView {
 1212    view: Box<dyn FollowableItemHandle>,
 1213    location: Option<proto::PanelId>,
 1214}
 1215
 1216impl Workspace {
 1217    pub fn new(
 1218        workspace_id: Option<WorkspaceId>,
 1219        project: Entity<Project>,
 1220        app_state: Arc<AppState>,
 1221        window: &mut Window,
 1222        cx: &mut Context<Self>,
 1223    ) -> Self {
 1224        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1225            match event {
 1226                project::Event::RemoteIdChanged(_) => {
 1227                    this.update_window_title(window, cx);
 1228                }
 1229
 1230                project::Event::CollaboratorLeft(peer_id) => {
 1231                    this.collaborator_left(*peer_id, window, cx);
 1232                }
 1233
 1234                project::Event::WorktreeRemoved(_) | project::Event::WorktreeAdded(_) => {
 1235                    this.update_window_title(window, cx);
 1236                    this.serialize_workspace(window, cx);
 1237                    // This event could be triggered by `AddFolderToProject` or `RemoveFromProject`.
 1238                    this.update_history(cx);
 1239                }
 1240
 1241                project::Event::DisconnectedFromHost => {
 1242                    this.update_window_edited(window, cx);
 1243                    let leaders_to_unfollow =
 1244                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1245                    for leader_id in leaders_to_unfollow {
 1246                        this.unfollow(leader_id, window, cx);
 1247                    }
 1248                }
 1249
 1250                project::Event::DisconnectedFromSshRemote => {
 1251                    this.update_window_edited(window, cx);
 1252                }
 1253
 1254                project::Event::Closed => {
 1255                    window.remove_window();
 1256                }
 1257
 1258                project::Event::DeletedEntry(_, entry_id) => {
 1259                    for pane in this.panes.iter() {
 1260                        pane.update(cx, |pane, cx| {
 1261                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1262                        });
 1263                    }
 1264                }
 1265
 1266                project::Event::Toast {
 1267                    notification_id,
 1268                    message,
 1269                } => this.show_notification(
 1270                    NotificationId::named(notification_id.clone()),
 1271                    cx,
 1272                    |cx| cx.new(|cx| MessageNotification::new(message.clone(), cx)),
 1273                ),
 1274
 1275                project::Event::HideToast { notification_id } => {
 1276                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1277                }
 1278
 1279                project::Event::LanguageServerPrompt(request) => {
 1280                    struct LanguageServerPrompt;
 1281
 1282                    let mut hasher = DefaultHasher::new();
 1283                    request.lsp_name.as_str().hash(&mut hasher);
 1284                    let id = hasher.finish();
 1285
 1286                    this.show_notification(
 1287                        NotificationId::composite::<LanguageServerPrompt>(id as usize),
 1288                        cx,
 1289                        |cx| {
 1290                            cx.new(|cx| {
 1291                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1292                            })
 1293                        },
 1294                    );
 1295                }
 1296
 1297                project::Event::AgentLocationChanged => {
 1298                    this.handle_agent_location_changed(window, cx)
 1299                }
 1300
 1301                _ => {}
 1302            }
 1303            cx.notify()
 1304        })
 1305        .detach();
 1306
 1307        cx.subscribe_in(
 1308            &project.read(cx).breakpoint_store(),
 1309            window,
 1310            |workspace, _, event, window, cx| match event {
 1311                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1312                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1313                    workspace.serialize_workspace(window, cx);
 1314                }
 1315                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1316            },
 1317        )
 1318        .detach();
 1319        if let Some(toolchain_store) = project.read(cx).toolchain_store() {
 1320            cx.subscribe_in(
 1321                &toolchain_store,
 1322                window,
 1323                |workspace, _, event, window, cx| match event {
 1324                    ToolchainStoreEvent::CustomToolchainsModified => {
 1325                        workspace.serialize_workspace(window, cx);
 1326                    }
 1327                    _ => {}
 1328                },
 1329            )
 1330            .detach();
 1331        }
 1332
 1333        cx.on_focus_lost(window, |this, window, cx| {
 1334            let focus_handle = this.focus_handle(cx);
 1335            window.focus(&focus_handle);
 1336        })
 1337        .detach();
 1338
 1339        let weak_handle = cx.entity().downgrade();
 1340        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1341
 1342        let center_pane = cx.new(|cx| {
 1343            let mut center_pane = Pane::new(
 1344                weak_handle.clone(),
 1345                project.clone(),
 1346                pane_history_timestamp.clone(),
 1347                None,
 1348                NewFile.boxed_clone(),
 1349                true,
 1350                window,
 1351                cx,
 1352            );
 1353            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1354            center_pane
 1355        });
 1356        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1357            .detach();
 1358
 1359        window.focus(&center_pane.focus_handle(cx));
 1360
 1361        cx.emit(Event::PaneAdded(center_pane.clone()));
 1362
 1363        let window_handle = window.window_handle().downcast::<Workspace>().unwrap();
 1364        app_state.workspace_store.update(cx, |store, _| {
 1365            store.workspaces.insert(window_handle);
 1366        });
 1367
 1368        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1369        let mut connection_status = app_state.client.status();
 1370        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1371            current_user.next().await;
 1372            connection_status.next().await;
 1373            let mut stream =
 1374                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1375
 1376            while stream.recv().await.is_some() {
 1377                this.update(cx, |_, cx| cx.notify())?;
 1378            }
 1379            anyhow::Ok(())
 1380        });
 1381
 1382        // All leader updates are enqueued and then processed in a single task, so
 1383        // that each asynchronous operation can be run in order.
 1384        let (leader_updates_tx, mut leader_updates_rx) =
 1385            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1386        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1387            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1388                Self::process_leader_update(&this, leader_id, update, cx)
 1389                    .await
 1390                    .log_err();
 1391            }
 1392
 1393            Ok(())
 1394        });
 1395
 1396        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1397        let modal_layer = cx.new(|_| ModalLayer::new());
 1398        let toast_layer = cx.new(|_| ToastLayer::new());
 1399        cx.subscribe(
 1400            &modal_layer,
 1401            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1402                cx.emit(Event::ModalOpened);
 1403            },
 1404        )
 1405        .detach();
 1406
 1407        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1408        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1409        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1410        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1411        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1412        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1413        let status_bar = cx.new(|cx| {
 1414            let mut status_bar = StatusBar::new(&center_pane.clone(), window, cx);
 1415            status_bar.add_left_item(left_dock_buttons, window, cx);
 1416            status_bar.add_right_item(right_dock_buttons, window, cx);
 1417            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1418            status_bar
 1419        });
 1420
 1421        let session_id = app_state.session.read(cx).id().to_owned();
 1422
 1423        let mut active_call = None;
 1424        if let Some(call) = ActiveCall::try_global(cx) {
 1425            let subscriptions = vec![cx.subscribe_in(&call, window, Self::on_active_call_event)];
 1426            active_call = Some((call, subscriptions));
 1427        }
 1428
 1429        let (serializable_items_tx, serializable_items_rx) =
 1430            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1431        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1432            Self::serialize_items(&this, serializable_items_rx, cx).await
 1433        });
 1434
 1435        let subscriptions = vec![
 1436            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1437            cx.observe_window_bounds(window, move |this, window, cx| {
 1438                if this.bounds_save_task_queued.is_some() {
 1439                    return;
 1440                }
 1441                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1442                    cx.background_executor()
 1443                        .timer(Duration::from_millis(100))
 1444                        .await;
 1445                    this.update_in(cx, |this, window, cx| {
 1446                        if let Some(display) = window.display(cx)
 1447                            && let Ok(display_uuid) = display.uuid()
 1448                        {
 1449                            let window_bounds = window.inner_window_bounds();
 1450                            if let Some(database_id) = workspace_id {
 1451                                cx.background_executor()
 1452                                    .spawn(DB.set_window_open_status(
 1453                                        database_id,
 1454                                        SerializedWindowBounds(window_bounds),
 1455                                        display_uuid,
 1456                                    ))
 1457                                    .detach_and_log_err(cx);
 1458                            }
 1459                        }
 1460                        this.bounds_save_task_queued.take();
 1461                    })
 1462                    .ok();
 1463                }));
 1464                cx.notify();
 1465            }),
 1466            cx.observe_window_appearance(window, |_, window, cx| {
 1467                let window_appearance = window.appearance();
 1468
 1469                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1470
 1471                GlobalTheme::reload_theme(cx);
 1472                GlobalTheme::reload_icon_theme(cx);
 1473            }),
 1474            cx.on_release(move |this, cx| {
 1475                this.app_state.workspace_store.update(cx, move |store, _| {
 1476                    store.workspaces.remove(&window_handle);
 1477                })
 1478            }),
 1479        ];
 1480
 1481        cx.defer_in(window, |this, window, cx| {
 1482            this.update_window_title(window, cx);
 1483            this.show_initial_notifications(cx);
 1484        });
 1485
 1486        let mut center = PaneGroup::new(center_pane.clone());
 1487        center.set_is_center(true);
 1488        center.mark_positions(cx);
 1489
 1490        Workspace {
 1491            weak_self: weak_handle.clone(),
 1492            zoomed: None,
 1493            zoomed_position: None,
 1494            previous_dock_drag_coordinates: None,
 1495            center,
 1496            panes: vec![center_pane.clone()],
 1497            panes_by_item: Default::default(),
 1498            active_pane: center_pane.clone(),
 1499            last_active_center_pane: Some(center_pane.downgrade()),
 1500            last_active_view_id: None,
 1501            status_bar,
 1502            modal_layer,
 1503            toast_layer,
 1504            titlebar_item: None,
 1505            notifications: Notifications::default(),
 1506            suppressed_notifications: HashSet::default(),
 1507            left_dock,
 1508            bottom_dock,
 1509            right_dock,
 1510            project: project.clone(),
 1511            follower_states: Default::default(),
 1512            last_leaders_by_pane: Default::default(),
 1513            dispatching_keystrokes: Default::default(),
 1514            window_edited: false,
 1515            last_window_title: None,
 1516            dirty_items: Default::default(),
 1517            active_call,
 1518            database_id: workspace_id,
 1519            app_state,
 1520            _observe_current_user,
 1521            _apply_leader_updates,
 1522            _schedule_serialize_workspace: None,
 1523            _schedule_serialize_ssh_paths: None,
 1524            leader_updates_tx,
 1525            _subscriptions: subscriptions,
 1526            pane_history_timestamp,
 1527            workspace_actions: Default::default(),
 1528            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1529            bounds: Default::default(),
 1530            centered_layout: false,
 1531            bounds_save_task_queued: None,
 1532            on_prompt_for_new_path: None,
 1533            on_prompt_for_open_path: None,
 1534            terminal_provider: None,
 1535            debugger_provider: None,
 1536            serializable_items_tx,
 1537            _items_serializer,
 1538            session_id: Some(session_id),
 1539
 1540            scheduled_tasks: Vec::new(),
 1541            last_open_dock_positions: Vec::new(),
 1542            removing: false,
 1543            utility_panes: UtilityPaneState::default(),
 1544        }
 1545    }
 1546
 1547    pub fn new_local(
 1548        abs_paths: Vec<PathBuf>,
 1549        app_state: Arc<AppState>,
 1550        requesting_window: Option<WindowHandle<Workspace>>,
 1551        env: Option<HashMap<String, String>>,
 1552        cx: &mut App,
 1553    ) -> Task<
 1554        anyhow::Result<(
 1555            WindowHandle<Workspace>,
 1556            Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 1557        )>,
 1558    > {
 1559        let project_handle = Project::local(
 1560            app_state.client.clone(),
 1561            app_state.node_runtime.clone(),
 1562            app_state.user_store.clone(),
 1563            app_state.languages.clone(),
 1564            app_state.fs.clone(),
 1565            env,
 1566            cx,
 1567        );
 1568
 1569        cx.spawn(async move |cx| {
 1570            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1571            for path in abs_paths.into_iter() {
 1572                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1573                    paths_to_open.push(canonical)
 1574                } else {
 1575                    paths_to_open.push(path)
 1576                }
 1577            }
 1578
 1579            let serialized_workspace =
 1580                persistence::DB.workspace_for_roots(paths_to_open.as_slice());
 1581
 1582            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1583                paths_to_open = paths.ordered_paths().cloned().collect();
 1584                if !paths.is_lexicographically_ordered() {
 1585                    project_handle
 1586                        .update(cx, |project, cx| {
 1587                            project.set_worktrees_reordered(true, cx);
 1588                        })
 1589                        .log_err();
 1590                }
 1591            }
 1592
 1593            // Get project paths for all of the abs_paths
 1594            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1595                Vec::with_capacity(paths_to_open.len());
 1596
 1597            for path in paths_to_open.into_iter() {
 1598                if let Some((_, project_entry)) = cx
 1599                    .update(|cx| {
 1600                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1601                    })?
 1602                    .await
 1603                    .log_err()
 1604                {
 1605                    project_paths.push((path, Some(project_entry)));
 1606                } else {
 1607                    project_paths.push((path, None));
 1608                }
 1609            }
 1610
 1611            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1612                serialized_workspace.id
 1613            } else {
 1614                DB.next_id().await.unwrap_or_else(|_| Default::default())
 1615            };
 1616
 1617            let toolchains = DB.toolchains(workspace_id).await?;
 1618
 1619            for (toolchain, worktree_id, path) in toolchains {
 1620                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1621                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1622                    continue;
 1623                }
 1624
 1625                project_handle
 1626                    .update(cx, |this, cx| {
 1627                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1628                    })?
 1629                    .await;
 1630            }
 1631            if let Some(workspace) = serialized_workspace.as_ref() {
 1632                project_handle.update(cx, |this, cx| {
 1633                    for (scope, toolchains) in &workspace.user_toolchains {
 1634                        for toolchain in toolchains {
 1635                            this.add_toolchain(toolchain.clone(), scope.clone(), cx);
 1636                        }
 1637                    }
 1638                })?;
 1639            }
 1640
 1641            let window = if let Some(window) = requesting_window {
 1642                let centered_layout = serialized_workspace
 1643                    .as_ref()
 1644                    .map(|w| w.centered_layout)
 1645                    .unwrap_or(false);
 1646
 1647                cx.update_window(window.into(), |_, window, cx| {
 1648                    window.replace_root(cx, |window, cx| {
 1649                        let mut workspace = Workspace::new(
 1650                            Some(workspace_id),
 1651                            project_handle.clone(),
 1652                            app_state.clone(),
 1653                            window,
 1654                            cx,
 1655                        );
 1656
 1657                        workspace.centered_layout = centered_layout;
 1658                        workspace
 1659                    });
 1660                })?;
 1661                window
 1662            } else {
 1663                let window_bounds_override = window_bounds_env_override();
 1664
 1665                let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1666                    (Some(WindowBounds::Windowed(bounds)), None)
 1667                } else if let Some(workspace) = serialized_workspace.as_ref() {
 1668                    // Reopening an existing workspace - restore its saved bounds
 1669                    if let (Some(display), Some(bounds)) =
 1670                        (workspace.display, workspace.window_bounds.as_ref())
 1671                    {
 1672                        (Some(bounds.0), Some(display))
 1673                    } else {
 1674                        (None, None)
 1675                    }
 1676                } else {
 1677                    // New window - let GPUI's default_bounds() handle cascading
 1678                    (None, None)
 1679                };
 1680
 1681                // Use the serialized workspace to construct the new window
 1682                let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx))?;
 1683                options.window_bounds = window_bounds;
 1684                let centered_layout = serialized_workspace
 1685                    .as_ref()
 1686                    .map(|w| w.centered_layout)
 1687                    .unwrap_or(false);
 1688                cx.open_window(options, {
 1689                    let app_state = app_state.clone();
 1690                    let project_handle = project_handle.clone();
 1691                    move |window, cx| {
 1692                        cx.new(|cx| {
 1693                            let mut workspace = Workspace::new(
 1694                                Some(workspace_id),
 1695                                project_handle,
 1696                                app_state,
 1697                                window,
 1698                                cx,
 1699                            );
 1700                            workspace.centered_layout = centered_layout;
 1701                            workspace
 1702                        })
 1703                    }
 1704                })?
 1705            };
 1706
 1707            notify_if_database_failed(window, cx);
 1708            let opened_items = window
 1709                .update(cx, |_workspace, window, cx| {
 1710                    open_items(serialized_workspace, project_paths, window, cx)
 1711                })?
 1712                .await
 1713                .unwrap_or_default();
 1714
 1715            window
 1716                .update(cx, |workspace, window, cx| {
 1717                    window.activate_window();
 1718                    workspace.update_history(cx);
 1719                })
 1720                .log_err();
 1721            Ok((window, opened_items))
 1722        })
 1723    }
 1724
 1725    pub fn weak_handle(&self) -> WeakEntity<Self> {
 1726        self.weak_self.clone()
 1727    }
 1728
 1729    pub fn left_dock(&self) -> &Entity<Dock> {
 1730        &self.left_dock
 1731    }
 1732
 1733    pub fn bottom_dock(&self) -> &Entity<Dock> {
 1734        &self.bottom_dock
 1735    }
 1736
 1737    pub fn set_bottom_dock_layout(
 1738        &mut self,
 1739        layout: BottomDockLayout,
 1740        window: &mut Window,
 1741        cx: &mut Context<Self>,
 1742    ) {
 1743        let fs = self.project().read(cx).fs();
 1744        settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
 1745            content.workspace.bottom_dock_layout = Some(layout);
 1746        });
 1747
 1748        cx.notify();
 1749        self.serialize_workspace(window, cx);
 1750    }
 1751
 1752    pub fn right_dock(&self) -> &Entity<Dock> {
 1753        &self.right_dock
 1754    }
 1755
 1756    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 1757        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 1758    }
 1759
 1760    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 1761        match position {
 1762            DockPosition::Left => &self.left_dock,
 1763            DockPosition::Bottom => &self.bottom_dock,
 1764            DockPosition::Right => &self.right_dock,
 1765        }
 1766    }
 1767
 1768    pub fn is_edited(&self) -> bool {
 1769        self.window_edited
 1770    }
 1771
 1772    pub fn add_panel<T: Panel>(
 1773        &mut self,
 1774        panel: Entity<T>,
 1775        window: &mut Window,
 1776        cx: &mut Context<Self>,
 1777    ) {
 1778        let focus_handle = panel.panel_focus_handle(cx);
 1779        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 1780            .detach();
 1781
 1782        let dock_position = panel.position(window, cx);
 1783        let dock = self.dock_at_position(dock_position);
 1784
 1785        dock.update(cx, |dock, cx| {
 1786            dock.add_panel(panel, self.weak_self.clone(), window, cx)
 1787        });
 1788    }
 1789
 1790    pub fn remove_panel<T: Panel>(
 1791        &mut self,
 1792        panel: &Entity<T>,
 1793        window: &mut Window,
 1794        cx: &mut Context<Self>,
 1795    ) {
 1796        let mut found_in_dock = None;
 1797        for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
 1798            let found = dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
 1799
 1800            if found {
 1801                found_in_dock = Some(dock.clone());
 1802            }
 1803        }
 1804        if let Some(found_in_dock) = found_in_dock {
 1805            let position = found_in_dock.read(cx).position();
 1806            let slot = utility_slot_for_dock_position(position);
 1807            self.clear_utility_pane_if_provider(slot, Entity::entity_id(panel), cx);
 1808        }
 1809    }
 1810
 1811    pub fn status_bar(&self) -> &Entity<StatusBar> {
 1812        &self.status_bar
 1813    }
 1814
 1815    pub fn status_bar_visible(&self, cx: &App) -> bool {
 1816        StatusBarSettings::get_global(cx).show
 1817    }
 1818
 1819    pub fn app_state(&self) -> &Arc<AppState> {
 1820        &self.app_state
 1821    }
 1822
 1823    pub fn user_store(&self) -> &Entity<UserStore> {
 1824        &self.app_state.user_store
 1825    }
 1826
 1827    pub fn project(&self) -> &Entity<Project> {
 1828        &self.project
 1829    }
 1830
 1831    pub fn path_style(&self, cx: &App) -> PathStyle {
 1832        self.project.read(cx).path_style(cx)
 1833    }
 1834
 1835    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 1836        let mut history: HashMap<EntityId, usize> = HashMap::default();
 1837
 1838        for pane_handle in &self.panes {
 1839            let pane = pane_handle.read(cx);
 1840
 1841            for entry in pane.activation_history() {
 1842                history.insert(
 1843                    entry.entity_id,
 1844                    history
 1845                        .get(&entry.entity_id)
 1846                        .cloned()
 1847                        .unwrap_or(0)
 1848                        .max(entry.timestamp),
 1849                );
 1850            }
 1851        }
 1852
 1853        history
 1854    }
 1855
 1856    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 1857        let mut recent_item: Option<Entity<T>> = None;
 1858        let mut recent_timestamp = 0;
 1859        for pane_handle in &self.panes {
 1860            let pane = pane_handle.read(cx);
 1861            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 1862                pane.items().map(|item| (item.item_id(), item)).collect();
 1863            for entry in pane.activation_history() {
 1864                if entry.timestamp > recent_timestamp
 1865                    && let Some(&item) = item_map.get(&entry.entity_id)
 1866                    && let Some(typed_item) = item.act_as::<T>(cx)
 1867                {
 1868                    recent_timestamp = entry.timestamp;
 1869                    recent_item = Some(typed_item);
 1870                }
 1871            }
 1872        }
 1873        recent_item
 1874    }
 1875
 1876    pub fn recent_navigation_history_iter(
 1877        &self,
 1878        cx: &App,
 1879    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
 1880        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 1881        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 1882
 1883        for pane in &self.panes {
 1884            let pane = pane.read(cx);
 1885
 1886            pane.nav_history()
 1887                .for_each_entry(cx, |entry, (project_path, fs_path)| {
 1888                    if let Some(fs_path) = &fs_path {
 1889                        abs_paths_opened
 1890                            .entry(fs_path.clone())
 1891                            .or_default()
 1892                            .insert(project_path.clone());
 1893                    }
 1894                    let timestamp = entry.timestamp;
 1895                    match history.entry(project_path) {
 1896                        hash_map::Entry::Occupied(mut entry) => {
 1897                            let (_, old_timestamp) = entry.get();
 1898                            if &timestamp > old_timestamp {
 1899                                entry.insert((fs_path, timestamp));
 1900                            }
 1901                        }
 1902                        hash_map::Entry::Vacant(entry) => {
 1903                            entry.insert((fs_path, timestamp));
 1904                        }
 1905                    }
 1906                });
 1907
 1908            if let Some(item) = pane.active_item()
 1909                && let Some(project_path) = item.project_path(cx)
 1910            {
 1911                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 1912
 1913                if let Some(fs_path) = &fs_path {
 1914                    abs_paths_opened
 1915                        .entry(fs_path.clone())
 1916                        .or_default()
 1917                        .insert(project_path.clone());
 1918                }
 1919
 1920                history.insert(project_path, (fs_path, std::usize::MAX));
 1921            }
 1922        }
 1923
 1924        history
 1925            .into_iter()
 1926            .sorted_by_key(|(_, (_, order))| *order)
 1927            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 1928            .rev()
 1929            .filter(move |(history_path, abs_path)| {
 1930                let latest_project_path_opened = abs_path
 1931                    .as_ref()
 1932                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 1933                    .and_then(|project_paths| {
 1934                        project_paths
 1935                            .iter()
 1936                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 1937                    });
 1938
 1939                latest_project_path_opened.is_none_or(|path| path == history_path)
 1940            })
 1941    }
 1942
 1943    pub fn recent_navigation_history(
 1944        &self,
 1945        limit: Option<usize>,
 1946        cx: &App,
 1947    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 1948        self.recent_navigation_history_iter(cx)
 1949            .take(limit.unwrap_or(usize::MAX))
 1950            .collect()
 1951    }
 1952
 1953    pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
 1954        for pane in &self.panes {
 1955            pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
 1956        }
 1957    }
 1958
 1959    fn navigate_history(
 1960        &mut self,
 1961        pane: WeakEntity<Pane>,
 1962        mode: NavigationMode,
 1963        window: &mut Window,
 1964        cx: &mut Context<Workspace>,
 1965    ) -> Task<Result<()>> {
 1966        let to_load = if let Some(pane) = pane.upgrade() {
 1967            pane.update(cx, |pane, cx| {
 1968                window.focus(&pane.focus_handle(cx));
 1969                loop {
 1970                    // Retrieve the weak item handle from the history.
 1971                    let entry = pane.nav_history_mut().pop(mode, cx)?;
 1972
 1973                    // If the item is still present in this pane, then activate it.
 1974                    if let Some(index) = entry
 1975                        .item
 1976                        .upgrade()
 1977                        .and_then(|v| pane.index_for_item(v.as_ref()))
 1978                    {
 1979                        let prev_active_item_index = pane.active_item_index();
 1980                        pane.nav_history_mut().set_mode(mode);
 1981                        pane.activate_item(index, true, true, window, cx);
 1982                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 1983
 1984                        let mut navigated = prev_active_item_index != pane.active_item_index();
 1985                        if let Some(data) = entry.data {
 1986                            navigated |= pane.active_item()?.navigate(data, window, cx);
 1987                        }
 1988
 1989                        if navigated {
 1990                            break None;
 1991                        }
 1992                    } else {
 1993                        // If the item is no longer present in this pane, then retrieve its
 1994                        // path info in order to reopen it.
 1995                        break pane
 1996                            .nav_history()
 1997                            .path_for_item(entry.item.id())
 1998                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 1999                    }
 2000                }
 2001            })
 2002        } else {
 2003            None
 2004        };
 2005
 2006        if let Some((project_path, abs_path, entry)) = to_load {
 2007            // If the item was no longer present, then load it again from its previous path, first try the local path
 2008            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 2009
 2010            cx.spawn_in(window, async move  |workspace, cx| {
 2011                let open_by_project_path = open_by_project_path.await;
 2012                let mut navigated = false;
 2013                match open_by_project_path
 2014                    .with_context(|| format!("Navigating to {project_path:?}"))
 2015                {
 2016                    Ok((project_entry_id, build_item)) => {
 2017                        let prev_active_item_id = pane.update(cx, |pane, _| {
 2018                            pane.nav_history_mut().set_mode(mode);
 2019                            pane.active_item().map(|p| p.item_id())
 2020                        })?;
 2021
 2022                        pane.update_in(cx, |pane, window, cx| {
 2023                            let item = pane.open_item(
 2024                                project_entry_id,
 2025                                project_path,
 2026                                true,
 2027                                entry.is_preview,
 2028                                true,
 2029                                None,
 2030                                window, cx,
 2031                                build_item,
 2032                            );
 2033                            navigated |= Some(item.item_id()) != prev_active_item_id;
 2034                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2035                            if let Some(data) = entry.data {
 2036                                navigated |= item.navigate(data, window, cx);
 2037                            }
 2038                        })?;
 2039                    }
 2040                    Err(open_by_project_path_e) => {
 2041                        // Fall back to opening by abs path, in case an external file was opened and closed,
 2042                        // and its worktree is now dropped
 2043                        if let Some(abs_path) = abs_path {
 2044                            let prev_active_item_id = pane.update(cx, |pane, _| {
 2045                                pane.nav_history_mut().set_mode(mode);
 2046                                pane.active_item().map(|p| p.item_id())
 2047                            })?;
 2048                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 2049                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 2050                            })?;
 2051                            match open_by_abs_path
 2052                                .await
 2053                                .with_context(|| format!("Navigating to {abs_path:?}"))
 2054                            {
 2055                                Ok(item) => {
 2056                                    pane.update_in(cx, |pane, window, cx| {
 2057                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 2058                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 2059                                        if let Some(data) = entry.data {
 2060                                            navigated |= item.navigate(data, window, cx);
 2061                                        }
 2062                                    })?;
 2063                                }
 2064                                Err(open_by_abs_path_e) => {
 2065                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 2066                                }
 2067                            }
 2068                        }
 2069                    }
 2070                }
 2071
 2072                if !navigated {
 2073                    workspace
 2074                        .update_in(cx, |workspace, window, cx| {
 2075                            Self::navigate_history(workspace, pane, mode, window, cx)
 2076                        })?
 2077                        .await?;
 2078                }
 2079
 2080                Ok(())
 2081            })
 2082        } else {
 2083            Task::ready(Ok(()))
 2084        }
 2085    }
 2086
 2087    pub fn go_back(
 2088        &mut self,
 2089        pane: WeakEntity<Pane>,
 2090        window: &mut Window,
 2091        cx: &mut Context<Workspace>,
 2092    ) -> Task<Result<()>> {
 2093        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 2094    }
 2095
 2096    pub fn go_forward(
 2097        &mut self,
 2098        pane: WeakEntity<Pane>,
 2099        window: &mut Window,
 2100        cx: &mut Context<Workspace>,
 2101    ) -> Task<Result<()>> {
 2102        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 2103    }
 2104
 2105    pub fn reopen_closed_item(
 2106        &mut self,
 2107        window: &mut Window,
 2108        cx: &mut Context<Workspace>,
 2109    ) -> Task<Result<()>> {
 2110        self.navigate_history(
 2111            self.active_pane().downgrade(),
 2112            NavigationMode::ReopeningClosedItem,
 2113            window,
 2114            cx,
 2115        )
 2116    }
 2117
 2118    pub fn client(&self) -> &Arc<Client> {
 2119        &self.app_state.client
 2120    }
 2121
 2122    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2123        self.titlebar_item = Some(item);
 2124        cx.notify();
 2125    }
 2126
 2127    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2128        self.on_prompt_for_new_path = Some(prompt)
 2129    }
 2130
 2131    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2132        self.on_prompt_for_open_path = Some(prompt)
 2133    }
 2134
 2135    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2136        self.terminal_provider = Some(Box::new(provider));
 2137    }
 2138
 2139    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2140        self.debugger_provider = Some(Arc::new(provider));
 2141    }
 2142
 2143    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2144        self.debugger_provider.clone()
 2145    }
 2146
 2147    pub fn prompt_for_open_path(
 2148        &mut self,
 2149        path_prompt_options: PathPromptOptions,
 2150        lister: DirectoryLister,
 2151        window: &mut Window,
 2152        cx: &mut Context<Self>,
 2153    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2154        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2155            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2156            let rx = prompt(self, lister, window, cx);
 2157            self.on_prompt_for_open_path = Some(prompt);
 2158            rx
 2159        } else {
 2160            let (tx, rx) = oneshot::channel();
 2161            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2162
 2163            cx.spawn_in(window, async move |workspace, cx| {
 2164                let Ok(result) = abs_path.await else {
 2165                    return Ok(());
 2166                };
 2167
 2168                match result {
 2169                    Ok(result) => {
 2170                        tx.send(result).ok();
 2171                    }
 2172                    Err(err) => {
 2173                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2174                            workspace.show_portal_error(err.to_string(), cx);
 2175                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2176                            let rx = prompt(workspace, lister, window, cx);
 2177                            workspace.on_prompt_for_open_path = Some(prompt);
 2178                            rx
 2179                        })?;
 2180                        if let Ok(path) = rx.await {
 2181                            tx.send(path).ok();
 2182                        }
 2183                    }
 2184                };
 2185                anyhow::Ok(())
 2186            })
 2187            .detach();
 2188
 2189            rx
 2190        }
 2191    }
 2192
 2193    pub fn prompt_for_new_path(
 2194        &mut self,
 2195        lister: DirectoryLister,
 2196        suggested_name: Option<String>,
 2197        window: &mut Window,
 2198        cx: &mut Context<Self>,
 2199    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2200        if self.project.read(cx).is_via_collab()
 2201            || self.project.read(cx).is_via_remote_server()
 2202            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2203        {
 2204            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2205            let rx = prompt(self, lister, window, cx);
 2206            self.on_prompt_for_new_path = Some(prompt);
 2207            return rx;
 2208        }
 2209
 2210        let (tx, rx) = oneshot::channel();
 2211        cx.spawn_in(window, async move |workspace, cx| {
 2212            let abs_path = workspace.update(cx, |workspace, cx| {
 2213                let relative_to = workspace
 2214                    .most_recent_active_path(cx)
 2215                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2216                    .or_else(|| {
 2217                        let project = workspace.project.read(cx);
 2218                        project.visible_worktrees(cx).find_map(|worktree| {
 2219                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2220                        })
 2221                    })
 2222                    .or_else(std::env::home_dir)
 2223                    .unwrap_or_else(|| PathBuf::from(""));
 2224                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2225            })?;
 2226            let abs_path = match abs_path.await? {
 2227                Ok(path) => path,
 2228                Err(err) => {
 2229                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2230                        workspace.show_portal_error(err.to_string(), cx);
 2231
 2232                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2233                        let rx = prompt(workspace, lister, window, cx);
 2234                        workspace.on_prompt_for_new_path = Some(prompt);
 2235                        rx
 2236                    })?;
 2237                    if let Ok(path) = rx.await {
 2238                        tx.send(path).ok();
 2239                    }
 2240                    return anyhow::Ok(());
 2241                }
 2242            };
 2243
 2244            tx.send(abs_path.map(|path| vec![path])).ok();
 2245            anyhow::Ok(())
 2246        })
 2247        .detach();
 2248
 2249        rx
 2250    }
 2251
 2252    pub fn titlebar_item(&self) -> Option<AnyView> {
 2253        self.titlebar_item.clone()
 2254    }
 2255
 2256    /// Call the given callback with a workspace whose project is local.
 2257    ///
 2258    /// If the given workspace has a local project, then it will be passed
 2259    /// to the callback. Otherwise, a new empty window will be created.
 2260    pub fn with_local_workspace<T, F>(
 2261        &mut self,
 2262        window: &mut Window,
 2263        cx: &mut Context<Self>,
 2264        callback: F,
 2265    ) -> Task<Result<T>>
 2266    where
 2267        T: 'static,
 2268        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2269    {
 2270        if self.project.read(cx).is_local() {
 2271            Task::ready(Ok(callback(self, window, cx)))
 2272        } else {
 2273            let env = self.project.read(cx).cli_environment(cx);
 2274            let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, cx);
 2275            cx.spawn_in(window, async move |_vh, cx| {
 2276                let (workspace, _) = task.await?;
 2277                workspace.update(cx, callback)
 2278            })
 2279        }
 2280    }
 2281
 2282    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2283        self.project.read(cx).worktrees(cx)
 2284    }
 2285
 2286    pub fn visible_worktrees<'a>(
 2287        &self,
 2288        cx: &'a App,
 2289    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2290        self.project.read(cx).visible_worktrees(cx)
 2291    }
 2292
 2293    #[cfg(any(test, feature = "test-support"))]
 2294    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2295        let futures = self
 2296            .worktrees(cx)
 2297            .filter_map(|worktree| worktree.read(cx).as_local())
 2298            .map(|worktree| worktree.scan_complete())
 2299            .collect::<Vec<_>>();
 2300        async move {
 2301            for future in futures {
 2302                future.await;
 2303            }
 2304        }
 2305    }
 2306
 2307    pub fn close_global(cx: &mut App) {
 2308        cx.defer(|cx| {
 2309            cx.windows().iter().find(|window| {
 2310                window
 2311                    .update(cx, |_, window, _| {
 2312                        if window.is_window_active() {
 2313                            //This can only get called when the window's project connection has been lost
 2314                            //so we don't need to prompt the user for anything and instead just close the window
 2315                            window.remove_window();
 2316                            true
 2317                        } else {
 2318                            false
 2319                        }
 2320                    })
 2321                    .unwrap_or(false)
 2322            });
 2323        });
 2324    }
 2325
 2326    pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
 2327        let prepare = self.prepare_to_close(CloseIntent::CloseWindow, window, cx);
 2328        cx.spawn_in(window, async move |_, cx| {
 2329            if prepare.await? {
 2330                cx.update(|window, _cx| window.remove_window())?;
 2331            }
 2332            anyhow::Ok(())
 2333        })
 2334        .detach_and_log_err(cx)
 2335    }
 2336
 2337    pub fn move_focused_panel_to_next_position(
 2338        &mut self,
 2339        _: &MoveFocusedPanelToNextPosition,
 2340        window: &mut Window,
 2341        cx: &mut Context<Self>,
 2342    ) {
 2343        let docks = self.all_docks();
 2344        let active_dock = docks
 2345            .into_iter()
 2346            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 2347
 2348        if let Some(dock) = active_dock {
 2349            dock.update(cx, |dock, cx| {
 2350                let active_panel = dock
 2351                    .active_panel()
 2352                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 2353
 2354                if let Some(panel) = active_panel {
 2355                    panel.move_to_next_position(window, cx);
 2356                }
 2357            })
 2358        }
 2359    }
 2360
 2361    pub fn prepare_to_close(
 2362        &mut self,
 2363        close_intent: CloseIntent,
 2364        window: &mut Window,
 2365        cx: &mut Context<Self>,
 2366    ) -> Task<Result<bool>> {
 2367        let active_call = self.active_call().cloned();
 2368
 2369        cx.spawn_in(window, async move |this, cx| {
 2370            this.update(cx, |this, _| {
 2371                if close_intent == CloseIntent::CloseWindow {
 2372                    this.removing = true;
 2373                }
 2374            })?;
 2375
 2376            let workspace_count = cx.update(|_window, cx| {
 2377                cx.windows()
 2378                    .iter()
 2379                    .filter(|window| window.downcast::<Workspace>().is_some())
 2380                    .count()
 2381            })?;
 2382
 2383            #[cfg(target_os = "macos")]
 2384            let save_last_workspace = false;
 2385
 2386            // On Linux and Windows, closing the last window should restore the last workspace.
 2387            #[cfg(not(target_os = "macos"))]
 2388            let save_last_workspace = {
 2389                let remaining_workspaces = cx.update(|_window, cx| {
 2390                    cx.windows()
 2391                        .iter()
 2392                        .filter_map(|window| window.downcast::<Workspace>())
 2393                        .filter_map(|workspace| {
 2394                            workspace
 2395                                .update(cx, |workspace, _, _| workspace.removing)
 2396                                .ok()
 2397                        })
 2398                        .filter(|removing| !removing)
 2399                        .count()
 2400                })?;
 2401
 2402                close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
 2403            };
 2404
 2405            if let Some(active_call) = active_call
 2406                && workspace_count == 1
 2407                && active_call.read_with(cx, |call, _| call.room().is_some())?
 2408            {
 2409                if close_intent == CloseIntent::CloseWindow {
 2410                    let answer = cx.update(|window, cx| {
 2411                        window.prompt(
 2412                            PromptLevel::Warning,
 2413                            "Do you want to leave the current call?",
 2414                            None,
 2415                            &["Close window and hang up", "Cancel"],
 2416                            cx,
 2417                        )
 2418                    })?;
 2419
 2420                    if answer.await.log_err() == Some(1) {
 2421                        return anyhow::Ok(false);
 2422                    } else {
 2423                        active_call
 2424                            .update(cx, |call, cx| call.hang_up(cx))?
 2425                            .await
 2426                            .log_err();
 2427                    }
 2428                }
 2429                if close_intent == CloseIntent::ReplaceWindow {
 2430                    _ = active_call.update(cx, |this, cx| {
 2431                        let workspace = cx
 2432                            .windows()
 2433                            .iter()
 2434                            .filter_map(|window| window.downcast::<Workspace>())
 2435                            .next()
 2436                            .unwrap();
 2437                        let project = workspace.read(cx)?.project.clone();
 2438                        if project.read(cx).is_shared() {
 2439                            this.unshare_project(project, cx)?;
 2440                        }
 2441                        Ok::<_, anyhow::Error>(())
 2442                    })?;
 2443                }
 2444            }
 2445
 2446            let save_result = this
 2447                .update_in(cx, |this, window, cx| {
 2448                    this.save_all_internal(SaveIntent::Close, window, cx)
 2449                })?
 2450                .await;
 2451
 2452            // If we're not quitting, but closing, we remove the workspace from
 2453            // the current session.
 2454            if close_intent != CloseIntent::Quit
 2455                && !save_last_workspace
 2456                && save_result.as_ref().is_ok_and(|&res| res)
 2457            {
 2458                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 2459                    .await;
 2460            }
 2461
 2462            save_result
 2463        })
 2464    }
 2465
 2466    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 2467        self.save_all_internal(
 2468            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 2469            window,
 2470            cx,
 2471        )
 2472        .detach_and_log_err(cx);
 2473    }
 2474
 2475    fn send_keystrokes(
 2476        &mut self,
 2477        action: &SendKeystrokes,
 2478        window: &mut Window,
 2479        cx: &mut Context<Self>,
 2480    ) {
 2481        let keystrokes: Vec<Keystroke> = action
 2482            .0
 2483            .split(' ')
 2484            .flat_map(|k| Keystroke::parse(k).log_err())
 2485            .map(|k| {
 2486                cx.keyboard_mapper()
 2487                    .map_key_equivalent(k, true)
 2488                    .inner()
 2489                    .clone()
 2490            })
 2491            .collect();
 2492        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 2493    }
 2494
 2495    pub fn send_keystrokes_impl(
 2496        &mut self,
 2497        keystrokes: Vec<Keystroke>,
 2498        window: &mut Window,
 2499        cx: &mut Context<Self>,
 2500    ) -> Shared<Task<()>> {
 2501        let mut state = self.dispatching_keystrokes.borrow_mut();
 2502        if !state.dispatched.insert(keystrokes.clone()) {
 2503            cx.propagate();
 2504            return state.task.clone().unwrap();
 2505        }
 2506
 2507        state.queue.extend(keystrokes);
 2508
 2509        let keystrokes = self.dispatching_keystrokes.clone();
 2510        if state.task.is_none() {
 2511            state.task = Some(
 2512                window
 2513                    .spawn(cx, async move |cx| {
 2514                        // limit to 100 keystrokes to avoid infinite recursion.
 2515                        for _ in 0..100 {
 2516                            let mut state = keystrokes.borrow_mut();
 2517                            let Some(keystroke) = state.queue.pop_front() else {
 2518                                state.dispatched.clear();
 2519                                state.task.take();
 2520                                return;
 2521                            };
 2522                            drop(state);
 2523                            cx.update(|window, cx| {
 2524                                let focused = window.focused(cx);
 2525                                window.dispatch_keystroke(keystroke.clone(), cx);
 2526                                if window.focused(cx) != focused {
 2527                                    // dispatch_keystroke may cause the focus to change.
 2528                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 2529                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 2530                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 2531                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 2532                                    // )
 2533                                    window.draw(cx).clear();
 2534                                }
 2535                            })
 2536                            .ok();
 2537                        }
 2538
 2539                        *keystrokes.borrow_mut() = Default::default();
 2540                        log::error!("over 100 keystrokes passed to send_keystrokes");
 2541                    })
 2542                    .shared(),
 2543            );
 2544        }
 2545        state.task.clone().unwrap()
 2546    }
 2547
 2548    fn save_all_internal(
 2549        &mut self,
 2550        mut save_intent: SaveIntent,
 2551        window: &mut Window,
 2552        cx: &mut Context<Self>,
 2553    ) -> Task<Result<bool>> {
 2554        if self.project.read(cx).is_disconnected(cx) {
 2555            return Task::ready(Ok(true));
 2556        }
 2557        let dirty_items = self
 2558            .panes
 2559            .iter()
 2560            .flat_map(|pane| {
 2561                pane.read(cx).items().filter_map(|item| {
 2562                    if item.is_dirty(cx) {
 2563                        item.tab_content_text(0, cx);
 2564                        Some((pane.downgrade(), item.boxed_clone()))
 2565                    } else {
 2566                        None
 2567                    }
 2568                })
 2569            })
 2570            .collect::<Vec<_>>();
 2571
 2572        let project = self.project.clone();
 2573        cx.spawn_in(window, async move |workspace, cx| {
 2574            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 2575                let (serialize_tasks, remaining_dirty_items) =
 2576                    workspace.update_in(cx, |workspace, window, cx| {
 2577                        let mut remaining_dirty_items = Vec::new();
 2578                        let mut serialize_tasks = Vec::new();
 2579                        for (pane, item) in dirty_items {
 2580                            if let Some(task) = item
 2581                                .to_serializable_item_handle(cx)
 2582                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 2583                            {
 2584                                serialize_tasks.push(task);
 2585                            } else {
 2586                                remaining_dirty_items.push((pane, item));
 2587                            }
 2588                        }
 2589                        (serialize_tasks, remaining_dirty_items)
 2590                    })?;
 2591
 2592                futures::future::try_join_all(serialize_tasks).await?;
 2593
 2594                if remaining_dirty_items.len() > 1 {
 2595                    let answer = workspace.update_in(cx, |_, window, cx| {
 2596                        let detail = Pane::file_names_for_prompt(
 2597                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 2598                            cx,
 2599                        );
 2600                        window.prompt(
 2601                            PromptLevel::Warning,
 2602                            "Do you want to save all changes in the following files?",
 2603                            Some(&detail),
 2604                            &["Save all", "Discard all", "Cancel"],
 2605                            cx,
 2606                        )
 2607                    })?;
 2608                    match answer.await.log_err() {
 2609                        Some(0) => save_intent = SaveIntent::SaveAll,
 2610                        Some(1) => save_intent = SaveIntent::Skip,
 2611                        Some(2) => return Ok(false),
 2612                        _ => {}
 2613                    }
 2614                }
 2615
 2616                remaining_dirty_items
 2617            } else {
 2618                dirty_items
 2619            };
 2620
 2621            for (pane, item) in dirty_items {
 2622                let (singleton, project_entry_ids) = cx.update(|_, cx| {
 2623                    (
 2624                        item.buffer_kind(cx) == ItemBufferKind::Singleton,
 2625                        item.project_entry_ids(cx),
 2626                    )
 2627                })?;
 2628                if (singleton || !project_entry_ids.is_empty())
 2629                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 2630                {
 2631                    return Ok(false);
 2632                }
 2633            }
 2634            Ok(true)
 2635        })
 2636    }
 2637
 2638    pub fn open_workspace_for_paths(
 2639        &mut self,
 2640        replace_current_window: bool,
 2641        paths: Vec<PathBuf>,
 2642        window: &mut Window,
 2643        cx: &mut Context<Self>,
 2644    ) -> Task<Result<()>> {
 2645        let window_handle = window.window_handle().downcast::<Self>();
 2646        let is_remote = self.project.read(cx).is_via_collab();
 2647        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 2648        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 2649
 2650        let window_to_replace = if replace_current_window {
 2651            window_handle
 2652        } else if is_remote || has_worktree || has_dirty_items {
 2653            None
 2654        } else {
 2655            window_handle
 2656        };
 2657        let app_state = self.app_state.clone();
 2658
 2659        cx.spawn(async move |_, cx| {
 2660            cx.update(|cx| {
 2661                open_paths(
 2662                    &paths,
 2663                    app_state,
 2664                    OpenOptions {
 2665                        replace_window: window_to_replace,
 2666                        ..Default::default()
 2667                    },
 2668                    cx,
 2669                )
 2670            })?
 2671            .await?;
 2672            Ok(())
 2673        })
 2674    }
 2675
 2676    #[allow(clippy::type_complexity)]
 2677    pub fn open_paths(
 2678        &mut self,
 2679        mut abs_paths: Vec<PathBuf>,
 2680        options: OpenOptions,
 2681        pane: Option<WeakEntity<Pane>>,
 2682        window: &mut Window,
 2683        cx: &mut Context<Self>,
 2684    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 2685        let fs = self.app_state.fs.clone();
 2686
 2687        // Sort the paths to ensure we add worktrees for parents before their children.
 2688        abs_paths.sort_unstable();
 2689        cx.spawn_in(window, async move |this, cx| {
 2690            let mut tasks = Vec::with_capacity(abs_paths.len());
 2691
 2692            for abs_path in &abs_paths {
 2693                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 2694                    OpenVisible::All => Some(true),
 2695                    OpenVisible::None => Some(false),
 2696                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 2697                        Some(Some(metadata)) => Some(!metadata.is_dir),
 2698                        Some(None) => Some(true),
 2699                        None => None,
 2700                    },
 2701                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 2702                        Some(Some(metadata)) => Some(metadata.is_dir),
 2703                        Some(None) => Some(false),
 2704                        None => None,
 2705                    },
 2706                };
 2707                let project_path = match visible {
 2708                    Some(visible) => match this
 2709                        .update(cx, |this, cx| {
 2710                            Workspace::project_path_for_path(
 2711                                this.project.clone(),
 2712                                abs_path,
 2713                                visible,
 2714                                cx,
 2715                            )
 2716                        })
 2717                        .log_err()
 2718                    {
 2719                        Some(project_path) => project_path.await.log_err(),
 2720                        None => None,
 2721                    },
 2722                    None => None,
 2723                };
 2724
 2725                let this = this.clone();
 2726                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 2727                let fs = fs.clone();
 2728                let pane = pane.clone();
 2729                let task = cx.spawn(async move |cx| {
 2730                    let (worktree, project_path) = project_path?;
 2731                    if fs.is_dir(&abs_path).await {
 2732                        this.update(cx, |workspace, cx| {
 2733                            let worktree = worktree.read(cx);
 2734                            let worktree_abs_path = worktree.abs_path();
 2735                            let entry_id = if abs_path.as_ref() == worktree_abs_path.as_ref() {
 2736                                worktree.root_entry()
 2737                            } else {
 2738                                abs_path
 2739                                    .strip_prefix(worktree_abs_path.as_ref())
 2740                                    .ok()
 2741                                    .and_then(|relative_path| {
 2742                                        let relative_path =
 2743                                            RelPath::new(relative_path, PathStyle::local())
 2744                                                .log_err()?;
 2745                                        worktree.entry_for_path(&relative_path)
 2746                                    })
 2747                            }
 2748                            .map(|entry| entry.id);
 2749                            if let Some(entry_id) = entry_id {
 2750                                workspace.project.update(cx, |_, cx| {
 2751                                    cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 2752                                })
 2753                            }
 2754                        })
 2755                        .ok()?;
 2756                        None
 2757                    } else {
 2758                        Some(
 2759                            this.update_in(cx, |this, window, cx| {
 2760                                this.open_path(
 2761                                    project_path,
 2762                                    pane,
 2763                                    options.focus.unwrap_or(true),
 2764                                    window,
 2765                                    cx,
 2766                                )
 2767                            })
 2768                            .ok()?
 2769                            .await,
 2770                        )
 2771                    }
 2772                });
 2773                tasks.push(task);
 2774            }
 2775
 2776            futures::future::join_all(tasks).await
 2777        })
 2778    }
 2779
 2780    pub fn open_resolved_path(
 2781        &mut self,
 2782        path: ResolvedPath,
 2783        window: &mut Window,
 2784        cx: &mut Context<Self>,
 2785    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 2786        match path {
 2787            ResolvedPath::ProjectPath { project_path, .. } => {
 2788                self.open_path(project_path, None, true, window, cx)
 2789            }
 2790            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 2791                PathBuf::from(path),
 2792                OpenOptions {
 2793                    visible: Some(OpenVisible::None),
 2794                    ..Default::default()
 2795                },
 2796                window,
 2797                cx,
 2798            ),
 2799        }
 2800    }
 2801
 2802    pub fn absolute_path_of_worktree(
 2803        &self,
 2804        worktree_id: WorktreeId,
 2805        cx: &mut Context<Self>,
 2806    ) -> Option<PathBuf> {
 2807        self.project
 2808            .read(cx)
 2809            .worktree_for_id(worktree_id, cx)
 2810            // TODO: use `abs_path` or `root_dir`
 2811            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 2812    }
 2813
 2814    fn add_folder_to_project(
 2815        &mut self,
 2816        _: &AddFolderToProject,
 2817        window: &mut Window,
 2818        cx: &mut Context<Self>,
 2819    ) {
 2820        let project = self.project.read(cx);
 2821        if project.is_via_collab() {
 2822            self.show_error(
 2823                &anyhow!("You cannot add folders to someone else's project"),
 2824                cx,
 2825            );
 2826            return;
 2827        }
 2828        let paths = self.prompt_for_open_path(
 2829            PathPromptOptions {
 2830                files: false,
 2831                directories: true,
 2832                multiple: true,
 2833                prompt: None,
 2834            },
 2835            DirectoryLister::Project(self.project.clone()),
 2836            window,
 2837            cx,
 2838        );
 2839        cx.spawn_in(window, async move |this, cx| {
 2840            if let Some(paths) = paths.await.log_err().flatten() {
 2841                let results = this
 2842                    .update_in(cx, |this, window, cx| {
 2843                        this.open_paths(
 2844                            paths,
 2845                            OpenOptions {
 2846                                visible: Some(OpenVisible::All),
 2847                                ..Default::default()
 2848                            },
 2849                            None,
 2850                            window,
 2851                            cx,
 2852                        )
 2853                    })?
 2854                    .await;
 2855                for result in results.into_iter().flatten() {
 2856                    result.log_err();
 2857                }
 2858            }
 2859            anyhow::Ok(())
 2860        })
 2861        .detach_and_log_err(cx);
 2862    }
 2863
 2864    pub fn project_path_for_path(
 2865        project: Entity<Project>,
 2866        abs_path: &Path,
 2867        visible: bool,
 2868        cx: &mut App,
 2869    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 2870        let entry = project.update(cx, |project, cx| {
 2871            project.find_or_create_worktree(abs_path, visible, cx)
 2872        });
 2873        cx.spawn(async move |cx| {
 2874            let (worktree, path) = entry.await?;
 2875            let worktree_id = worktree.read_with(cx, |t, _| t.id())?;
 2876            Ok((
 2877                worktree,
 2878                ProjectPath {
 2879                    worktree_id,
 2880                    path: path,
 2881                },
 2882            ))
 2883        })
 2884    }
 2885
 2886    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 2887        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 2888    }
 2889
 2890    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 2891        self.items_of_type(cx).max_by_key(|item| item.item_id())
 2892    }
 2893
 2894    pub fn items_of_type<'a, T: Item>(
 2895        &'a self,
 2896        cx: &'a App,
 2897    ) -> impl 'a + Iterator<Item = Entity<T>> {
 2898        self.panes
 2899            .iter()
 2900            .flat_map(|pane| pane.read(cx).items_of_type())
 2901    }
 2902
 2903    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 2904        self.active_pane().read(cx).active_item()
 2905    }
 2906
 2907    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 2908        let item = self.active_item(cx)?;
 2909        item.to_any_view().downcast::<I>().ok()
 2910    }
 2911
 2912    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 2913        self.active_item(cx).and_then(|item| item.project_path(cx))
 2914    }
 2915
 2916    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 2917        self.recent_navigation_history_iter(cx)
 2918            .filter_map(|(path, abs_path)| {
 2919                let worktree = self
 2920                    .project
 2921                    .read(cx)
 2922                    .worktree_for_id(path.worktree_id, cx)?;
 2923                if worktree.read(cx).is_visible() {
 2924                    abs_path
 2925                } else {
 2926                    None
 2927                }
 2928            })
 2929            .next()
 2930    }
 2931
 2932    pub fn save_active_item(
 2933        &mut self,
 2934        save_intent: SaveIntent,
 2935        window: &mut Window,
 2936        cx: &mut App,
 2937    ) -> Task<Result<()>> {
 2938        let project = self.project.clone();
 2939        let pane = self.active_pane();
 2940        let item = pane.read(cx).active_item();
 2941        let pane = pane.downgrade();
 2942
 2943        window.spawn(cx, async move |cx| {
 2944            if let Some(item) = item {
 2945                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 2946                    .await
 2947                    .map(|_| ())
 2948            } else {
 2949                Ok(())
 2950            }
 2951        })
 2952    }
 2953
 2954    pub fn close_inactive_items_and_panes(
 2955        &mut self,
 2956        action: &CloseInactiveTabsAndPanes,
 2957        window: &mut Window,
 2958        cx: &mut Context<Self>,
 2959    ) {
 2960        if let Some(task) = self.close_all_internal(
 2961            true,
 2962            action.save_intent.unwrap_or(SaveIntent::Close),
 2963            window,
 2964            cx,
 2965        ) {
 2966            task.detach_and_log_err(cx)
 2967        }
 2968    }
 2969
 2970    pub fn close_all_items_and_panes(
 2971        &mut self,
 2972        action: &CloseAllItemsAndPanes,
 2973        window: &mut Window,
 2974        cx: &mut Context<Self>,
 2975    ) {
 2976        if let Some(task) = self.close_all_internal(
 2977            false,
 2978            action.save_intent.unwrap_or(SaveIntent::Close),
 2979            window,
 2980            cx,
 2981        ) {
 2982            task.detach_and_log_err(cx)
 2983        }
 2984    }
 2985
 2986    fn close_all_internal(
 2987        &mut self,
 2988        retain_active_pane: bool,
 2989        save_intent: SaveIntent,
 2990        window: &mut Window,
 2991        cx: &mut Context<Self>,
 2992    ) -> Option<Task<Result<()>>> {
 2993        let current_pane = self.active_pane();
 2994
 2995        let mut tasks = Vec::new();
 2996
 2997        if retain_active_pane {
 2998            let current_pane_close = current_pane.update(cx, |pane, cx| {
 2999                pane.close_other_items(
 3000                    &CloseOtherItems {
 3001                        save_intent: None,
 3002                        close_pinned: false,
 3003                    },
 3004                    None,
 3005                    window,
 3006                    cx,
 3007                )
 3008            });
 3009
 3010            tasks.push(current_pane_close);
 3011        }
 3012
 3013        for pane in self.panes() {
 3014            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 3015                continue;
 3016            }
 3017
 3018            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 3019                pane.close_all_items(
 3020                    &CloseAllItems {
 3021                        save_intent: Some(save_intent),
 3022                        close_pinned: false,
 3023                    },
 3024                    window,
 3025                    cx,
 3026                )
 3027            });
 3028
 3029            tasks.push(close_pane_items)
 3030        }
 3031
 3032        if tasks.is_empty() {
 3033            None
 3034        } else {
 3035            Some(cx.spawn_in(window, async move |_, _| {
 3036                for task in tasks {
 3037                    task.await?
 3038                }
 3039                Ok(())
 3040            }))
 3041        }
 3042    }
 3043
 3044    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 3045        self.dock_at_position(position).read(cx).is_open()
 3046    }
 3047
 3048    pub fn toggle_dock(
 3049        &mut self,
 3050        dock_side: DockPosition,
 3051        window: &mut Window,
 3052        cx: &mut Context<Self>,
 3053    ) {
 3054        let mut focus_center = false;
 3055        let mut reveal_dock = false;
 3056
 3057        let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 3058        let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
 3059        if was_visible {
 3060            self.save_open_dock_positions(cx);
 3061        }
 3062
 3063        let dock = self.dock_at_position(dock_side);
 3064        dock.update(cx, |dock, cx| {
 3065            dock.set_open(!was_visible, window, cx);
 3066
 3067            if dock.active_panel().is_none() {
 3068                let Some(panel_ix) = dock
 3069                    .first_enabled_panel_idx(cx)
 3070                    .log_with_level(log::Level::Info)
 3071                else {
 3072                    return;
 3073                };
 3074                dock.activate_panel(panel_ix, window, cx);
 3075            }
 3076
 3077            if let Some(active_panel) = dock.active_panel() {
 3078                if was_visible {
 3079                    if active_panel
 3080                        .panel_focus_handle(cx)
 3081                        .contains_focused(window, cx)
 3082                    {
 3083                        focus_center = true;
 3084                    }
 3085                } else {
 3086                    let focus_handle = &active_panel.panel_focus_handle(cx);
 3087                    window.focus(focus_handle);
 3088                    reveal_dock = true;
 3089                }
 3090            }
 3091        });
 3092
 3093        if reveal_dock {
 3094            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 3095        }
 3096
 3097        if focus_center {
 3098            self.active_pane
 3099                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
 3100        }
 3101
 3102        cx.notify();
 3103        self.serialize_workspace(window, cx);
 3104    }
 3105
 3106    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 3107        self.all_docks().into_iter().find(|&dock| {
 3108            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 3109        })
 3110    }
 3111
 3112    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 3113        if let Some(dock) = self.active_dock(window, cx).cloned() {
 3114            self.save_open_dock_positions(cx);
 3115            dock.update(cx, |dock, cx| {
 3116                dock.set_open(false, window, cx);
 3117            });
 3118            return true;
 3119        }
 3120        false
 3121    }
 3122
 3123    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3124        self.save_open_dock_positions(cx);
 3125        for dock in self.all_docks() {
 3126            dock.update(cx, |dock, cx| {
 3127                dock.set_open(false, window, cx);
 3128            });
 3129        }
 3130
 3131        cx.focus_self(window);
 3132        cx.notify();
 3133        self.serialize_workspace(window, cx);
 3134    }
 3135
 3136    fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
 3137        self.all_docks()
 3138            .into_iter()
 3139            .filter_map(|dock| {
 3140                let dock_ref = dock.read(cx);
 3141                if dock_ref.is_open() {
 3142                    Some(dock_ref.position())
 3143                } else {
 3144                    None
 3145                }
 3146            })
 3147            .collect()
 3148    }
 3149
 3150    /// Saves the positions of currently open docks.
 3151    ///
 3152    /// Updates `last_open_dock_positions` with positions of all currently open
 3153    /// docks, to later be restored by the 'Toggle All Docks' action.
 3154    fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
 3155        let open_dock_positions = self.get_open_dock_positions(cx);
 3156        if !open_dock_positions.is_empty() {
 3157            self.last_open_dock_positions = open_dock_positions;
 3158        }
 3159    }
 3160
 3161    /// Toggles all docks between open and closed states.
 3162    ///
 3163    /// If any docks are open, closes all and remembers their positions. If all
 3164    /// docks are closed, restores the last remembered dock configuration.
 3165    fn toggle_all_docks(
 3166        &mut self,
 3167        _: &ToggleAllDocks,
 3168        window: &mut Window,
 3169        cx: &mut Context<Self>,
 3170    ) {
 3171        let open_dock_positions = self.get_open_dock_positions(cx);
 3172
 3173        if !open_dock_positions.is_empty() {
 3174            self.close_all_docks(window, cx);
 3175        } else if !self.last_open_dock_positions.is_empty() {
 3176            self.restore_last_open_docks(window, cx);
 3177        }
 3178    }
 3179
 3180    /// Reopens docks from the most recently remembered configuration.
 3181    ///
 3182    /// Opens all docks whose positions are stored in `last_open_dock_positions`
 3183    /// and clears the stored positions.
 3184    fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3185        let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
 3186
 3187        for position in positions_to_open {
 3188            let dock = self.dock_at_position(position);
 3189            dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 3190        }
 3191
 3192        cx.focus_self(window);
 3193        cx.notify();
 3194        self.serialize_workspace(window, cx);
 3195    }
 3196
 3197    /// Transfer focus to the panel of the given type.
 3198    pub fn focus_panel<T: Panel>(
 3199        &mut self,
 3200        window: &mut Window,
 3201        cx: &mut Context<Self>,
 3202    ) -> Option<Entity<T>> {
 3203        let panel = self.focus_or_unfocus_panel::<T>(window, cx, |_, _, _| true)?;
 3204        panel.to_any().downcast().ok()
 3205    }
 3206
 3207    /// Focus the panel of the given type if it isn't already focused. If it is
 3208    /// already focused, then transfer focus back to the workspace center.
 3209    pub fn toggle_panel_focus<T: Panel>(
 3210        &mut self,
 3211        window: &mut Window,
 3212        cx: &mut Context<Self>,
 3213    ) -> bool {
 3214        let mut did_focus_panel = false;
 3215        self.focus_or_unfocus_panel::<T>(window, cx, |panel, window, cx| {
 3216            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 3217            did_focus_panel
 3218        });
 3219        did_focus_panel
 3220    }
 3221
 3222    pub fn activate_panel_for_proto_id(
 3223        &mut self,
 3224        panel_id: PanelId,
 3225        window: &mut Window,
 3226        cx: &mut Context<Self>,
 3227    ) -> Option<Arc<dyn PanelHandle>> {
 3228        let mut panel = None;
 3229        for dock in self.all_docks() {
 3230            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 3231                panel = dock.update(cx, |dock, cx| {
 3232                    dock.activate_panel(panel_index, window, cx);
 3233                    dock.set_open(true, window, cx);
 3234                    dock.active_panel().cloned()
 3235                });
 3236                break;
 3237            }
 3238        }
 3239
 3240        if panel.is_some() {
 3241            cx.notify();
 3242            self.serialize_workspace(window, cx);
 3243        }
 3244
 3245        panel
 3246    }
 3247
 3248    /// Focus or unfocus the given panel type, depending on the given callback.
 3249    fn focus_or_unfocus_panel<T: Panel>(
 3250        &mut self,
 3251        window: &mut Window,
 3252        cx: &mut Context<Self>,
 3253        mut should_focus: impl FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 3254    ) -> Option<Arc<dyn PanelHandle>> {
 3255        let mut result_panel = None;
 3256        let mut serialize = false;
 3257        for dock in self.all_docks() {
 3258            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3259                let mut focus_center = false;
 3260                let panel = dock.update(cx, |dock, cx| {
 3261                    dock.activate_panel(panel_index, window, cx);
 3262
 3263                    let panel = dock.active_panel().cloned();
 3264                    if let Some(panel) = panel.as_ref() {
 3265                        if should_focus(&**panel, window, cx) {
 3266                            dock.set_open(true, window, cx);
 3267                            panel.panel_focus_handle(cx).focus(window);
 3268                        } else {
 3269                            focus_center = true;
 3270                        }
 3271                    }
 3272                    panel
 3273                });
 3274
 3275                if focus_center {
 3276                    self.active_pane
 3277                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
 3278                }
 3279
 3280                result_panel = panel;
 3281                serialize = true;
 3282                break;
 3283            }
 3284        }
 3285
 3286        if serialize {
 3287            self.serialize_workspace(window, cx);
 3288        }
 3289
 3290        cx.notify();
 3291        result_panel
 3292    }
 3293
 3294    /// Open the panel of the given type
 3295    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3296        for dock in self.all_docks() {
 3297            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3298                dock.update(cx, |dock, cx| {
 3299                    dock.activate_panel(panel_index, window, cx);
 3300                    dock.set_open(true, window, cx);
 3301                });
 3302            }
 3303        }
 3304    }
 3305
 3306    pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
 3307        for dock in self.all_docks().iter() {
 3308            dock.update(cx, |dock, cx| {
 3309                if dock.panel::<T>().is_some() {
 3310                    dock.set_open(false, window, cx)
 3311                }
 3312            })
 3313        }
 3314    }
 3315
 3316    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 3317        self.all_docks()
 3318            .iter()
 3319            .find_map(|dock| dock.read(cx).panel::<T>())
 3320    }
 3321
 3322    fn dismiss_zoomed_items_to_reveal(
 3323        &mut self,
 3324        dock_to_reveal: Option<DockPosition>,
 3325        window: &mut Window,
 3326        cx: &mut Context<Self>,
 3327    ) {
 3328        // If a center pane is zoomed, unzoom it.
 3329        for pane in &self.panes {
 3330            if pane != &self.active_pane || dock_to_reveal.is_some() {
 3331                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 3332            }
 3333        }
 3334
 3335        // If another dock is zoomed, hide it.
 3336        let mut focus_center = false;
 3337        for dock in self.all_docks() {
 3338            dock.update(cx, |dock, cx| {
 3339                if Some(dock.position()) != dock_to_reveal
 3340                    && let Some(panel) = dock.active_panel()
 3341                    && panel.is_zoomed(window, cx)
 3342                {
 3343                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 3344                    dock.set_open(false, window, cx);
 3345                }
 3346            });
 3347        }
 3348
 3349        if focus_center {
 3350            self.active_pane
 3351                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
 3352        }
 3353
 3354        if self.zoomed_position != dock_to_reveal {
 3355            self.zoomed = None;
 3356            self.zoomed_position = None;
 3357            cx.emit(Event::ZoomChanged);
 3358        }
 3359
 3360        cx.notify();
 3361    }
 3362
 3363    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 3364        let pane = cx.new(|cx| {
 3365            let mut pane = Pane::new(
 3366                self.weak_handle(),
 3367                self.project.clone(),
 3368                self.pane_history_timestamp.clone(),
 3369                None,
 3370                NewFile.boxed_clone(),
 3371                true,
 3372                window,
 3373                cx,
 3374            );
 3375            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 3376            pane
 3377        });
 3378        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 3379            .detach();
 3380        self.panes.push(pane.clone());
 3381
 3382        window.focus(&pane.focus_handle(cx));
 3383
 3384        cx.emit(Event::PaneAdded(pane.clone()));
 3385        pane
 3386    }
 3387
 3388    pub fn add_item_to_center(
 3389        &mut self,
 3390        item: Box<dyn ItemHandle>,
 3391        window: &mut Window,
 3392        cx: &mut Context<Self>,
 3393    ) -> bool {
 3394        if let Some(center_pane) = self.last_active_center_pane.clone() {
 3395            if let Some(center_pane) = center_pane.upgrade() {
 3396                center_pane.update(cx, |pane, cx| {
 3397                    pane.add_item(item, true, true, None, window, cx)
 3398                });
 3399                true
 3400            } else {
 3401                false
 3402            }
 3403        } else {
 3404            false
 3405        }
 3406    }
 3407
 3408    pub fn add_item_to_active_pane(
 3409        &mut self,
 3410        item: Box<dyn ItemHandle>,
 3411        destination_index: Option<usize>,
 3412        focus_item: bool,
 3413        window: &mut Window,
 3414        cx: &mut App,
 3415    ) {
 3416        self.add_item(
 3417            self.active_pane.clone(),
 3418            item,
 3419            destination_index,
 3420            false,
 3421            focus_item,
 3422            window,
 3423            cx,
 3424        )
 3425    }
 3426
 3427    pub fn add_item(
 3428        &mut self,
 3429        pane: Entity<Pane>,
 3430        item: Box<dyn ItemHandle>,
 3431        destination_index: Option<usize>,
 3432        activate_pane: bool,
 3433        focus_item: bool,
 3434        window: &mut Window,
 3435        cx: &mut App,
 3436    ) {
 3437        pane.update(cx, |pane, cx| {
 3438            pane.add_item(
 3439                item,
 3440                activate_pane,
 3441                focus_item,
 3442                destination_index,
 3443                window,
 3444                cx,
 3445            )
 3446        });
 3447    }
 3448
 3449    pub fn split_item(
 3450        &mut self,
 3451        split_direction: SplitDirection,
 3452        item: Box<dyn ItemHandle>,
 3453        window: &mut Window,
 3454        cx: &mut Context<Self>,
 3455    ) {
 3456        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 3457        self.add_item(new_pane, item, None, true, true, window, cx);
 3458    }
 3459
 3460    pub fn open_abs_path(
 3461        &mut self,
 3462        abs_path: PathBuf,
 3463        options: OpenOptions,
 3464        window: &mut Window,
 3465        cx: &mut Context<Self>,
 3466    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3467        cx.spawn_in(window, async move |workspace, cx| {
 3468            let open_paths_task_result = workspace
 3469                .update_in(cx, |workspace, window, cx| {
 3470                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 3471                })
 3472                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 3473                .await;
 3474            anyhow::ensure!(
 3475                open_paths_task_result.len() == 1,
 3476                "open abs path {abs_path:?} task returned incorrect number of results"
 3477            );
 3478            match open_paths_task_result
 3479                .into_iter()
 3480                .next()
 3481                .expect("ensured single task result")
 3482            {
 3483                Some(open_result) => {
 3484                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 3485                }
 3486                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 3487            }
 3488        })
 3489    }
 3490
 3491    pub fn split_abs_path(
 3492        &mut self,
 3493        abs_path: PathBuf,
 3494        visible: bool,
 3495        window: &mut Window,
 3496        cx: &mut Context<Self>,
 3497    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3498        let project_path_task =
 3499            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 3500        cx.spawn_in(window, async move |this, cx| {
 3501            let (_, path) = project_path_task.await?;
 3502            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 3503                .await
 3504        })
 3505    }
 3506
 3507    pub fn open_path(
 3508        &mut self,
 3509        path: impl Into<ProjectPath>,
 3510        pane: Option<WeakEntity<Pane>>,
 3511        focus_item: bool,
 3512        window: &mut Window,
 3513        cx: &mut App,
 3514    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3515        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 3516    }
 3517
 3518    pub fn open_path_preview(
 3519        &mut self,
 3520        path: impl Into<ProjectPath>,
 3521        pane: Option<WeakEntity<Pane>>,
 3522        focus_item: bool,
 3523        allow_preview: bool,
 3524        activate: bool,
 3525        window: &mut Window,
 3526        cx: &mut App,
 3527    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3528        let pane = pane.unwrap_or_else(|| {
 3529            self.last_active_center_pane.clone().unwrap_or_else(|| {
 3530                self.panes
 3531                    .first()
 3532                    .expect("There must be an active pane")
 3533                    .downgrade()
 3534            })
 3535        });
 3536
 3537        let project_path = path.into();
 3538        let task = self.load_path(project_path.clone(), window, cx);
 3539        window.spawn(cx, async move |cx| {
 3540            let (project_entry_id, build_item) = task.await?;
 3541
 3542            pane.update_in(cx, |pane, window, cx| {
 3543                pane.open_item(
 3544                    project_entry_id,
 3545                    project_path,
 3546                    focus_item,
 3547                    allow_preview,
 3548                    activate,
 3549                    None,
 3550                    window,
 3551                    cx,
 3552                    build_item,
 3553                )
 3554            })
 3555        })
 3556    }
 3557
 3558    pub fn split_path(
 3559        &mut self,
 3560        path: impl Into<ProjectPath>,
 3561        window: &mut Window,
 3562        cx: &mut Context<Self>,
 3563    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3564        self.split_path_preview(path, false, None, window, cx)
 3565    }
 3566
 3567    pub fn split_path_preview(
 3568        &mut self,
 3569        path: impl Into<ProjectPath>,
 3570        allow_preview: bool,
 3571        split_direction: Option<SplitDirection>,
 3572        window: &mut Window,
 3573        cx: &mut Context<Self>,
 3574    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3575        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 3576            self.panes
 3577                .first()
 3578                .expect("There must be an active pane")
 3579                .downgrade()
 3580        });
 3581
 3582        if let Member::Pane(center_pane) = &self.center.root
 3583            && center_pane.read(cx).items_len() == 0
 3584        {
 3585            return self.open_path(path, Some(pane), true, window, cx);
 3586        }
 3587
 3588        let project_path = path.into();
 3589        let task = self.load_path(project_path.clone(), window, cx);
 3590        cx.spawn_in(window, async move |this, cx| {
 3591            let (project_entry_id, build_item) = task.await?;
 3592            this.update_in(cx, move |this, window, cx| -> Option<_> {
 3593                let pane = pane.upgrade()?;
 3594                let new_pane = this.split_pane(
 3595                    pane,
 3596                    split_direction.unwrap_or(SplitDirection::Right),
 3597                    window,
 3598                    cx,
 3599                );
 3600                new_pane.update(cx, |new_pane, cx| {
 3601                    Some(new_pane.open_item(
 3602                        project_entry_id,
 3603                        project_path,
 3604                        true,
 3605                        allow_preview,
 3606                        true,
 3607                        None,
 3608                        window,
 3609                        cx,
 3610                        build_item,
 3611                    ))
 3612                })
 3613            })
 3614            .map(|option| option.context("pane was dropped"))?
 3615        })
 3616    }
 3617
 3618    fn load_path(
 3619        &mut self,
 3620        path: ProjectPath,
 3621        window: &mut Window,
 3622        cx: &mut App,
 3623    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 3624        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 3625        registry.open_path(self.project(), &path, window, cx)
 3626    }
 3627
 3628    pub fn find_project_item<T>(
 3629        &self,
 3630        pane: &Entity<Pane>,
 3631        project_item: &Entity<T::Item>,
 3632        cx: &App,
 3633    ) -> Option<Entity<T>>
 3634    where
 3635        T: ProjectItem,
 3636    {
 3637        use project::ProjectItem as _;
 3638        let project_item = project_item.read(cx);
 3639        let entry_id = project_item.entry_id(cx);
 3640        let project_path = project_item.project_path(cx);
 3641
 3642        let mut item = None;
 3643        if let Some(entry_id) = entry_id {
 3644            item = pane.read(cx).item_for_entry(entry_id, cx);
 3645        }
 3646        if item.is_none()
 3647            && let Some(project_path) = project_path
 3648        {
 3649            item = pane.read(cx).item_for_path(project_path, cx);
 3650        }
 3651
 3652        item.and_then(|item| item.downcast::<T>())
 3653    }
 3654
 3655    pub fn is_project_item_open<T>(
 3656        &self,
 3657        pane: &Entity<Pane>,
 3658        project_item: &Entity<T::Item>,
 3659        cx: &App,
 3660    ) -> bool
 3661    where
 3662        T: ProjectItem,
 3663    {
 3664        self.find_project_item::<T>(pane, project_item, cx)
 3665            .is_some()
 3666    }
 3667
 3668    pub fn open_project_item<T>(
 3669        &mut self,
 3670        pane: Entity<Pane>,
 3671        project_item: Entity<T::Item>,
 3672        activate_pane: bool,
 3673        focus_item: bool,
 3674        keep_old_preview: bool,
 3675        allow_new_preview: bool,
 3676        window: &mut Window,
 3677        cx: &mut Context<Self>,
 3678    ) -> Entity<T>
 3679    where
 3680        T: ProjectItem,
 3681    {
 3682        let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
 3683
 3684        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 3685            if !keep_old_preview
 3686                && let Some(old_id) = old_item_id
 3687                && old_id != item.item_id()
 3688            {
 3689                // switching to a different item, so unpreview old active item
 3690                pane.update(cx, |pane, _| {
 3691                    pane.unpreview_item_if_preview(old_id);
 3692                });
 3693            }
 3694
 3695            self.activate_item(&item, activate_pane, focus_item, window, cx);
 3696            if !allow_new_preview {
 3697                pane.update(cx, |pane, _| {
 3698                    pane.unpreview_item_if_preview(item.item_id());
 3699                });
 3700            }
 3701            return item;
 3702        }
 3703
 3704        let item = pane.update(cx, |pane, cx| {
 3705            cx.new(|cx| {
 3706                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 3707            })
 3708        });
 3709        let mut destination_index = None;
 3710        pane.update(cx, |pane, cx| {
 3711            if !keep_old_preview && let Some(old_id) = old_item_id {
 3712                pane.unpreview_item_if_preview(old_id);
 3713            }
 3714            if allow_new_preview {
 3715                destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
 3716            }
 3717        });
 3718
 3719        self.add_item(
 3720            pane,
 3721            Box::new(item.clone()),
 3722            destination_index,
 3723            activate_pane,
 3724            focus_item,
 3725            window,
 3726            cx,
 3727        );
 3728        item
 3729    }
 3730
 3731    pub fn open_shared_screen(
 3732        &mut self,
 3733        peer_id: PeerId,
 3734        window: &mut Window,
 3735        cx: &mut Context<Self>,
 3736    ) {
 3737        if let Some(shared_screen) =
 3738            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 3739        {
 3740            self.active_pane.update(cx, |pane, cx| {
 3741                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 3742            });
 3743        }
 3744    }
 3745
 3746    pub fn activate_item(
 3747        &mut self,
 3748        item: &dyn ItemHandle,
 3749        activate_pane: bool,
 3750        focus_item: bool,
 3751        window: &mut Window,
 3752        cx: &mut App,
 3753    ) -> bool {
 3754        let result = self.panes.iter().find_map(|pane| {
 3755            pane.read(cx)
 3756                .index_for_item(item)
 3757                .map(|ix| (pane.clone(), ix))
 3758        });
 3759        if let Some((pane, ix)) = result {
 3760            pane.update(cx, |pane, cx| {
 3761                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 3762            });
 3763            true
 3764        } else {
 3765            false
 3766        }
 3767    }
 3768
 3769    fn activate_pane_at_index(
 3770        &mut self,
 3771        action: &ActivatePane,
 3772        window: &mut Window,
 3773        cx: &mut Context<Self>,
 3774    ) {
 3775        let panes = self.center.panes();
 3776        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 3777            window.focus(&pane.focus_handle(cx));
 3778        } else {
 3779            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
 3780                .detach();
 3781        }
 3782    }
 3783
 3784    fn move_item_to_pane_at_index(
 3785        &mut self,
 3786        action: &MoveItemToPane,
 3787        window: &mut Window,
 3788        cx: &mut Context<Self>,
 3789    ) {
 3790        let panes = self.center.panes();
 3791        let destination = match panes.get(action.destination) {
 3792            Some(&destination) => destination.clone(),
 3793            None => {
 3794                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 3795                    return;
 3796                }
 3797                let direction = SplitDirection::Right;
 3798                let split_off_pane = self
 3799                    .find_pane_in_direction(direction, cx)
 3800                    .unwrap_or_else(|| self.active_pane.clone());
 3801                let new_pane = self.add_pane(window, cx);
 3802                if self
 3803                    .center
 3804                    .split(&split_off_pane, &new_pane, direction, cx)
 3805                    .log_err()
 3806                    .is_none()
 3807                {
 3808                    return;
 3809                };
 3810                new_pane
 3811            }
 3812        };
 3813
 3814        if action.clone {
 3815            if self
 3816                .active_pane
 3817                .read(cx)
 3818                .active_item()
 3819                .is_some_and(|item| item.can_split(cx))
 3820            {
 3821                clone_active_item(
 3822                    self.database_id(),
 3823                    &self.active_pane,
 3824                    &destination,
 3825                    action.focus,
 3826                    window,
 3827                    cx,
 3828                );
 3829                return;
 3830            }
 3831        }
 3832        move_active_item(
 3833            &self.active_pane,
 3834            &destination,
 3835            action.focus,
 3836            true,
 3837            window,
 3838            cx,
 3839        )
 3840    }
 3841
 3842    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 3843        let panes = self.center.panes();
 3844        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 3845            let next_ix = (ix + 1) % panes.len();
 3846            let next_pane = panes[next_ix].clone();
 3847            window.focus(&next_pane.focus_handle(cx));
 3848        }
 3849    }
 3850
 3851    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 3852        let panes = self.center.panes();
 3853        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 3854            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 3855            let prev_pane = panes[prev_ix].clone();
 3856            window.focus(&prev_pane.focus_handle(cx));
 3857        }
 3858    }
 3859
 3860    pub fn activate_pane_in_direction(
 3861        &mut self,
 3862        direction: SplitDirection,
 3863        window: &mut Window,
 3864        cx: &mut App,
 3865    ) {
 3866        use ActivateInDirectionTarget as Target;
 3867        enum Origin {
 3868            LeftDock,
 3869            RightDock,
 3870            BottomDock,
 3871            Center,
 3872        }
 3873
 3874        let origin: Origin = [
 3875            (&self.left_dock, Origin::LeftDock),
 3876            (&self.right_dock, Origin::RightDock),
 3877            (&self.bottom_dock, Origin::BottomDock),
 3878        ]
 3879        .into_iter()
 3880        .find_map(|(dock, origin)| {
 3881            if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 3882                Some(origin)
 3883            } else {
 3884                None
 3885            }
 3886        })
 3887        .unwrap_or(Origin::Center);
 3888
 3889        let get_last_active_pane = || {
 3890            let pane = self
 3891                .last_active_center_pane
 3892                .clone()
 3893                .unwrap_or_else(|| {
 3894                    self.panes
 3895                        .first()
 3896                        .expect("There must be an active pane")
 3897                        .downgrade()
 3898                })
 3899                .upgrade()?;
 3900            (pane.read(cx).items_len() != 0).then_some(pane)
 3901        };
 3902
 3903        let try_dock =
 3904            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 3905
 3906        let target = match (origin, direction) {
 3907            // We're in the center, so we first try to go to a different pane,
 3908            // otherwise try to go to a dock.
 3909            (Origin::Center, direction) => {
 3910                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 3911                    Some(Target::Pane(pane))
 3912                } else {
 3913                    match direction {
 3914                        SplitDirection::Up => None,
 3915                        SplitDirection::Down => try_dock(&self.bottom_dock),
 3916                        SplitDirection::Left => try_dock(&self.left_dock),
 3917                        SplitDirection::Right => try_dock(&self.right_dock),
 3918                    }
 3919                }
 3920            }
 3921
 3922            (Origin::LeftDock, SplitDirection::Right) => {
 3923                if let Some(last_active_pane) = get_last_active_pane() {
 3924                    Some(Target::Pane(last_active_pane))
 3925                } else {
 3926                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 3927                }
 3928            }
 3929
 3930            (Origin::LeftDock, SplitDirection::Down)
 3931            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 3932
 3933            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 3934            (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
 3935            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 3936
 3937            (Origin::RightDock, SplitDirection::Left) => {
 3938                if let Some(last_active_pane) = get_last_active_pane() {
 3939                    Some(Target::Pane(last_active_pane))
 3940                } else {
 3941                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 3942                }
 3943            }
 3944
 3945            _ => None,
 3946        };
 3947
 3948        match target {
 3949            Some(ActivateInDirectionTarget::Pane(pane)) => {
 3950                let pane = pane.read(cx);
 3951                if let Some(item) = pane.active_item() {
 3952                    item.item_focus_handle(cx).focus(window);
 3953                } else {
 3954                    log::error!(
 3955                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 3956                    );
 3957                }
 3958            }
 3959            Some(ActivateInDirectionTarget::Dock(dock)) => {
 3960                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 3961                window.defer(cx, move |window, cx| {
 3962                    let dock = dock.read(cx);
 3963                    if let Some(panel) = dock.active_panel() {
 3964                        panel.panel_focus_handle(cx).focus(window);
 3965                    } else {
 3966                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 3967                    }
 3968                })
 3969            }
 3970            None => {}
 3971        }
 3972    }
 3973
 3974    pub fn move_item_to_pane_in_direction(
 3975        &mut self,
 3976        action: &MoveItemToPaneInDirection,
 3977        window: &mut Window,
 3978        cx: &mut Context<Self>,
 3979    ) {
 3980        let destination = match self.find_pane_in_direction(action.direction, cx) {
 3981            Some(destination) => destination,
 3982            None => {
 3983                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 3984                    return;
 3985                }
 3986                let new_pane = self.add_pane(window, cx);
 3987                if self
 3988                    .center
 3989                    .split(&self.active_pane, &new_pane, action.direction, cx)
 3990                    .log_err()
 3991                    .is_none()
 3992                {
 3993                    return;
 3994                };
 3995                new_pane
 3996            }
 3997        };
 3998
 3999        if action.clone {
 4000            if self
 4001                .active_pane
 4002                .read(cx)
 4003                .active_item()
 4004                .is_some_and(|item| item.can_split(cx))
 4005            {
 4006                clone_active_item(
 4007                    self.database_id(),
 4008                    &self.active_pane,
 4009                    &destination,
 4010                    action.focus,
 4011                    window,
 4012                    cx,
 4013                );
 4014                return;
 4015            }
 4016        }
 4017        move_active_item(
 4018            &self.active_pane,
 4019            &destination,
 4020            action.focus,
 4021            true,
 4022            window,
 4023            cx,
 4024        );
 4025    }
 4026
 4027    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 4028        self.center.bounding_box_for_pane(pane)
 4029    }
 4030
 4031    pub fn find_pane_in_direction(
 4032        &mut self,
 4033        direction: SplitDirection,
 4034        cx: &App,
 4035    ) -> Option<Entity<Pane>> {
 4036        self.center
 4037            .find_pane_in_direction(&self.active_pane, direction, cx)
 4038            .cloned()
 4039    }
 4040
 4041    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4042        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 4043            self.center.swap(&self.active_pane, &to, cx);
 4044            cx.notify();
 4045        }
 4046    }
 4047
 4048    pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 4049        if self
 4050            .center
 4051            .move_to_border(&self.active_pane, direction, cx)
 4052            .unwrap()
 4053        {
 4054            cx.notify();
 4055        }
 4056    }
 4057
 4058    pub fn resize_pane(
 4059        &mut self,
 4060        axis: gpui::Axis,
 4061        amount: Pixels,
 4062        window: &mut Window,
 4063        cx: &mut Context<Self>,
 4064    ) {
 4065        let docks = self.all_docks();
 4066        let active_dock = docks
 4067            .into_iter()
 4068            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 4069
 4070        if let Some(dock) = active_dock {
 4071            let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
 4072                return;
 4073            };
 4074            match dock.read(cx).position() {
 4075                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 4076                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 4077                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 4078            }
 4079        } else {
 4080            self.center
 4081                .resize(&self.active_pane, axis, amount, &self.bounds, cx);
 4082        }
 4083        cx.notify();
 4084    }
 4085
 4086    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 4087        self.center.reset_pane_sizes(cx);
 4088        cx.notify();
 4089    }
 4090
 4091    fn handle_pane_focused(
 4092        &mut self,
 4093        pane: Entity<Pane>,
 4094        window: &mut Window,
 4095        cx: &mut Context<Self>,
 4096    ) {
 4097        // This is explicitly hoisted out of the following check for pane identity as
 4098        // terminal panel panes are not registered as a center panes.
 4099        self.status_bar.update(cx, |status_bar, cx| {
 4100            status_bar.set_active_pane(&pane, window, cx);
 4101        });
 4102        if self.active_pane != pane {
 4103            self.set_active_pane(&pane, window, cx);
 4104        }
 4105
 4106        if self.last_active_center_pane.is_none() {
 4107            self.last_active_center_pane = Some(pane.downgrade());
 4108        }
 4109
 4110        self.dismiss_zoomed_items_to_reveal(None, window, cx);
 4111        if pane.read(cx).is_zoomed() {
 4112            self.zoomed = Some(pane.downgrade().into());
 4113        } else {
 4114            self.zoomed = None;
 4115        }
 4116        self.zoomed_position = None;
 4117        cx.emit(Event::ZoomChanged);
 4118        self.update_active_view_for_followers(window, cx);
 4119        pane.update(cx, |pane, _| {
 4120            pane.track_alternate_file_items();
 4121        });
 4122
 4123        cx.notify();
 4124    }
 4125
 4126    fn set_active_pane(
 4127        &mut self,
 4128        pane: &Entity<Pane>,
 4129        window: &mut Window,
 4130        cx: &mut Context<Self>,
 4131    ) {
 4132        self.active_pane = pane.clone();
 4133        self.active_item_path_changed(window, cx);
 4134        self.last_active_center_pane = Some(pane.downgrade());
 4135    }
 4136
 4137    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4138        self.update_active_view_for_followers(window, cx);
 4139    }
 4140
 4141    fn handle_pane_event(
 4142        &mut self,
 4143        pane: &Entity<Pane>,
 4144        event: &pane::Event,
 4145        window: &mut Window,
 4146        cx: &mut Context<Self>,
 4147    ) {
 4148        let mut serialize_workspace = true;
 4149        match event {
 4150            pane::Event::AddItem { item } => {
 4151                item.added_to_pane(self, pane.clone(), window, cx);
 4152                cx.emit(Event::ItemAdded {
 4153                    item: item.boxed_clone(),
 4154                });
 4155            }
 4156            pane::Event::Split {
 4157                direction,
 4158                clone_active_item,
 4159            } => {
 4160                if *clone_active_item {
 4161                    self.split_and_clone(pane.clone(), *direction, window, cx)
 4162                        .detach();
 4163                } else {
 4164                    self.split_and_move(pane.clone(), *direction, window, cx);
 4165                }
 4166            }
 4167            pane::Event::JoinIntoNext => {
 4168                self.join_pane_into_next(pane.clone(), window, cx);
 4169            }
 4170            pane::Event::JoinAll => {
 4171                self.join_all_panes(window, cx);
 4172            }
 4173            pane::Event::Remove { focus_on_pane } => {
 4174                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 4175            }
 4176            pane::Event::ActivateItem {
 4177                local,
 4178                focus_changed,
 4179            } => {
 4180                window.invalidate_character_coordinates();
 4181
 4182                pane.update(cx, |pane, _| {
 4183                    pane.track_alternate_file_items();
 4184                });
 4185                if *local {
 4186                    self.unfollow_in_pane(pane, window, cx);
 4187                }
 4188                serialize_workspace = *focus_changed || pane != self.active_pane();
 4189                if pane == self.active_pane() {
 4190                    self.active_item_path_changed(window, cx);
 4191                    self.update_active_view_for_followers(window, cx);
 4192                } else if *local {
 4193                    self.set_active_pane(pane, window, cx);
 4194                }
 4195            }
 4196            pane::Event::UserSavedItem { item, save_intent } => {
 4197                cx.emit(Event::UserSavedItem {
 4198                    pane: pane.downgrade(),
 4199                    item: item.boxed_clone(),
 4200                    save_intent: *save_intent,
 4201                });
 4202                serialize_workspace = false;
 4203            }
 4204            pane::Event::ChangeItemTitle => {
 4205                if *pane == self.active_pane {
 4206                    self.active_item_path_changed(window, cx);
 4207                }
 4208                serialize_workspace = false;
 4209            }
 4210            pane::Event::RemovedItem { item } => {
 4211                cx.emit(Event::ActiveItemChanged);
 4212                self.update_window_edited(window, cx);
 4213                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 4214                    && entry.get().entity_id() == pane.entity_id()
 4215                {
 4216                    entry.remove();
 4217                }
 4218                cx.emit(Event::ItemRemoved {
 4219                    item_id: item.item_id(),
 4220                });
 4221            }
 4222            pane::Event::Focus => {
 4223                window.invalidate_character_coordinates();
 4224                self.handle_pane_focused(pane.clone(), window, cx);
 4225            }
 4226            pane::Event::ZoomIn => {
 4227                if *pane == self.active_pane {
 4228                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 4229                    if pane.read(cx).has_focus(window, cx) {
 4230                        self.zoomed = Some(pane.downgrade().into());
 4231                        self.zoomed_position = None;
 4232                        cx.emit(Event::ZoomChanged);
 4233                    }
 4234                    cx.notify();
 4235                }
 4236            }
 4237            pane::Event::ZoomOut => {
 4238                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 4239                if self.zoomed_position.is_none() {
 4240                    self.zoomed = None;
 4241                    cx.emit(Event::ZoomChanged);
 4242                }
 4243                cx.notify();
 4244            }
 4245            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 4246        }
 4247
 4248        if serialize_workspace {
 4249            self.serialize_workspace(window, cx);
 4250        }
 4251    }
 4252
 4253    pub fn unfollow_in_pane(
 4254        &mut self,
 4255        pane: &Entity<Pane>,
 4256        window: &mut Window,
 4257        cx: &mut Context<Workspace>,
 4258    ) -> Option<CollaboratorId> {
 4259        let leader_id = self.leader_for_pane(pane)?;
 4260        self.unfollow(leader_id, window, cx);
 4261        Some(leader_id)
 4262    }
 4263
 4264    pub fn split_pane(
 4265        &mut self,
 4266        pane_to_split: Entity<Pane>,
 4267        split_direction: SplitDirection,
 4268        window: &mut Window,
 4269        cx: &mut Context<Self>,
 4270    ) -> Entity<Pane> {
 4271        let new_pane = self.add_pane(window, cx);
 4272        self.center
 4273            .split(&pane_to_split, &new_pane, split_direction, cx)
 4274            .unwrap();
 4275        cx.notify();
 4276        new_pane
 4277    }
 4278
 4279    pub fn split_and_move(
 4280        &mut self,
 4281        pane: Entity<Pane>,
 4282        direction: SplitDirection,
 4283        window: &mut Window,
 4284        cx: &mut Context<Self>,
 4285    ) {
 4286        let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
 4287            return;
 4288        };
 4289        let new_pane = self.add_pane(window, cx);
 4290        new_pane.update(cx, |pane, cx| {
 4291            pane.add_item(item, true, true, None, window, cx)
 4292        });
 4293        self.center.split(&pane, &new_pane, direction, cx).unwrap();
 4294        cx.notify();
 4295    }
 4296
 4297    pub fn split_and_clone(
 4298        &mut self,
 4299        pane: Entity<Pane>,
 4300        direction: SplitDirection,
 4301        window: &mut Window,
 4302        cx: &mut Context<Self>,
 4303    ) -> Task<Option<Entity<Pane>>> {
 4304        let Some(item) = pane.read(cx).active_item() else {
 4305            return Task::ready(None);
 4306        };
 4307        if !item.can_split(cx) {
 4308            return Task::ready(None);
 4309        }
 4310        let task = item.clone_on_split(self.database_id(), window, cx);
 4311        cx.spawn_in(window, async move |this, cx| {
 4312            if let Some(clone) = task.await {
 4313                this.update_in(cx, |this, window, cx| {
 4314                    let new_pane = this.add_pane(window, cx);
 4315                    new_pane.update(cx, |pane, cx| {
 4316                        pane.add_item(clone, true, true, None, window, cx)
 4317                    });
 4318                    this.center.split(&pane, &new_pane, direction, cx).unwrap();
 4319                    cx.notify();
 4320                    new_pane
 4321                })
 4322                .ok()
 4323            } else {
 4324                None
 4325            }
 4326        })
 4327    }
 4328
 4329    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4330        let active_item = self.active_pane.read(cx).active_item();
 4331        for pane in &self.panes {
 4332            join_pane_into_active(&self.active_pane, pane, window, cx);
 4333        }
 4334        if let Some(active_item) = active_item {
 4335            self.activate_item(active_item.as_ref(), true, true, window, cx);
 4336        }
 4337        cx.notify();
 4338    }
 4339
 4340    pub fn join_pane_into_next(
 4341        &mut self,
 4342        pane: Entity<Pane>,
 4343        window: &mut Window,
 4344        cx: &mut Context<Self>,
 4345    ) {
 4346        let next_pane = self
 4347            .find_pane_in_direction(SplitDirection::Right, cx)
 4348            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 4349            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 4350            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 4351        let Some(next_pane) = next_pane else {
 4352            return;
 4353        };
 4354        move_all_items(&pane, &next_pane, window, cx);
 4355        cx.notify();
 4356    }
 4357
 4358    fn remove_pane(
 4359        &mut self,
 4360        pane: Entity<Pane>,
 4361        focus_on: Option<Entity<Pane>>,
 4362        window: &mut Window,
 4363        cx: &mut Context<Self>,
 4364    ) {
 4365        if self.center.remove(&pane, cx).unwrap() {
 4366            self.force_remove_pane(&pane, &focus_on, window, cx);
 4367            self.unfollow_in_pane(&pane, window, cx);
 4368            self.last_leaders_by_pane.remove(&pane.downgrade());
 4369            for removed_item in pane.read(cx).items() {
 4370                self.panes_by_item.remove(&removed_item.item_id());
 4371            }
 4372
 4373            cx.notify();
 4374        } else {
 4375            self.active_item_path_changed(window, cx);
 4376        }
 4377        cx.emit(Event::PaneRemoved);
 4378    }
 4379
 4380    pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
 4381        &mut self.panes
 4382    }
 4383
 4384    pub fn panes(&self) -> &[Entity<Pane>] {
 4385        &self.panes
 4386    }
 4387
 4388    pub fn active_pane(&self) -> &Entity<Pane> {
 4389        &self.active_pane
 4390    }
 4391
 4392    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 4393        for dock in self.all_docks() {
 4394            if dock.focus_handle(cx).contains_focused(window, cx)
 4395                && let Some(pane) = dock
 4396                    .read(cx)
 4397                    .active_panel()
 4398                    .and_then(|panel| panel.pane(cx))
 4399            {
 4400                return pane;
 4401            }
 4402        }
 4403        self.active_pane().clone()
 4404    }
 4405
 4406    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4407        self.find_pane_in_direction(SplitDirection::Right, cx)
 4408            .unwrap_or_else(|| {
 4409                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4410            })
 4411    }
 4412
 4413    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 4414        let weak_pane = self.panes_by_item.get(&handle.item_id())?;
 4415        weak_pane.upgrade()
 4416    }
 4417
 4418    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 4419        self.follower_states.retain(|leader_id, state| {
 4420            if *leader_id == CollaboratorId::PeerId(peer_id) {
 4421                for item in state.items_by_leader_view_id.values() {
 4422                    item.view.set_leader_id(None, window, cx);
 4423                }
 4424                false
 4425            } else {
 4426                true
 4427            }
 4428        });
 4429        cx.notify();
 4430    }
 4431
 4432    pub fn start_following(
 4433        &mut self,
 4434        leader_id: impl Into<CollaboratorId>,
 4435        window: &mut Window,
 4436        cx: &mut Context<Self>,
 4437    ) -> Option<Task<Result<()>>> {
 4438        let leader_id = leader_id.into();
 4439        let pane = self.active_pane().clone();
 4440
 4441        self.last_leaders_by_pane
 4442            .insert(pane.downgrade(), leader_id);
 4443        self.unfollow(leader_id, window, cx);
 4444        self.unfollow_in_pane(&pane, window, cx);
 4445        self.follower_states.insert(
 4446            leader_id,
 4447            FollowerState {
 4448                center_pane: pane.clone(),
 4449                dock_pane: None,
 4450                active_view_id: None,
 4451                items_by_leader_view_id: Default::default(),
 4452            },
 4453        );
 4454        cx.notify();
 4455
 4456        match leader_id {
 4457            CollaboratorId::PeerId(leader_peer_id) => {
 4458                let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
 4459                let project_id = self.project.read(cx).remote_id();
 4460                let request = self.app_state.client.request(proto::Follow {
 4461                    room_id,
 4462                    project_id,
 4463                    leader_id: Some(leader_peer_id),
 4464                });
 4465
 4466                Some(cx.spawn_in(window, async move |this, cx| {
 4467                    let response = request.await?;
 4468                    this.update(cx, |this, _| {
 4469                        let state = this
 4470                            .follower_states
 4471                            .get_mut(&leader_id)
 4472                            .context("following interrupted")?;
 4473                        state.active_view_id = response
 4474                            .active_view
 4475                            .as_ref()
 4476                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 4477                        anyhow::Ok(())
 4478                    })??;
 4479                    if let Some(view) = response.active_view {
 4480                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 4481                    }
 4482                    this.update_in(cx, |this, window, cx| {
 4483                        this.leader_updated(leader_id, window, cx)
 4484                    })?;
 4485                    Ok(())
 4486                }))
 4487            }
 4488            CollaboratorId::Agent => {
 4489                self.leader_updated(leader_id, window, cx)?;
 4490                Some(Task::ready(Ok(())))
 4491            }
 4492        }
 4493    }
 4494
 4495    pub fn follow_next_collaborator(
 4496        &mut self,
 4497        _: &FollowNextCollaborator,
 4498        window: &mut Window,
 4499        cx: &mut Context<Self>,
 4500    ) {
 4501        let collaborators = self.project.read(cx).collaborators();
 4502        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 4503            let mut collaborators = collaborators.keys().copied();
 4504            for peer_id in collaborators.by_ref() {
 4505                if CollaboratorId::PeerId(peer_id) == leader_id {
 4506                    break;
 4507                }
 4508            }
 4509            collaborators.next().map(CollaboratorId::PeerId)
 4510        } else if let Some(last_leader_id) =
 4511            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 4512        {
 4513            match last_leader_id {
 4514                CollaboratorId::PeerId(peer_id) => {
 4515                    if collaborators.contains_key(peer_id) {
 4516                        Some(*last_leader_id)
 4517                    } else {
 4518                        None
 4519                    }
 4520                }
 4521                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 4522            }
 4523        } else {
 4524            None
 4525        };
 4526
 4527        let pane = self.active_pane.clone();
 4528        let Some(leader_id) = next_leader_id.or_else(|| {
 4529            Some(CollaboratorId::PeerId(
 4530                collaborators.keys().copied().next()?,
 4531            ))
 4532        }) else {
 4533            return;
 4534        };
 4535        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 4536            return;
 4537        }
 4538        if let Some(task) = self.start_following(leader_id, window, cx) {
 4539            task.detach_and_log_err(cx)
 4540        }
 4541    }
 4542
 4543    pub fn follow(
 4544        &mut self,
 4545        leader_id: impl Into<CollaboratorId>,
 4546        window: &mut Window,
 4547        cx: &mut Context<Self>,
 4548    ) {
 4549        let leader_id = leader_id.into();
 4550
 4551        if let CollaboratorId::PeerId(peer_id) = leader_id {
 4552            let Some(room) = ActiveCall::global(cx).read(cx).room() else {
 4553                return;
 4554            };
 4555            let room = room.read(cx);
 4556            let Some(remote_participant) = room.remote_participant_for_peer_id(peer_id) else {
 4557                return;
 4558            };
 4559
 4560            let project = self.project.read(cx);
 4561
 4562            let other_project_id = match remote_participant.location {
 4563                call::ParticipantLocation::External => None,
 4564                call::ParticipantLocation::UnsharedProject => None,
 4565                call::ParticipantLocation::SharedProject { project_id } => {
 4566                    if Some(project_id) == project.remote_id() {
 4567                        None
 4568                    } else {
 4569                        Some(project_id)
 4570                    }
 4571                }
 4572            };
 4573
 4574            // if they are active in another project, follow there.
 4575            if let Some(project_id) = other_project_id {
 4576                let app_state = self.app_state.clone();
 4577                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 4578                    .detach_and_log_err(cx);
 4579            }
 4580        }
 4581
 4582        // if you're already following, find the right pane and focus it.
 4583        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 4584            window.focus(&follower_state.pane().focus_handle(cx));
 4585
 4586            return;
 4587        }
 4588
 4589        // Otherwise, follow.
 4590        if let Some(task) = self.start_following(leader_id, window, cx) {
 4591            task.detach_and_log_err(cx)
 4592        }
 4593    }
 4594
 4595    pub fn unfollow(
 4596        &mut self,
 4597        leader_id: impl Into<CollaboratorId>,
 4598        window: &mut Window,
 4599        cx: &mut Context<Self>,
 4600    ) -> Option<()> {
 4601        cx.notify();
 4602
 4603        let leader_id = leader_id.into();
 4604        let state = self.follower_states.remove(&leader_id)?;
 4605        for (_, item) in state.items_by_leader_view_id {
 4606            item.view.set_leader_id(None, window, cx);
 4607        }
 4608
 4609        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 4610            let project_id = self.project.read(cx).remote_id();
 4611            let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
 4612            self.app_state
 4613                .client
 4614                .send(proto::Unfollow {
 4615                    room_id,
 4616                    project_id,
 4617                    leader_id: Some(leader_peer_id),
 4618                })
 4619                .log_err();
 4620        }
 4621
 4622        Some(())
 4623    }
 4624
 4625    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 4626        self.follower_states.contains_key(&id.into())
 4627    }
 4628
 4629    fn active_item_path_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4630        cx.emit(Event::ActiveItemChanged);
 4631        let active_entry = self.active_project_path(cx);
 4632        self.project.update(cx, |project, cx| {
 4633            project.set_active_path(active_entry.clone(), cx)
 4634        });
 4635
 4636        if let Some(project_path) = &active_entry {
 4637            let git_store_entity = self.project.read(cx).git_store().clone();
 4638            git_store_entity.update(cx, |git_store, cx| {
 4639                git_store.set_active_repo_for_path(project_path, cx);
 4640            });
 4641        }
 4642
 4643        self.update_window_title(window, cx);
 4644    }
 4645
 4646    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 4647        let project = self.project().read(cx);
 4648        let mut title = String::new();
 4649
 4650        for (i, worktree) in project.visible_worktrees(cx).enumerate() {
 4651            let name = {
 4652                let settings_location = SettingsLocation {
 4653                    worktree_id: worktree.read(cx).id(),
 4654                    path: RelPath::empty(),
 4655                };
 4656
 4657                let settings = WorktreeSettings::get(Some(settings_location), cx);
 4658                match &settings.project_name {
 4659                    Some(name) => name.as_str(),
 4660                    None => worktree.read(cx).root_name_str(),
 4661                }
 4662            };
 4663            if i > 0 {
 4664                title.push_str(", ");
 4665            }
 4666            title.push_str(name);
 4667        }
 4668
 4669        if title.is_empty() {
 4670            title = "empty project".to_string();
 4671        }
 4672
 4673        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 4674            let filename = path.path.file_name().or_else(|| {
 4675                Some(
 4676                    project
 4677                        .worktree_for_id(path.worktree_id, cx)?
 4678                        .read(cx)
 4679                        .root_name_str(),
 4680                )
 4681            });
 4682
 4683            if let Some(filename) = filename {
 4684                title.push_str("");
 4685                title.push_str(filename.as_ref());
 4686            }
 4687        }
 4688
 4689        if project.is_via_collab() {
 4690            title.push_str("");
 4691        } else if project.is_shared() {
 4692            title.push_str("");
 4693        }
 4694
 4695        if let Some(last_title) = self.last_window_title.as_ref()
 4696            && &title == last_title
 4697        {
 4698            return;
 4699        }
 4700        window.set_window_title(&title);
 4701        SystemWindowTabController::update_tab_title(
 4702            cx,
 4703            window.window_handle().window_id(),
 4704            SharedString::from(&title),
 4705        );
 4706        self.last_window_title = Some(title);
 4707    }
 4708
 4709    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 4710        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 4711        if is_edited != self.window_edited {
 4712            self.window_edited = is_edited;
 4713            window.set_window_edited(self.window_edited)
 4714        }
 4715    }
 4716
 4717    fn update_item_dirty_state(
 4718        &mut self,
 4719        item: &dyn ItemHandle,
 4720        window: &mut Window,
 4721        cx: &mut App,
 4722    ) {
 4723        let is_dirty = item.is_dirty(cx);
 4724        let item_id = item.item_id();
 4725        let was_dirty = self.dirty_items.contains_key(&item_id);
 4726        if is_dirty == was_dirty {
 4727            return;
 4728        }
 4729        if was_dirty {
 4730            self.dirty_items.remove(&item_id);
 4731            self.update_window_edited(window, cx);
 4732            return;
 4733        }
 4734        if let Some(window_handle) = window.window_handle().downcast::<Self>() {
 4735            let s = item.on_release(
 4736                cx,
 4737                Box::new(move |cx| {
 4738                    window_handle
 4739                        .update(cx, |this, window, cx| {
 4740                            this.dirty_items.remove(&item_id);
 4741                            this.update_window_edited(window, cx)
 4742                        })
 4743                        .ok();
 4744                }),
 4745            );
 4746            self.dirty_items.insert(item_id, s);
 4747            self.update_window_edited(window, cx);
 4748        }
 4749    }
 4750
 4751    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 4752        if self.notifications.is_empty() {
 4753            None
 4754        } else {
 4755            Some(
 4756                div()
 4757                    .absolute()
 4758                    .right_3()
 4759                    .bottom_3()
 4760                    .w_112()
 4761                    .h_full()
 4762                    .flex()
 4763                    .flex_col()
 4764                    .justify_end()
 4765                    .gap_2()
 4766                    .children(
 4767                        self.notifications
 4768                            .iter()
 4769                            .map(|(_, notification)| notification.clone().into_any()),
 4770                    ),
 4771            )
 4772        }
 4773    }
 4774
 4775    // RPC handlers
 4776
 4777    fn active_view_for_follower(
 4778        &self,
 4779        follower_project_id: Option<u64>,
 4780        window: &mut Window,
 4781        cx: &mut Context<Self>,
 4782    ) -> Option<proto::View> {
 4783        let (item, panel_id) = self.active_item_for_followers(window, cx);
 4784        let item = item?;
 4785        let leader_id = self
 4786            .pane_for(&*item)
 4787            .and_then(|pane| self.leader_for_pane(&pane));
 4788        let leader_peer_id = match leader_id {
 4789            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 4790            Some(CollaboratorId::Agent) | None => None,
 4791        };
 4792
 4793        let item_handle = item.to_followable_item_handle(cx)?;
 4794        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 4795        let variant = item_handle.to_state_proto(window, cx)?;
 4796
 4797        if item_handle.is_project_item(window, cx)
 4798            && (follower_project_id.is_none()
 4799                || follower_project_id != self.project.read(cx).remote_id())
 4800        {
 4801            return None;
 4802        }
 4803
 4804        Some(proto::View {
 4805            id: id.to_proto(),
 4806            leader_id: leader_peer_id,
 4807            variant: Some(variant),
 4808            panel_id: panel_id.map(|id| id as i32),
 4809        })
 4810    }
 4811
 4812    fn handle_follow(
 4813        &mut self,
 4814        follower_project_id: Option<u64>,
 4815        window: &mut Window,
 4816        cx: &mut Context<Self>,
 4817    ) -> proto::FollowResponse {
 4818        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 4819
 4820        cx.notify();
 4821        proto::FollowResponse {
 4822            // TODO: Remove after version 0.145.x stabilizes.
 4823            active_view_id: active_view.as_ref().and_then(|view| view.id.clone()),
 4824            views: active_view.iter().cloned().collect(),
 4825            active_view,
 4826        }
 4827    }
 4828
 4829    fn handle_update_followers(
 4830        &mut self,
 4831        leader_id: PeerId,
 4832        message: proto::UpdateFollowers,
 4833        _window: &mut Window,
 4834        _cx: &mut Context<Self>,
 4835    ) {
 4836        self.leader_updates_tx
 4837            .unbounded_send((leader_id, message))
 4838            .ok();
 4839    }
 4840
 4841    async fn process_leader_update(
 4842        this: &WeakEntity<Self>,
 4843        leader_id: PeerId,
 4844        update: proto::UpdateFollowers,
 4845        cx: &mut AsyncWindowContext,
 4846    ) -> Result<()> {
 4847        match update.variant.context("invalid update")? {
 4848            proto::update_followers::Variant::CreateView(view) => {
 4849                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 4850                let should_add_view = this.update(cx, |this, _| {
 4851                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 4852                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 4853                    } else {
 4854                        anyhow::Ok(false)
 4855                    }
 4856                })??;
 4857
 4858                if should_add_view {
 4859                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 4860                }
 4861            }
 4862            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 4863                let should_add_view = this.update(cx, |this, _| {
 4864                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 4865                        state.active_view_id = update_active_view
 4866                            .view
 4867                            .as_ref()
 4868                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 4869
 4870                        if state.active_view_id.is_some_and(|view_id| {
 4871                            !state.items_by_leader_view_id.contains_key(&view_id)
 4872                        }) {
 4873                            anyhow::Ok(true)
 4874                        } else {
 4875                            anyhow::Ok(false)
 4876                        }
 4877                    } else {
 4878                        anyhow::Ok(false)
 4879                    }
 4880                })??;
 4881
 4882                if should_add_view && let Some(view) = update_active_view.view {
 4883                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 4884                }
 4885            }
 4886            proto::update_followers::Variant::UpdateView(update_view) => {
 4887                let variant = update_view.variant.context("missing update view variant")?;
 4888                let id = update_view.id.context("missing update view id")?;
 4889                let mut tasks = Vec::new();
 4890                this.update_in(cx, |this, window, cx| {
 4891                    let project = this.project.clone();
 4892                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 4893                        let view_id = ViewId::from_proto(id.clone())?;
 4894                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 4895                            tasks.push(item.view.apply_update_proto(
 4896                                &project,
 4897                                variant.clone(),
 4898                                window,
 4899                                cx,
 4900                            ));
 4901                        }
 4902                    }
 4903                    anyhow::Ok(())
 4904                })??;
 4905                try_join_all(tasks).await.log_err();
 4906            }
 4907        }
 4908        this.update_in(cx, |this, window, cx| {
 4909            this.leader_updated(leader_id, window, cx)
 4910        })?;
 4911        Ok(())
 4912    }
 4913
 4914    async fn add_view_from_leader(
 4915        this: WeakEntity<Self>,
 4916        leader_id: PeerId,
 4917        view: &proto::View,
 4918        cx: &mut AsyncWindowContext,
 4919    ) -> Result<()> {
 4920        let this = this.upgrade().context("workspace dropped")?;
 4921
 4922        let Some(id) = view.id.clone() else {
 4923            anyhow::bail!("no id for view");
 4924        };
 4925        let id = ViewId::from_proto(id)?;
 4926        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 4927
 4928        let pane = this.update(cx, |this, _cx| {
 4929            let state = this
 4930                .follower_states
 4931                .get(&leader_id.into())
 4932                .context("stopped following")?;
 4933            anyhow::Ok(state.pane().clone())
 4934        })??;
 4935        let existing_item = pane.update_in(cx, |pane, window, cx| {
 4936            let client = this.read(cx).client().clone();
 4937            pane.items().find_map(|item| {
 4938                let item = item.to_followable_item_handle(cx)?;
 4939                if item.remote_id(&client, window, cx) == Some(id) {
 4940                    Some(item)
 4941                } else {
 4942                    None
 4943                }
 4944            })
 4945        })?;
 4946        let item = if let Some(existing_item) = existing_item {
 4947            existing_item
 4948        } else {
 4949            let variant = view.variant.clone();
 4950            anyhow::ensure!(variant.is_some(), "missing view variant");
 4951
 4952            let task = cx.update(|window, cx| {
 4953                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 4954            })?;
 4955
 4956            let Some(task) = task else {
 4957                anyhow::bail!(
 4958                    "failed to construct view from leader (maybe from a different version of zed?)"
 4959                );
 4960            };
 4961
 4962            let mut new_item = task.await?;
 4963            pane.update_in(cx, |pane, window, cx| {
 4964                let mut item_to_remove = None;
 4965                for (ix, item) in pane.items().enumerate() {
 4966                    if let Some(item) = item.to_followable_item_handle(cx) {
 4967                        match new_item.dedup(item.as_ref(), window, cx) {
 4968                            Some(item::Dedup::KeepExisting) => {
 4969                                new_item =
 4970                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 4971                                break;
 4972                            }
 4973                            Some(item::Dedup::ReplaceExisting) => {
 4974                                item_to_remove = Some((ix, item.item_id()));
 4975                                break;
 4976                            }
 4977                            None => {}
 4978                        }
 4979                    }
 4980                }
 4981
 4982                if let Some((ix, id)) = item_to_remove {
 4983                    pane.remove_item(id, false, false, window, cx);
 4984                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 4985                }
 4986            })?;
 4987
 4988            new_item
 4989        };
 4990
 4991        this.update_in(cx, |this, window, cx| {
 4992            let state = this.follower_states.get_mut(&leader_id.into())?;
 4993            item.set_leader_id(Some(leader_id.into()), window, cx);
 4994            state.items_by_leader_view_id.insert(
 4995                id,
 4996                FollowerView {
 4997                    view: item,
 4998                    location: panel_id,
 4999                },
 5000            );
 5001
 5002            Some(())
 5003        })?;
 5004
 5005        Ok(())
 5006    }
 5007
 5008    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5009        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 5010            return;
 5011        };
 5012
 5013        if let Some(agent_location) = self.project.read(cx).agent_location() {
 5014            let buffer_entity_id = agent_location.buffer.entity_id();
 5015            let view_id = ViewId {
 5016                creator: CollaboratorId::Agent,
 5017                id: buffer_entity_id.as_u64(),
 5018            };
 5019            follower_state.active_view_id = Some(view_id);
 5020
 5021            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 5022                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 5023                hash_map::Entry::Vacant(entry) => {
 5024                    let existing_view =
 5025                        follower_state
 5026                            .center_pane
 5027                            .read(cx)
 5028                            .items()
 5029                            .find_map(|item| {
 5030                                let item = item.to_followable_item_handle(cx)?;
 5031                                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 5032                                    && item.project_item_model_ids(cx).as_slice()
 5033                                        == [buffer_entity_id]
 5034                                {
 5035                                    Some(item)
 5036                                } else {
 5037                                    None
 5038                                }
 5039                            });
 5040                    let view = existing_view.or_else(|| {
 5041                        agent_location.buffer.upgrade().and_then(|buffer| {
 5042                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 5043                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 5044                            })?
 5045                            .to_followable_item_handle(cx)
 5046                        })
 5047                    });
 5048
 5049                    view.map(|view| {
 5050                        entry.insert(FollowerView {
 5051                            view,
 5052                            location: None,
 5053                        })
 5054                    })
 5055                }
 5056            };
 5057
 5058            if let Some(item) = item {
 5059                item.view
 5060                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 5061                item.view
 5062                    .update_agent_location(agent_location.position, window, cx);
 5063            }
 5064        } else {
 5065            follower_state.active_view_id = None;
 5066        }
 5067
 5068        self.leader_updated(CollaboratorId::Agent, window, cx);
 5069    }
 5070
 5071    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 5072        let mut is_project_item = true;
 5073        let mut update = proto::UpdateActiveView::default();
 5074        if window.is_window_active() {
 5075            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 5076
 5077            if let Some(item) = active_item
 5078                && item.item_focus_handle(cx).contains_focused(window, cx)
 5079            {
 5080                let leader_id = self
 5081                    .pane_for(&*item)
 5082                    .and_then(|pane| self.leader_for_pane(&pane));
 5083                let leader_peer_id = match leader_id {
 5084                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 5085                    Some(CollaboratorId::Agent) | None => None,
 5086                };
 5087
 5088                if let Some(item) = item.to_followable_item_handle(cx) {
 5089                    let id = item
 5090                        .remote_id(&self.app_state.client, window, cx)
 5091                        .map(|id| id.to_proto());
 5092
 5093                    if let Some(id) = id
 5094                        && let Some(variant) = item.to_state_proto(window, cx)
 5095                    {
 5096                        let view = Some(proto::View {
 5097                            id: id.clone(),
 5098                            leader_id: leader_peer_id,
 5099                            variant: Some(variant),
 5100                            panel_id: panel_id.map(|id| id as i32),
 5101                        });
 5102
 5103                        is_project_item = item.is_project_item(window, cx);
 5104                        update = proto::UpdateActiveView {
 5105                            view,
 5106                            // TODO: Remove after version 0.145.x stabilizes.
 5107                            id,
 5108                            leader_id: leader_peer_id,
 5109                        };
 5110                    };
 5111                }
 5112            }
 5113        }
 5114
 5115        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 5116        if active_view_id != self.last_active_view_id.as_ref() {
 5117            self.last_active_view_id = active_view_id.cloned();
 5118            self.update_followers(
 5119                is_project_item,
 5120                proto::update_followers::Variant::UpdateActiveView(update),
 5121                window,
 5122                cx,
 5123            );
 5124        }
 5125    }
 5126
 5127    fn active_item_for_followers(
 5128        &self,
 5129        window: &mut Window,
 5130        cx: &mut App,
 5131    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 5132        let mut active_item = None;
 5133        let mut panel_id = None;
 5134        for dock in self.all_docks() {
 5135            if dock.focus_handle(cx).contains_focused(window, cx)
 5136                && let Some(panel) = dock.read(cx).active_panel()
 5137                && let Some(pane) = panel.pane(cx)
 5138                && let Some(item) = pane.read(cx).active_item()
 5139            {
 5140                active_item = Some(item);
 5141                panel_id = panel.remote_id();
 5142                break;
 5143            }
 5144        }
 5145
 5146        if active_item.is_none() {
 5147            active_item = self.active_pane().read(cx).active_item();
 5148        }
 5149        (active_item, panel_id)
 5150    }
 5151
 5152    fn update_followers(
 5153        &self,
 5154        project_only: bool,
 5155        update: proto::update_followers::Variant,
 5156        _: &mut Window,
 5157        cx: &mut App,
 5158    ) -> Option<()> {
 5159        // If this update only applies to for followers in the current project,
 5160        // then skip it unless this project is shared. If it applies to all
 5161        // followers, regardless of project, then set `project_id` to none,
 5162        // indicating that it goes to all followers.
 5163        let project_id = if project_only {
 5164            Some(self.project.read(cx).remote_id()?)
 5165        } else {
 5166            None
 5167        };
 5168        self.app_state().workspace_store.update(cx, |store, cx| {
 5169            store.update_followers(project_id, update, cx)
 5170        })
 5171    }
 5172
 5173    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 5174        self.follower_states.iter().find_map(|(leader_id, state)| {
 5175            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 5176                Some(*leader_id)
 5177            } else {
 5178                None
 5179            }
 5180        })
 5181    }
 5182
 5183    fn leader_updated(
 5184        &mut self,
 5185        leader_id: impl Into<CollaboratorId>,
 5186        window: &mut Window,
 5187        cx: &mut Context<Self>,
 5188    ) -> Option<Box<dyn ItemHandle>> {
 5189        cx.notify();
 5190
 5191        let leader_id = leader_id.into();
 5192        let (panel_id, item) = match leader_id {
 5193            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 5194            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 5195        };
 5196
 5197        let state = self.follower_states.get(&leader_id)?;
 5198        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 5199        let pane;
 5200        if let Some(panel_id) = panel_id {
 5201            pane = self
 5202                .activate_panel_for_proto_id(panel_id, window, cx)?
 5203                .pane(cx)?;
 5204            let state = self.follower_states.get_mut(&leader_id)?;
 5205            state.dock_pane = Some(pane.clone());
 5206        } else {
 5207            pane = state.center_pane.clone();
 5208            let state = self.follower_states.get_mut(&leader_id)?;
 5209            if let Some(dock_pane) = state.dock_pane.take() {
 5210                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 5211            }
 5212        }
 5213
 5214        pane.update(cx, |pane, cx| {
 5215            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 5216            if let Some(index) = pane.index_for_item(item.as_ref()) {
 5217                pane.activate_item(index, false, false, window, cx);
 5218            } else {
 5219                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 5220            }
 5221
 5222            if focus_active_item {
 5223                pane.focus_active_item(window, cx)
 5224            }
 5225        });
 5226
 5227        Some(item)
 5228    }
 5229
 5230    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 5231        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 5232        let active_view_id = state.active_view_id?;
 5233        Some(
 5234            state
 5235                .items_by_leader_view_id
 5236                .get(&active_view_id)?
 5237                .view
 5238                .boxed_clone(),
 5239        )
 5240    }
 5241
 5242    fn active_item_for_peer(
 5243        &self,
 5244        peer_id: PeerId,
 5245        window: &mut Window,
 5246        cx: &mut Context<Self>,
 5247    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 5248        let call = self.active_call()?;
 5249        let room = call.read(cx).room()?.read(cx);
 5250        let participant = room.remote_participant_for_peer_id(peer_id)?;
 5251        let leader_in_this_app;
 5252        let leader_in_this_project;
 5253        match participant.location {
 5254            call::ParticipantLocation::SharedProject { project_id } => {
 5255                leader_in_this_app = true;
 5256                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 5257            }
 5258            call::ParticipantLocation::UnsharedProject => {
 5259                leader_in_this_app = true;
 5260                leader_in_this_project = false;
 5261            }
 5262            call::ParticipantLocation::External => {
 5263                leader_in_this_app = false;
 5264                leader_in_this_project = false;
 5265            }
 5266        };
 5267        let state = self.follower_states.get(&peer_id.into())?;
 5268        let mut item_to_activate = None;
 5269        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 5270            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 5271                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 5272            {
 5273                item_to_activate = Some((item.location, item.view.boxed_clone()));
 5274            }
 5275        } else if let Some(shared_screen) =
 5276            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 5277        {
 5278            item_to_activate = Some((None, Box::new(shared_screen)));
 5279        }
 5280        item_to_activate
 5281    }
 5282
 5283    fn shared_screen_for_peer(
 5284        &self,
 5285        peer_id: PeerId,
 5286        pane: &Entity<Pane>,
 5287        window: &mut Window,
 5288        cx: &mut App,
 5289    ) -> Option<Entity<SharedScreen>> {
 5290        let call = self.active_call()?;
 5291        let room = call.read(cx).room()?.clone();
 5292        let participant = room.read(cx).remote_participant_for_peer_id(peer_id)?;
 5293        let track = participant.video_tracks.values().next()?.clone();
 5294        let user = participant.user.clone();
 5295
 5296        for item in pane.read(cx).items_of_type::<SharedScreen>() {
 5297            if item.read(cx).peer_id == peer_id {
 5298                return Some(item);
 5299            }
 5300        }
 5301
 5302        Some(cx.new(|cx| SharedScreen::new(track, peer_id, user.clone(), room.clone(), window, cx)))
 5303    }
 5304
 5305    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5306        if window.is_window_active() {
 5307            self.update_active_view_for_followers(window, cx);
 5308
 5309            if let Some(database_id) = self.database_id {
 5310                cx.background_spawn(persistence::DB.update_timestamp(database_id))
 5311                    .detach();
 5312            }
 5313        } else {
 5314            for pane in &self.panes {
 5315                pane.update(cx, |pane, cx| {
 5316                    if let Some(item) = pane.active_item() {
 5317                        item.workspace_deactivated(window, cx);
 5318                    }
 5319                    for item in pane.items() {
 5320                        if matches!(
 5321                            item.workspace_settings(cx).autosave,
 5322                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 5323                        ) {
 5324                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 5325                                .detach_and_log_err(cx);
 5326                        }
 5327                    }
 5328                });
 5329            }
 5330        }
 5331    }
 5332
 5333    pub fn active_call(&self) -> Option<&Entity<ActiveCall>> {
 5334        self.active_call.as_ref().map(|(call, _)| call)
 5335    }
 5336
 5337    fn on_active_call_event(
 5338        &mut self,
 5339        _: &Entity<ActiveCall>,
 5340        event: &call::room::Event,
 5341        window: &mut Window,
 5342        cx: &mut Context<Self>,
 5343    ) {
 5344        match event {
 5345            call::room::Event::ParticipantLocationChanged { participant_id }
 5346            | call::room::Event::RemoteVideoTracksChanged { participant_id } => {
 5347                self.leader_updated(participant_id, window, cx);
 5348            }
 5349            _ => {}
 5350        }
 5351    }
 5352
 5353    pub fn database_id(&self) -> Option<WorkspaceId> {
 5354        self.database_id
 5355    }
 5356
 5357    pub fn session_id(&self) -> Option<String> {
 5358        self.session_id.clone()
 5359    }
 5360
 5361    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 5362        let project = self.project().read(cx);
 5363        project
 5364            .visible_worktrees(cx)
 5365            .map(|worktree| worktree.read(cx).abs_path())
 5366            .collect::<Vec<_>>()
 5367    }
 5368
 5369    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 5370        match member {
 5371            Member::Axis(PaneAxis { members, .. }) => {
 5372                for child in members.iter() {
 5373                    self.remove_panes(child.clone(), window, cx)
 5374                }
 5375            }
 5376            Member::Pane(pane) => {
 5377                self.force_remove_pane(&pane, &None, window, cx);
 5378            }
 5379        }
 5380    }
 5381
 5382    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 5383        self.session_id.take();
 5384        self.serialize_workspace_internal(window, cx)
 5385    }
 5386
 5387    fn force_remove_pane(
 5388        &mut self,
 5389        pane: &Entity<Pane>,
 5390        focus_on: &Option<Entity<Pane>>,
 5391        window: &mut Window,
 5392        cx: &mut Context<Workspace>,
 5393    ) {
 5394        self.panes.retain(|p| p != pane);
 5395        if let Some(focus_on) = focus_on {
 5396            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
 5397        } else if self.active_pane() == pane {
 5398            self.panes
 5399                .last()
 5400                .unwrap()
 5401                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
 5402        }
 5403        if self.last_active_center_pane == Some(pane.downgrade()) {
 5404            self.last_active_center_pane = None;
 5405        }
 5406        cx.notify();
 5407    }
 5408
 5409    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5410        if self._schedule_serialize_workspace.is_none() {
 5411            self._schedule_serialize_workspace =
 5412                Some(cx.spawn_in(window, async move |this, cx| {
 5413                    cx.background_executor()
 5414                        .timer(SERIALIZATION_THROTTLE_TIME)
 5415                        .await;
 5416                    this.update_in(cx, |this, window, cx| {
 5417                        this.serialize_workspace_internal(window, cx).detach();
 5418                        this._schedule_serialize_workspace.take();
 5419                    })
 5420                    .log_err();
 5421                }));
 5422        }
 5423    }
 5424
 5425    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 5426        let Some(database_id) = self.database_id() else {
 5427            return Task::ready(());
 5428        };
 5429
 5430        fn serialize_pane_handle(
 5431            pane_handle: &Entity<Pane>,
 5432            window: &mut Window,
 5433            cx: &mut App,
 5434        ) -> SerializedPane {
 5435            let (items, active, pinned_count) = {
 5436                let pane = pane_handle.read(cx);
 5437                let active_item_id = pane.active_item().map(|item| item.item_id());
 5438                (
 5439                    pane.items()
 5440                        .filter_map(|handle| {
 5441                            let handle = handle.to_serializable_item_handle(cx)?;
 5442
 5443                            Some(SerializedItem {
 5444                                kind: Arc::from(handle.serialized_item_kind()),
 5445                                item_id: handle.item_id().as_u64(),
 5446                                active: Some(handle.item_id()) == active_item_id,
 5447                                preview: pane.is_active_preview_item(handle.item_id()),
 5448                            })
 5449                        })
 5450                        .collect::<Vec<_>>(),
 5451                    pane.has_focus(window, cx),
 5452                    pane.pinned_count(),
 5453                )
 5454            };
 5455
 5456            SerializedPane::new(items, active, pinned_count)
 5457        }
 5458
 5459        fn build_serialized_pane_group(
 5460            pane_group: &Member,
 5461            window: &mut Window,
 5462            cx: &mut App,
 5463        ) -> SerializedPaneGroup {
 5464            match pane_group {
 5465                Member::Axis(PaneAxis {
 5466                    axis,
 5467                    members,
 5468                    flexes,
 5469                    bounding_boxes: _,
 5470                }) => SerializedPaneGroup::Group {
 5471                    axis: SerializedAxis(*axis),
 5472                    children: members
 5473                        .iter()
 5474                        .map(|member| build_serialized_pane_group(member, window, cx))
 5475                        .collect::<Vec<_>>(),
 5476                    flexes: Some(flexes.lock().clone()),
 5477                },
 5478                Member::Pane(pane_handle) => {
 5479                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 5480                }
 5481            }
 5482        }
 5483
 5484        fn build_serialized_docks(
 5485            this: &Workspace,
 5486            window: &mut Window,
 5487            cx: &mut App,
 5488        ) -> DockStructure {
 5489            let left_dock = this.left_dock.read(cx);
 5490            let left_visible = left_dock.is_open();
 5491            let left_active_panel = left_dock
 5492                .active_panel()
 5493                .map(|panel| panel.persistent_name().to_string());
 5494            let left_dock_zoom = left_dock
 5495                .active_panel()
 5496                .map(|panel| panel.is_zoomed(window, cx))
 5497                .unwrap_or(false);
 5498
 5499            let right_dock = this.right_dock.read(cx);
 5500            let right_visible = right_dock.is_open();
 5501            let right_active_panel = right_dock
 5502                .active_panel()
 5503                .map(|panel| panel.persistent_name().to_string());
 5504            let right_dock_zoom = right_dock
 5505                .active_panel()
 5506                .map(|panel| panel.is_zoomed(window, cx))
 5507                .unwrap_or(false);
 5508
 5509            let bottom_dock = this.bottom_dock.read(cx);
 5510            let bottom_visible = bottom_dock.is_open();
 5511            let bottom_active_panel = bottom_dock
 5512                .active_panel()
 5513                .map(|panel| panel.persistent_name().to_string());
 5514            let bottom_dock_zoom = bottom_dock
 5515                .active_panel()
 5516                .map(|panel| panel.is_zoomed(window, cx))
 5517                .unwrap_or(false);
 5518
 5519            DockStructure {
 5520                left: DockData {
 5521                    visible: left_visible,
 5522                    active_panel: left_active_panel,
 5523                    zoom: left_dock_zoom,
 5524                },
 5525                right: DockData {
 5526                    visible: right_visible,
 5527                    active_panel: right_active_panel,
 5528                    zoom: right_dock_zoom,
 5529                },
 5530                bottom: DockData {
 5531                    visible: bottom_visible,
 5532                    active_panel: bottom_active_panel,
 5533                    zoom: bottom_dock_zoom,
 5534                },
 5535            }
 5536        }
 5537
 5538        match self.serialize_workspace_location(cx) {
 5539            WorkspaceLocation::Location(location, paths) => {
 5540                let breakpoints = self.project.update(cx, |project, cx| {
 5541                    project
 5542                        .breakpoint_store()
 5543                        .read(cx)
 5544                        .all_source_breakpoints(cx)
 5545                });
 5546                let user_toolchains = self
 5547                    .project
 5548                    .read(cx)
 5549                    .user_toolchains(cx)
 5550                    .unwrap_or_default();
 5551
 5552                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 5553                let docks = build_serialized_docks(self, window, cx);
 5554                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 5555
 5556                let serialized_workspace = SerializedWorkspace {
 5557                    id: database_id,
 5558                    location,
 5559                    paths,
 5560                    center_group,
 5561                    window_bounds,
 5562                    display: Default::default(),
 5563                    docks,
 5564                    centered_layout: self.centered_layout,
 5565                    session_id: self.session_id.clone(),
 5566                    breakpoints,
 5567                    window_id: Some(window.window_handle().window_id().as_u64()),
 5568                    user_toolchains,
 5569                };
 5570
 5571                window.spawn(cx, async move |_| {
 5572                    persistence::DB.save_workspace(serialized_workspace).await;
 5573                })
 5574            }
 5575            WorkspaceLocation::DetachFromSession => window.spawn(cx, async move |_| {
 5576                persistence::DB
 5577                    .set_session_id(database_id, None)
 5578                    .await
 5579                    .log_err();
 5580            }),
 5581            WorkspaceLocation::None => Task::ready(()),
 5582        }
 5583    }
 5584
 5585    fn serialize_workspace_location(&self, cx: &App) -> WorkspaceLocation {
 5586        let paths = PathList::new(&self.root_paths(cx));
 5587        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 5588            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 5589        } else if self.project.read(cx).is_local() {
 5590            if !paths.is_empty() {
 5591                WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
 5592            } else {
 5593                WorkspaceLocation::DetachFromSession
 5594            }
 5595        } else {
 5596            WorkspaceLocation::None
 5597        }
 5598    }
 5599
 5600    fn update_history(&self, cx: &mut App) {
 5601        let Some(id) = self.database_id() else {
 5602            return;
 5603        };
 5604        if !self.project.read(cx).is_local() {
 5605            return;
 5606        }
 5607        if let Some(manager) = HistoryManager::global(cx) {
 5608            let paths = PathList::new(&self.root_paths(cx));
 5609            manager.update(cx, |this, cx| {
 5610                this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
 5611            });
 5612        }
 5613    }
 5614
 5615    async fn serialize_items(
 5616        this: &WeakEntity<Self>,
 5617        items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
 5618        cx: &mut AsyncWindowContext,
 5619    ) -> Result<()> {
 5620        const CHUNK_SIZE: usize = 200;
 5621
 5622        let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
 5623
 5624        while let Some(items_received) = serializable_items.next().await {
 5625            let unique_items =
 5626                items_received
 5627                    .into_iter()
 5628                    .fold(HashMap::default(), |mut acc, item| {
 5629                        acc.entry(item.item_id()).or_insert(item);
 5630                        acc
 5631                    });
 5632
 5633            // We use into_iter() here so that the references to the items are moved into
 5634            // the tasks and not kept alive while we're sleeping.
 5635            for (_, item) in unique_items.into_iter() {
 5636                if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
 5637                    item.serialize(workspace, false, window, cx)
 5638                }) {
 5639                    cx.background_spawn(async move { task.await.log_err() })
 5640                        .detach();
 5641                }
 5642            }
 5643
 5644            cx.background_executor()
 5645                .timer(SERIALIZATION_THROTTLE_TIME)
 5646                .await;
 5647        }
 5648
 5649        Ok(())
 5650    }
 5651
 5652    pub(crate) fn enqueue_item_serialization(
 5653        &mut self,
 5654        item: Box<dyn SerializableItemHandle>,
 5655    ) -> Result<()> {
 5656        self.serializable_items_tx
 5657            .unbounded_send(item)
 5658            .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
 5659    }
 5660
 5661    pub(crate) fn load_workspace(
 5662        serialized_workspace: SerializedWorkspace,
 5663        paths_to_open: Vec<Option<ProjectPath>>,
 5664        window: &mut Window,
 5665        cx: &mut Context<Workspace>,
 5666    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 5667        cx.spawn_in(window, async move |workspace, cx| {
 5668            let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
 5669
 5670            let mut center_group = None;
 5671            let mut center_items = None;
 5672
 5673            // Traverse the splits tree and add to things
 5674            if let Some((group, active_pane, items)) = serialized_workspace
 5675                .center_group
 5676                .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
 5677                .await
 5678            {
 5679                center_items = Some(items);
 5680                center_group = Some((group, active_pane))
 5681            }
 5682
 5683            let mut items_by_project_path = HashMap::default();
 5684            let mut item_ids_by_kind = HashMap::default();
 5685            let mut all_deserialized_items = Vec::default();
 5686            cx.update(|_, cx| {
 5687                for item in center_items.unwrap_or_default().into_iter().flatten() {
 5688                    if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
 5689                        item_ids_by_kind
 5690                            .entry(serializable_item_handle.serialized_item_kind())
 5691                            .or_insert(Vec::new())
 5692                            .push(item.item_id().as_u64() as ItemId);
 5693                    }
 5694
 5695                    if let Some(project_path) = item.project_path(cx) {
 5696                        items_by_project_path.insert(project_path, item.clone());
 5697                    }
 5698                    all_deserialized_items.push(item);
 5699                }
 5700            })?;
 5701
 5702            let opened_items = paths_to_open
 5703                .into_iter()
 5704                .map(|path_to_open| {
 5705                    path_to_open
 5706                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
 5707                })
 5708                .collect::<Vec<_>>();
 5709
 5710            // Remove old panes from workspace panes list
 5711            workspace.update_in(cx, |workspace, window, cx| {
 5712                if let Some((center_group, active_pane)) = center_group {
 5713                    workspace.remove_panes(workspace.center.root.clone(), window, cx);
 5714
 5715                    // Swap workspace center group
 5716                    workspace.center = PaneGroup::with_root(center_group);
 5717                    workspace.center.set_is_center(true);
 5718                    workspace.center.mark_positions(cx);
 5719
 5720                    if let Some(active_pane) = active_pane {
 5721                        workspace.set_active_pane(&active_pane, window, cx);
 5722                        cx.focus_self(window);
 5723                    } else {
 5724                        workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
 5725                    }
 5726                }
 5727
 5728                let docks = serialized_workspace.docks;
 5729
 5730                for (dock, serialized_dock) in [
 5731                    (&mut workspace.right_dock, docks.right),
 5732                    (&mut workspace.left_dock, docks.left),
 5733                    (&mut workspace.bottom_dock, docks.bottom),
 5734                ]
 5735                .iter_mut()
 5736                {
 5737                    dock.update(cx, |dock, cx| {
 5738                        dock.serialized_dock = Some(serialized_dock.clone());
 5739                        dock.restore_state(window, cx);
 5740                    });
 5741                }
 5742
 5743                cx.notify();
 5744            })?;
 5745
 5746            let _ = project
 5747                .update(cx, |project, cx| {
 5748                    project
 5749                        .breakpoint_store()
 5750                        .update(cx, |breakpoint_store, cx| {
 5751                            breakpoint_store
 5752                                .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
 5753                        })
 5754                })?
 5755                .await;
 5756
 5757            // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
 5758            // after loading the items, we might have different items and in order to avoid
 5759            // the database filling up, we delete items that haven't been loaded now.
 5760            //
 5761            // The items that have been loaded, have been saved after they've been added to the workspace.
 5762            let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
 5763                item_ids_by_kind
 5764                    .into_iter()
 5765                    .map(|(item_kind, loaded_items)| {
 5766                        SerializableItemRegistry::cleanup(
 5767                            item_kind,
 5768                            serialized_workspace.id,
 5769                            loaded_items,
 5770                            window,
 5771                            cx,
 5772                        )
 5773                        .log_err()
 5774                    })
 5775                    .collect::<Vec<_>>()
 5776            })?;
 5777
 5778            futures::future::join_all(clean_up_tasks).await;
 5779
 5780            workspace
 5781                .update_in(cx, |workspace, window, cx| {
 5782                    // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
 5783                    workspace.serialize_workspace_internal(window, cx).detach();
 5784
 5785                    // Ensure that we mark the window as edited if we did load dirty items
 5786                    workspace.update_window_edited(window, cx);
 5787                })
 5788                .ok();
 5789
 5790            Ok(opened_items)
 5791        })
 5792    }
 5793
 5794    fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
 5795        self.add_workspace_actions_listeners(div, window, cx)
 5796            .on_action(cx.listener(
 5797                |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
 5798                    for action in &action_sequence.0 {
 5799                        window.dispatch_action(action.boxed_clone(), cx);
 5800                    }
 5801                },
 5802            ))
 5803            .on_action(cx.listener(Self::close_inactive_items_and_panes))
 5804            .on_action(cx.listener(Self::close_all_items_and_panes))
 5805            .on_action(cx.listener(Self::save_all))
 5806            .on_action(cx.listener(Self::send_keystrokes))
 5807            .on_action(cx.listener(Self::add_folder_to_project))
 5808            .on_action(cx.listener(Self::follow_next_collaborator))
 5809            .on_action(cx.listener(Self::close_window))
 5810            .on_action(cx.listener(Self::activate_pane_at_index))
 5811            .on_action(cx.listener(Self::move_item_to_pane_at_index))
 5812            .on_action(cx.listener(Self::move_focused_panel_to_next_position))
 5813            .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
 5814            .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
 5815                let pane = workspace.active_pane().clone();
 5816                workspace.unfollow_in_pane(&pane, window, cx);
 5817            }))
 5818            .on_action(cx.listener(|workspace, action: &Save, window, cx| {
 5819                workspace
 5820                    .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
 5821                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 5822            }))
 5823            .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
 5824                workspace
 5825                    .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
 5826                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 5827            }))
 5828            .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
 5829                workspace
 5830                    .save_active_item(SaveIntent::SaveAs, window, cx)
 5831                    .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
 5832            }))
 5833            .on_action(
 5834                cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
 5835                    workspace.activate_previous_pane(window, cx)
 5836                }),
 5837            )
 5838            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 5839                workspace.activate_next_pane(window, cx)
 5840            }))
 5841            .on_action(
 5842                cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
 5843                    workspace.activate_next_window(cx)
 5844                }),
 5845            )
 5846            .on_action(
 5847                cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
 5848                    workspace.activate_previous_window(cx)
 5849                }),
 5850            )
 5851            .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
 5852                workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
 5853            }))
 5854            .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
 5855                workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
 5856            }))
 5857            .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
 5858                workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
 5859            }))
 5860            .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
 5861                workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
 5862            }))
 5863            .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
 5864                workspace.activate_next_pane(window, cx)
 5865            }))
 5866            .on_action(cx.listener(
 5867                |workspace, action: &MoveItemToPaneInDirection, window, cx| {
 5868                    workspace.move_item_to_pane_in_direction(action, window, cx)
 5869                },
 5870            ))
 5871            .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
 5872                workspace.swap_pane_in_direction(SplitDirection::Left, cx)
 5873            }))
 5874            .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
 5875                workspace.swap_pane_in_direction(SplitDirection::Right, cx)
 5876            }))
 5877            .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
 5878                workspace.swap_pane_in_direction(SplitDirection::Up, cx)
 5879            }))
 5880            .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
 5881                workspace.swap_pane_in_direction(SplitDirection::Down, cx)
 5882            }))
 5883            .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
 5884                const DIRECTION_PRIORITY: [SplitDirection; 4] = [
 5885                    SplitDirection::Down,
 5886                    SplitDirection::Up,
 5887                    SplitDirection::Right,
 5888                    SplitDirection::Left,
 5889                ];
 5890                for dir in DIRECTION_PRIORITY {
 5891                    if workspace.find_pane_in_direction(dir, cx).is_some() {
 5892                        workspace.swap_pane_in_direction(dir, cx);
 5893                        workspace.activate_pane_in_direction(dir.opposite(), window, cx);
 5894                        break;
 5895                    }
 5896                }
 5897            }))
 5898            .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
 5899                workspace.move_pane_to_border(SplitDirection::Left, cx)
 5900            }))
 5901            .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
 5902                workspace.move_pane_to_border(SplitDirection::Right, cx)
 5903            }))
 5904            .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
 5905                workspace.move_pane_to_border(SplitDirection::Up, cx)
 5906            }))
 5907            .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
 5908                workspace.move_pane_to_border(SplitDirection::Down, cx)
 5909            }))
 5910            .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
 5911                this.toggle_dock(DockPosition::Left, window, cx);
 5912            }))
 5913            .on_action(cx.listener(
 5914                |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
 5915                    workspace.toggle_dock(DockPosition::Right, window, cx);
 5916                },
 5917            ))
 5918            .on_action(cx.listener(
 5919                |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
 5920                    workspace.toggle_dock(DockPosition::Bottom, window, cx);
 5921                },
 5922            ))
 5923            .on_action(cx.listener(
 5924                |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
 5925                    if !workspace.close_active_dock(window, cx) {
 5926                        cx.propagate();
 5927                    }
 5928                },
 5929            ))
 5930            .on_action(
 5931                cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
 5932                    workspace.close_all_docks(window, cx);
 5933                }),
 5934            )
 5935            .on_action(cx.listener(Self::toggle_all_docks))
 5936            .on_action(cx.listener(
 5937                |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
 5938                    workspace.clear_all_notifications(cx);
 5939                },
 5940            ))
 5941            .on_action(cx.listener(
 5942                |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
 5943                    workspace.clear_navigation_history(window, cx);
 5944                },
 5945            ))
 5946            .on_action(cx.listener(
 5947                |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
 5948                    if let Some((notification_id, _)) = workspace.notifications.pop() {
 5949                        workspace.suppress_notification(&notification_id, cx);
 5950                    }
 5951                },
 5952            ))
 5953            .on_action(cx.listener(
 5954                |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
 5955                    workspace.reopen_closed_item(window, cx).detach();
 5956                },
 5957            ))
 5958            .on_action(cx.listener(
 5959                |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
 5960                    for dock in workspace.all_docks() {
 5961                        if dock.focus_handle(cx).contains_focused(window, cx) {
 5962                            let Some(panel) = dock.read(cx).active_panel() else {
 5963                                return;
 5964                            };
 5965
 5966                            // Set to `None`, then the size will fall back to the default.
 5967                            panel.clone().set_size(None, window, cx);
 5968
 5969                            return;
 5970                        }
 5971                    }
 5972                },
 5973            ))
 5974            .on_action(cx.listener(
 5975                |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
 5976                    for dock in workspace.all_docks() {
 5977                        if let Some(panel) = dock.read(cx).visible_panel() {
 5978                            // Set to `None`, then the size will fall back to the default.
 5979                            panel.clone().set_size(None, window, cx);
 5980                        }
 5981                    }
 5982                },
 5983            ))
 5984            .on_action(cx.listener(
 5985                |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
 5986                    adjust_active_dock_size_by_px(
 5987                        px_with_ui_font_fallback(act.px, cx),
 5988                        workspace,
 5989                        window,
 5990                        cx,
 5991                    );
 5992                },
 5993            ))
 5994            .on_action(cx.listener(
 5995                |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
 5996                    adjust_active_dock_size_by_px(
 5997                        px_with_ui_font_fallback(act.px, cx) * -1.,
 5998                        workspace,
 5999                        window,
 6000                        cx,
 6001                    );
 6002                },
 6003            ))
 6004            .on_action(cx.listener(
 6005                |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
 6006                    adjust_open_docks_size_by_px(
 6007                        px_with_ui_font_fallback(act.px, cx),
 6008                        workspace,
 6009                        window,
 6010                        cx,
 6011                    );
 6012                },
 6013            ))
 6014            .on_action(cx.listener(
 6015                |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
 6016                    adjust_open_docks_size_by_px(
 6017                        px_with_ui_font_fallback(act.px, cx) * -1.,
 6018                        workspace,
 6019                        window,
 6020                        cx,
 6021                    );
 6022                },
 6023            ))
 6024            .on_action(cx.listener(Workspace::toggle_centered_layout))
 6025            .on_action(cx.listener(
 6026                |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
 6027                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6028                        let dock = active_dock.read(cx);
 6029                        if let Some(active_panel) = dock.active_panel() {
 6030                            if active_panel.pane(cx).is_none() {
 6031                                let mut recent_pane: Option<Entity<Pane>> = None;
 6032                                let mut recent_timestamp = 0;
 6033                                for pane_handle in workspace.panes() {
 6034                                    let pane = pane_handle.read(cx);
 6035                                    for entry in pane.activation_history() {
 6036                                        if entry.timestamp > recent_timestamp {
 6037                                            recent_timestamp = entry.timestamp;
 6038                                            recent_pane = Some(pane_handle.clone());
 6039                                        }
 6040                                    }
 6041                                }
 6042
 6043                                if let Some(pane) = recent_pane {
 6044                                    pane.update(cx, |pane, cx| {
 6045                                        let current_index = pane.active_item_index();
 6046                                        let items_len = pane.items_len();
 6047                                        if items_len > 0 {
 6048                                            let next_index = if current_index + 1 < items_len {
 6049                                                current_index + 1
 6050                                            } else {
 6051                                                0
 6052                                            };
 6053                                            pane.activate_item(
 6054                                                next_index, false, false, window, cx,
 6055                                            );
 6056                                        }
 6057                                    });
 6058                                    return;
 6059                                }
 6060                            }
 6061                        }
 6062                    }
 6063                    cx.propagate();
 6064                },
 6065            ))
 6066            .on_action(cx.listener(
 6067                |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
 6068                    if let Some(active_dock) = workspace.active_dock(window, cx) {
 6069                        let dock = active_dock.read(cx);
 6070                        if let Some(active_panel) = dock.active_panel() {
 6071                            if active_panel.pane(cx).is_none() {
 6072                                let mut recent_pane: Option<Entity<Pane>> = None;
 6073                                let mut recent_timestamp = 0;
 6074                                for pane_handle in workspace.panes() {
 6075                                    let pane = pane_handle.read(cx);
 6076                                    for entry in pane.activation_history() {
 6077                                        if entry.timestamp > recent_timestamp {
 6078                                            recent_timestamp = entry.timestamp;
 6079                                            recent_pane = Some(pane_handle.clone());
 6080                                        }
 6081                                    }
 6082                                }
 6083
 6084                                if let Some(pane) = recent_pane {
 6085                                    pane.update(cx, |pane, cx| {
 6086                                        let current_index = pane.active_item_index();
 6087                                        let items_len = pane.items_len();
 6088                                        if items_len > 0 {
 6089                                            let prev_index = if current_index > 0 {
 6090                                                current_index - 1
 6091                                            } else {
 6092                                                items_len.saturating_sub(1)
 6093                                            };
 6094                                            pane.activate_item(
 6095                                                prev_index, false, false, window, cx,
 6096                                            );
 6097                                        }
 6098                                    });
 6099                                    return;
 6100                                }
 6101                            }
 6102                        }
 6103                    }
 6104                    cx.propagate();
 6105                },
 6106            ))
 6107            .on_action(cx.listener(Workspace::cancel))
 6108    }
 6109
 6110    #[cfg(any(test, feature = "test-support"))]
 6111    pub fn set_random_database_id(&mut self) {
 6112        self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
 6113    }
 6114
 6115    #[cfg(any(test, feature = "test-support"))]
 6116    pub fn test_new(project: Entity<Project>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 6117        use node_runtime::NodeRuntime;
 6118        use session::Session;
 6119
 6120        let client = project.read(cx).client();
 6121        let user_store = project.read(cx).user_store();
 6122        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 6123        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
 6124        window.activate_window();
 6125        let app_state = Arc::new(AppState {
 6126            languages: project.read(cx).languages().clone(),
 6127            workspace_store,
 6128            client,
 6129            user_store,
 6130            fs: project.read(cx).fs().clone(),
 6131            build_window_options: |_, _| Default::default(),
 6132            node_runtime: NodeRuntime::unavailable(),
 6133            session,
 6134        });
 6135        let workspace = Self::new(Default::default(), project, app_state, window, cx);
 6136        workspace
 6137            .active_pane
 6138            .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
 6139        workspace
 6140    }
 6141
 6142    pub fn register_action<A: Action>(
 6143        &mut self,
 6144        callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
 6145    ) -> &mut Self {
 6146        let callback = Arc::new(callback);
 6147
 6148        self.workspace_actions.push(Box::new(move |div, _, _, cx| {
 6149            let callback = callback.clone();
 6150            div.on_action(cx.listener(move |workspace, event, window, cx| {
 6151                (callback)(workspace, event, window, cx)
 6152            }))
 6153        }));
 6154        self
 6155    }
 6156    pub fn register_action_renderer(
 6157        &mut self,
 6158        callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
 6159    ) -> &mut Self {
 6160        self.workspace_actions.push(Box::new(callback));
 6161        self
 6162    }
 6163
 6164    fn add_workspace_actions_listeners(
 6165        &self,
 6166        mut div: Div,
 6167        window: &mut Window,
 6168        cx: &mut Context<Self>,
 6169    ) -> Div {
 6170        for action in self.workspace_actions.iter() {
 6171            div = (action)(div, self, window, cx)
 6172        }
 6173        div
 6174    }
 6175
 6176    pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
 6177        self.modal_layer.read(cx).has_active_modal()
 6178    }
 6179
 6180    pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
 6181        self.modal_layer.read(cx).active_modal()
 6182    }
 6183
 6184    pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
 6185    where
 6186        B: FnOnce(&mut Window, &mut Context<V>) -> V,
 6187    {
 6188        self.modal_layer.update(cx, |modal_layer, cx| {
 6189            modal_layer.toggle_modal(window, cx, build)
 6190        })
 6191    }
 6192
 6193    pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
 6194        self.modal_layer
 6195            .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
 6196    }
 6197
 6198    pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
 6199        self.toast_layer
 6200            .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
 6201    }
 6202
 6203    pub fn toggle_centered_layout(
 6204        &mut self,
 6205        _: &ToggleCenteredLayout,
 6206        _: &mut Window,
 6207        cx: &mut Context<Self>,
 6208    ) {
 6209        self.centered_layout = !self.centered_layout;
 6210        if let Some(database_id) = self.database_id() {
 6211            cx.background_spawn(DB.set_centered_layout(database_id, self.centered_layout))
 6212                .detach_and_log_err(cx);
 6213        }
 6214        cx.notify();
 6215    }
 6216
 6217    fn adjust_padding(padding: Option<f32>) -> f32 {
 6218        padding
 6219            .unwrap_or(CenteredPaddingSettings::default().0)
 6220            .clamp(
 6221                CenteredPaddingSettings::MIN_PADDING,
 6222                CenteredPaddingSettings::MAX_PADDING,
 6223            )
 6224    }
 6225
 6226    fn render_dock(
 6227        &self,
 6228        position: DockPosition,
 6229        dock: &Entity<Dock>,
 6230        window: &mut Window,
 6231        cx: &mut App,
 6232    ) -> Option<Div> {
 6233        if self.zoomed_position == Some(position) {
 6234            return None;
 6235        }
 6236
 6237        let leader_border = dock.read(cx).active_panel().and_then(|panel| {
 6238            let pane = panel.pane(cx)?;
 6239            let follower_states = &self.follower_states;
 6240            leader_border_for_pane(follower_states, &pane, window, cx)
 6241        });
 6242
 6243        Some(
 6244            div()
 6245                .flex()
 6246                .flex_none()
 6247                .overflow_hidden()
 6248                .child(dock.clone())
 6249                .children(leader_border),
 6250        )
 6251    }
 6252
 6253    pub fn for_window(window: &mut Window, _: &mut App) -> Option<Entity<Workspace>> {
 6254        window.root().flatten()
 6255    }
 6256
 6257    pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
 6258        self.zoomed.as_ref()
 6259    }
 6260
 6261    pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
 6262        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 6263            return;
 6264        };
 6265        let windows = cx.windows();
 6266        let next_window =
 6267            SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
 6268                || {
 6269                    windows
 6270                        .iter()
 6271                        .cycle()
 6272                        .skip_while(|window| window.window_id() != current_window_id)
 6273                        .nth(1)
 6274                },
 6275            );
 6276
 6277        if let Some(window) = next_window {
 6278            window
 6279                .update(cx, |_, window, _| window.activate_window())
 6280                .ok();
 6281        }
 6282    }
 6283
 6284    pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
 6285        let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
 6286            return;
 6287        };
 6288        let windows = cx.windows();
 6289        let prev_window =
 6290            SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
 6291                || {
 6292                    windows
 6293                        .iter()
 6294                        .rev()
 6295                        .cycle()
 6296                        .skip_while(|window| window.window_id() != current_window_id)
 6297                        .nth(1)
 6298                },
 6299            );
 6300
 6301        if let Some(window) = prev_window {
 6302            window
 6303                .update(cx, |_, window, _| window.activate_window())
 6304                .ok();
 6305        }
 6306    }
 6307
 6308    pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
 6309        if cx.stop_active_drag(window) {
 6310        } else if let Some((notification_id, _)) = self.notifications.pop() {
 6311            dismiss_app_notification(&notification_id, cx);
 6312        } else {
 6313            cx.propagate();
 6314        }
 6315    }
 6316
 6317    fn adjust_dock_size_by_px(
 6318        &mut self,
 6319        panel_size: Pixels,
 6320        dock_pos: DockPosition,
 6321        px: Pixels,
 6322        window: &mut Window,
 6323        cx: &mut Context<Self>,
 6324    ) {
 6325        match dock_pos {
 6326            DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
 6327            DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
 6328            DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
 6329        }
 6330    }
 6331
 6332    fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6333        let size = new_size.min(self.bounds.right() - RESIZE_HANDLE_SIZE);
 6334
 6335        self.left_dock.update(cx, |left_dock, cx| {
 6336            if WorkspaceSettings::get_global(cx)
 6337                .resize_all_panels_in_dock
 6338                .contains(&DockPosition::Left)
 6339            {
 6340                left_dock.resize_all_panels(Some(size), window, cx);
 6341            } else {
 6342                left_dock.resize_active_panel(Some(size), window, cx);
 6343            }
 6344        });
 6345        self.clamp_utility_pane_widths(window, cx);
 6346    }
 6347
 6348    fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6349        let mut size = new_size.max(self.bounds.left() - RESIZE_HANDLE_SIZE);
 6350        self.left_dock.read_with(cx, |left_dock, cx| {
 6351            let left_dock_size = left_dock
 6352                .active_panel_size(window, cx)
 6353                .unwrap_or(Pixels::ZERO);
 6354            if left_dock_size + size > self.bounds.right() {
 6355                size = self.bounds.right() - left_dock_size
 6356            }
 6357        });
 6358        self.right_dock.update(cx, |right_dock, cx| {
 6359            if WorkspaceSettings::get_global(cx)
 6360                .resize_all_panels_in_dock
 6361                .contains(&DockPosition::Right)
 6362            {
 6363                right_dock.resize_all_panels(Some(size), window, cx);
 6364            } else {
 6365                right_dock.resize_active_panel(Some(size), window, cx);
 6366            }
 6367        });
 6368        self.clamp_utility_pane_widths(window, cx);
 6369    }
 6370
 6371    fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
 6372        let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
 6373        self.bottom_dock.update(cx, |bottom_dock, cx| {
 6374            if WorkspaceSettings::get_global(cx)
 6375                .resize_all_panels_in_dock
 6376                .contains(&DockPosition::Bottom)
 6377            {
 6378                bottom_dock.resize_all_panels(Some(size), window, cx);
 6379            } else {
 6380                bottom_dock.resize_active_panel(Some(size), window, cx);
 6381            }
 6382        });
 6383        self.clamp_utility_pane_widths(window, cx);
 6384    }
 6385
 6386    fn max_utility_pane_width(&self, window: &Window, cx: &App) -> Pixels {
 6387        let left_dock_width = self
 6388            .left_dock
 6389            .read(cx)
 6390            .active_panel_size(window, cx)
 6391            .unwrap_or(px(0.0));
 6392        let right_dock_width = self
 6393            .right_dock
 6394            .read(cx)
 6395            .active_panel_size(window, cx)
 6396            .unwrap_or(px(0.0));
 6397        let center_pane_width = self.bounds.size.width - left_dock_width - right_dock_width;
 6398        center_pane_width - px(10.0)
 6399    }
 6400
 6401    fn clamp_utility_pane_widths(&mut self, window: &mut Window, cx: &mut App) {
 6402        let max_width = self.max_utility_pane_width(window, cx);
 6403
 6404        // Clamp left slot utility pane if it exists
 6405        if let Some(handle) = self.utility_pane(UtilityPaneSlot::Left) {
 6406            let current_width = handle.width(cx);
 6407            if current_width > max_width {
 6408                handle.set_width(Some(max_width.max(UTILITY_PANE_MIN_WIDTH)), cx);
 6409            }
 6410        }
 6411
 6412        // Clamp right slot utility pane if it exists
 6413        if let Some(handle) = self.utility_pane(UtilityPaneSlot::Right) {
 6414            let current_width = handle.width(cx);
 6415            if current_width > max_width {
 6416                handle.set_width(Some(max_width.max(UTILITY_PANE_MIN_WIDTH)), cx);
 6417            }
 6418        }
 6419    }
 6420
 6421    fn toggle_edit_predictions_all_files(
 6422        &mut self,
 6423        _: &ToggleEditPrediction,
 6424        _window: &mut Window,
 6425        cx: &mut Context<Self>,
 6426    ) {
 6427        let fs = self.project().read(cx).fs().clone();
 6428        let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
 6429        update_settings_file(fs, cx, move |file, _| {
 6430            file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
 6431        });
 6432    }
 6433}
 6434
 6435fn leader_border_for_pane(
 6436    follower_states: &HashMap<CollaboratorId, FollowerState>,
 6437    pane: &Entity<Pane>,
 6438    _: &Window,
 6439    cx: &App,
 6440) -> Option<Div> {
 6441    let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
 6442        if state.pane() == pane {
 6443            Some((*leader_id, state))
 6444        } else {
 6445            None
 6446        }
 6447    })?;
 6448
 6449    let mut leader_color = match leader_id {
 6450        CollaboratorId::PeerId(leader_peer_id) => {
 6451            let room = ActiveCall::try_global(cx)?.read(cx).room()?.read(cx);
 6452            let leader = room.remote_participant_for_peer_id(leader_peer_id)?;
 6453
 6454            cx.theme()
 6455                .players()
 6456                .color_for_participant(leader.participant_index.0)
 6457                .cursor
 6458        }
 6459        CollaboratorId::Agent => cx.theme().players().agent().cursor,
 6460    };
 6461    leader_color.fade_out(0.3);
 6462    Some(
 6463        div()
 6464            .absolute()
 6465            .size_full()
 6466            .left_0()
 6467            .top_0()
 6468            .border_2()
 6469            .border_color(leader_color),
 6470    )
 6471}
 6472
 6473fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
 6474    ZED_WINDOW_POSITION
 6475        .zip(*ZED_WINDOW_SIZE)
 6476        .map(|(position, size)| Bounds {
 6477            origin: position,
 6478            size,
 6479        })
 6480}
 6481
 6482fn open_items(
 6483    serialized_workspace: Option<SerializedWorkspace>,
 6484    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
 6485    window: &mut Window,
 6486    cx: &mut Context<Workspace>,
 6487) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
 6488    let restored_items = serialized_workspace.map(|serialized_workspace| {
 6489        Workspace::load_workspace(
 6490            serialized_workspace,
 6491            project_paths_to_open
 6492                .iter()
 6493                .map(|(_, project_path)| project_path)
 6494                .cloned()
 6495                .collect(),
 6496            window,
 6497            cx,
 6498        )
 6499    });
 6500
 6501    cx.spawn_in(window, async move |workspace, cx| {
 6502        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
 6503
 6504        if let Some(restored_items) = restored_items {
 6505            let restored_items = restored_items.await?;
 6506
 6507            let restored_project_paths = restored_items
 6508                .iter()
 6509                .filter_map(|item| {
 6510                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
 6511                        .ok()
 6512                        .flatten()
 6513                })
 6514                .collect::<HashSet<_>>();
 6515
 6516            for restored_item in restored_items {
 6517                opened_items.push(restored_item.map(Ok));
 6518            }
 6519
 6520            project_paths_to_open
 6521                .iter_mut()
 6522                .for_each(|(_, project_path)| {
 6523                    if let Some(project_path_to_open) = project_path
 6524                        && restored_project_paths.contains(project_path_to_open)
 6525                    {
 6526                        *project_path = None;
 6527                    }
 6528                });
 6529        } else {
 6530            for _ in 0..project_paths_to_open.len() {
 6531                opened_items.push(None);
 6532            }
 6533        }
 6534        assert!(opened_items.len() == project_paths_to_open.len());
 6535
 6536        let tasks =
 6537            project_paths_to_open
 6538                .into_iter()
 6539                .enumerate()
 6540                .map(|(ix, (abs_path, project_path))| {
 6541                    let workspace = workspace.clone();
 6542                    cx.spawn(async move |cx| {
 6543                        let file_project_path = project_path?;
 6544                        let abs_path_task = workspace.update(cx, |workspace, cx| {
 6545                            workspace.project().update(cx, |project, cx| {
 6546                                project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
 6547                            })
 6548                        });
 6549
 6550                        // We only want to open file paths here. If one of the items
 6551                        // here is a directory, it was already opened further above
 6552                        // with a `find_or_create_worktree`.
 6553                        if let Ok(task) = abs_path_task
 6554                            && task.await.is_none_or(|p| p.is_file())
 6555                        {
 6556                            return Some((
 6557                                ix,
 6558                                workspace
 6559                                    .update_in(cx, |workspace, window, cx| {
 6560                                        workspace.open_path(
 6561                                            file_project_path,
 6562                                            None,
 6563                                            true,
 6564                                            window,
 6565                                            cx,
 6566                                        )
 6567                                    })
 6568                                    .log_err()?
 6569                                    .await,
 6570                            ));
 6571                        }
 6572                        None
 6573                    })
 6574                });
 6575
 6576        let tasks = tasks.collect::<Vec<_>>();
 6577
 6578        let tasks = futures::future::join_all(tasks);
 6579        for (ix, path_open_result) in tasks.await.into_iter().flatten() {
 6580            opened_items[ix] = Some(path_open_result);
 6581        }
 6582
 6583        Ok(opened_items)
 6584    })
 6585}
 6586
 6587enum ActivateInDirectionTarget {
 6588    Pane(Entity<Pane>),
 6589    Dock(Entity<Dock>),
 6590}
 6591
 6592fn notify_if_database_failed(workspace: WindowHandle<Workspace>, cx: &mut AsyncApp) {
 6593    workspace
 6594        .update(cx, |workspace, _, cx| {
 6595            if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
 6596                struct DatabaseFailedNotification;
 6597
 6598                workspace.show_notification(
 6599                    NotificationId::unique::<DatabaseFailedNotification>(),
 6600                    cx,
 6601                    |cx| {
 6602                        cx.new(|cx| {
 6603                            MessageNotification::new("Failed to load the database file.", cx)
 6604                                .primary_message("File an Issue")
 6605                                .primary_icon(IconName::Plus)
 6606                                .primary_on_click(|window, cx| {
 6607                                    window.dispatch_action(Box::new(FileBugReport), cx)
 6608                                })
 6609                        })
 6610                    },
 6611                );
 6612            }
 6613        })
 6614        .log_err();
 6615}
 6616
 6617fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
 6618    if val == 0 {
 6619        ThemeSettings::get_global(cx).ui_font_size(cx)
 6620    } else {
 6621        px(val as f32)
 6622    }
 6623}
 6624
 6625fn adjust_active_dock_size_by_px(
 6626    px: Pixels,
 6627    workspace: &mut Workspace,
 6628    window: &mut Window,
 6629    cx: &mut Context<Workspace>,
 6630) {
 6631    let Some(active_dock) = workspace
 6632        .all_docks()
 6633        .into_iter()
 6634        .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
 6635    else {
 6636        return;
 6637    };
 6638    let dock = active_dock.read(cx);
 6639    let Some(panel_size) = dock.active_panel_size(window, cx) else {
 6640        return;
 6641    };
 6642    let dock_pos = dock.position();
 6643    workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
 6644}
 6645
 6646fn adjust_open_docks_size_by_px(
 6647    px: Pixels,
 6648    workspace: &mut Workspace,
 6649    window: &mut Window,
 6650    cx: &mut Context<Workspace>,
 6651) {
 6652    let docks = workspace
 6653        .all_docks()
 6654        .into_iter()
 6655        .filter_map(|dock| {
 6656            if dock.read(cx).is_open() {
 6657                let dock = dock.read(cx);
 6658                let panel_size = dock.active_panel_size(window, cx)?;
 6659                let dock_pos = dock.position();
 6660                Some((panel_size, dock_pos, px))
 6661            } else {
 6662                None
 6663            }
 6664        })
 6665        .collect::<Vec<_>>();
 6666
 6667    docks
 6668        .into_iter()
 6669        .for_each(|(panel_size, dock_pos, offset)| {
 6670            workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
 6671        });
 6672}
 6673
 6674impl Focusable for Workspace {
 6675    fn focus_handle(&self, cx: &App) -> FocusHandle {
 6676        self.active_pane.focus_handle(cx)
 6677    }
 6678}
 6679
 6680#[derive(Clone)]
 6681struct DraggedDock(DockPosition);
 6682
 6683impl Render for DraggedDock {
 6684    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 6685        gpui::Empty
 6686    }
 6687}
 6688
 6689impl Render for Workspace {
 6690    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 6691        static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
 6692        if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
 6693            log::info!("Rendered first frame");
 6694        }
 6695        let mut context = KeyContext::new_with_defaults();
 6696        context.add("Workspace");
 6697        context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
 6698        if let Some(status) = self
 6699            .debugger_provider
 6700            .as_ref()
 6701            .and_then(|provider| provider.active_thread_state(cx))
 6702        {
 6703            match status {
 6704                ThreadStatus::Running | ThreadStatus::Stepping => {
 6705                    context.add("debugger_running");
 6706                }
 6707                ThreadStatus::Stopped => context.add("debugger_stopped"),
 6708                ThreadStatus::Exited | ThreadStatus::Ended => {}
 6709            }
 6710        }
 6711
 6712        if self.left_dock.read(cx).is_open() {
 6713            if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
 6714                context.set("left_dock", active_panel.panel_key());
 6715            }
 6716        }
 6717
 6718        if self.right_dock.read(cx).is_open() {
 6719            if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
 6720                context.set("right_dock", active_panel.panel_key());
 6721            }
 6722        }
 6723
 6724        if self.bottom_dock.read(cx).is_open() {
 6725            if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
 6726                context.set("bottom_dock", active_panel.panel_key());
 6727            }
 6728        }
 6729
 6730        let centered_layout = self.centered_layout
 6731            && self.center.panes().len() == 1
 6732            && self.active_item(cx).is_some();
 6733        let render_padding = |size| {
 6734            (size > 0.0).then(|| {
 6735                div()
 6736                    .h_full()
 6737                    .w(relative(size))
 6738                    .bg(cx.theme().colors().editor_background)
 6739                    .border_color(cx.theme().colors().pane_group_border)
 6740            })
 6741        };
 6742        let paddings = if centered_layout {
 6743            let settings = WorkspaceSettings::get_global(cx).centered_layout;
 6744            (
 6745                render_padding(Self::adjust_padding(
 6746                    settings.left_padding.map(|padding| padding.0),
 6747                )),
 6748                render_padding(Self::adjust_padding(
 6749                    settings.right_padding.map(|padding| padding.0),
 6750                )),
 6751            )
 6752        } else {
 6753            (None, None)
 6754        };
 6755        let ui_font = theme::setup_ui_font(window, cx);
 6756
 6757        let theme = cx.theme().clone();
 6758        let colors = theme.colors();
 6759        let notification_entities = self
 6760            .notifications
 6761            .iter()
 6762            .map(|(_, notification)| notification.entity_id())
 6763            .collect::<Vec<_>>();
 6764        let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
 6765
 6766        client_side_decorations(
 6767            self.actions(div(), window, cx)
 6768                .key_context(context)
 6769                .relative()
 6770                .size_full()
 6771                .flex()
 6772                .flex_col()
 6773                .font(ui_font)
 6774                .gap_0()
 6775                .justify_start()
 6776                .items_start()
 6777                .text_color(colors.text)
 6778                .overflow_hidden()
 6779                .children(self.titlebar_item.clone())
 6780                .on_modifiers_changed(move |_, _, cx| {
 6781                    for &id in &notification_entities {
 6782                        cx.notify(id);
 6783                    }
 6784                })
 6785                .child(
 6786                    div()
 6787                        .size_full()
 6788                        .relative()
 6789                        .flex_1()
 6790                        .flex()
 6791                        .flex_col()
 6792                        .child(
 6793                            div()
 6794                                .id("workspace")
 6795                                .bg(colors.background)
 6796                                .relative()
 6797                                .flex_1()
 6798                                .w_full()
 6799                                .flex()
 6800                                .flex_col()
 6801                                .overflow_hidden()
 6802                                .border_t_1()
 6803                                .border_b_1()
 6804                                .border_color(colors.border)
 6805                                .child({
 6806                                    let this = cx.entity();
 6807                                    canvas(
 6808                                        move |bounds, window, cx| {
 6809                                            this.update(cx, |this, cx| {
 6810                                                let bounds_changed = this.bounds != bounds;
 6811                                                this.bounds = bounds;
 6812
 6813                                                if bounds_changed {
 6814                                                    this.left_dock.update(cx, |dock, cx| {
 6815                                                        dock.clamp_panel_size(
 6816                                                            bounds.size.width,
 6817                                                            window,
 6818                                                            cx,
 6819                                                        )
 6820                                                    });
 6821
 6822                                                    this.right_dock.update(cx, |dock, cx| {
 6823                                                        dock.clamp_panel_size(
 6824                                                            bounds.size.width,
 6825                                                            window,
 6826                                                            cx,
 6827                                                        )
 6828                                                    });
 6829
 6830                                                    this.bottom_dock.update(cx, |dock, cx| {
 6831                                                        dock.clamp_panel_size(
 6832                                                            bounds.size.height,
 6833                                                            window,
 6834                                                            cx,
 6835                                                        )
 6836                                                    });
 6837                                                }
 6838                                            })
 6839                                        },
 6840                                        |_, _, _, _| {},
 6841                                    )
 6842                                    .absolute()
 6843                                    .size_full()
 6844                                })
 6845                                .when(self.zoomed.is_none(), |this| {
 6846                                    this.on_drag_move(cx.listener(
 6847                                        move |workspace,
 6848                                              e: &DragMoveEvent<DraggedDock>,
 6849                                              window,
 6850                                              cx| {
 6851                                            if workspace.previous_dock_drag_coordinates
 6852                                                != Some(e.event.position)
 6853                                            {
 6854                                                workspace.previous_dock_drag_coordinates =
 6855                                                    Some(e.event.position);
 6856                                                match e.drag(cx).0 {
 6857                                                    DockPosition::Left => {
 6858                                                        workspace.resize_left_dock(
 6859                                                            e.event.position.x
 6860                                                                - workspace.bounds.left(),
 6861                                                            window,
 6862                                                            cx,
 6863                                                        );
 6864                                                    }
 6865                                                    DockPosition::Right => {
 6866                                                        workspace.resize_right_dock(
 6867                                                            workspace.bounds.right()
 6868                                                                - e.event.position.x,
 6869                                                            window,
 6870                                                            cx,
 6871                                                        );
 6872                                                    }
 6873                                                    DockPosition::Bottom => {
 6874                                                        workspace.resize_bottom_dock(
 6875                                                            workspace.bounds.bottom()
 6876                                                                - e.event.position.y,
 6877                                                            window,
 6878                                                            cx,
 6879                                                        );
 6880                                                    }
 6881                                                };
 6882                                                workspace.serialize_workspace(window, cx);
 6883                                            }
 6884                                        },
 6885                                    ))
 6886                                    .on_drag_move(cx.listener(
 6887                                        move |workspace,
 6888                                              e: &DragMoveEvent<DraggedUtilityPane>,
 6889                                              window,
 6890                                              cx| {
 6891                                            let slot = e.drag(cx).0;
 6892                                            match slot {
 6893                                                UtilityPaneSlot::Left => {
 6894                                                    let left_dock_width = workspace.left_dock.read(cx)
 6895                                                        .active_panel_size(window, cx)
 6896                                                        .unwrap_or(gpui::px(0.0));
 6897                                                    let new_width = e.event.position.x
 6898                                                        - workspace.bounds.left()
 6899                                                        - left_dock_width;
 6900                                                    workspace.resize_utility_pane(slot, new_width, window, cx);
 6901                                                }
 6902                                                UtilityPaneSlot::Right => {
 6903                                                    let right_dock_width = workspace.right_dock.read(cx)
 6904                                                        .active_panel_size(window, cx)
 6905                                                        .unwrap_or(gpui::px(0.0));
 6906                                                    let new_width = workspace.bounds.right()
 6907                                                        - e.event.position.x
 6908                                                        - right_dock_width;
 6909                                                    workspace.resize_utility_pane(slot, new_width, window, cx);
 6910                                                }
 6911                                            }
 6912                                        },
 6913                                    ))
 6914                                })
 6915                                .child({
 6916                                    match bottom_dock_layout {
 6917                                        BottomDockLayout::Full => div()
 6918                                            .flex()
 6919                                            .flex_col()
 6920                                            .h_full()
 6921                                            .child(
 6922                                                div()
 6923                                                    .flex()
 6924                                                    .flex_row()
 6925                                                    .flex_1()
 6926                                                    .overflow_hidden()
 6927                                                    .children(self.render_dock(
 6928                                                        DockPosition::Left,
 6929                                                        &self.left_dock,
 6930                                                        window,
 6931                                                        cx,
 6932                                                    ))
 6933                                                    .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 6934                                                        this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 6935                                                            this.when(pane.expanded(cx), |this| {
 6936                                                                this.child(
 6937                                                                    UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 6938                                                                )
 6939                                                            })
 6940                                                        })
 6941                                                    })
 6942                                                    .child(
 6943                                                        div()
 6944                                                            .flex()
 6945                                                            .flex_col()
 6946                                                            .flex_1()
 6947                                                            .overflow_hidden()
 6948                                                            .child(
 6949                                                                h_flex()
 6950                                                                    .flex_1()
 6951                                                                    .when_some(
 6952                                                                        paddings.0,
 6953                                                                        |this, p| {
 6954                                                                            this.child(
 6955                                                                                p.border_r_1(),
 6956                                                                            )
 6957                                                                        },
 6958                                                                    )
 6959                                                                    .child(self.center.render(
 6960                                                                        self.zoomed.as_ref(),
 6961                                                                        &PaneRenderContext {
 6962                                                                            follower_states:
 6963                                                                                &self.follower_states,
 6964                                                                            active_call: self.active_call(),
 6965                                                                            active_pane: &self.active_pane,
 6966                                                                            app_state: &self.app_state,
 6967                                                                            project: &self.project,
 6968                                                                            workspace: &self.weak_self,
 6969                                                                        },
 6970                                                                        window,
 6971                                                                        cx,
 6972                                                                    ))
 6973                                                                    .when_some(
 6974                                                                        paddings.1,
 6975                                                                        |this, p| {
 6976                                                                            this.child(
 6977                                                                                p.border_l_1(),
 6978                                                                            )
 6979                                                                        },
 6980                                                                    ),
 6981                                                            ),
 6982                                                    )
 6983                                                    .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 6984                                                        this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 6985                                                            this.when(pane.expanded(cx), |this| {
 6986                                                                this.child(
 6987                                                                    UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 6988                                                                )
 6989                                                            })
 6990                                                        })
 6991                                                    })
 6992                                                    .children(self.render_dock(
 6993                                                        DockPosition::Right,
 6994                                                        &self.right_dock,
 6995                                                        window,
 6996                                                        cx,
 6997                                                    )),
 6998                                            )
 6999                                            .child(div().w_full().children(self.render_dock(
 7000                                                DockPosition::Bottom,
 7001                                                &self.bottom_dock,
 7002                                                window,
 7003                                                cx
 7004                                            ))),
 7005
 7006                                        BottomDockLayout::LeftAligned => div()
 7007                                            .flex()
 7008                                            .flex_row()
 7009                                            .h_full()
 7010                                            .child(
 7011                                                div()
 7012                                                    .flex()
 7013                                                    .flex_col()
 7014                                                    .flex_1()
 7015                                                    .h_full()
 7016                                                    .child(
 7017                                                        div()
 7018                                                            .flex()
 7019                                                            .flex_row()
 7020                                                            .flex_1()
 7021                                                            .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
 7022                                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7023                                                                this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 7024                                                                    this.when(pane.expanded(cx), |this| {
 7025                                                                        this.child(
 7026                                                                            UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 7027                                                                        )
 7028                                                                    })
 7029                                                                })
 7030                                                            })
 7031                                                            .child(
 7032                                                                div()
 7033                                                                    .flex()
 7034                                                                    .flex_col()
 7035                                                                    .flex_1()
 7036                                                                    .overflow_hidden()
 7037                                                                    .child(
 7038                                                                        h_flex()
 7039                                                                            .flex_1()
 7040                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7041                                                                            .child(self.center.render(
 7042                                                                                self.zoomed.as_ref(),
 7043                                                                                &PaneRenderContext {
 7044                                                                                    follower_states:
 7045                                                                                        &self.follower_states,
 7046                                                                                    active_call: self.active_call(),
 7047                                                                                    active_pane: &self.active_pane,
 7048                                                                                    app_state: &self.app_state,
 7049                                                                                    project: &self.project,
 7050                                                                                    workspace: &self.weak_self,
 7051                                                                                },
 7052                                                                                window,
 7053                                                                                cx,
 7054                                                                            ))
 7055                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7056                                                                    )
 7057                                                            )
 7058                                                            .when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 7059                                                                this.when(pane.expanded(cx), |this| {
 7060                                                                    this.child(
 7061                                                                        UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 7062                                                                    )
 7063                                                                })
 7064                                                            })
 7065                                                    )
 7066                                                    .child(
 7067                                                        div()
 7068                                                            .w_full()
 7069                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7070                                                    ),
 7071                                            )
 7072                                            .children(self.render_dock(
 7073                                                DockPosition::Right,
 7074                                                &self.right_dock,
 7075                                                window,
 7076                                                cx,
 7077                                            )),
 7078
 7079                                        BottomDockLayout::RightAligned => div()
 7080                                            .flex()
 7081                                            .flex_row()
 7082                                            .h_full()
 7083                                            .children(self.render_dock(
 7084                                                DockPosition::Left,
 7085                                                &self.left_dock,
 7086                                                window,
 7087                                                cx,
 7088                                            ))
 7089                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7090                                                this.when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 7091                                                    this.when(pane.expanded(cx), |this| {
 7092                                                        this.child(
 7093                                                            UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 7094                                                        )
 7095                                                    })
 7096                                                })
 7097                                            })
 7098                                            .child(
 7099                                                div()
 7100                                                    .flex()
 7101                                                    .flex_col()
 7102                                                    .flex_1()
 7103                                                    .h_full()
 7104                                                    .child(
 7105                                                        div()
 7106                                                            .flex()
 7107                                                            .flex_row()
 7108                                                            .flex_1()
 7109                                                            .child(
 7110                                                                div()
 7111                                                                    .flex()
 7112                                                                    .flex_col()
 7113                                                                    .flex_1()
 7114                                                                    .overflow_hidden()
 7115                                                                    .child(
 7116                                                                        h_flex()
 7117                                                                            .flex_1()
 7118                                                                            .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
 7119                                                                            .child(self.center.render(
 7120                                                                                self.zoomed.as_ref(),
 7121                                                                                &PaneRenderContext {
 7122                                                                                    follower_states:
 7123                                                                                        &self.follower_states,
 7124                                                                                    active_call: self.active_call(),
 7125                                                                                    active_pane: &self.active_pane,
 7126                                                                                    app_state: &self.app_state,
 7127                                                                                    project: &self.project,
 7128                                                                                    workspace: &self.weak_self,
 7129                                                                                },
 7130                                                                                window,
 7131                                                                                cx,
 7132                                                                            ))
 7133                                                                            .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
 7134                                                                    )
 7135                                                            )
 7136                                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7137                                                                this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 7138                                                                    this.when(pane.expanded(cx), |this| {
 7139                                                                        this.child(
 7140                                                                            UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 7141                                                                        )
 7142                                                                    })
 7143                                                                })
 7144                                                            })
 7145                                                            .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
 7146                                                    )
 7147                                                    .child(
 7148                                                        div()
 7149                                                            .w_full()
 7150                                                            .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
 7151                                                    ),
 7152                                            ),
 7153
 7154                                        BottomDockLayout::Contained => div()
 7155                                            .flex()
 7156                                            .flex_row()
 7157                                            .h_full()
 7158                                            .children(self.render_dock(
 7159                                                DockPosition::Left,
 7160                                                &self.left_dock,
 7161                                                window,
 7162                                                cx,
 7163                                            ))
 7164                                            .when_some(self.utility_pane(UtilityPaneSlot::Left), |this, pane| {
 7165                                                this.when(pane.expanded(cx), |this| {
 7166                                                    this.child(
 7167                                                        UtilityPaneFrame::new(UtilityPaneSlot::Left, pane.box_clone(), cx)
 7168                                                    )
 7169                                                })
 7170                                            })
 7171                                            .child(
 7172                                                div()
 7173                                                    .flex()
 7174                                                    .flex_col()
 7175                                                    .flex_1()
 7176                                                    .overflow_hidden()
 7177                                                    .child(
 7178                                                        h_flex()
 7179                                                            .flex_1()
 7180                                                            .when_some(paddings.0, |this, p| {
 7181                                                                this.child(p.border_r_1())
 7182                                                            })
 7183                                                            .child(self.center.render(
 7184                                                                self.zoomed.as_ref(),
 7185                                                                &PaneRenderContext {
 7186                                                                    follower_states:
 7187                                                                        &self.follower_states,
 7188                                                                    active_call: self.active_call(),
 7189                                                                    active_pane: &self.active_pane,
 7190                                                                    app_state: &self.app_state,
 7191                                                                    project: &self.project,
 7192                                                                    workspace: &self.weak_self,
 7193                                                                },
 7194                                                                window,
 7195                                                                cx,
 7196                                                            ))
 7197                                                            .when_some(paddings.1, |this, p| {
 7198                                                                this.child(p.border_l_1())
 7199                                                            }),
 7200                                                    )
 7201                                                    .children(self.render_dock(
 7202                                                        DockPosition::Bottom,
 7203                                                        &self.bottom_dock,
 7204                                                        window,
 7205                                                        cx,
 7206                                                    )),
 7207                                            )
 7208                                            .when(cx.has_flag::<AgentV2FeatureFlag>(), |this| {
 7209                                                this.when_some(self.utility_pane(UtilityPaneSlot::Right), |this, pane| {
 7210                                                    this.when(pane.expanded(cx), |this| {
 7211                                                        this.child(
 7212                                                            UtilityPaneFrame::new(UtilityPaneSlot::Right, pane.box_clone(), cx)
 7213                                                        )
 7214                                                    })
 7215                                                })
 7216                                            })
 7217                                            .children(self.render_dock(
 7218                                                DockPosition::Right,
 7219                                                &self.right_dock,
 7220                                                window,
 7221                                                cx,
 7222                                            )),
 7223                                    }
 7224                                })
 7225                                .children(self.zoomed.as_ref().and_then(|view| {
 7226                                    let zoomed_view = view.upgrade()?;
 7227                                    let div = div()
 7228                                        .occlude()
 7229                                        .absolute()
 7230                                        .overflow_hidden()
 7231                                        .border_color(colors.border)
 7232                                        .bg(colors.background)
 7233                                        .child(zoomed_view)
 7234                                        .inset_0()
 7235                                        .shadow_lg();
 7236
 7237                                    if !WorkspaceSettings::get_global(cx).zoomed_padding {
 7238                                       return Some(div);
 7239                                    }
 7240
 7241                                    Some(match self.zoomed_position {
 7242                                        Some(DockPosition::Left) => div.right_2().border_r_1(),
 7243                                        Some(DockPosition::Right) => div.left_2().border_l_1(),
 7244                                        Some(DockPosition::Bottom) => div.top_2().border_t_1(),
 7245                                        None => {
 7246                                            div.top_2().bottom_2().left_2().right_2().border_1()
 7247                                        }
 7248                                    })
 7249                                }))
 7250                                .children(self.render_notifications(window, cx)),
 7251                        )
 7252                        .when(self.status_bar_visible(cx), |parent| {
 7253                            parent.child(self.status_bar.clone())
 7254                        })
 7255                        .child(self.modal_layer.clone())
 7256                        .child(self.toast_layer.clone()),
 7257                ),
 7258            window,
 7259            cx,
 7260        )
 7261    }
 7262}
 7263
 7264impl WorkspaceStore {
 7265    pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
 7266        Self {
 7267            workspaces: Default::default(),
 7268            _subscriptions: vec![
 7269                client.add_request_handler(cx.weak_entity(), Self::handle_follow),
 7270                client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
 7271            ],
 7272            client,
 7273        }
 7274    }
 7275
 7276    pub fn update_followers(
 7277        &self,
 7278        project_id: Option<u64>,
 7279        update: proto::update_followers::Variant,
 7280        cx: &App,
 7281    ) -> Option<()> {
 7282        let active_call = ActiveCall::try_global(cx)?;
 7283        let room_id = active_call.read(cx).room()?.read(cx).id();
 7284        self.client
 7285            .send(proto::UpdateFollowers {
 7286                room_id,
 7287                project_id,
 7288                variant: Some(update),
 7289            })
 7290            .log_err()
 7291    }
 7292
 7293    pub async fn handle_follow(
 7294        this: Entity<Self>,
 7295        envelope: TypedEnvelope<proto::Follow>,
 7296        mut cx: AsyncApp,
 7297    ) -> Result<proto::FollowResponse> {
 7298        this.update(&mut cx, |this, cx| {
 7299            let follower = Follower {
 7300                project_id: envelope.payload.project_id,
 7301                peer_id: envelope.original_sender_id()?,
 7302            };
 7303
 7304            let mut response = proto::FollowResponse::default();
 7305            this.workspaces.retain(|workspace| {
 7306                workspace
 7307                    .update(cx, |workspace, window, cx| {
 7308                        let handler_response =
 7309                            workspace.handle_follow(follower.project_id, window, cx);
 7310                        if let Some(active_view) = handler_response.active_view
 7311                            && workspace.project.read(cx).remote_id() == follower.project_id
 7312                        {
 7313                            response.active_view = Some(active_view)
 7314                        }
 7315                    })
 7316                    .is_ok()
 7317            });
 7318
 7319            Ok(response)
 7320        })?
 7321    }
 7322
 7323    async fn handle_update_followers(
 7324        this: Entity<Self>,
 7325        envelope: TypedEnvelope<proto::UpdateFollowers>,
 7326        mut cx: AsyncApp,
 7327    ) -> Result<()> {
 7328        let leader_id = envelope.original_sender_id()?;
 7329        let update = envelope.payload;
 7330
 7331        this.update(&mut cx, |this, cx| {
 7332            this.workspaces.retain(|workspace| {
 7333                workspace
 7334                    .update(cx, |workspace, window, cx| {
 7335                        let project_id = workspace.project.read(cx).remote_id();
 7336                        if update.project_id != project_id && update.project_id.is_some() {
 7337                            return;
 7338                        }
 7339                        workspace.handle_update_followers(leader_id, update.clone(), window, cx);
 7340                    })
 7341                    .is_ok()
 7342            });
 7343            Ok(())
 7344        })?
 7345    }
 7346
 7347    pub fn workspaces(&self) -> &HashSet<WindowHandle<Workspace>> {
 7348        &self.workspaces
 7349    }
 7350}
 7351
 7352impl ViewId {
 7353    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
 7354        Ok(Self {
 7355            creator: message
 7356                .creator
 7357                .map(CollaboratorId::PeerId)
 7358                .context("creator is missing")?,
 7359            id: message.id,
 7360        })
 7361    }
 7362
 7363    pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
 7364        if let CollaboratorId::PeerId(peer_id) = self.creator {
 7365            Some(proto::ViewId {
 7366                creator: Some(peer_id),
 7367                id: self.id,
 7368            })
 7369        } else {
 7370            None
 7371        }
 7372    }
 7373}
 7374
 7375impl FollowerState {
 7376    fn pane(&self) -> &Entity<Pane> {
 7377        self.dock_pane.as_ref().unwrap_or(&self.center_pane)
 7378    }
 7379}
 7380
 7381pub trait WorkspaceHandle {
 7382    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
 7383}
 7384
 7385impl WorkspaceHandle for Entity<Workspace> {
 7386    fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
 7387        self.read(cx)
 7388            .worktrees(cx)
 7389            .flat_map(|worktree| {
 7390                let worktree_id = worktree.read(cx).id();
 7391                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
 7392                    worktree_id,
 7393                    path: f.path.clone(),
 7394                })
 7395            })
 7396            .collect::<Vec<_>>()
 7397    }
 7398}
 7399
 7400pub async fn last_opened_workspace_location() -> Option<(SerializedWorkspaceLocation, PathList)> {
 7401    DB.last_workspace().await.log_err().flatten()
 7402}
 7403
 7404pub fn last_session_workspace_locations(
 7405    last_session_id: &str,
 7406    last_session_window_stack: Option<Vec<WindowId>>,
 7407) -> Option<Vec<(SerializedWorkspaceLocation, PathList)>> {
 7408    DB.last_session_workspace_locations(last_session_id, last_session_window_stack)
 7409        .log_err()
 7410}
 7411
 7412actions!(
 7413    collab,
 7414    [
 7415        /// Opens the channel notes for the current call.
 7416        ///
 7417        /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
 7418        /// channel in the collab panel.
 7419        ///
 7420        /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
 7421        /// can be copied via "Copy link to section" in the context menu of the channel notes
 7422        /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
 7423        OpenChannelNotes,
 7424        /// Mutes your microphone.
 7425        Mute,
 7426        /// Deafens yourself (mute both microphone and speakers).
 7427        Deafen,
 7428        /// Leaves the current call.
 7429        LeaveCall,
 7430        /// Shares the current project with collaborators.
 7431        ShareProject,
 7432        /// Shares your screen with collaborators.
 7433        ScreenShare,
 7434        /// Copies the current room name and session id for debugging purposes.
 7435        CopyRoomId,
 7436    ]
 7437);
 7438actions!(
 7439    zed,
 7440    [
 7441        /// Opens the Zed log file.
 7442        OpenLog,
 7443        /// Reveals the Zed log file in the system file manager.
 7444        RevealLogInFileManager
 7445    ]
 7446);
 7447
 7448async fn join_channel_internal(
 7449    channel_id: ChannelId,
 7450    app_state: &Arc<AppState>,
 7451    requesting_window: Option<WindowHandle<Workspace>>,
 7452    active_call: &Entity<ActiveCall>,
 7453    cx: &mut AsyncApp,
 7454) -> Result<bool> {
 7455    let (should_prompt, open_room) = active_call.update(cx, |active_call, cx| {
 7456        let Some(room) = active_call.room().map(|room| room.read(cx)) else {
 7457            return (false, None);
 7458        };
 7459
 7460        let already_in_channel = room.channel_id() == Some(channel_id);
 7461        let should_prompt = room.is_sharing_project()
 7462            && !room.remote_participants().is_empty()
 7463            && !already_in_channel;
 7464        let open_room = if already_in_channel {
 7465            active_call.room().cloned()
 7466        } else {
 7467            None
 7468        };
 7469        (should_prompt, open_room)
 7470    })?;
 7471
 7472    if let Some(room) = open_room {
 7473        let task = room.update(cx, |room, cx| {
 7474            if let Some((project, host)) = room.most_active_project(cx) {
 7475                return Some(join_in_room_project(project, host, app_state.clone(), cx));
 7476            }
 7477
 7478            None
 7479        })?;
 7480        if let Some(task) = task {
 7481            task.await?;
 7482        }
 7483        return anyhow::Ok(true);
 7484    }
 7485
 7486    if should_prompt {
 7487        if let Some(workspace) = requesting_window {
 7488            let answer = workspace
 7489                .update(cx, |_, window, cx| {
 7490                    window.prompt(
 7491                        PromptLevel::Warning,
 7492                        "Do you want to switch channels?",
 7493                        Some("Leaving this call will unshare your current project."),
 7494                        &["Yes, Join Channel", "Cancel"],
 7495                        cx,
 7496                    )
 7497                })?
 7498                .await;
 7499
 7500            if answer == Ok(1) {
 7501                return Ok(false);
 7502            }
 7503        } else {
 7504            return Ok(false); // unreachable!() hopefully
 7505        }
 7506    }
 7507
 7508    let client = cx.update(|cx| active_call.read(cx).client())?;
 7509
 7510    let mut client_status = client.status();
 7511
 7512    // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
 7513    'outer: loop {
 7514        let Some(status) = client_status.recv().await else {
 7515            anyhow::bail!("error connecting");
 7516        };
 7517
 7518        match status {
 7519            Status::Connecting
 7520            | Status::Authenticating
 7521            | Status::Authenticated
 7522            | Status::Reconnecting
 7523            | Status::Reauthenticating
 7524            | Status::Reauthenticated => continue,
 7525            Status::Connected { .. } => break 'outer,
 7526            Status::SignedOut | Status::AuthenticationError => {
 7527                return Err(ErrorCode::SignedOut.into());
 7528            }
 7529            Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
 7530            Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
 7531                return Err(ErrorCode::Disconnected.into());
 7532            }
 7533        }
 7534    }
 7535
 7536    let room = active_call
 7537        .update(cx, |active_call, cx| {
 7538            active_call.join_channel(channel_id, cx)
 7539        })?
 7540        .await?;
 7541
 7542    let Some(room) = room else {
 7543        return anyhow::Ok(true);
 7544    };
 7545
 7546    room.update(cx, |room, _| room.room_update_completed())?
 7547        .await;
 7548
 7549    let task = room.update(cx, |room, cx| {
 7550        if let Some((project, host)) = room.most_active_project(cx) {
 7551            return Some(join_in_room_project(project, host, app_state.clone(), cx));
 7552        }
 7553
 7554        // If you are the first to join a channel, see if you should share your project.
 7555        if room.remote_participants().is_empty()
 7556            && !room.local_participant_is_guest()
 7557            && let Some(workspace) = requesting_window
 7558        {
 7559            let project = workspace.update(cx, |workspace, _, cx| {
 7560                let project = workspace.project.read(cx);
 7561
 7562                if !CallSettings::get_global(cx).share_on_join {
 7563                    return None;
 7564                }
 7565
 7566                if (project.is_local() || project.is_via_remote_server())
 7567                    && project.visible_worktrees(cx).any(|tree| {
 7568                        tree.read(cx)
 7569                            .root_entry()
 7570                            .is_some_and(|entry| entry.is_dir())
 7571                    })
 7572                {
 7573                    Some(workspace.project.clone())
 7574                } else {
 7575                    None
 7576                }
 7577            });
 7578            if let Ok(Some(project)) = project {
 7579                return Some(cx.spawn(async move |room, cx| {
 7580                    room.update(cx, |room, cx| room.share_project(project, cx))?
 7581                        .await?;
 7582                    Ok(())
 7583                }));
 7584            }
 7585        }
 7586
 7587        None
 7588    })?;
 7589    if let Some(task) = task {
 7590        task.await?;
 7591        return anyhow::Ok(true);
 7592    }
 7593    anyhow::Ok(false)
 7594}
 7595
 7596pub fn join_channel(
 7597    channel_id: ChannelId,
 7598    app_state: Arc<AppState>,
 7599    requesting_window: Option<WindowHandle<Workspace>>,
 7600    cx: &mut App,
 7601) -> Task<Result<()>> {
 7602    let active_call = ActiveCall::global(cx);
 7603    cx.spawn(async move |cx| {
 7604        let result =
 7605            join_channel_internal(channel_id, &app_state, requesting_window, &active_call, cx)
 7606                .await;
 7607
 7608        // join channel succeeded, and opened a window
 7609        if matches!(result, Ok(true)) {
 7610            return anyhow::Ok(());
 7611        }
 7612
 7613        // find an existing workspace to focus and show call controls
 7614        let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
 7615        if active_window.is_none() {
 7616            // no open workspaces, make one to show the error in (blergh)
 7617            let (window_handle, _) = cx
 7618                .update(|cx| {
 7619                    Workspace::new_local(vec![], app_state.clone(), requesting_window, None, cx)
 7620                })?
 7621                .await?;
 7622
 7623            if result.is_ok() {
 7624                cx.update(|cx| {
 7625                    cx.dispatch_action(&OpenChannelNotes);
 7626                })
 7627                .log_err();
 7628            }
 7629
 7630            active_window = Some(window_handle);
 7631        }
 7632
 7633        if let Err(err) = result {
 7634            log::error!("failed to join channel: {}", err);
 7635            if let Some(active_window) = active_window {
 7636                active_window
 7637                    .update(cx, |_, window, cx| {
 7638                        let detail: SharedString = match err.error_code() {
 7639                            ErrorCode::SignedOut => "Please sign in to continue.".into(),
 7640                            ErrorCode::UpgradeRequired => concat!(
 7641                                "Your are running an unsupported version of Zed. ",
 7642                                "Please update to continue."
 7643                            )
 7644                            .into(),
 7645                            ErrorCode::NoSuchChannel => concat!(
 7646                                "No matching channel was found. ",
 7647                                "Please check the link and try again."
 7648                            )
 7649                            .into(),
 7650                            ErrorCode::Forbidden => concat!(
 7651                                "This channel is private, and you do not have access. ",
 7652                                "Please ask someone to add you and try again."
 7653                            )
 7654                            .into(),
 7655                            ErrorCode::Disconnected => {
 7656                                "Please check your internet connection and try again.".into()
 7657                            }
 7658                            _ => format!("{}\n\nPlease try again.", err).into(),
 7659                        };
 7660                        window.prompt(
 7661                            PromptLevel::Critical,
 7662                            "Failed to join channel",
 7663                            Some(&detail),
 7664                            &["Ok"],
 7665                            cx,
 7666                        )
 7667                    })?
 7668                    .await
 7669                    .ok();
 7670            }
 7671        }
 7672
 7673        // return ok, we showed the error to the user.
 7674        anyhow::Ok(())
 7675    })
 7676}
 7677
 7678pub async fn get_any_active_workspace(
 7679    app_state: Arc<AppState>,
 7680    mut cx: AsyncApp,
 7681) -> anyhow::Result<WindowHandle<Workspace>> {
 7682    // find an existing workspace to focus and show call controls
 7683    let active_window = activate_any_workspace_window(&mut cx);
 7684    if active_window.is_none() {
 7685        cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, cx))?
 7686            .await?;
 7687    }
 7688    activate_any_workspace_window(&mut cx).context("could not open zed")
 7689}
 7690
 7691fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<Workspace>> {
 7692    cx.update(|cx| {
 7693        if let Some(workspace_window) = cx
 7694            .active_window()
 7695            .and_then(|window| window.downcast::<Workspace>())
 7696        {
 7697            return Some(workspace_window);
 7698        }
 7699
 7700        for window in cx.windows() {
 7701            if let Some(workspace_window) = window.downcast::<Workspace>() {
 7702                workspace_window
 7703                    .update(cx, |_, window, _| window.activate_window())
 7704                    .ok();
 7705                return Some(workspace_window);
 7706            }
 7707        }
 7708        None
 7709    })
 7710    .ok()
 7711    .flatten()
 7712}
 7713
 7714pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<Workspace>> {
 7715    cx.windows()
 7716        .into_iter()
 7717        .filter_map(|window| window.downcast::<Workspace>())
 7718        .filter(|workspace| {
 7719            workspace
 7720                .read(cx)
 7721                .is_ok_and(|workspace| workspace.project.read(cx).is_local())
 7722        })
 7723        .collect()
 7724}
 7725
 7726#[derive(Default)]
 7727pub struct OpenOptions {
 7728    pub visible: Option<OpenVisible>,
 7729    pub focus: Option<bool>,
 7730    pub open_new_workspace: Option<bool>,
 7731    pub prefer_focused_window: bool,
 7732    pub replace_window: Option<WindowHandle<Workspace>>,
 7733    pub env: Option<HashMap<String, String>>,
 7734}
 7735
 7736#[allow(clippy::type_complexity)]
 7737pub fn open_paths(
 7738    abs_paths: &[PathBuf],
 7739    app_state: Arc<AppState>,
 7740    open_options: OpenOptions,
 7741    cx: &mut App,
 7742) -> Task<
 7743    anyhow::Result<(
 7744        WindowHandle<Workspace>,
 7745        Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 7746    )>,
 7747> {
 7748    let abs_paths = abs_paths.to_vec();
 7749    let mut existing = None;
 7750    let mut best_match = None;
 7751    let mut open_visible = OpenVisible::All;
 7752    #[cfg(target_os = "windows")]
 7753    let wsl_path = abs_paths
 7754        .iter()
 7755        .find_map(|p| util::paths::WslPath::from_path(p));
 7756
 7757    cx.spawn(async move |cx| {
 7758        if open_options.open_new_workspace != Some(true) {
 7759            let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
 7760            let all_metadatas = futures::future::join_all(all_paths)
 7761                .await
 7762                .into_iter()
 7763                .filter_map(|result| result.ok().flatten())
 7764                .collect::<Vec<_>>();
 7765
 7766            cx.update(|cx| {
 7767                for window in local_workspace_windows(cx) {
 7768                    if let Ok(workspace) = window.read(cx) {
 7769                        let m = workspace.project.read(cx).visibility_for_paths(
 7770                            &abs_paths,
 7771                            &all_metadatas,
 7772                            open_options.open_new_workspace == None,
 7773                            cx,
 7774                        );
 7775                        if m > best_match {
 7776                            existing = Some(window);
 7777                            best_match = m;
 7778                        } else if best_match.is_none()
 7779                            && open_options.open_new_workspace == Some(false)
 7780                        {
 7781                            existing = Some(window)
 7782                        }
 7783                    }
 7784                }
 7785            })?;
 7786
 7787            if open_options.open_new_workspace.is_none()
 7788                && (existing.is_none() || open_options.prefer_focused_window)
 7789                && all_metadatas.iter().all(|file| !file.is_dir)
 7790            {
 7791                cx.update(|cx| {
 7792                    if let Some(window) = cx
 7793                        .active_window()
 7794                        .and_then(|window| window.downcast::<Workspace>())
 7795                        && let Ok(workspace) = window.read(cx)
 7796                    {
 7797                        let project = workspace.project().read(cx);
 7798                        if project.is_local() && !project.is_via_collab() {
 7799                            existing = Some(window);
 7800                            open_visible = OpenVisible::None;
 7801                            return;
 7802                        }
 7803                    }
 7804                    for window in local_workspace_windows(cx) {
 7805                        if let Ok(workspace) = window.read(cx) {
 7806                            let project = workspace.project().read(cx);
 7807                            if project.is_via_collab() {
 7808                                continue;
 7809                            }
 7810                            existing = Some(window);
 7811                            open_visible = OpenVisible::None;
 7812                            break;
 7813                        }
 7814                    }
 7815                })?;
 7816            }
 7817        }
 7818
 7819        let result = if let Some(existing) = existing {
 7820            let open_task = existing
 7821                .update(cx, |workspace, window, cx| {
 7822                    window.activate_window();
 7823                    workspace.open_paths(
 7824                        abs_paths,
 7825                        OpenOptions {
 7826                            visible: Some(open_visible),
 7827                            ..Default::default()
 7828                        },
 7829                        None,
 7830                        window,
 7831                        cx,
 7832                    )
 7833                })?
 7834                .await;
 7835
 7836            _ = existing.update(cx, |workspace, _, cx| {
 7837                for item in open_task.iter().flatten() {
 7838                    if let Err(e) = item {
 7839                        workspace.show_error(&e, cx);
 7840                    }
 7841                }
 7842            });
 7843
 7844            Ok((existing, open_task))
 7845        } else {
 7846            cx.update(move |cx| {
 7847                Workspace::new_local(
 7848                    abs_paths,
 7849                    app_state.clone(),
 7850                    open_options.replace_window,
 7851                    open_options.env,
 7852                    cx,
 7853                )
 7854            })?
 7855            .await
 7856        };
 7857
 7858        #[cfg(target_os = "windows")]
 7859        if let Some(util::paths::WslPath{distro, path}) = wsl_path
 7860            && let Ok((workspace, _)) = &result
 7861        {
 7862            workspace
 7863                .update(cx, move |workspace, _window, cx| {
 7864                    struct OpenInWsl;
 7865                    workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
 7866                        let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
 7867                        let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
 7868                        cx.new(move |cx| {
 7869                            MessageNotification::new(msg, cx)
 7870                                .primary_message("Open in WSL")
 7871                                .primary_icon(IconName::FolderOpen)
 7872                                .primary_on_click(move |window, cx| {
 7873                                    window.dispatch_action(Box::new(remote::OpenWslPath {
 7874                                            distro: remote::WslConnectionOptions {
 7875                                                    distro_name: distro.clone(),
 7876                                                user: None,
 7877                                            },
 7878                                            paths: vec![path.clone().into()],
 7879                                        }), cx)
 7880                                })
 7881                        })
 7882                    });
 7883                })
 7884                .unwrap();
 7885        };
 7886        result
 7887    })
 7888}
 7889
 7890pub fn open_new(
 7891    open_options: OpenOptions,
 7892    app_state: Arc<AppState>,
 7893    cx: &mut App,
 7894    init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
 7895) -> Task<anyhow::Result<()>> {
 7896    let task = Workspace::new_local(Vec::new(), app_state, None, open_options.env, cx);
 7897    cx.spawn(async move |cx| {
 7898        let (workspace, opened_paths) = task.await?;
 7899        workspace.update(cx, |workspace, window, cx| {
 7900            if opened_paths.is_empty() {
 7901                init(workspace, window, cx)
 7902            }
 7903        })?;
 7904        Ok(())
 7905    })
 7906}
 7907
 7908pub fn create_and_open_local_file(
 7909    path: &'static Path,
 7910    window: &mut Window,
 7911    cx: &mut Context<Workspace>,
 7912    default_content: impl 'static + Send + FnOnce() -> Rope,
 7913) -> Task<Result<Box<dyn ItemHandle>>> {
 7914    cx.spawn_in(window, async move |workspace, cx| {
 7915        let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
 7916        if !fs.is_file(path).await {
 7917            fs.create_file(path, Default::default()).await?;
 7918            fs.save(path, &default_content(), Default::default())
 7919                .await?;
 7920        }
 7921
 7922        let mut items = workspace
 7923            .update_in(cx, |workspace, window, cx| {
 7924                workspace.with_local_workspace(window, cx, |workspace, window, cx| {
 7925                    workspace.open_paths(
 7926                        vec![path.to_path_buf()],
 7927                        OpenOptions {
 7928                            visible: Some(OpenVisible::None),
 7929                            ..Default::default()
 7930                        },
 7931                        None,
 7932                        window,
 7933                        cx,
 7934                    )
 7935                })
 7936            })?
 7937            .await?
 7938            .await;
 7939
 7940        let item = items.pop().flatten();
 7941        item.with_context(|| format!("path {path:?} is not a file"))?
 7942    })
 7943}
 7944
 7945pub fn open_remote_project_with_new_connection(
 7946    window: WindowHandle<Workspace>,
 7947    remote_connection: Arc<dyn RemoteConnection>,
 7948    cancel_rx: oneshot::Receiver<()>,
 7949    delegate: Arc<dyn RemoteClientDelegate>,
 7950    app_state: Arc<AppState>,
 7951    paths: Vec<PathBuf>,
 7952    cx: &mut App,
 7953) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 7954    cx.spawn(async move |cx| {
 7955        let (workspace_id, serialized_workspace) =
 7956            deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
 7957                .await?;
 7958
 7959        let session = match cx
 7960            .update(|cx| {
 7961                remote::RemoteClient::new(
 7962                    ConnectionIdentifier::Workspace(workspace_id.0),
 7963                    remote_connection,
 7964                    cancel_rx,
 7965                    delegate,
 7966                    cx,
 7967                )
 7968            })?
 7969            .await?
 7970        {
 7971            Some(result) => result,
 7972            None => return Ok(Vec::new()),
 7973        };
 7974
 7975        let project = cx.update(|cx| {
 7976            project::Project::remote(
 7977                session,
 7978                app_state.client.clone(),
 7979                app_state.node_runtime.clone(),
 7980                app_state.user_store.clone(),
 7981                app_state.languages.clone(),
 7982                app_state.fs.clone(),
 7983                cx,
 7984            )
 7985        })?;
 7986
 7987        open_remote_project_inner(
 7988            project,
 7989            paths,
 7990            workspace_id,
 7991            serialized_workspace,
 7992            app_state,
 7993            window,
 7994            cx,
 7995        )
 7996        .await
 7997    })
 7998}
 7999
 8000pub fn open_remote_project_with_existing_connection(
 8001    connection_options: RemoteConnectionOptions,
 8002    project: Entity<Project>,
 8003    paths: Vec<PathBuf>,
 8004    app_state: Arc<AppState>,
 8005    window: WindowHandle<Workspace>,
 8006    cx: &mut AsyncApp,
 8007) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
 8008    cx.spawn(async move |cx| {
 8009        let (workspace_id, serialized_workspace) =
 8010            deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 8011
 8012        open_remote_project_inner(
 8013            project,
 8014            paths,
 8015            workspace_id,
 8016            serialized_workspace,
 8017            app_state,
 8018            window,
 8019            cx,
 8020        )
 8021        .await
 8022    })
 8023}
 8024
 8025async fn open_remote_project_inner(
 8026    project: Entity<Project>,
 8027    paths: Vec<PathBuf>,
 8028    workspace_id: WorkspaceId,
 8029    serialized_workspace: Option<SerializedWorkspace>,
 8030    app_state: Arc<AppState>,
 8031    window: WindowHandle<Workspace>,
 8032    cx: &mut AsyncApp,
 8033) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
 8034    let toolchains = DB.toolchains(workspace_id).await?;
 8035    for (toolchain, worktree_id, path) in toolchains {
 8036        project
 8037            .update(cx, |this, cx| {
 8038                this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 8039            })?
 8040            .await;
 8041    }
 8042    let mut project_paths_to_open = vec![];
 8043    let mut project_path_errors = vec![];
 8044
 8045    for path in paths {
 8046        let result = cx
 8047            .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))?
 8048            .await;
 8049        match result {
 8050            Ok((_, project_path)) => {
 8051                project_paths_to_open.push((path.clone(), Some(project_path)));
 8052            }
 8053            Err(error) => {
 8054                project_path_errors.push(error);
 8055            }
 8056        };
 8057    }
 8058
 8059    if project_paths_to_open.is_empty() {
 8060        return Err(project_path_errors.pop().context("no paths given")?);
 8061    }
 8062
 8063    if let Some(detach_session_task) = window
 8064        .update(cx, |_workspace, window, cx| {
 8065            cx.spawn_in(window, async move |this, cx| {
 8066                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))
 8067            })
 8068        })
 8069        .ok()
 8070    {
 8071        detach_session_task.await.ok();
 8072    }
 8073
 8074    cx.update_window(window.into(), |_, window, cx| {
 8075        window.replace_root(cx, |window, cx| {
 8076            telemetry::event!("SSH Project Opened");
 8077
 8078            let mut workspace =
 8079                Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
 8080            workspace.update_history(cx);
 8081
 8082            if let Some(ref serialized) = serialized_workspace {
 8083                workspace.centered_layout = serialized.centered_layout;
 8084            }
 8085
 8086            workspace
 8087        });
 8088    })?;
 8089
 8090    let items = window
 8091        .update(cx, |_, window, cx| {
 8092            window.activate_window();
 8093            open_items(serialized_workspace, project_paths_to_open, window, cx)
 8094        })?
 8095        .await?;
 8096
 8097    window.update(cx, |workspace, _, cx| {
 8098        for error in project_path_errors {
 8099            if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
 8100                if let Some(path) = error.error_tag("path") {
 8101                    workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
 8102                }
 8103            } else {
 8104                workspace.show_error(&error, cx)
 8105            }
 8106        }
 8107    })?;
 8108
 8109    Ok(items.into_iter().map(|item| item?.ok()).collect())
 8110}
 8111
 8112fn deserialize_remote_project(
 8113    connection_options: RemoteConnectionOptions,
 8114    paths: Vec<PathBuf>,
 8115    cx: &AsyncApp,
 8116) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 8117    cx.background_spawn(async move {
 8118        let remote_connection_id = persistence::DB
 8119            .get_or_create_remote_connection(connection_options)
 8120            .await?;
 8121
 8122        let serialized_workspace =
 8123            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 8124
 8125        let workspace_id = if let Some(workspace_id) =
 8126            serialized_workspace.as_ref().map(|workspace| workspace.id)
 8127        {
 8128            workspace_id
 8129        } else {
 8130            persistence::DB.next_id().await?
 8131        };
 8132
 8133        Ok((workspace_id, serialized_workspace))
 8134    })
 8135}
 8136
 8137pub fn join_in_room_project(
 8138    project_id: u64,
 8139    follow_user_id: u64,
 8140    app_state: Arc<AppState>,
 8141    cx: &mut App,
 8142) -> Task<Result<()>> {
 8143    let windows = cx.windows();
 8144    cx.spawn(async move |cx| {
 8145        let existing_workspace = windows.into_iter().find_map(|window_handle| {
 8146            window_handle
 8147                .downcast::<Workspace>()
 8148                .and_then(|window_handle| {
 8149                    window_handle
 8150                        .update(cx, |workspace, _window, cx| {
 8151                            if workspace.project().read(cx).remote_id() == Some(project_id) {
 8152                                Some(window_handle)
 8153                            } else {
 8154                                None
 8155                            }
 8156                        })
 8157                        .unwrap_or(None)
 8158                })
 8159        });
 8160
 8161        let workspace = if let Some(existing_workspace) = existing_workspace {
 8162            existing_workspace
 8163        } else {
 8164            let active_call = cx.update(|cx| ActiveCall::global(cx))?;
 8165            let room = active_call
 8166                .read_with(cx, |call, _| call.room().cloned())?
 8167                .context("not in a call")?;
 8168            let project = room
 8169                .update(cx, |room, cx| {
 8170                    room.join_project(
 8171                        project_id,
 8172                        app_state.languages.clone(),
 8173                        app_state.fs.clone(),
 8174                        cx,
 8175                    )
 8176                })?
 8177                .await?;
 8178
 8179            let window_bounds_override = window_bounds_env_override();
 8180            cx.update(|cx| {
 8181                let mut options = (app_state.build_window_options)(None, cx);
 8182                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 8183                cx.open_window(options, |window, cx| {
 8184                    cx.new(|cx| {
 8185                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 8186                    })
 8187                })
 8188            })??
 8189        };
 8190
 8191        workspace.update(cx, |workspace, window, cx| {
 8192            cx.activate(true);
 8193            window.activate_window();
 8194
 8195            if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
 8196                let follow_peer_id = room
 8197                    .read(cx)
 8198                    .remote_participants()
 8199                    .iter()
 8200                    .find(|(_, participant)| participant.user.id == follow_user_id)
 8201                    .map(|(_, p)| p.peer_id)
 8202                    .or_else(|| {
 8203                        // If we couldn't follow the given user, follow the host instead.
 8204                        let collaborator = workspace
 8205                            .project()
 8206                            .read(cx)
 8207                            .collaborators()
 8208                            .values()
 8209                            .find(|collaborator| collaborator.is_host)?;
 8210                        Some(collaborator.peer_id)
 8211                    });
 8212
 8213                if let Some(follow_peer_id) = follow_peer_id {
 8214                    workspace.follow(follow_peer_id, window, cx);
 8215                }
 8216            }
 8217        })?;
 8218
 8219        anyhow::Ok(())
 8220    })
 8221}
 8222
 8223pub fn reload(cx: &mut App) {
 8224    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 8225    let mut workspace_windows = cx
 8226        .windows()
 8227        .into_iter()
 8228        .filter_map(|window| window.downcast::<Workspace>())
 8229        .collect::<Vec<_>>();
 8230
 8231    // If multiple windows have unsaved changes, and need a save prompt,
 8232    // prompt in the active window before switching to a different window.
 8233    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 8234
 8235    let mut prompt = None;
 8236    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 8237        prompt = window
 8238            .update(cx, |_, window, cx| {
 8239                window.prompt(
 8240                    PromptLevel::Info,
 8241                    "Are you sure you want to restart?",
 8242                    None,
 8243                    &["Restart", "Cancel"],
 8244                    cx,
 8245                )
 8246            })
 8247            .ok();
 8248    }
 8249
 8250    cx.spawn(async move |cx| {
 8251        if let Some(prompt) = prompt {
 8252            let answer = prompt.await?;
 8253            if answer != 0 {
 8254                return Ok(());
 8255            }
 8256        }
 8257
 8258        // If the user cancels any save prompt, then keep the app open.
 8259        for window in workspace_windows {
 8260            if let Ok(should_close) = window.update(cx, |workspace, window, cx| {
 8261                workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 8262            }) && !should_close.await?
 8263            {
 8264                return Ok(());
 8265            }
 8266        }
 8267        cx.update(|cx| cx.restart())
 8268    })
 8269    .detach_and_log_err(cx);
 8270}
 8271
 8272fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 8273    let mut parts = value.split(',');
 8274    let x: usize = parts.next()?.parse().ok()?;
 8275    let y: usize = parts.next()?.parse().ok()?;
 8276    Some(point(px(x as f32), px(y as f32)))
 8277}
 8278
 8279fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 8280    let mut parts = value.split(',');
 8281    let width: usize = parts.next()?.parse().ok()?;
 8282    let height: usize = parts.next()?.parse().ok()?;
 8283    Some(size(px(width as f32), px(height as f32)))
 8284}
 8285
 8286/// Add client-side decorations (rounded corners, shadows, resize handling) when appropriate.
 8287pub fn client_side_decorations(
 8288    element: impl IntoElement,
 8289    window: &mut Window,
 8290    cx: &mut App,
 8291) -> Stateful<Div> {
 8292    const BORDER_SIZE: Pixels = px(1.0);
 8293    let decorations = window.window_decorations();
 8294
 8295    match decorations {
 8296        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 8297        Decorations::Server => window.set_client_inset(px(0.0)),
 8298    }
 8299
 8300    struct GlobalResizeEdge(ResizeEdge);
 8301    impl Global for GlobalResizeEdge {}
 8302
 8303    div()
 8304        .id("window-backdrop")
 8305        .bg(transparent_black())
 8306        .map(|div| match decorations {
 8307            Decorations::Server => div,
 8308            Decorations::Client { tiling, .. } => div
 8309                .when(!(tiling.top || tiling.right), |div| {
 8310                    div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8311                })
 8312                .when(!(tiling.top || tiling.left), |div| {
 8313                    div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8314                })
 8315                .when(!(tiling.bottom || tiling.right), |div| {
 8316                    div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8317                })
 8318                .when(!(tiling.bottom || tiling.left), |div| {
 8319                    div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8320                })
 8321                .when(!tiling.top, |div| {
 8322                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8323                })
 8324                .when(!tiling.bottom, |div| {
 8325                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8326                })
 8327                .when(!tiling.left, |div| {
 8328                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8329                })
 8330                .when(!tiling.right, |div| {
 8331                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 8332                })
 8333                .on_mouse_move(move |e, window, cx| {
 8334                    let size = window.window_bounds().get_bounds().size;
 8335                    let pos = e.position;
 8336
 8337                    let new_edge =
 8338                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 8339
 8340                    let edge = cx.try_global::<GlobalResizeEdge>();
 8341                    if new_edge != edge.map(|edge| edge.0) {
 8342                        window
 8343                            .window_handle()
 8344                            .update(cx, |workspace, _, cx| {
 8345                                cx.notify(workspace.entity_id());
 8346                            })
 8347                            .ok();
 8348                    }
 8349                })
 8350                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 8351                    let size = window.window_bounds().get_bounds().size;
 8352                    let pos = e.position;
 8353
 8354                    let edge = match resize_edge(
 8355                        pos,
 8356                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 8357                        size,
 8358                        tiling,
 8359                    ) {
 8360                        Some(value) => value,
 8361                        None => return,
 8362                    };
 8363
 8364                    window.start_window_resize(edge);
 8365                }),
 8366        })
 8367        .size_full()
 8368        .child(
 8369            div()
 8370                .cursor(CursorStyle::Arrow)
 8371                .map(|div| match decorations {
 8372                    Decorations::Server => div,
 8373                    Decorations::Client { tiling } => div
 8374                        .border_color(cx.theme().colors().border)
 8375                        .when(!(tiling.top || tiling.right), |div| {
 8376                            div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8377                        })
 8378                        .when(!(tiling.top || tiling.left), |div| {
 8379                            div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8380                        })
 8381                        .when(!(tiling.bottom || tiling.right), |div| {
 8382                            div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8383                        })
 8384                        .when(!(tiling.bottom || tiling.left), |div| {
 8385                            div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 8386                        })
 8387                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 8388                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 8389                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 8390                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 8391                        .when(!tiling.is_tiled(), |div| {
 8392                            div.shadow(vec![gpui::BoxShadow {
 8393                                color: Hsla {
 8394                                    h: 0.,
 8395                                    s: 0.,
 8396                                    l: 0.,
 8397                                    a: 0.4,
 8398                                },
 8399                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 8400                                spread_radius: px(0.),
 8401                                offset: point(px(0.0), px(0.0)),
 8402                            }])
 8403                        }),
 8404                })
 8405                .on_mouse_move(|_e, _, cx| {
 8406                    cx.stop_propagation();
 8407                })
 8408                .size_full()
 8409                .child(element),
 8410        )
 8411        .map(|div| match decorations {
 8412            Decorations::Server => div,
 8413            Decorations::Client { tiling, .. } => div.child(
 8414                canvas(
 8415                    |_bounds, window, _| {
 8416                        window.insert_hitbox(
 8417                            Bounds::new(
 8418                                point(px(0.0), px(0.0)),
 8419                                window.window_bounds().get_bounds().size,
 8420                            ),
 8421                            HitboxBehavior::Normal,
 8422                        )
 8423                    },
 8424                    move |_bounds, hitbox, window, cx| {
 8425                        let mouse = window.mouse_position();
 8426                        let size = window.window_bounds().get_bounds().size;
 8427                        let Some(edge) =
 8428                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 8429                        else {
 8430                            return;
 8431                        };
 8432                        cx.set_global(GlobalResizeEdge(edge));
 8433                        window.set_cursor_style(
 8434                            match edge {
 8435                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 8436                                ResizeEdge::Left | ResizeEdge::Right => {
 8437                                    CursorStyle::ResizeLeftRight
 8438                                }
 8439                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 8440                                    CursorStyle::ResizeUpLeftDownRight
 8441                                }
 8442                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 8443                                    CursorStyle::ResizeUpRightDownLeft
 8444                                }
 8445                            },
 8446                            &hitbox,
 8447                        );
 8448                    },
 8449                )
 8450                .size_full()
 8451                .absolute(),
 8452            ),
 8453        })
 8454}
 8455
 8456fn resize_edge(
 8457    pos: Point<Pixels>,
 8458    shadow_size: Pixels,
 8459    window_size: Size<Pixels>,
 8460    tiling: Tiling,
 8461) -> Option<ResizeEdge> {
 8462    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 8463    if bounds.contains(&pos) {
 8464        return None;
 8465    }
 8466
 8467    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 8468    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 8469    if !tiling.top && top_left_bounds.contains(&pos) {
 8470        return Some(ResizeEdge::TopLeft);
 8471    }
 8472
 8473    let top_right_bounds = Bounds::new(
 8474        Point::new(window_size.width - corner_size.width, px(0.)),
 8475        corner_size,
 8476    );
 8477    if !tiling.top && top_right_bounds.contains(&pos) {
 8478        return Some(ResizeEdge::TopRight);
 8479    }
 8480
 8481    let bottom_left_bounds = Bounds::new(
 8482        Point::new(px(0.), window_size.height - corner_size.height),
 8483        corner_size,
 8484    );
 8485    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 8486        return Some(ResizeEdge::BottomLeft);
 8487    }
 8488
 8489    let bottom_right_bounds = Bounds::new(
 8490        Point::new(
 8491            window_size.width - corner_size.width,
 8492            window_size.height - corner_size.height,
 8493        ),
 8494        corner_size,
 8495    );
 8496    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 8497        return Some(ResizeEdge::BottomRight);
 8498    }
 8499
 8500    if !tiling.top && pos.y < shadow_size {
 8501        Some(ResizeEdge::Top)
 8502    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 8503        Some(ResizeEdge::Bottom)
 8504    } else if !tiling.left && pos.x < shadow_size {
 8505        Some(ResizeEdge::Left)
 8506    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 8507        Some(ResizeEdge::Right)
 8508    } else {
 8509        None
 8510    }
 8511}
 8512
 8513fn join_pane_into_active(
 8514    active_pane: &Entity<Pane>,
 8515    pane: &Entity<Pane>,
 8516    window: &mut Window,
 8517    cx: &mut App,
 8518) {
 8519    if pane == active_pane {
 8520    } else if pane.read(cx).items_len() == 0 {
 8521        pane.update(cx, |_, cx| {
 8522            cx.emit(pane::Event::Remove {
 8523                focus_on_pane: None,
 8524            });
 8525        })
 8526    } else {
 8527        move_all_items(pane, active_pane, window, cx);
 8528    }
 8529}
 8530
 8531fn move_all_items(
 8532    from_pane: &Entity<Pane>,
 8533    to_pane: &Entity<Pane>,
 8534    window: &mut Window,
 8535    cx: &mut App,
 8536) {
 8537    let destination_is_different = from_pane != to_pane;
 8538    let mut moved_items = 0;
 8539    for (item_ix, item_handle) in from_pane
 8540        .read(cx)
 8541        .items()
 8542        .enumerate()
 8543        .map(|(ix, item)| (ix, item.clone()))
 8544        .collect::<Vec<_>>()
 8545    {
 8546        let ix = item_ix - moved_items;
 8547        if destination_is_different {
 8548            // Close item from previous pane
 8549            from_pane.update(cx, |source, cx| {
 8550                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 8551            });
 8552            moved_items += 1;
 8553        }
 8554
 8555        // This automatically removes duplicate items in the pane
 8556        to_pane.update(cx, |destination, cx| {
 8557            destination.add_item(item_handle, true, true, None, window, cx);
 8558            window.focus(&destination.focus_handle(cx))
 8559        });
 8560    }
 8561}
 8562
 8563pub fn move_item(
 8564    source: &Entity<Pane>,
 8565    destination: &Entity<Pane>,
 8566    item_id_to_move: EntityId,
 8567    destination_index: usize,
 8568    activate: bool,
 8569    window: &mut Window,
 8570    cx: &mut App,
 8571) {
 8572    let Some((item_ix, item_handle)) = source
 8573        .read(cx)
 8574        .items()
 8575        .enumerate()
 8576        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 8577        .map(|(ix, item)| (ix, item.clone()))
 8578    else {
 8579        // Tab was closed during drag
 8580        return;
 8581    };
 8582
 8583    if source != destination {
 8584        // Close item from previous pane
 8585        source.update(cx, |source, cx| {
 8586            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 8587        });
 8588    }
 8589
 8590    // This automatically removes duplicate items in the pane
 8591    destination.update(cx, |destination, cx| {
 8592        destination.add_item_inner(
 8593            item_handle,
 8594            activate,
 8595            activate,
 8596            activate,
 8597            Some(destination_index),
 8598            window,
 8599            cx,
 8600        );
 8601        if activate {
 8602            window.focus(&destination.focus_handle(cx))
 8603        }
 8604    });
 8605}
 8606
 8607pub fn move_active_item(
 8608    source: &Entity<Pane>,
 8609    destination: &Entity<Pane>,
 8610    focus_destination: bool,
 8611    close_if_empty: bool,
 8612    window: &mut Window,
 8613    cx: &mut App,
 8614) {
 8615    if source == destination {
 8616        return;
 8617    }
 8618    let Some(active_item) = source.read(cx).active_item() else {
 8619        return;
 8620    };
 8621    source.update(cx, |source_pane, cx| {
 8622        let item_id = active_item.item_id();
 8623        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 8624        destination.update(cx, |target_pane, cx| {
 8625            target_pane.add_item(
 8626                active_item,
 8627                focus_destination,
 8628                focus_destination,
 8629                Some(target_pane.items_len()),
 8630                window,
 8631                cx,
 8632            );
 8633        });
 8634    });
 8635}
 8636
 8637pub fn clone_active_item(
 8638    workspace_id: Option<WorkspaceId>,
 8639    source: &Entity<Pane>,
 8640    destination: &Entity<Pane>,
 8641    focus_destination: bool,
 8642    window: &mut Window,
 8643    cx: &mut App,
 8644) {
 8645    if source == destination {
 8646        return;
 8647    }
 8648    let Some(active_item) = source.read(cx).active_item() else {
 8649        return;
 8650    };
 8651    if !active_item.can_split(cx) {
 8652        return;
 8653    }
 8654    let destination = destination.downgrade();
 8655    let task = active_item.clone_on_split(workspace_id, window, cx);
 8656    window
 8657        .spawn(cx, async move |cx| {
 8658            let Some(clone) = task.await else {
 8659                return;
 8660            };
 8661            destination
 8662                .update_in(cx, |target_pane, window, cx| {
 8663                    target_pane.add_item(
 8664                        clone,
 8665                        focus_destination,
 8666                        focus_destination,
 8667                        Some(target_pane.items_len()),
 8668                        window,
 8669                        cx,
 8670                    );
 8671                })
 8672                .log_err();
 8673        })
 8674        .detach();
 8675}
 8676
 8677#[derive(Debug)]
 8678pub struct WorkspacePosition {
 8679    pub window_bounds: Option<WindowBounds>,
 8680    pub display: Option<Uuid>,
 8681    pub centered_layout: bool,
 8682}
 8683
 8684pub fn remote_workspace_position_from_db(
 8685    connection_options: RemoteConnectionOptions,
 8686    paths_to_open: &[PathBuf],
 8687    cx: &App,
 8688) -> Task<Result<WorkspacePosition>> {
 8689    let paths = paths_to_open.to_vec();
 8690
 8691    cx.background_spawn(async move {
 8692        let remote_connection_id = persistence::DB
 8693            .get_or_create_remote_connection(connection_options)
 8694            .await
 8695            .context("fetching serialized ssh project")?;
 8696        let serialized_workspace =
 8697            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 8698
 8699        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
 8700            (Some(WindowBounds::Windowed(bounds)), None)
 8701        } else {
 8702            let restorable_bounds = serialized_workspace
 8703                .as_ref()
 8704                .and_then(|workspace| Some((workspace.display?, workspace.window_bounds?)))
 8705                .or_else(|| {
 8706                    let (display, window_bounds) = DB.last_window().log_err()?;
 8707                    Some((display?, window_bounds?))
 8708                });
 8709
 8710            if let Some((serialized_display, serialized_status)) = restorable_bounds {
 8711                (Some(serialized_status.0), Some(serialized_display))
 8712            } else {
 8713                (None, None)
 8714            }
 8715        };
 8716
 8717        let centered_layout = serialized_workspace
 8718            .as_ref()
 8719            .map(|w| w.centered_layout)
 8720            .unwrap_or(false);
 8721
 8722        Ok(WorkspacePosition {
 8723            window_bounds,
 8724            display,
 8725            centered_layout,
 8726        })
 8727    })
 8728}
 8729
 8730pub fn with_active_or_new_workspace(
 8731    cx: &mut App,
 8732    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
 8733) {
 8734    match cx.active_window().and_then(|w| w.downcast::<Workspace>()) {
 8735        Some(workspace) => {
 8736            cx.defer(move |cx| {
 8737                workspace
 8738                    .update(cx, |workspace, window, cx| f(workspace, window, cx))
 8739                    .log_err();
 8740            });
 8741        }
 8742        None => {
 8743            let app_state = AppState::global(cx);
 8744            if let Some(app_state) = app_state.upgrade() {
 8745                open_new(
 8746                    OpenOptions::default(),
 8747                    app_state,
 8748                    cx,
 8749                    move |workspace, window, cx| f(workspace, window, cx),
 8750                )
 8751                .detach_and_log_err(cx);
 8752            }
 8753        }
 8754    }
 8755}
 8756
 8757#[cfg(test)]
 8758mod tests {
 8759    use std::{cell::RefCell, rc::Rc};
 8760
 8761    use super::*;
 8762    use crate::{
 8763        dock::{PanelEvent, test::TestPanel},
 8764        item::{
 8765            ItemBufferKind, ItemEvent,
 8766            test::{TestItem, TestProjectItem},
 8767        },
 8768    };
 8769    use fs::FakeFs;
 8770    use gpui::{
 8771        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
 8772        UpdateGlobal, VisualTestContext, px,
 8773    };
 8774    use project::{Project, ProjectEntryId};
 8775    use serde_json::json;
 8776    use settings::SettingsStore;
 8777    use util::rel_path::rel_path;
 8778
 8779    #[gpui::test]
 8780    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
 8781        init_test(cx);
 8782
 8783        let fs = FakeFs::new(cx.executor());
 8784        let project = Project::test(fs, [], cx).await;
 8785        let (workspace, cx) =
 8786            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8787
 8788        // Adding an item with no ambiguity renders the tab without detail.
 8789        let item1 = cx.new(|cx| {
 8790            let mut item = TestItem::new(cx);
 8791            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
 8792            item
 8793        });
 8794        workspace.update_in(cx, |workspace, window, cx| {
 8795            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8796        });
 8797        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
 8798
 8799        // Adding an item that creates ambiguity increases the level of detail on
 8800        // both tabs.
 8801        let item2 = cx.new_window_entity(|_window, cx| {
 8802            let mut item = TestItem::new(cx);
 8803            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 8804            item
 8805        });
 8806        workspace.update_in(cx, |workspace, window, cx| {
 8807            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8808        });
 8809        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8810        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8811
 8812        // Adding an item that creates ambiguity increases the level of detail only
 8813        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
 8814        // we stop at the highest detail available.
 8815        let item3 = cx.new(|cx| {
 8816            let mut item = TestItem::new(cx);
 8817            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 8818            item
 8819        });
 8820        workspace.update_in(cx, |workspace, window, cx| {
 8821            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8822        });
 8823        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8824        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 8825        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 8826    }
 8827
 8828    #[gpui::test]
 8829    async fn test_tracking_active_path(cx: &mut TestAppContext) {
 8830        init_test(cx);
 8831
 8832        let fs = FakeFs::new(cx.executor());
 8833        fs.insert_tree(
 8834            "/root1",
 8835            json!({
 8836                "one.txt": "",
 8837                "two.txt": "",
 8838            }),
 8839        )
 8840        .await;
 8841        fs.insert_tree(
 8842            "/root2",
 8843            json!({
 8844                "three.txt": "",
 8845            }),
 8846        )
 8847        .await;
 8848
 8849        let project = Project::test(fs, ["root1".as_ref()], cx).await;
 8850        let (workspace, cx) =
 8851            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8852        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8853        let worktree_id = project.update(cx, |project, cx| {
 8854            project.worktrees(cx).next().unwrap().read(cx).id()
 8855        });
 8856
 8857        let item1 = cx.new(|cx| {
 8858            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
 8859        });
 8860        let item2 = cx.new(|cx| {
 8861            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
 8862        });
 8863
 8864        // Add an item to an empty pane
 8865        workspace.update_in(cx, |workspace, window, cx| {
 8866            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
 8867        });
 8868        project.update(cx, |project, cx| {
 8869            assert_eq!(
 8870                project.active_entry(),
 8871                project
 8872                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 8873                    .map(|e| e.id)
 8874            );
 8875        });
 8876        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 8877
 8878        // Add a second item to a non-empty pane
 8879        workspace.update_in(cx, |workspace, window, cx| {
 8880            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
 8881        });
 8882        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
 8883        project.update(cx, |project, cx| {
 8884            assert_eq!(
 8885                project.active_entry(),
 8886                project
 8887                    .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
 8888                    .map(|e| e.id)
 8889            );
 8890        });
 8891
 8892        // Close the active item
 8893        pane.update_in(cx, |pane, window, cx| {
 8894            pane.close_active_item(&Default::default(), window, cx)
 8895        })
 8896        .await
 8897        .unwrap();
 8898        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 8899        project.update(cx, |project, cx| {
 8900            assert_eq!(
 8901                project.active_entry(),
 8902                project
 8903                    .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
 8904                    .map(|e| e.id)
 8905            );
 8906        });
 8907
 8908        // Add a project folder
 8909        project
 8910            .update(cx, |project, cx| {
 8911                project.find_or_create_worktree("root2", true, cx)
 8912            })
 8913            .await
 8914            .unwrap();
 8915        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
 8916
 8917        // Remove a project folder
 8918        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
 8919        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
 8920    }
 8921
 8922    #[gpui::test]
 8923    async fn test_close_window(cx: &mut TestAppContext) {
 8924        init_test(cx);
 8925
 8926        let fs = FakeFs::new(cx.executor());
 8927        fs.insert_tree("/root", json!({ "one": "" })).await;
 8928
 8929        let project = Project::test(fs, ["root".as_ref()], cx).await;
 8930        let (workspace, cx) =
 8931            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8932
 8933        // When there are no dirty items, there's nothing to do.
 8934        let item1 = cx.new(TestItem::new);
 8935        workspace.update_in(cx, |w, window, cx| {
 8936            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
 8937        });
 8938        let task = workspace.update_in(cx, |w, window, cx| {
 8939            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8940        });
 8941        assert!(task.await.unwrap());
 8942
 8943        // When there are dirty untitled items, prompt to save each one. If the user
 8944        // cancels any prompt, then abort.
 8945        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
 8946        let item3 = cx.new(|cx| {
 8947            TestItem::new(cx)
 8948                .with_dirty(true)
 8949                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8950        });
 8951        workspace.update_in(cx, |w, window, cx| {
 8952            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8953            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8954        });
 8955        let task = workspace.update_in(cx, |w, window, cx| {
 8956            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8957        });
 8958        cx.executor().run_until_parked();
 8959        cx.simulate_prompt_answer("Cancel"); // cancel save all
 8960        cx.executor().run_until_parked();
 8961        assert!(!cx.has_pending_prompt());
 8962        assert!(!task.await.unwrap());
 8963    }
 8964
 8965    #[gpui::test]
 8966    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
 8967        init_test(cx);
 8968
 8969        // Register TestItem as a serializable item
 8970        cx.update(|cx| {
 8971            register_serializable_item::<TestItem>(cx);
 8972        });
 8973
 8974        let fs = FakeFs::new(cx.executor());
 8975        fs.insert_tree("/root", json!({ "one": "" })).await;
 8976
 8977        let project = Project::test(fs, ["root".as_ref()], cx).await;
 8978        let (workspace, cx) =
 8979            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8980
 8981        // When there are dirty untitled items, but they can serialize, then there is no prompt.
 8982        let item1 = cx.new(|cx| {
 8983            TestItem::new(cx)
 8984                .with_dirty(true)
 8985                .with_serialize(|| Some(Task::ready(Ok(()))))
 8986        });
 8987        let item2 = cx.new(|cx| {
 8988            TestItem::new(cx)
 8989                .with_dirty(true)
 8990                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8991                .with_serialize(|| Some(Task::ready(Ok(()))))
 8992        });
 8993        workspace.update_in(cx, |w, window, cx| {
 8994            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8995            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8996        });
 8997        let task = workspace.update_in(cx, |w, window, cx| {
 8998            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8999        });
 9000        assert!(task.await.unwrap());
 9001    }
 9002
 9003    #[gpui::test]
 9004    async fn test_close_pane_items(cx: &mut TestAppContext) {
 9005        init_test(cx);
 9006
 9007        let fs = FakeFs::new(cx.executor());
 9008
 9009        let project = Project::test(fs, None, cx).await;
 9010        let (workspace, cx) =
 9011            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9012
 9013        let item1 = cx.new(|cx| {
 9014            TestItem::new(cx)
 9015                .with_dirty(true)
 9016                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9017        });
 9018        let item2 = cx.new(|cx| {
 9019            TestItem::new(cx)
 9020                .with_dirty(true)
 9021                .with_conflict(true)
 9022                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 9023        });
 9024        let item3 = cx.new(|cx| {
 9025            TestItem::new(cx)
 9026                .with_dirty(true)
 9027                .with_conflict(true)
 9028                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
 9029        });
 9030        let item4 = cx.new(|cx| {
 9031            TestItem::new(cx).with_dirty(true).with_project_items(&[{
 9032                let project_item = TestProjectItem::new_untitled(cx);
 9033                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 9034                project_item
 9035            }])
 9036        });
 9037        let pane = workspace.update_in(cx, |workspace, window, cx| {
 9038            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 9039            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 9040            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 9041            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
 9042            workspace.active_pane().clone()
 9043        });
 9044
 9045        let close_items = pane.update_in(cx, |pane, window, cx| {
 9046            pane.activate_item(1, true, true, window, cx);
 9047            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 9048            let item1_id = item1.item_id();
 9049            let item3_id = item3.item_id();
 9050            let item4_id = item4.item_id();
 9051            pane.close_items(window, cx, SaveIntent::Close, move |id| {
 9052                [item1_id, item3_id, item4_id].contains(&id)
 9053            })
 9054        });
 9055        cx.executor().run_until_parked();
 9056
 9057        assert!(cx.has_pending_prompt());
 9058        cx.simulate_prompt_answer("Save all");
 9059
 9060        cx.executor().run_until_parked();
 9061
 9062        // Item 1 is saved. There's a prompt to save item 3.
 9063        pane.update(cx, |pane, cx| {
 9064            assert_eq!(item1.read(cx).save_count, 1);
 9065            assert_eq!(item1.read(cx).save_as_count, 0);
 9066            assert_eq!(item1.read(cx).reload_count, 0);
 9067            assert_eq!(pane.items_len(), 3);
 9068            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
 9069        });
 9070        assert!(cx.has_pending_prompt());
 9071
 9072        // Cancel saving item 3.
 9073        cx.simulate_prompt_answer("Discard");
 9074        cx.executor().run_until_parked();
 9075
 9076        // Item 3 is reloaded. There's a prompt to save item 4.
 9077        pane.update(cx, |pane, cx| {
 9078            assert_eq!(item3.read(cx).save_count, 0);
 9079            assert_eq!(item3.read(cx).save_as_count, 0);
 9080            assert_eq!(item3.read(cx).reload_count, 1);
 9081            assert_eq!(pane.items_len(), 2);
 9082            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
 9083        });
 9084
 9085        // There's a prompt for a path for item 4.
 9086        cx.simulate_new_path_selection(|_| Some(Default::default()));
 9087        close_items.await.unwrap();
 9088
 9089        // The requested items are closed.
 9090        pane.update(cx, |pane, cx| {
 9091            assert_eq!(item4.read(cx).save_count, 0);
 9092            assert_eq!(item4.read(cx).save_as_count, 1);
 9093            assert_eq!(item4.read(cx).reload_count, 0);
 9094            assert_eq!(pane.items_len(), 1);
 9095            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 9096        });
 9097    }
 9098
 9099    #[gpui::test]
 9100    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
 9101        init_test(cx);
 9102
 9103        let fs = FakeFs::new(cx.executor());
 9104        let project = Project::test(fs, [], cx).await;
 9105        let (workspace, cx) =
 9106            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9107
 9108        // Create several workspace items with single project entries, and two
 9109        // workspace items with multiple project entries.
 9110        let single_entry_items = (0..=4)
 9111            .map(|project_entry_id| {
 9112                cx.new(|cx| {
 9113                    TestItem::new(cx)
 9114                        .with_dirty(true)
 9115                        .with_project_items(&[dirty_project_item(
 9116                            project_entry_id,
 9117                            &format!("{project_entry_id}.txt"),
 9118                            cx,
 9119                        )])
 9120                })
 9121            })
 9122            .collect::<Vec<_>>();
 9123        let item_2_3 = cx.new(|cx| {
 9124            TestItem::new(cx)
 9125                .with_dirty(true)
 9126                .with_buffer_kind(ItemBufferKind::Multibuffer)
 9127                .with_project_items(&[
 9128                    single_entry_items[2].read(cx).project_items[0].clone(),
 9129                    single_entry_items[3].read(cx).project_items[0].clone(),
 9130                ])
 9131        });
 9132        let item_3_4 = cx.new(|cx| {
 9133            TestItem::new(cx)
 9134                .with_dirty(true)
 9135                .with_buffer_kind(ItemBufferKind::Multibuffer)
 9136                .with_project_items(&[
 9137                    single_entry_items[3].read(cx).project_items[0].clone(),
 9138                    single_entry_items[4].read(cx).project_items[0].clone(),
 9139                ])
 9140        });
 9141
 9142        // Create two panes that contain the following project entries:
 9143        //   left pane:
 9144        //     multi-entry items:   (2, 3)
 9145        //     single-entry items:  0, 2, 3, 4
 9146        //   right pane:
 9147        //     single-entry items:  4, 1
 9148        //     multi-entry items:   (3, 4)
 9149        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
 9150            let left_pane = workspace.active_pane().clone();
 9151            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
 9152            workspace.add_item_to_active_pane(
 9153                single_entry_items[0].boxed_clone(),
 9154                None,
 9155                true,
 9156                window,
 9157                cx,
 9158            );
 9159            workspace.add_item_to_active_pane(
 9160                single_entry_items[2].boxed_clone(),
 9161                None,
 9162                true,
 9163                window,
 9164                cx,
 9165            );
 9166            workspace.add_item_to_active_pane(
 9167                single_entry_items[3].boxed_clone(),
 9168                None,
 9169                true,
 9170                window,
 9171                cx,
 9172            );
 9173            workspace.add_item_to_active_pane(
 9174                single_entry_items[4].boxed_clone(),
 9175                None,
 9176                true,
 9177                window,
 9178                cx,
 9179            );
 9180
 9181            let right_pane =
 9182                workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
 9183
 9184            let boxed_clone = single_entry_items[1].boxed_clone();
 9185            let right_pane = window.spawn(cx, async move |cx| {
 9186                right_pane.await.inspect(|right_pane| {
 9187                    right_pane
 9188                        .update_in(cx, |pane, window, cx| {
 9189                            pane.add_item(boxed_clone, true, true, None, window, cx);
 9190                            pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
 9191                        })
 9192                        .unwrap();
 9193                })
 9194            });
 9195
 9196            (left_pane, right_pane)
 9197        });
 9198        let right_pane = right_pane.await.unwrap();
 9199        cx.focus(&right_pane);
 9200
 9201        let mut close = right_pane.update_in(cx, |pane, window, cx| {
 9202            pane.close_all_items(&CloseAllItems::default(), window, cx)
 9203                .unwrap()
 9204        });
 9205        cx.executor().run_until_parked();
 9206
 9207        let msg = cx.pending_prompt().unwrap().0;
 9208        assert!(msg.contains("1.txt"));
 9209        assert!(!msg.contains("2.txt"));
 9210        assert!(!msg.contains("3.txt"));
 9211        assert!(!msg.contains("4.txt"));
 9212
 9213        cx.simulate_prompt_answer("Cancel");
 9214        close.await;
 9215
 9216        left_pane
 9217            .update_in(cx, |left_pane, window, cx| {
 9218                left_pane.close_item_by_id(
 9219                    single_entry_items[3].entity_id(),
 9220                    SaveIntent::Skip,
 9221                    window,
 9222                    cx,
 9223                )
 9224            })
 9225            .await
 9226            .unwrap();
 9227
 9228        close = right_pane.update_in(cx, |pane, window, cx| {
 9229            pane.close_all_items(&CloseAllItems::default(), window, cx)
 9230                .unwrap()
 9231        });
 9232        cx.executor().run_until_parked();
 9233
 9234        let details = cx.pending_prompt().unwrap().1;
 9235        assert!(details.contains("1.txt"));
 9236        assert!(!details.contains("2.txt"));
 9237        assert!(details.contains("3.txt"));
 9238        // ideally this assertion could be made, but today we can only
 9239        // save whole items not project items, so the orphaned item 3 causes
 9240        // 4 to be saved too.
 9241        // assert!(!details.contains("4.txt"));
 9242
 9243        cx.simulate_prompt_answer("Save all");
 9244
 9245        cx.executor().run_until_parked();
 9246        close.await;
 9247        right_pane.read_with(cx, |pane, _| {
 9248            assert_eq!(pane.items_len(), 0);
 9249        });
 9250    }
 9251
 9252    #[gpui::test]
 9253    async fn test_autosave(cx: &mut gpui::TestAppContext) {
 9254        init_test(cx);
 9255
 9256        let fs = FakeFs::new(cx.executor());
 9257        let project = Project::test(fs, [], cx).await;
 9258        let (workspace, cx) =
 9259            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9260        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9261
 9262        let item = cx.new(|cx| {
 9263            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 9264        });
 9265        let item_id = item.entity_id();
 9266        workspace.update_in(cx, |workspace, window, cx| {
 9267            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9268        });
 9269
 9270        // Autosave on window change.
 9271        item.update(cx, |item, cx| {
 9272            SettingsStore::update_global(cx, |settings, cx| {
 9273                settings.update_user_settings(cx, |settings| {
 9274                    settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
 9275                })
 9276            });
 9277            item.is_dirty = true;
 9278        });
 9279
 9280        // Deactivating the window saves the file.
 9281        cx.deactivate_window();
 9282        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 9283
 9284        // Re-activating the window doesn't save the file.
 9285        cx.update(|window, _| window.activate_window());
 9286        cx.executor().run_until_parked();
 9287        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 9288
 9289        // Autosave on focus change.
 9290        item.update_in(cx, |item, window, cx| {
 9291            cx.focus_self(window);
 9292            SettingsStore::update_global(cx, |settings, cx| {
 9293                settings.update_user_settings(cx, |settings| {
 9294                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
 9295                })
 9296            });
 9297            item.is_dirty = true;
 9298        });
 9299        // Blurring the item saves the file.
 9300        item.update_in(cx, |_, window, _| window.blur());
 9301        cx.executor().run_until_parked();
 9302        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
 9303
 9304        // Deactivating the window still saves the file.
 9305        item.update_in(cx, |item, window, cx| {
 9306            cx.focus_self(window);
 9307            item.is_dirty = true;
 9308        });
 9309        cx.deactivate_window();
 9310        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
 9311
 9312        // Autosave after delay.
 9313        item.update(cx, |item, cx| {
 9314            SettingsStore::update_global(cx, |settings, cx| {
 9315                settings.update_user_settings(cx, |settings| {
 9316                    settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
 9317                        milliseconds: 500.into(),
 9318                    });
 9319                })
 9320            });
 9321            item.is_dirty = true;
 9322            cx.emit(ItemEvent::Edit);
 9323        });
 9324
 9325        // Delay hasn't fully expired, so the file is still dirty and unsaved.
 9326        cx.executor().advance_clock(Duration::from_millis(250));
 9327        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
 9328
 9329        // After delay expires, the file is saved.
 9330        cx.executor().advance_clock(Duration::from_millis(250));
 9331        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
 9332
 9333        // Autosave after delay, should save earlier than delay if tab is closed
 9334        item.update(cx, |item, cx| {
 9335            item.is_dirty = true;
 9336            cx.emit(ItemEvent::Edit);
 9337        });
 9338        cx.executor().advance_clock(Duration::from_millis(250));
 9339        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
 9340
 9341        // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
 9342        pane.update_in(cx, |pane, window, cx| {
 9343            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 9344        })
 9345        .await
 9346        .unwrap();
 9347        assert!(!cx.has_pending_prompt());
 9348        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 9349
 9350        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
 9351        workspace.update_in(cx, |workspace, window, cx| {
 9352            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9353        });
 9354        item.update_in(cx, |item, _window, cx| {
 9355            item.is_dirty = true;
 9356            for project_item in &mut item.project_items {
 9357                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 9358            }
 9359        });
 9360        cx.run_until_parked();
 9361        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 9362
 9363        // Autosave on focus change, ensuring closing the tab counts as such.
 9364        item.update(cx, |item, cx| {
 9365            SettingsStore::update_global(cx, |settings, cx| {
 9366                settings.update_user_settings(cx, |settings| {
 9367                    settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
 9368                })
 9369            });
 9370            item.is_dirty = true;
 9371            for project_item in &mut item.project_items {
 9372                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 9373            }
 9374        });
 9375
 9376        pane.update_in(cx, |pane, window, cx| {
 9377            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 9378        })
 9379        .await
 9380        .unwrap();
 9381        assert!(!cx.has_pending_prompt());
 9382        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 9383
 9384        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
 9385        workspace.update_in(cx, |workspace, window, cx| {
 9386            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9387        });
 9388        item.update_in(cx, |item, window, cx| {
 9389            item.project_items[0].update(cx, |item, _| {
 9390                item.entry_id = None;
 9391            });
 9392            item.is_dirty = true;
 9393            window.blur();
 9394        });
 9395        cx.run_until_parked();
 9396        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 9397
 9398        // Ensure autosave is prevented for deleted files also when closing the buffer.
 9399        let _close_items = pane.update_in(cx, |pane, window, cx| {
 9400            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 9401        });
 9402        cx.run_until_parked();
 9403        assert!(cx.has_pending_prompt());
 9404        item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
 9405    }
 9406
 9407    #[gpui::test]
 9408    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
 9409        init_test(cx);
 9410
 9411        let fs = FakeFs::new(cx.executor());
 9412
 9413        let project = Project::test(fs, [], cx).await;
 9414        let (workspace, cx) =
 9415            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9416
 9417        let item = cx.new(|cx| {
 9418            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 9419        });
 9420        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9421        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
 9422        let toolbar_notify_count = Rc::new(RefCell::new(0));
 9423
 9424        workspace.update_in(cx, |workspace, window, cx| {
 9425            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 9426            let toolbar_notification_count = toolbar_notify_count.clone();
 9427            cx.observe_in(&toolbar, window, move |_, _, _, _| {
 9428                *toolbar_notification_count.borrow_mut() += 1
 9429            })
 9430            .detach();
 9431        });
 9432
 9433        pane.read_with(cx, |pane, _| {
 9434            assert!(!pane.can_navigate_backward());
 9435            assert!(!pane.can_navigate_forward());
 9436        });
 9437
 9438        item.update_in(cx, |item, _, cx| {
 9439            item.set_state("one".to_string(), cx);
 9440        });
 9441
 9442        // Toolbar must be notified to re-render the navigation buttons
 9443        assert_eq!(*toolbar_notify_count.borrow(), 1);
 9444
 9445        pane.read_with(cx, |pane, _| {
 9446            assert!(pane.can_navigate_backward());
 9447            assert!(!pane.can_navigate_forward());
 9448        });
 9449
 9450        workspace
 9451            .update_in(cx, |workspace, window, cx| {
 9452                workspace.go_back(pane.downgrade(), window, cx)
 9453            })
 9454            .await
 9455            .unwrap();
 9456
 9457        assert_eq!(*toolbar_notify_count.borrow(), 2);
 9458        pane.read_with(cx, |pane, _| {
 9459            assert!(!pane.can_navigate_backward());
 9460            assert!(pane.can_navigate_forward());
 9461        });
 9462    }
 9463
 9464    #[gpui::test]
 9465    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
 9466        init_test(cx);
 9467        let fs = FakeFs::new(cx.executor());
 9468
 9469        let project = Project::test(fs, [], cx).await;
 9470        let (workspace, cx) =
 9471            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9472
 9473        let panel = workspace.update_in(cx, |workspace, window, cx| {
 9474            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
 9475            workspace.add_panel(panel.clone(), window, cx);
 9476
 9477            workspace
 9478                .right_dock()
 9479                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
 9480
 9481            panel
 9482        });
 9483
 9484        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9485        pane.update_in(cx, |pane, window, cx| {
 9486            let item = cx.new(TestItem::new);
 9487            pane.add_item(Box::new(item), true, true, None, window, cx);
 9488        });
 9489
 9490        // Transfer focus from center to panel
 9491        workspace.update_in(cx, |workspace, window, cx| {
 9492            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9493        });
 9494
 9495        workspace.update_in(cx, |workspace, window, cx| {
 9496            assert!(workspace.right_dock().read(cx).is_open());
 9497            assert!(!panel.is_zoomed(window, cx));
 9498            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9499        });
 9500
 9501        // Transfer focus from panel to center
 9502        workspace.update_in(cx, |workspace, window, cx| {
 9503            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9504        });
 9505
 9506        workspace.update_in(cx, |workspace, window, cx| {
 9507            assert!(workspace.right_dock().read(cx).is_open());
 9508            assert!(!panel.is_zoomed(window, cx));
 9509            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9510        });
 9511
 9512        // Close the dock
 9513        workspace.update_in(cx, |workspace, window, cx| {
 9514            workspace.toggle_dock(DockPosition::Right, window, cx);
 9515        });
 9516
 9517        workspace.update_in(cx, |workspace, window, cx| {
 9518            assert!(!workspace.right_dock().read(cx).is_open());
 9519            assert!(!panel.is_zoomed(window, cx));
 9520            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9521        });
 9522
 9523        // Open the dock
 9524        workspace.update_in(cx, |workspace, window, cx| {
 9525            workspace.toggle_dock(DockPosition::Right, window, cx);
 9526        });
 9527
 9528        workspace.update_in(cx, |workspace, window, cx| {
 9529            assert!(workspace.right_dock().read(cx).is_open());
 9530            assert!(!panel.is_zoomed(window, cx));
 9531            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9532        });
 9533
 9534        // Focus and zoom panel
 9535        panel.update_in(cx, |panel, window, cx| {
 9536            cx.focus_self(window);
 9537            panel.set_zoomed(true, window, cx)
 9538        });
 9539
 9540        workspace.update_in(cx, |workspace, window, cx| {
 9541            assert!(workspace.right_dock().read(cx).is_open());
 9542            assert!(panel.is_zoomed(window, cx));
 9543            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9544        });
 9545
 9546        // Transfer focus to the center closes the dock
 9547        workspace.update_in(cx, |workspace, window, cx| {
 9548            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9549        });
 9550
 9551        workspace.update_in(cx, |workspace, window, cx| {
 9552            assert!(!workspace.right_dock().read(cx).is_open());
 9553            assert!(panel.is_zoomed(window, cx));
 9554            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9555        });
 9556
 9557        // Transferring focus back to the panel keeps it zoomed
 9558        workspace.update_in(cx, |workspace, window, cx| {
 9559            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 9560        });
 9561
 9562        workspace.update_in(cx, |workspace, window, cx| {
 9563            assert!(workspace.right_dock().read(cx).is_open());
 9564            assert!(panel.is_zoomed(window, cx));
 9565            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9566        });
 9567
 9568        // Close the dock while it is zoomed
 9569        workspace.update_in(cx, |workspace, window, cx| {
 9570            workspace.toggle_dock(DockPosition::Right, window, cx)
 9571        });
 9572
 9573        workspace.update_in(cx, |workspace, window, cx| {
 9574            assert!(!workspace.right_dock().read(cx).is_open());
 9575            assert!(panel.is_zoomed(window, cx));
 9576            assert!(workspace.zoomed.is_none());
 9577            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9578        });
 9579
 9580        // Opening the dock, when it's zoomed, retains focus
 9581        workspace.update_in(cx, |workspace, window, cx| {
 9582            workspace.toggle_dock(DockPosition::Right, window, cx)
 9583        });
 9584
 9585        workspace.update_in(cx, |workspace, window, cx| {
 9586            assert!(workspace.right_dock().read(cx).is_open());
 9587            assert!(panel.is_zoomed(window, cx));
 9588            assert!(workspace.zoomed.is_some());
 9589            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 9590        });
 9591
 9592        // Unzoom and close the panel, zoom the active pane.
 9593        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
 9594        workspace.update_in(cx, |workspace, window, cx| {
 9595            workspace.toggle_dock(DockPosition::Right, window, cx)
 9596        });
 9597        pane.update_in(cx, |pane, window, cx| {
 9598            pane.toggle_zoom(&Default::default(), window, cx)
 9599        });
 9600
 9601        // Opening a dock unzooms the pane.
 9602        workspace.update_in(cx, |workspace, window, cx| {
 9603            workspace.toggle_dock(DockPosition::Right, window, cx)
 9604        });
 9605        workspace.update_in(cx, |workspace, window, cx| {
 9606            let pane = pane.read(cx);
 9607            assert!(!pane.is_zoomed());
 9608            assert!(!pane.focus_handle(cx).is_focused(window));
 9609            assert!(workspace.right_dock().read(cx).is_open());
 9610            assert!(workspace.zoomed.is_none());
 9611        });
 9612    }
 9613
 9614    #[gpui::test]
 9615    async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
 9616        init_test(cx);
 9617        let fs = FakeFs::new(cx.executor());
 9618
 9619        let project = Project::test(fs, [], cx).await;
 9620        let (workspace, cx) =
 9621            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9622
 9623        let pane = workspace.update_in(cx, |workspace, _window, _cx| {
 9624            workspace.active_pane().clone()
 9625        });
 9626
 9627        // Add an item to the pane so it can be zoomed
 9628        workspace.update_in(cx, |workspace, window, cx| {
 9629            let item = cx.new(TestItem::new);
 9630            workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
 9631        });
 9632
 9633        // Initially not zoomed
 9634        workspace.update_in(cx, |workspace, _window, cx| {
 9635            assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
 9636            assert!(
 9637                workspace.zoomed.is_none(),
 9638                "Workspace should track no zoomed pane"
 9639            );
 9640            assert!(pane.read(cx).items_len() > 0, "Pane should have items");
 9641        });
 9642
 9643        // Zoom In
 9644        pane.update_in(cx, |pane, window, cx| {
 9645            pane.zoom_in(&crate::ZoomIn, window, cx);
 9646        });
 9647
 9648        workspace.update_in(cx, |workspace, window, cx| {
 9649            assert!(
 9650                pane.read(cx).is_zoomed(),
 9651                "Pane should be zoomed after ZoomIn"
 9652            );
 9653            assert!(
 9654                workspace.zoomed.is_some(),
 9655                "Workspace should track the zoomed pane"
 9656            );
 9657            assert!(
 9658                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
 9659                "ZoomIn should focus the pane"
 9660            );
 9661        });
 9662
 9663        // Zoom In again is a no-op
 9664        pane.update_in(cx, |pane, window, cx| {
 9665            pane.zoom_in(&crate::ZoomIn, window, cx);
 9666        });
 9667
 9668        workspace.update_in(cx, |workspace, window, cx| {
 9669            assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
 9670            assert!(
 9671                workspace.zoomed.is_some(),
 9672                "Workspace still tracks zoomed pane"
 9673            );
 9674            assert!(
 9675                pane.read(cx).focus_handle(cx).contains_focused(window, cx),
 9676                "Pane remains focused after repeated ZoomIn"
 9677            );
 9678        });
 9679
 9680        // Zoom Out
 9681        pane.update_in(cx, |pane, window, cx| {
 9682            pane.zoom_out(&crate::ZoomOut, window, cx);
 9683        });
 9684
 9685        workspace.update_in(cx, |workspace, _window, cx| {
 9686            assert!(
 9687                !pane.read(cx).is_zoomed(),
 9688                "Pane should unzoom after ZoomOut"
 9689            );
 9690            assert!(
 9691                workspace.zoomed.is_none(),
 9692                "Workspace clears zoom tracking after ZoomOut"
 9693            );
 9694        });
 9695
 9696        // Zoom Out again is a no-op
 9697        pane.update_in(cx, |pane, window, cx| {
 9698            pane.zoom_out(&crate::ZoomOut, window, cx);
 9699        });
 9700
 9701        workspace.update_in(cx, |workspace, _window, cx| {
 9702            assert!(
 9703                !pane.read(cx).is_zoomed(),
 9704                "Second ZoomOut keeps pane unzoomed"
 9705            );
 9706            assert!(
 9707                workspace.zoomed.is_none(),
 9708                "Workspace remains without zoomed pane"
 9709            );
 9710        });
 9711    }
 9712
 9713    #[gpui::test]
 9714    async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
 9715        init_test(cx);
 9716        let fs = FakeFs::new(cx.executor());
 9717
 9718        let project = Project::test(fs, [], cx).await;
 9719        let (workspace, cx) =
 9720            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9721        workspace.update_in(cx, |workspace, window, cx| {
 9722            // Open two docks
 9723            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9724            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9725
 9726            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 9727            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 9728
 9729            assert!(left_dock.read(cx).is_open());
 9730            assert!(right_dock.read(cx).is_open());
 9731        });
 9732
 9733        workspace.update_in(cx, |workspace, window, cx| {
 9734            // Toggle all docks - should close both
 9735            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
 9736
 9737            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9738            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9739            assert!(!left_dock.read(cx).is_open());
 9740            assert!(!right_dock.read(cx).is_open());
 9741        });
 9742
 9743        workspace.update_in(cx, |workspace, window, cx| {
 9744            // Toggle again - should reopen both
 9745            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
 9746
 9747            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9748            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9749            assert!(left_dock.read(cx).is_open());
 9750            assert!(right_dock.read(cx).is_open());
 9751        });
 9752    }
 9753
 9754    #[gpui::test]
 9755    async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
 9756        init_test(cx);
 9757        let fs = FakeFs::new(cx.executor());
 9758
 9759        let project = Project::test(fs, [], cx).await;
 9760        let (workspace, cx) =
 9761            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9762        workspace.update_in(cx, |workspace, window, cx| {
 9763            // Open two docks
 9764            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9765            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9766
 9767            left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 9768            right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
 9769
 9770            assert!(left_dock.read(cx).is_open());
 9771            assert!(right_dock.read(cx).is_open());
 9772        });
 9773
 9774        workspace.update_in(cx, |workspace, window, cx| {
 9775            // Close them manually
 9776            workspace.toggle_dock(DockPosition::Left, window, cx);
 9777            workspace.toggle_dock(DockPosition::Right, window, cx);
 9778
 9779            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9780            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9781            assert!(!left_dock.read(cx).is_open());
 9782            assert!(!right_dock.read(cx).is_open());
 9783        });
 9784
 9785        workspace.update_in(cx, |workspace, window, cx| {
 9786            // Toggle all docks - only last closed (right dock) should reopen
 9787            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
 9788
 9789            let left_dock = workspace.dock_at_position(DockPosition::Left);
 9790            let right_dock = workspace.dock_at_position(DockPosition::Right);
 9791            assert!(!left_dock.read(cx).is_open());
 9792            assert!(right_dock.read(cx).is_open());
 9793        });
 9794    }
 9795
 9796    #[gpui::test]
 9797    async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
 9798        init_test(cx);
 9799        let fs = FakeFs::new(cx.executor());
 9800        let project = Project::test(fs, [], cx).await;
 9801        let (workspace, cx) =
 9802            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9803
 9804        // Open two docks (left and right) with one panel each
 9805        let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
 9806            let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
 9807            workspace.add_panel(left_panel.clone(), window, cx);
 9808
 9809            let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
 9810            workspace.add_panel(right_panel.clone(), window, cx);
 9811
 9812            workspace.toggle_dock(DockPosition::Left, window, cx);
 9813            workspace.toggle_dock(DockPosition::Right, window, cx);
 9814
 9815            // Verify initial state
 9816            assert!(
 9817                workspace.left_dock().read(cx).is_open(),
 9818                "Left dock should be open"
 9819            );
 9820            assert_eq!(
 9821                workspace
 9822                    .left_dock()
 9823                    .read(cx)
 9824                    .visible_panel()
 9825                    .unwrap()
 9826                    .panel_id(),
 9827                left_panel.panel_id(),
 9828                "Left panel should be visible in left dock"
 9829            );
 9830            assert!(
 9831                workspace.right_dock().read(cx).is_open(),
 9832                "Right dock should be open"
 9833            );
 9834            assert_eq!(
 9835                workspace
 9836                    .right_dock()
 9837                    .read(cx)
 9838                    .visible_panel()
 9839                    .unwrap()
 9840                    .panel_id(),
 9841                right_panel.panel_id(),
 9842                "Right panel should be visible in right dock"
 9843            );
 9844            assert!(
 9845                !workspace.bottom_dock().read(cx).is_open(),
 9846                "Bottom dock should be closed"
 9847            );
 9848
 9849            (left_panel, right_panel)
 9850        });
 9851
 9852        // Focus the left panel and move it to the next position (bottom dock)
 9853        workspace.update_in(cx, |workspace, window, cx| {
 9854            workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
 9855            assert!(
 9856                left_panel.read(cx).focus_handle(cx).is_focused(window),
 9857                "Left panel should be focused"
 9858            );
 9859        });
 9860
 9861        cx.dispatch_action(MoveFocusedPanelToNextPosition);
 9862
 9863        // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
 9864        workspace.update(cx, |workspace, cx| {
 9865            assert!(
 9866                !workspace.left_dock().read(cx).is_open(),
 9867                "Left dock should be closed"
 9868            );
 9869            assert!(
 9870                workspace.bottom_dock().read(cx).is_open(),
 9871                "Bottom dock should now be open"
 9872            );
 9873            assert_eq!(
 9874                left_panel.read(cx).position,
 9875                DockPosition::Bottom,
 9876                "Left panel should now be in the bottom dock"
 9877            );
 9878            assert_eq!(
 9879                workspace
 9880                    .bottom_dock()
 9881                    .read(cx)
 9882                    .visible_panel()
 9883                    .unwrap()
 9884                    .panel_id(),
 9885                left_panel.panel_id(),
 9886                "Left panel should be the visible panel in the bottom dock"
 9887            );
 9888        });
 9889
 9890        // Toggle all docks off
 9891        workspace.update_in(cx, |workspace, window, cx| {
 9892            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
 9893            assert!(
 9894                !workspace.left_dock().read(cx).is_open(),
 9895                "Left dock should be closed"
 9896            );
 9897            assert!(
 9898                !workspace.right_dock().read(cx).is_open(),
 9899                "Right dock should be closed"
 9900            );
 9901            assert!(
 9902                !workspace.bottom_dock().read(cx).is_open(),
 9903                "Bottom dock should be closed"
 9904            );
 9905        });
 9906
 9907        // Toggle all docks back on and verify positions are restored
 9908        workspace.update_in(cx, |workspace, window, cx| {
 9909            workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
 9910            assert!(
 9911                !workspace.left_dock().read(cx).is_open(),
 9912                "Left dock should remain closed"
 9913            );
 9914            assert!(
 9915                workspace.right_dock().read(cx).is_open(),
 9916                "Right dock should remain open"
 9917            );
 9918            assert!(
 9919                workspace.bottom_dock().read(cx).is_open(),
 9920                "Bottom dock should remain open"
 9921            );
 9922            assert_eq!(
 9923                left_panel.read(cx).position,
 9924                DockPosition::Bottom,
 9925                "Left panel should remain in the bottom dock"
 9926            );
 9927            assert_eq!(
 9928                right_panel.read(cx).position,
 9929                DockPosition::Right,
 9930                "Right panel should remain in the right dock"
 9931            );
 9932            assert_eq!(
 9933                workspace
 9934                    .bottom_dock()
 9935                    .read(cx)
 9936                    .visible_panel()
 9937                    .unwrap()
 9938                    .panel_id(),
 9939                left_panel.panel_id(),
 9940                "Left panel should be the visible panel in the right dock"
 9941            );
 9942        });
 9943    }
 9944
 9945    #[gpui::test]
 9946    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
 9947        init_test(cx);
 9948
 9949        let fs = FakeFs::new(cx.executor());
 9950
 9951        let project = Project::test(fs, None, cx).await;
 9952        let (workspace, cx) =
 9953            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9954
 9955        // Let's arrange the panes like this:
 9956        //
 9957        // +-----------------------+
 9958        // |         top           |
 9959        // +------+--------+-------+
 9960        // | left | center | right |
 9961        // +------+--------+-------+
 9962        // |        bottom         |
 9963        // +-----------------------+
 9964
 9965        let top_item = cx.new(|cx| {
 9966            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
 9967        });
 9968        let bottom_item = cx.new(|cx| {
 9969            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
 9970        });
 9971        let left_item = cx.new(|cx| {
 9972            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
 9973        });
 9974        let right_item = cx.new(|cx| {
 9975            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
 9976        });
 9977        let center_item = cx.new(|cx| {
 9978            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
 9979        });
 9980
 9981        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9982            let top_pane_id = workspace.active_pane().entity_id();
 9983            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
 9984            workspace.split_pane(
 9985                workspace.active_pane().clone(),
 9986                SplitDirection::Down,
 9987                window,
 9988                cx,
 9989            );
 9990            top_pane_id
 9991        });
 9992        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 9993            let bottom_pane_id = workspace.active_pane().entity_id();
 9994            workspace.add_item_to_active_pane(
 9995                Box::new(bottom_item.clone()),
 9996                None,
 9997                false,
 9998                window,
 9999                cx,
10000            );
10001            workspace.split_pane(
10002                workspace.active_pane().clone(),
10003                SplitDirection::Up,
10004                window,
10005                cx,
10006            );
10007            bottom_pane_id
10008        });
10009        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10010            let left_pane_id = workspace.active_pane().entity_id();
10011            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
10012            workspace.split_pane(
10013                workspace.active_pane().clone(),
10014                SplitDirection::Right,
10015                window,
10016                cx,
10017            );
10018            left_pane_id
10019        });
10020        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10021            let right_pane_id = workspace.active_pane().entity_id();
10022            workspace.add_item_to_active_pane(
10023                Box::new(right_item.clone()),
10024                None,
10025                false,
10026                window,
10027                cx,
10028            );
10029            workspace.split_pane(
10030                workspace.active_pane().clone(),
10031                SplitDirection::Left,
10032                window,
10033                cx,
10034            );
10035            right_pane_id
10036        });
10037        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
10038            let center_pane_id = workspace.active_pane().entity_id();
10039            workspace.add_item_to_active_pane(
10040                Box::new(center_item.clone()),
10041                None,
10042                false,
10043                window,
10044                cx,
10045            );
10046            center_pane_id
10047        });
10048        cx.executor().run_until_parked();
10049
10050        workspace.update_in(cx, |workspace, window, cx| {
10051            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
10052
10053            // Join into next from center pane into right
10054            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10055        });
10056
10057        workspace.update_in(cx, |workspace, window, cx| {
10058            let active_pane = workspace.active_pane();
10059            assert_eq!(right_pane_id, active_pane.entity_id());
10060            assert_eq!(2, active_pane.read(cx).items_len());
10061            let item_ids_in_pane =
10062                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10063            assert!(item_ids_in_pane.contains(&center_item.item_id()));
10064            assert!(item_ids_in_pane.contains(&right_item.item_id()));
10065
10066            // Join into next from right pane into bottom
10067            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10068        });
10069
10070        workspace.update_in(cx, |workspace, window, cx| {
10071            let active_pane = workspace.active_pane();
10072            assert_eq!(bottom_pane_id, active_pane.entity_id());
10073            assert_eq!(3, active_pane.read(cx).items_len());
10074            let item_ids_in_pane =
10075                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10076            assert!(item_ids_in_pane.contains(&center_item.item_id()));
10077            assert!(item_ids_in_pane.contains(&right_item.item_id()));
10078            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10079
10080            // Join into next from bottom pane into left
10081            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10082        });
10083
10084        workspace.update_in(cx, |workspace, window, cx| {
10085            let active_pane = workspace.active_pane();
10086            assert_eq!(left_pane_id, active_pane.entity_id());
10087            assert_eq!(4, active_pane.read(cx).items_len());
10088            let item_ids_in_pane =
10089                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10090            assert!(item_ids_in_pane.contains(&center_item.item_id()));
10091            assert!(item_ids_in_pane.contains(&right_item.item_id()));
10092            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10093            assert!(item_ids_in_pane.contains(&left_item.item_id()));
10094
10095            // Join into next from left pane into top
10096            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
10097        });
10098
10099        workspace.update_in(cx, |workspace, window, cx| {
10100            let active_pane = workspace.active_pane();
10101            assert_eq!(top_pane_id, active_pane.entity_id());
10102            assert_eq!(5, active_pane.read(cx).items_len());
10103            let item_ids_in_pane =
10104                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
10105            assert!(item_ids_in_pane.contains(&center_item.item_id()));
10106            assert!(item_ids_in_pane.contains(&right_item.item_id()));
10107            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
10108            assert!(item_ids_in_pane.contains(&left_item.item_id()));
10109            assert!(item_ids_in_pane.contains(&top_item.item_id()));
10110
10111            // Single pane left: no-op
10112            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
10113        });
10114
10115        workspace.update(cx, |workspace, _cx| {
10116            let active_pane = workspace.active_pane();
10117            assert_eq!(top_pane_id, active_pane.entity_id());
10118        });
10119    }
10120
10121    fn add_an_item_to_active_pane(
10122        cx: &mut VisualTestContext,
10123        workspace: &Entity<Workspace>,
10124        item_id: u64,
10125    ) -> Entity<TestItem> {
10126        let item = cx.new(|cx| {
10127            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
10128                item_id,
10129                "item{item_id}.txt",
10130                cx,
10131            )])
10132        });
10133        workspace.update_in(cx, |workspace, window, cx| {
10134            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
10135        });
10136        item
10137    }
10138
10139    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
10140        workspace.update_in(cx, |workspace, window, cx| {
10141            workspace.split_pane(
10142                workspace.active_pane().clone(),
10143                SplitDirection::Right,
10144                window,
10145                cx,
10146            )
10147        })
10148    }
10149
10150    #[gpui::test]
10151    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
10152        init_test(cx);
10153        let fs = FakeFs::new(cx.executor());
10154        let project = Project::test(fs, None, cx).await;
10155        let (workspace, cx) =
10156            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10157
10158        add_an_item_to_active_pane(cx, &workspace, 1);
10159        split_pane(cx, &workspace);
10160        add_an_item_to_active_pane(cx, &workspace, 2);
10161        split_pane(cx, &workspace); // empty pane
10162        split_pane(cx, &workspace);
10163        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
10164
10165        cx.executor().run_until_parked();
10166
10167        workspace.update(cx, |workspace, cx| {
10168            let num_panes = workspace.panes().len();
10169            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
10170            let active_item = workspace
10171                .active_pane()
10172                .read(cx)
10173                .active_item()
10174                .expect("item is in focus");
10175
10176            assert_eq!(num_panes, 4);
10177            assert_eq!(num_items_in_current_pane, 1);
10178            assert_eq!(active_item.item_id(), last_item.item_id());
10179        });
10180
10181        workspace.update_in(cx, |workspace, window, cx| {
10182            workspace.join_all_panes(window, cx);
10183        });
10184
10185        workspace.update(cx, |workspace, cx| {
10186            let num_panes = workspace.panes().len();
10187            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
10188            let active_item = workspace
10189                .active_pane()
10190                .read(cx)
10191                .active_item()
10192                .expect("item is in focus");
10193
10194            assert_eq!(num_panes, 1);
10195            assert_eq!(num_items_in_current_pane, 3);
10196            assert_eq!(active_item.item_id(), last_item.item_id());
10197        });
10198    }
10199    struct TestModal(FocusHandle);
10200
10201    impl TestModal {
10202        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
10203            Self(cx.focus_handle())
10204        }
10205    }
10206
10207    impl EventEmitter<DismissEvent> for TestModal {}
10208
10209    impl Focusable for TestModal {
10210        fn focus_handle(&self, _cx: &App) -> FocusHandle {
10211            self.0.clone()
10212        }
10213    }
10214
10215    impl ModalView for TestModal {}
10216
10217    impl Render for TestModal {
10218        fn render(
10219            &mut self,
10220            _window: &mut Window,
10221            _cx: &mut Context<TestModal>,
10222        ) -> impl IntoElement {
10223            div().track_focus(&self.0)
10224        }
10225    }
10226
10227    #[gpui::test]
10228    async fn test_panels(cx: &mut gpui::TestAppContext) {
10229        init_test(cx);
10230        let fs = FakeFs::new(cx.executor());
10231
10232        let project = Project::test(fs, [], cx).await;
10233        let (workspace, cx) =
10234            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10235
10236        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
10237            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
10238            workspace.add_panel(panel_1.clone(), window, cx);
10239            workspace.toggle_dock(DockPosition::Left, window, cx);
10240            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
10241            workspace.add_panel(panel_2.clone(), window, cx);
10242            workspace.toggle_dock(DockPosition::Right, window, cx);
10243
10244            let left_dock = workspace.left_dock();
10245            assert_eq!(
10246                left_dock.read(cx).visible_panel().unwrap().panel_id(),
10247                panel_1.panel_id()
10248            );
10249            assert_eq!(
10250                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
10251                panel_1.size(window, cx)
10252            );
10253
10254            left_dock.update(cx, |left_dock, cx| {
10255                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
10256            });
10257            assert_eq!(
10258                workspace
10259                    .right_dock()
10260                    .read(cx)
10261                    .visible_panel()
10262                    .unwrap()
10263                    .panel_id(),
10264                panel_2.panel_id(),
10265            );
10266
10267            (panel_1, panel_2)
10268        });
10269
10270        // Move panel_1 to the right
10271        panel_1.update_in(cx, |panel_1, window, cx| {
10272            panel_1.set_position(DockPosition::Right, window, cx)
10273        });
10274
10275        workspace.update_in(cx, |workspace, window, cx| {
10276            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
10277            // Since it was the only panel on the left, the left dock should now be closed.
10278            assert!(!workspace.left_dock().read(cx).is_open());
10279            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
10280            let right_dock = workspace.right_dock();
10281            assert_eq!(
10282                right_dock.read(cx).visible_panel().unwrap().panel_id(),
10283                panel_1.panel_id()
10284            );
10285            assert_eq!(
10286                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
10287                px(1337.)
10288            );
10289
10290            // Now we move panel_2 to the left
10291            panel_2.set_position(DockPosition::Left, window, cx);
10292        });
10293
10294        workspace.update(cx, |workspace, cx| {
10295            // Since panel_2 was not visible on the right, we don't open the left dock.
10296            assert!(!workspace.left_dock().read(cx).is_open());
10297            // And the right dock is unaffected in its displaying of panel_1
10298            assert!(workspace.right_dock().read(cx).is_open());
10299            assert_eq!(
10300                workspace
10301                    .right_dock()
10302                    .read(cx)
10303                    .visible_panel()
10304                    .unwrap()
10305                    .panel_id(),
10306                panel_1.panel_id(),
10307            );
10308        });
10309
10310        // Move panel_1 back to the left
10311        panel_1.update_in(cx, |panel_1, window, cx| {
10312            panel_1.set_position(DockPosition::Left, window, cx)
10313        });
10314
10315        workspace.update_in(cx, |workspace, window, cx| {
10316            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
10317            let left_dock = workspace.left_dock();
10318            assert!(left_dock.read(cx).is_open());
10319            assert_eq!(
10320                left_dock.read(cx).visible_panel().unwrap().panel_id(),
10321                panel_1.panel_id()
10322            );
10323            assert_eq!(
10324                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
10325                px(1337.)
10326            );
10327            // And the right dock should be closed as it no longer has any panels.
10328            assert!(!workspace.right_dock().read(cx).is_open());
10329
10330            // Now we move panel_1 to the bottom
10331            panel_1.set_position(DockPosition::Bottom, window, cx);
10332        });
10333
10334        workspace.update_in(cx, |workspace, window, cx| {
10335            // Since panel_1 was visible on the left, we close the left dock.
10336            assert!(!workspace.left_dock().read(cx).is_open());
10337            // The bottom dock is sized based on the panel's default size,
10338            // since the panel orientation changed from vertical to horizontal.
10339            let bottom_dock = workspace.bottom_dock();
10340            assert_eq!(
10341                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
10342                panel_1.size(window, cx),
10343            );
10344            // Close bottom dock and move panel_1 back to the left.
10345            bottom_dock.update(cx, |bottom_dock, cx| {
10346                bottom_dock.set_open(false, window, cx)
10347            });
10348            panel_1.set_position(DockPosition::Left, window, cx);
10349        });
10350
10351        // Emit activated event on panel 1
10352        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
10353
10354        // Now the left dock is open and panel_1 is active and focused.
10355        workspace.update_in(cx, |workspace, window, cx| {
10356            let left_dock = workspace.left_dock();
10357            assert!(left_dock.read(cx).is_open());
10358            assert_eq!(
10359                left_dock.read(cx).visible_panel().unwrap().panel_id(),
10360                panel_1.panel_id(),
10361            );
10362            assert!(panel_1.focus_handle(cx).is_focused(window));
10363        });
10364
10365        // Emit closed event on panel 2, which is not active
10366        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
10367
10368        // Wo don't close the left dock, because panel_2 wasn't the active panel
10369        workspace.update(cx, |workspace, cx| {
10370            let left_dock = workspace.left_dock();
10371            assert!(left_dock.read(cx).is_open());
10372            assert_eq!(
10373                left_dock.read(cx).visible_panel().unwrap().panel_id(),
10374                panel_1.panel_id(),
10375            );
10376        });
10377
10378        // Emitting a ZoomIn event shows the panel as zoomed.
10379        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
10380        workspace.read_with(cx, |workspace, _| {
10381            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10382            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
10383        });
10384
10385        // Move panel to another dock while it is zoomed
10386        panel_1.update_in(cx, |panel, window, cx| {
10387            panel.set_position(DockPosition::Right, window, cx)
10388        });
10389        workspace.read_with(cx, |workspace, _| {
10390            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10391
10392            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10393        });
10394
10395        // This is a helper for getting a:
10396        // - valid focus on an element,
10397        // - that isn't a part of the panes and panels system of the Workspace,
10398        // - and doesn't trigger the 'on_focus_lost' API.
10399        let focus_other_view = {
10400            let workspace = workspace.clone();
10401            move |cx: &mut VisualTestContext| {
10402                workspace.update_in(cx, |workspace, window, cx| {
10403                    if workspace.active_modal::<TestModal>(cx).is_some() {
10404                        workspace.toggle_modal(window, cx, TestModal::new);
10405                        workspace.toggle_modal(window, cx, TestModal::new);
10406                    } else {
10407                        workspace.toggle_modal(window, cx, TestModal::new);
10408                    }
10409                })
10410            }
10411        };
10412
10413        // If focus is transferred to another view that's not a panel or another pane, we still show
10414        // the panel as zoomed.
10415        focus_other_view(cx);
10416        workspace.read_with(cx, |workspace, _| {
10417            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10418            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10419        });
10420
10421        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
10422        workspace.update_in(cx, |_workspace, window, cx| {
10423            cx.focus_self(window);
10424        });
10425        workspace.read_with(cx, |workspace, _| {
10426            assert_eq!(workspace.zoomed, None);
10427            assert_eq!(workspace.zoomed_position, None);
10428        });
10429
10430        // If focus is transferred again to another view that's not a panel or a pane, we won't
10431        // show the panel as zoomed because it wasn't zoomed before.
10432        focus_other_view(cx);
10433        workspace.read_with(cx, |workspace, _| {
10434            assert_eq!(workspace.zoomed, None);
10435            assert_eq!(workspace.zoomed_position, None);
10436        });
10437
10438        // When the panel is activated, it is zoomed again.
10439        cx.dispatch_action(ToggleRightDock);
10440        workspace.read_with(cx, |workspace, _| {
10441            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
10442            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
10443        });
10444
10445        // Emitting a ZoomOut event unzooms the panel.
10446        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
10447        workspace.read_with(cx, |workspace, _| {
10448            assert_eq!(workspace.zoomed, None);
10449            assert_eq!(workspace.zoomed_position, None);
10450        });
10451
10452        // Emit closed event on panel 1, which is active
10453        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
10454
10455        // Now the left dock is closed, because panel_1 was the active panel
10456        workspace.update(cx, |workspace, cx| {
10457            let right_dock = workspace.right_dock();
10458            assert!(!right_dock.read(cx).is_open());
10459        });
10460    }
10461
10462    #[gpui::test]
10463    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
10464        init_test(cx);
10465
10466        let fs = FakeFs::new(cx.background_executor.clone());
10467        let project = Project::test(fs, [], cx).await;
10468        let (workspace, cx) =
10469            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10470        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10471
10472        let dirty_regular_buffer = cx.new(|cx| {
10473            TestItem::new(cx)
10474                .with_dirty(true)
10475                .with_label("1.txt")
10476                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10477        });
10478        let dirty_regular_buffer_2 = cx.new(|cx| {
10479            TestItem::new(cx)
10480                .with_dirty(true)
10481                .with_label("2.txt")
10482                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10483        });
10484        let dirty_multi_buffer_with_both = cx.new(|cx| {
10485            TestItem::new(cx)
10486                .with_dirty(true)
10487                .with_buffer_kind(ItemBufferKind::Multibuffer)
10488                .with_label("Fake Project Search")
10489                .with_project_items(&[
10490                    dirty_regular_buffer.read(cx).project_items[0].clone(),
10491                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10492                ])
10493        });
10494        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
10495        workspace.update_in(cx, |workspace, window, cx| {
10496            workspace.add_item(
10497                pane.clone(),
10498                Box::new(dirty_regular_buffer.clone()),
10499                None,
10500                false,
10501                false,
10502                window,
10503                cx,
10504            );
10505            workspace.add_item(
10506                pane.clone(),
10507                Box::new(dirty_regular_buffer_2.clone()),
10508                None,
10509                false,
10510                false,
10511                window,
10512                cx,
10513            );
10514            workspace.add_item(
10515                pane.clone(),
10516                Box::new(dirty_multi_buffer_with_both.clone()),
10517                None,
10518                false,
10519                false,
10520                window,
10521                cx,
10522            );
10523        });
10524
10525        pane.update_in(cx, |pane, window, cx| {
10526            pane.activate_item(2, true, true, window, cx);
10527            assert_eq!(
10528                pane.active_item().unwrap().item_id(),
10529                multi_buffer_with_both_files_id,
10530                "Should select the multi buffer in the pane"
10531            );
10532        });
10533        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10534            pane.close_other_items(
10535                &CloseOtherItems {
10536                    save_intent: Some(SaveIntent::Save),
10537                    close_pinned: true,
10538                },
10539                None,
10540                window,
10541                cx,
10542            )
10543        });
10544        cx.background_executor.run_until_parked();
10545        assert!(!cx.has_pending_prompt());
10546        close_all_but_multi_buffer_task
10547            .await
10548            .expect("Closing all buffers but the multi buffer failed");
10549        pane.update(cx, |pane, cx| {
10550            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
10551            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
10552            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
10553            assert_eq!(pane.items_len(), 1);
10554            assert_eq!(
10555                pane.active_item().unwrap().item_id(),
10556                multi_buffer_with_both_files_id,
10557                "Should have only the multi buffer left in the pane"
10558            );
10559            assert!(
10560                dirty_multi_buffer_with_both.read(cx).is_dirty,
10561                "The multi buffer containing the unsaved buffer should still be dirty"
10562            );
10563        });
10564
10565        dirty_regular_buffer.update(cx, |buffer, cx| {
10566            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
10567        });
10568
10569        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10570            pane.close_active_item(
10571                &CloseActiveItem {
10572                    save_intent: Some(SaveIntent::Close),
10573                    close_pinned: false,
10574                },
10575                window,
10576                cx,
10577            )
10578        });
10579        cx.background_executor.run_until_parked();
10580        assert!(
10581            cx.has_pending_prompt(),
10582            "Dirty multi buffer should prompt a save dialog"
10583        );
10584        cx.simulate_prompt_answer("Save");
10585        cx.background_executor.run_until_parked();
10586        close_multi_buffer_task
10587            .await
10588            .expect("Closing the multi buffer failed");
10589        pane.update(cx, |pane, cx| {
10590            assert_eq!(
10591                dirty_multi_buffer_with_both.read(cx).save_count,
10592                1,
10593                "Multi buffer item should get be saved"
10594            );
10595            // Test impl does not save inner items, so we do not assert them
10596            assert_eq!(
10597                pane.items_len(),
10598                0,
10599                "No more items should be left in the pane"
10600            );
10601            assert!(pane.active_item().is_none());
10602        });
10603    }
10604
10605    #[gpui::test]
10606    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
10607        cx: &mut TestAppContext,
10608    ) {
10609        init_test(cx);
10610
10611        let fs = FakeFs::new(cx.background_executor.clone());
10612        let project = Project::test(fs, [], cx).await;
10613        let (workspace, cx) =
10614            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10615        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10616
10617        let dirty_regular_buffer = cx.new(|cx| {
10618            TestItem::new(cx)
10619                .with_dirty(true)
10620                .with_label("1.txt")
10621                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10622        });
10623        let dirty_regular_buffer_2 = cx.new(|cx| {
10624            TestItem::new(cx)
10625                .with_dirty(true)
10626                .with_label("2.txt")
10627                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10628        });
10629        let clear_regular_buffer = cx.new(|cx| {
10630            TestItem::new(cx)
10631                .with_label("3.txt")
10632                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
10633        });
10634
10635        let dirty_multi_buffer_with_both = cx.new(|cx| {
10636            TestItem::new(cx)
10637                .with_dirty(true)
10638                .with_buffer_kind(ItemBufferKind::Multibuffer)
10639                .with_label("Fake Project Search")
10640                .with_project_items(&[
10641                    dirty_regular_buffer.read(cx).project_items[0].clone(),
10642                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10643                    clear_regular_buffer.read(cx).project_items[0].clone(),
10644                ])
10645        });
10646        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
10647        workspace.update_in(cx, |workspace, window, cx| {
10648            workspace.add_item(
10649                pane.clone(),
10650                Box::new(dirty_regular_buffer.clone()),
10651                None,
10652                false,
10653                false,
10654                window,
10655                cx,
10656            );
10657            workspace.add_item(
10658                pane.clone(),
10659                Box::new(dirty_multi_buffer_with_both.clone()),
10660                None,
10661                false,
10662                false,
10663                window,
10664                cx,
10665            );
10666        });
10667
10668        pane.update_in(cx, |pane, window, cx| {
10669            pane.activate_item(1, true, true, window, cx);
10670            assert_eq!(
10671                pane.active_item().unwrap().item_id(),
10672                multi_buffer_with_both_files_id,
10673                "Should select the multi buffer in the pane"
10674            );
10675        });
10676        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10677            pane.close_active_item(
10678                &CloseActiveItem {
10679                    save_intent: None,
10680                    close_pinned: false,
10681                },
10682                window,
10683                cx,
10684            )
10685        });
10686        cx.background_executor.run_until_parked();
10687        assert!(
10688            cx.has_pending_prompt(),
10689            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
10690        );
10691    }
10692
10693    /// Tests that when `close_on_file_delete` is enabled, files are automatically
10694    /// closed when they are deleted from disk.
10695    #[gpui::test]
10696    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
10697        init_test(cx);
10698
10699        // Enable the close_on_disk_deletion setting
10700        cx.update_global(|store: &mut SettingsStore, cx| {
10701            store.update_user_settings(cx, |settings| {
10702                settings.workspace.close_on_file_delete = Some(true);
10703            });
10704        });
10705
10706        let fs = FakeFs::new(cx.background_executor.clone());
10707        let project = Project::test(fs, [], cx).await;
10708        let (workspace, cx) =
10709            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10710        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10711
10712        // Create a test item that simulates a file
10713        let item = cx.new(|cx| {
10714            TestItem::new(cx)
10715                .with_label("test.txt")
10716                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10717        });
10718
10719        // Add item to workspace
10720        workspace.update_in(cx, |workspace, window, cx| {
10721            workspace.add_item(
10722                pane.clone(),
10723                Box::new(item.clone()),
10724                None,
10725                false,
10726                false,
10727                window,
10728                cx,
10729            );
10730        });
10731
10732        // Verify the item is in the pane
10733        pane.read_with(cx, |pane, _| {
10734            assert_eq!(pane.items().count(), 1);
10735        });
10736
10737        // Simulate file deletion by setting the item's deleted state
10738        item.update(cx, |item, _| {
10739            item.set_has_deleted_file(true);
10740        });
10741
10742        // Emit UpdateTab event to trigger the close behavior
10743        cx.run_until_parked();
10744        item.update(cx, |_, cx| {
10745            cx.emit(ItemEvent::UpdateTab);
10746        });
10747
10748        // Allow the close operation to complete
10749        cx.run_until_parked();
10750
10751        // Verify the item was automatically closed
10752        pane.read_with(cx, |pane, _| {
10753            assert_eq!(
10754                pane.items().count(),
10755                0,
10756                "Item should be automatically closed when file is deleted"
10757            );
10758        });
10759    }
10760
10761    /// Tests that when `close_on_file_delete` is disabled (default), files remain
10762    /// open with a strikethrough when they are deleted from disk.
10763    #[gpui::test]
10764    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
10765        init_test(cx);
10766
10767        // Ensure close_on_disk_deletion is disabled (default)
10768        cx.update_global(|store: &mut SettingsStore, cx| {
10769            store.update_user_settings(cx, |settings| {
10770                settings.workspace.close_on_file_delete = Some(false);
10771            });
10772        });
10773
10774        let fs = FakeFs::new(cx.background_executor.clone());
10775        let project = Project::test(fs, [], cx).await;
10776        let (workspace, cx) =
10777            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10778        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10779
10780        // Create a test item that simulates a file
10781        let item = cx.new(|cx| {
10782            TestItem::new(cx)
10783                .with_label("test.txt")
10784                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10785        });
10786
10787        // Add item to workspace
10788        workspace.update_in(cx, |workspace, window, cx| {
10789            workspace.add_item(
10790                pane.clone(),
10791                Box::new(item.clone()),
10792                None,
10793                false,
10794                false,
10795                window,
10796                cx,
10797            );
10798        });
10799
10800        // Verify the item is in the pane
10801        pane.read_with(cx, |pane, _| {
10802            assert_eq!(pane.items().count(), 1);
10803        });
10804
10805        // Simulate file deletion
10806        item.update(cx, |item, _| {
10807            item.set_has_deleted_file(true);
10808        });
10809
10810        // Emit UpdateTab event
10811        cx.run_until_parked();
10812        item.update(cx, |_, cx| {
10813            cx.emit(ItemEvent::UpdateTab);
10814        });
10815
10816        // Allow any potential close operation to complete
10817        cx.run_until_parked();
10818
10819        // Verify the item remains open (with strikethrough)
10820        pane.read_with(cx, |pane, _| {
10821            assert_eq!(
10822                pane.items().count(),
10823                1,
10824                "Item should remain open when close_on_disk_deletion is disabled"
10825            );
10826        });
10827
10828        // Verify the item shows as deleted
10829        item.read_with(cx, |item, _| {
10830            assert!(
10831                item.has_deleted_file,
10832                "Item should be marked as having deleted file"
10833            );
10834        });
10835    }
10836
10837    /// Tests that dirty files are not automatically closed when deleted from disk,
10838    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
10839    /// unsaved changes without being prompted.
10840    #[gpui::test]
10841    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
10842        init_test(cx);
10843
10844        // Enable the close_on_file_delete setting
10845        cx.update_global(|store: &mut SettingsStore, cx| {
10846            store.update_user_settings(cx, |settings| {
10847                settings.workspace.close_on_file_delete = Some(true);
10848            });
10849        });
10850
10851        let fs = FakeFs::new(cx.background_executor.clone());
10852        let project = Project::test(fs, [], cx).await;
10853        let (workspace, cx) =
10854            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10855        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10856
10857        // Create a dirty test item
10858        let item = cx.new(|cx| {
10859            TestItem::new(cx)
10860                .with_dirty(true)
10861                .with_label("test.txt")
10862                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
10863        });
10864
10865        // Add item to workspace
10866        workspace.update_in(cx, |workspace, window, cx| {
10867            workspace.add_item(
10868                pane.clone(),
10869                Box::new(item.clone()),
10870                None,
10871                false,
10872                false,
10873                window,
10874                cx,
10875            );
10876        });
10877
10878        // Simulate file deletion
10879        item.update(cx, |item, _| {
10880            item.set_has_deleted_file(true);
10881        });
10882
10883        // Emit UpdateTab event to trigger the close behavior
10884        cx.run_until_parked();
10885        item.update(cx, |_, cx| {
10886            cx.emit(ItemEvent::UpdateTab);
10887        });
10888
10889        // Allow any potential close operation to complete
10890        cx.run_until_parked();
10891
10892        // Verify the item remains open (dirty files are not auto-closed)
10893        pane.read_with(cx, |pane, _| {
10894            assert_eq!(
10895                pane.items().count(),
10896                1,
10897                "Dirty items should not be automatically closed even when file is deleted"
10898            );
10899        });
10900
10901        // Verify the item is marked as deleted and still dirty
10902        item.read_with(cx, |item, _| {
10903            assert!(
10904                item.has_deleted_file,
10905                "Item should be marked as having deleted file"
10906            );
10907            assert!(item.is_dirty, "Item should still be dirty");
10908        });
10909    }
10910
10911    /// Tests that navigation history is cleaned up when files are auto-closed
10912    /// due to deletion from disk.
10913    #[gpui::test]
10914    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
10915        init_test(cx);
10916
10917        // Enable the close_on_file_delete setting
10918        cx.update_global(|store: &mut SettingsStore, cx| {
10919            store.update_user_settings(cx, |settings| {
10920                settings.workspace.close_on_file_delete = Some(true);
10921            });
10922        });
10923
10924        let fs = FakeFs::new(cx.background_executor.clone());
10925        let project = Project::test(fs, [], cx).await;
10926        let (workspace, cx) =
10927            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10928        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10929
10930        // Create test items
10931        let item1 = cx.new(|cx| {
10932            TestItem::new(cx)
10933                .with_label("test1.txt")
10934                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
10935        });
10936        let item1_id = item1.item_id();
10937
10938        let item2 = cx.new(|cx| {
10939            TestItem::new(cx)
10940                .with_label("test2.txt")
10941                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
10942        });
10943
10944        // Add items to workspace
10945        workspace.update_in(cx, |workspace, window, cx| {
10946            workspace.add_item(
10947                pane.clone(),
10948                Box::new(item1.clone()),
10949                None,
10950                false,
10951                false,
10952                window,
10953                cx,
10954            );
10955            workspace.add_item(
10956                pane.clone(),
10957                Box::new(item2.clone()),
10958                None,
10959                false,
10960                false,
10961                window,
10962                cx,
10963            );
10964        });
10965
10966        // Activate item1 to ensure it gets navigation entries
10967        pane.update_in(cx, |pane, window, cx| {
10968            pane.activate_item(0, true, true, window, cx);
10969        });
10970
10971        // Switch to item2 and back to create navigation history
10972        pane.update_in(cx, |pane, window, cx| {
10973            pane.activate_item(1, true, true, window, cx);
10974        });
10975        cx.run_until_parked();
10976
10977        pane.update_in(cx, |pane, window, cx| {
10978            pane.activate_item(0, true, true, window, cx);
10979        });
10980        cx.run_until_parked();
10981
10982        // Simulate file deletion for item1
10983        item1.update(cx, |item, _| {
10984            item.set_has_deleted_file(true);
10985        });
10986
10987        // Emit UpdateTab event to trigger the close behavior
10988        item1.update(cx, |_, cx| {
10989            cx.emit(ItemEvent::UpdateTab);
10990        });
10991        cx.run_until_parked();
10992
10993        // Verify item1 was closed
10994        pane.read_with(cx, |pane, _| {
10995            assert_eq!(
10996                pane.items().count(),
10997                1,
10998                "Should have 1 item remaining after auto-close"
10999            );
11000        });
11001
11002        // Check navigation history after close
11003        let has_item = pane.read_with(cx, |pane, cx| {
11004            let mut has_item = false;
11005            pane.nav_history().for_each_entry(cx, |entry, _| {
11006                if entry.item.id() == item1_id {
11007                    has_item = true;
11008                }
11009            });
11010            has_item
11011        });
11012
11013        assert!(
11014            !has_item,
11015            "Navigation history should not contain closed item entries"
11016        );
11017    }
11018
11019    #[gpui::test]
11020    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
11021        cx: &mut TestAppContext,
11022    ) {
11023        init_test(cx);
11024
11025        let fs = FakeFs::new(cx.background_executor.clone());
11026        let project = Project::test(fs, [], cx).await;
11027        let (workspace, cx) =
11028            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11029        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11030
11031        let dirty_regular_buffer = cx.new(|cx| {
11032            TestItem::new(cx)
11033                .with_dirty(true)
11034                .with_label("1.txt")
11035                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11036        });
11037        let dirty_regular_buffer_2 = cx.new(|cx| {
11038            TestItem::new(cx)
11039                .with_dirty(true)
11040                .with_label("2.txt")
11041                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11042        });
11043        let clear_regular_buffer = cx.new(|cx| {
11044            TestItem::new(cx)
11045                .with_label("3.txt")
11046                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
11047        });
11048
11049        let dirty_multi_buffer = cx.new(|cx| {
11050            TestItem::new(cx)
11051                .with_dirty(true)
11052                .with_buffer_kind(ItemBufferKind::Multibuffer)
11053                .with_label("Fake Project Search")
11054                .with_project_items(&[
11055                    dirty_regular_buffer.read(cx).project_items[0].clone(),
11056                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
11057                    clear_regular_buffer.read(cx).project_items[0].clone(),
11058                ])
11059        });
11060        workspace.update_in(cx, |workspace, window, cx| {
11061            workspace.add_item(
11062                pane.clone(),
11063                Box::new(dirty_regular_buffer.clone()),
11064                None,
11065                false,
11066                false,
11067                window,
11068                cx,
11069            );
11070            workspace.add_item(
11071                pane.clone(),
11072                Box::new(dirty_regular_buffer_2.clone()),
11073                None,
11074                false,
11075                false,
11076                window,
11077                cx,
11078            );
11079            workspace.add_item(
11080                pane.clone(),
11081                Box::new(dirty_multi_buffer.clone()),
11082                None,
11083                false,
11084                false,
11085                window,
11086                cx,
11087            );
11088        });
11089
11090        pane.update_in(cx, |pane, window, cx| {
11091            pane.activate_item(2, true, true, window, cx);
11092            assert_eq!(
11093                pane.active_item().unwrap().item_id(),
11094                dirty_multi_buffer.item_id(),
11095                "Should select the multi buffer in the pane"
11096            );
11097        });
11098        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
11099            pane.close_active_item(
11100                &CloseActiveItem {
11101                    save_intent: None,
11102                    close_pinned: false,
11103                },
11104                window,
11105                cx,
11106            )
11107        });
11108        cx.background_executor.run_until_parked();
11109        assert!(
11110            !cx.has_pending_prompt(),
11111            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
11112        );
11113        close_multi_buffer_task
11114            .await
11115            .expect("Closing multi buffer failed");
11116        pane.update(cx, |pane, cx| {
11117            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
11118            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
11119            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
11120            assert_eq!(
11121                pane.items()
11122                    .map(|item| item.item_id())
11123                    .sorted()
11124                    .collect::<Vec<_>>(),
11125                vec![
11126                    dirty_regular_buffer.item_id(),
11127                    dirty_regular_buffer_2.item_id(),
11128                ],
11129                "Should have no multi buffer left in the pane"
11130            );
11131            assert!(dirty_regular_buffer.read(cx).is_dirty);
11132            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
11133        });
11134    }
11135
11136    #[gpui::test]
11137    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
11138        init_test(cx);
11139        let fs = FakeFs::new(cx.executor());
11140        let project = Project::test(fs, [], cx).await;
11141        let (workspace, cx) =
11142            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11143
11144        // Add a new panel to the right dock, opening the dock and setting the
11145        // focus to the new panel.
11146        let panel = workspace.update_in(cx, |workspace, window, cx| {
11147            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11148            workspace.add_panel(panel.clone(), window, cx);
11149
11150            workspace
11151                .right_dock()
11152                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11153
11154            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11155
11156            panel
11157        });
11158
11159        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
11160        // panel to the next valid position which, in this case, is the left
11161        // dock.
11162        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11163        workspace.update(cx, |workspace, cx| {
11164            assert!(workspace.left_dock().read(cx).is_open());
11165            assert_eq!(panel.read(cx).position, DockPosition::Left);
11166        });
11167
11168        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
11169        // panel to the next valid position which, in this case, is the bottom
11170        // dock.
11171        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11172        workspace.update(cx, |workspace, cx| {
11173            assert!(workspace.bottom_dock().read(cx).is_open());
11174            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
11175        });
11176
11177        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
11178        // around moving the panel to its initial position, the right dock.
11179        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11180        workspace.update(cx, |workspace, cx| {
11181            assert!(workspace.right_dock().read(cx).is_open());
11182            assert_eq!(panel.read(cx).position, DockPosition::Right);
11183        });
11184
11185        // Remove focus from the panel, ensuring that, if the panel is not
11186        // focused, the `MoveFocusedPanelToNextPosition` action does not update
11187        // the panel's position, so the panel is still in the right dock.
11188        workspace.update_in(cx, |workspace, window, cx| {
11189            workspace.toggle_panel_focus::<TestPanel>(window, cx);
11190        });
11191
11192        cx.dispatch_action(MoveFocusedPanelToNextPosition);
11193        workspace.update(cx, |workspace, cx| {
11194            assert!(workspace.right_dock().read(cx).is_open());
11195            assert_eq!(panel.read(cx).position, DockPosition::Right);
11196        });
11197    }
11198
11199    #[gpui::test]
11200    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
11201        init_test(cx);
11202
11203        let fs = FakeFs::new(cx.executor());
11204        let project = Project::test(fs, [], cx).await;
11205        let (workspace, cx) =
11206            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11207
11208        let item_1 = cx.new(|cx| {
11209            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
11210        });
11211        workspace.update_in(cx, |workspace, window, cx| {
11212            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
11213            workspace.move_item_to_pane_in_direction(
11214                &MoveItemToPaneInDirection {
11215                    direction: SplitDirection::Right,
11216                    focus: true,
11217                    clone: false,
11218                },
11219                window,
11220                cx,
11221            );
11222            workspace.move_item_to_pane_at_index(
11223                &MoveItemToPane {
11224                    destination: 3,
11225                    focus: true,
11226                    clone: false,
11227                },
11228                window,
11229                cx,
11230            );
11231
11232            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
11233            assert_eq!(
11234                pane_items_paths(&workspace.active_pane, cx),
11235                vec!["first.txt".to_string()],
11236                "Single item was not moved anywhere"
11237            );
11238        });
11239
11240        let item_2 = cx.new(|cx| {
11241            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
11242        });
11243        workspace.update_in(cx, |workspace, window, cx| {
11244            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
11245            assert_eq!(
11246                pane_items_paths(&workspace.panes[0], cx),
11247                vec!["first.txt".to_string(), "second.txt".to_string()],
11248            );
11249            workspace.move_item_to_pane_in_direction(
11250                &MoveItemToPaneInDirection {
11251                    direction: SplitDirection::Right,
11252                    focus: true,
11253                    clone: false,
11254                },
11255                window,
11256                cx,
11257            );
11258
11259            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
11260            assert_eq!(
11261                pane_items_paths(&workspace.panes[0], cx),
11262                vec!["first.txt".to_string()],
11263                "After moving, one item should be left in the original pane"
11264            );
11265            assert_eq!(
11266                pane_items_paths(&workspace.panes[1], cx),
11267                vec!["second.txt".to_string()],
11268                "New item should have been moved to the new pane"
11269            );
11270        });
11271
11272        let item_3 = cx.new(|cx| {
11273            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
11274        });
11275        workspace.update_in(cx, |workspace, window, cx| {
11276            let original_pane = workspace.panes[0].clone();
11277            workspace.set_active_pane(&original_pane, window, cx);
11278            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
11279            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
11280            assert_eq!(
11281                pane_items_paths(&workspace.active_pane, cx),
11282                vec!["first.txt".to_string(), "third.txt".to_string()],
11283                "New pane should be ready to move one item out"
11284            );
11285
11286            workspace.move_item_to_pane_at_index(
11287                &MoveItemToPane {
11288                    destination: 3,
11289                    focus: true,
11290                    clone: false,
11291                },
11292                window,
11293                cx,
11294            );
11295            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
11296            assert_eq!(
11297                pane_items_paths(&workspace.active_pane, cx),
11298                vec!["first.txt".to_string()],
11299                "After moving, one item should be left in the original pane"
11300            );
11301            assert_eq!(
11302                pane_items_paths(&workspace.panes[1], cx),
11303                vec!["second.txt".to_string()],
11304                "Previously created pane should be unchanged"
11305            );
11306            assert_eq!(
11307                pane_items_paths(&workspace.panes[2], cx),
11308                vec!["third.txt".to_string()],
11309                "New item should have been moved to the new pane"
11310            );
11311        });
11312    }
11313
11314    #[gpui::test]
11315    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
11316        init_test(cx);
11317
11318        let fs = FakeFs::new(cx.executor());
11319        let project = Project::test(fs, [], cx).await;
11320        let (workspace, cx) =
11321            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11322
11323        let item_1 = cx.new(|cx| {
11324            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
11325        });
11326        workspace.update_in(cx, |workspace, window, cx| {
11327            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
11328            workspace.move_item_to_pane_in_direction(
11329                &MoveItemToPaneInDirection {
11330                    direction: SplitDirection::Right,
11331                    focus: true,
11332                    clone: true,
11333                },
11334                window,
11335                cx,
11336            );
11337            workspace.move_item_to_pane_at_index(
11338                &MoveItemToPane {
11339                    destination: 3,
11340                    focus: true,
11341                    clone: true,
11342                },
11343                window,
11344                cx,
11345            );
11346        });
11347        cx.run_until_parked();
11348
11349        workspace.update(cx, |workspace, cx| {
11350            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
11351            for pane in workspace.panes() {
11352                assert_eq!(
11353                    pane_items_paths(pane, cx),
11354                    vec!["first.txt".to_string()],
11355                    "Single item exists in all panes"
11356                );
11357            }
11358        });
11359
11360        // verify that the active pane has been updated after waiting for the
11361        // pane focus event to fire and resolve
11362        workspace.read_with(cx, |workspace, _app| {
11363            assert_eq!(
11364                workspace.active_pane(),
11365                &workspace.panes[2],
11366                "The third pane should be the active one: {:?}",
11367                workspace.panes
11368            );
11369        })
11370    }
11371
11372    mod register_project_item_tests {
11373
11374        use super::*;
11375
11376        // View
11377        struct TestPngItemView {
11378            focus_handle: FocusHandle,
11379        }
11380        // Model
11381        struct TestPngItem {}
11382
11383        impl project::ProjectItem for TestPngItem {
11384            fn try_open(
11385                _project: &Entity<Project>,
11386                path: &ProjectPath,
11387                cx: &mut App,
11388            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
11389                if path.path.extension().unwrap() == "png" {
11390                    Some(cx.spawn(async move |cx| cx.new(|_| TestPngItem {})))
11391                } else {
11392                    None
11393                }
11394            }
11395
11396            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
11397                None
11398            }
11399
11400            fn project_path(&self, _: &App) -> Option<ProjectPath> {
11401                None
11402            }
11403
11404            fn is_dirty(&self) -> bool {
11405                false
11406            }
11407        }
11408
11409        impl Item for TestPngItemView {
11410            type Event = ();
11411            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11412                "".into()
11413            }
11414        }
11415        impl EventEmitter<()> for TestPngItemView {}
11416        impl Focusable for TestPngItemView {
11417            fn focus_handle(&self, _cx: &App) -> FocusHandle {
11418                self.focus_handle.clone()
11419            }
11420        }
11421
11422        impl Render for TestPngItemView {
11423            fn render(
11424                &mut self,
11425                _window: &mut Window,
11426                _cx: &mut Context<Self>,
11427            ) -> impl IntoElement {
11428                Empty
11429            }
11430        }
11431
11432        impl ProjectItem for TestPngItemView {
11433            type Item = TestPngItem;
11434
11435            fn for_project_item(
11436                _project: Entity<Project>,
11437                _pane: Option<&Pane>,
11438                _item: Entity<Self::Item>,
11439                _: &mut Window,
11440                cx: &mut Context<Self>,
11441            ) -> Self
11442            where
11443                Self: Sized,
11444            {
11445                Self {
11446                    focus_handle: cx.focus_handle(),
11447                }
11448            }
11449        }
11450
11451        // View
11452        struct TestIpynbItemView {
11453            focus_handle: FocusHandle,
11454        }
11455        // Model
11456        struct TestIpynbItem {}
11457
11458        impl project::ProjectItem for TestIpynbItem {
11459            fn try_open(
11460                _project: &Entity<Project>,
11461                path: &ProjectPath,
11462                cx: &mut App,
11463            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
11464                if path.path.extension().unwrap() == "ipynb" {
11465                    Some(cx.spawn(async move |cx| cx.new(|_| TestIpynbItem {})))
11466                } else {
11467                    None
11468                }
11469            }
11470
11471            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
11472                None
11473            }
11474
11475            fn project_path(&self, _: &App) -> Option<ProjectPath> {
11476                None
11477            }
11478
11479            fn is_dirty(&self) -> bool {
11480                false
11481            }
11482        }
11483
11484        impl Item for TestIpynbItemView {
11485            type Event = ();
11486            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11487                "".into()
11488            }
11489        }
11490        impl EventEmitter<()> for TestIpynbItemView {}
11491        impl Focusable for TestIpynbItemView {
11492            fn focus_handle(&self, _cx: &App) -> FocusHandle {
11493                self.focus_handle.clone()
11494            }
11495        }
11496
11497        impl Render for TestIpynbItemView {
11498            fn render(
11499                &mut self,
11500                _window: &mut Window,
11501                _cx: &mut Context<Self>,
11502            ) -> impl IntoElement {
11503                Empty
11504            }
11505        }
11506
11507        impl ProjectItem for TestIpynbItemView {
11508            type Item = TestIpynbItem;
11509
11510            fn for_project_item(
11511                _project: Entity<Project>,
11512                _pane: Option<&Pane>,
11513                _item: Entity<Self::Item>,
11514                _: &mut Window,
11515                cx: &mut Context<Self>,
11516            ) -> Self
11517            where
11518                Self: Sized,
11519            {
11520                Self {
11521                    focus_handle: cx.focus_handle(),
11522                }
11523            }
11524        }
11525
11526        struct TestAlternatePngItemView {
11527            focus_handle: FocusHandle,
11528        }
11529
11530        impl Item for TestAlternatePngItemView {
11531            type Event = ();
11532            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
11533                "".into()
11534            }
11535        }
11536
11537        impl EventEmitter<()> for TestAlternatePngItemView {}
11538        impl Focusable for TestAlternatePngItemView {
11539            fn focus_handle(&self, _cx: &App) -> FocusHandle {
11540                self.focus_handle.clone()
11541            }
11542        }
11543
11544        impl Render for TestAlternatePngItemView {
11545            fn render(
11546                &mut self,
11547                _window: &mut Window,
11548                _cx: &mut Context<Self>,
11549            ) -> impl IntoElement {
11550                Empty
11551            }
11552        }
11553
11554        impl ProjectItem for TestAlternatePngItemView {
11555            type Item = TestPngItem;
11556
11557            fn for_project_item(
11558                _project: Entity<Project>,
11559                _pane: Option<&Pane>,
11560                _item: Entity<Self::Item>,
11561                _: &mut Window,
11562                cx: &mut Context<Self>,
11563            ) -> Self
11564            where
11565                Self: Sized,
11566            {
11567                Self {
11568                    focus_handle: cx.focus_handle(),
11569                }
11570            }
11571        }
11572
11573        #[gpui::test]
11574        async fn test_register_project_item(cx: &mut TestAppContext) {
11575            init_test(cx);
11576
11577            cx.update(|cx| {
11578                register_project_item::<TestPngItemView>(cx);
11579                register_project_item::<TestIpynbItemView>(cx);
11580            });
11581
11582            let fs = FakeFs::new(cx.executor());
11583            fs.insert_tree(
11584                "/root1",
11585                json!({
11586                    "one.png": "BINARYDATAHERE",
11587                    "two.ipynb": "{ totally a notebook }",
11588                    "three.txt": "editing text, sure why not?"
11589                }),
11590            )
11591            .await;
11592
11593            let project = Project::test(fs, ["root1".as_ref()], cx).await;
11594            let (workspace, cx) =
11595                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11596
11597            let worktree_id = project.update(cx, |project, cx| {
11598                project.worktrees(cx).next().unwrap().read(cx).id()
11599            });
11600
11601            let handle = workspace
11602                .update_in(cx, |workspace, window, cx| {
11603                    let project_path = (worktree_id, rel_path("one.png"));
11604                    workspace.open_path(project_path, None, true, window, cx)
11605                })
11606                .await
11607                .unwrap();
11608
11609            // Now we can check if the handle we got back errored or not
11610            assert_eq!(
11611                handle.to_any_view().entity_type(),
11612                TypeId::of::<TestPngItemView>()
11613            );
11614
11615            let handle = workspace
11616                .update_in(cx, |workspace, window, cx| {
11617                    let project_path = (worktree_id, rel_path("two.ipynb"));
11618                    workspace.open_path(project_path, None, true, window, cx)
11619                })
11620                .await
11621                .unwrap();
11622
11623            assert_eq!(
11624                handle.to_any_view().entity_type(),
11625                TypeId::of::<TestIpynbItemView>()
11626            );
11627
11628            let handle = workspace
11629                .update_in(cx, |workspace, window, cx| {
11630                    let project_path = (worktree_id, rel_path("three.txt"));
11631                    workspace.open_path(project_path, None, true, window, cx)
11632                })
11633                .await;
11634            assert!(handle.is_err());
11635        }
11636
11637        #[gpui::test]
11638        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
11639            init_test(cx);
11640
11641            cx.update(|cx| {
11642                register_project_item::<TestPngItemView>(cx);
11643                register_project_item::<TestAlternatePngItemView>(cx);
11644            });
11645
11646            let fs = FakeFs::new(cx.executor());
11647            fs.insert_tree(
11648                "/root1",
11649                json!({
11650                    "one.png": "BINARYDATAHERE",
11651                    "two.ipynb": "{ totally a notebook }",
11652                    "three.txt": "editing text, sure why not?"
11653                }),
11654            )
11655            .await;
11656            let project = Project::test(fs, ["root1".as_ref()], cx).await;
11657            let (workspace, cx) =
11658                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11659            let worktree_id = project.update(cx, |project, cx| {
11660                project.worktrees(cx).next().unwrap().read(cx).id()
11661            });
11662
11663            let handle = workspace
11664                .update_in(cx, |workspace, window, cx| {
11665                    let project_path = (worktree_id, rel_path("one.png"));
11666                    workspace.open_path(project_path, None, true, window, cx)
11667                })
11668                .await
11669                .unwrap();
11670
11671            // This _must_ be the second item registered
11672            assert_eq!(
11673                handle.to_any_view().entity_type(),
11674                TypeId::of::<TestAlternatePngItemView>()
11675            );
11676
11677            let handle = workspace
11678                .update_in(cx, |workspace, window, cx| {
11679                    let project_path = (worktree_id, rel_path("three.txt"));
11680                    workspace.open_path(project_path, None, true, window, cx)
11681                })
11682                .await;
11683            assert!(handle.is_err());
11684        }
11685    }
11686
11687    #[gpui::test]
11688    async fn test_status_bar_visibility(cx: &mut TestAppContext) {
11689        init_test(cx);
11690
11691        let fs = FakeFs::new(cx.executor());
11692        let project = Project::test(fs, [], cx).await;
11693        let (workspace, _cx) =
11694            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11695
11696        // Test with status bar shown (default)
11697        workspace.read_with(cx, |workspace, cx| {
11698            let visible = workspace.status_bar_visible(cx);
11699            assert!(visible, "Status bar should be visible by default");
11700        });
11701
11702        // Test with status bar hidden
11703        cx.update_global(|store: &mut SettingsStore, cx| {
11704            store.update_user_settings(cx, |settings| {
11705                settings.status_bar.get_or_insert_default().show = Some(false);
11706            });
11707        });
11708
11709        workspace.read_with(cx, |workspace, cx| {
11710            let visible = workspace.status_bar_visible(cx);
11711            assert!(!visible, "Status bar should be hidden when show is false");
11712        });
11713
11714        // Test with status bar shown explicitly
11715        cx.update_global(|store: &mut SettingsStore, cx| {
11716            store.update_user_settings(cx, |settings| {
11717                settings.status_bar.get_or_insert_default().show = Some(true);
11718            });
11719        });
11720
11721        workspace.read_with(cx, |workspace, cx| {
11722            let visible = workspace.status_bar_visible(cx);
11723            assert!(visible, "Status bar should be visible when show is true");
11724        });
11725    }
11726
11727    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
11728        pane.read(cx)
11729            .items()
11730            .flat_map(|item| {
11731                item.project_paths(cx)
11732                    .into_iter()
11733                    .map(|path| path.path.display(PathStyle::local()).into_owned())
11734            })
11735            .collect()
11736    }
11737
11738    pub fn init_test(cx: &mut TestAppContext) {
11739        cx.update(|cx| {
11740            let settings_store = SettingsStore::test(cx);
11741            cx.set_global(settings_store);
11742            theme::init(theme::LoadThemes::JustBase, cx);
11743        });
11744    }
11745
11746    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
11747        let item = TestProjectItem::new(id, path, cx);
11748        item.update(cx, |item, _| {
11749            item.is_dirty = true;
11750        });
11751        item
11752    }
11753}