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