workspace.rs

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