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