workspace.rs

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