workspace.rs

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