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