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