workspace.rs

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