workspace.rs

    1pub mod dock;
    2pub mod history_manager;
    3pub mod invalid_buffer_view;
    4pub mod item;
    5mod modal_layer;
    6pub mod notifications;
    7pub mod pane;
    8pub mod pane_group;
    9mod path_list;
   10mod persistence;
   11pub mod searchable;
   12pub mod shared_screen;
   13mod status_bar;
   14pub mod tasks;
   15mod theme_preview;
   16mod toast_layer;
   17mod toolbar;
   18mod workspace_settings;
   19
   20pub use crate::notifications::NotificationFrame;
   21pub use dock::Panel;
   22pub use path_list::PathList;
   23pub use toast_layer::{ToastAction, ToastLayer, ToastView};
   24
   25use anyhow::{Context as _, Result, anyhow};
   26use call::{ActiveCall, call_settings::CallSettings};
   27use client::{
   28    ChannelId, Client, ErrorExt, Status, TypedEnvelope, UserStore,
   29    proto::{self, ErrorCode, PanelId, PeerId},
   30};
   31use collections::{HashMap, HashSet, hash_map};
   32use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
   33use futures::{
   34    Future, FutureExt, StreamExt,
   35    channel::{
   36        mpsc::{self, UnboundedReceiver, UnboundedSender},
   37        oneshot,
   38    },
   39    future::{Shared, try_join_all},
   40};
   41use gpui::{
   42    Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
   43    CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
   44    Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
   45    PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
   46    SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
   47    WindowOptions, actions, canvas, point, relative, size, transparent_black,
   48};
   49pub use history_manager::*;
   50pub use item::{
   51    FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
   52    ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
   53};
   54use itertools::Itertools;
   55use language::{
   56    Buffer, LanguageRegistry, Rope,
   57    language_settings::{AllLanguageSettings, all_language_settings},
   58};
   59pub use modal_layer::*;
   60use node_runtime::NodeRuntime;
   61use notifications::{
   62    DetachAndPromptErr, Notifications, dismiss_app_notification,
   63    simple_message_notification::MessageNotification,
   64};
   65pub use pane::*;
   66pub use pane_group::*;
   67use persistence::{DB, SerializedWindowBounds, model::SerializedWorkspace};
   68pub use persistence::{
   69    DB as WORKSPACE_DB, WorkspaceDb, delete_unloaded_items,
   70    model::{ItemId, SerializedWorkspaceLocation},
   71};
   72use postage::stream::Stream;
   73use project::{
   74    DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
   75    debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
   76};
   77use remote::{RemoteClientDelegate, RemoteConnectionOptions, 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) => {
  652                            if e.error_code() == ErrorCode::Internal {
  653                                if let Some(abs_path) =
  654                                    entry_abs_path.as_deref().filter(|_| is_file)
  655                                {
  656                                    if let Some(broken_project_item_view) =
  657                                        cx.update(|window, cx| {
  658                                            T::for_broken_project_item(
  659                                                abs_path, is_local, &e, window, cx,
  660                                            )
  661                                        })?
  662                                    {
  663                                        let build_workspace_item = Box::new(
  664                                            move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
  665                                                cx.new(|_| broken_project_item_view).boxed_clone()
  666                                            },
  667                                        )
  668                                        as Box<_>;
  669                                        return Ok((None, build_workspace_item));
  670                                    }
  671                                }
  672                            }
  673                            Err(e)
  674                        }
  675                    }
  676                }))
  677            });
  678    }
  679
  680    fn open_path(
  681        &self,
  682        project: &Entity<Project>,
  683        path: &ProjectPath,
  684        window: &mut Window,
  685        cx: &mut App,
  686    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
  687        let Some(open_project_item) = self
  688            .build_project_item_for_path_fns
  689            .iter()
  690            .rev()
  691            .find_map(|open_project_item| open_project_item(project, path, window, cx))
  692        else {
  693            return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
  694        };
  695        open_project_item
  696    }
  697
  698    fn build_item<T: project::ProjectItem>(
  699        &self,
  700        item: Entity<T>,
  701        project: Entity<Project>,
  702        pane: Option<&Pane>,
  703        window: &mut Window,
  704        cx: &mut App,
  705    ) -> Option<Box<dyn ItemHandle>> {
  706        let build = self
  707            .build_project_item_fns_by_type
  708            .get(&TypeId::of::<T>())?;
  709        Some(build(item.into_any(), project, pane, window, cx))
  710    }
  711}
  712
  713type WorkspaceItemBuilder =
  714    Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
  715
  716impl Global for ProjectItemRegistry {}
  717
  718/// Registers a [ProjectItem] for the app. When opening a file, all the registered
  719/// items will get a chance to open the file, starting from the project item that
  720/// was added last.
  721pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
  722    cx.default_global::<ProjectItemRegistry>().register::<I>();
  723}
  724
  725#[derive(Default)]
  726pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
  727
  728struct FollowableViewDescriptor {
  729    from_state_proto: fn(
  730        Entity<Workspace>,
  731        ViewId,
  732        &mut Option<proto::view::Variant>,
  733        &mut Window,
  734        &mut App,
  735    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
  736    to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
  737}
  738
  739impl Global for FollowableViewRegistry {}
  740
  741impl FollowableViewRegistry {
  742    pub fn register<I: FollowableItem>(cx: &mut App) {
  743        cx.default_global::<Self>().0.insert(
  744            TypeId::of::<I>(),
  745            FollowableViewDescriptor {
  746                from_state_proto: |workspace, id, state, window, cx| {
  747                    I::from_state_proto(workspace, id, state, window, cx).map(|task| {
  748                        cx.foreground_executor()
  749                            .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
  750                    })
  751                },
  752                to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
  753            },
  754        );
  755    }
  756
  757    pub fn from_state_proto(
  758        workspace: Entity<Workspace>,
  759        view_id: ViewId,
  760        mut state: Option<proto::view::Variant>,
  761        window: &mut Window,
  762        cx: &mut App,
  763    ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
  764        cx.update_default_global(|this: &mut Self, cx| {
  765            this.0.values().find_map(|descriptor| {
  766                (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
  767            })
  768        })
  769    }
  770
  771    pub fn to_followable_view(
  772        view: impl Into<AnyView>,
  773        cx: &App,
  774    ) -> Option<Box<dyn FollowableItemHandle>> {
  775        let this = cx.try_global::<Self>()?;
  776        let view = view.into();
  777        let descriptor = this.0.get(&view.entity_type())?;
  778        Some((descriptor.to_followable_view)(&view))
  779    }
  780}
  781
  782#[derive(Copy, Clone)]
  783struct SerializableItemDescriptor {
  784    deserialize: fn(
  785        Entity<Project>,
  786        WeakEntity<Workspace>,
  787        WorkspaceId,
  788        ItemId,
  789        &mut Window,
  790        &mut Context<Pane>,
  791    ) -> Task<Result<Box<dyn ItemHandle>>>,
  792    cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
  793    view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
  794}
  795
  796#[derive(Default)]
  797struct SerializableItemRegistry {
  798    descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
  799    descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
  800}
  801
  802impl Global for SerializableItemRegistry {}
  803
  804impl SerializableItemRegistry {
  805    fn deserialize(
  806        item_kind: &str,
  807        project: Entity<Project>,
  808        workspace: WeakEntity<Workspace>,
  809        workspace_id: WorkspaceId,
  810        item_item: ItemId,
  811        window: &mut Window,
  812        cx: &mut Context<Pane>,
  813    ) -> Task<Result<Box<dyn ItemHandle>>> {
  814        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  815            return Task::ready(Err(anyhow!(
  816                "cannot deserialize {}, descriptor not found",
  817                item_kind
  818            )));
  819        };
  820
  821        (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
  822    }
  823
  824    fn cleanup(
  825        item_kind: &str,
  826        workspace_id: WorkspaceId,
  827        loaded_items: Vec<ItemId>,
  828        window: &mut Window,
  829        cx: &mut App,
  830    ) -> Task<Result<()>> {
  831        let Some(descriptor) = Self::descriptor(item_kind, cx) else {
  832            return Task::ready(Err(anyhow!(
  833                "cannot cleanup {}, descriptor not found",
  834                item_kind
  835            )));
  836        };
  837
  838        (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
  839    }
  840
  841    fn view_to_serializable_item_handle(
  842        view: AnyView,
  843        cx: &App,
  844    ) -> Option<Box<dyn SerializableItemHandle>> {
  845        let this = cx.try_global::<Self>()?;
  846        let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
  847        Some((descriptor.view_to_serializable_item)(view))
  848    }
  849
  850    fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
  851        let this = cx.try_global::<Self>()?;
  852        this.descriptors_by_kind.get(item_kind).copied()
  853    }
  854}
  855
  856pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
  857    let serialized_item_kind = I::serialized_item_kind();
  858
  859    let registry = cx.default_global::<SerializableItemRegistry>();
  860    let descriptor = SerializableItemDescriptor {
  861        deserialize: |project, workspace, workspace_id, item_id, window, cx| {
  862            let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
  863            cx.foreground_executor()
  864                .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
  865        },
  866        cleanup: |workspace_id, loaded_items, window, cx| {
  867            I::cleanup(workspace_id, loaded_items, window, cx)
  868        },
  869        view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
  870    };
  871    registry
  872        .descriptors_by_kind
  873        .insert(Arc::from(serialized_item_kind), descriptor);
  874    registry
  875        .descriptors_by_type
  876        .insert(TypeId::of::<I>(), descriptor);
  877}
  878
  879pub struct AppState {
  880    pub languages: Arc<LanguageRegistry>,
  881    pub client: Arc<Client>,
  882    pub user_store: Entity<UserStore>,
  883    pub workspace_store: Entity<WorkspaceStore>,
  884    pub fs: Arc<dyn fs::Fs>,
  885    pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
  886    pub node_runtime: NodeRuntime,
  887    pub session: Entity<AppSession>,
  888}
  889
  890struct GlobalAppState(Weak<AppState>);
  891
  892impl Global for GlobalAppState {}
  893
  894pub struct WorkspaceStore {
  895    workspaces: HashSet<WindowHandle<Workspace>>,
  896    client: Arc<Client>,
  897    _subscriptions: Vec<client::Subscription>,
  898}
  899
  900#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
  901pub enum CollaboratorId {
  902    PeerId(PeerId),
  903    Agent,
  904}
  905
  906impl From<PeerId> for CollaboratorId {
  907    fn from(peer_id: PeerId) -> Self {
  908        CollaboratorId::PeerId(peer_id)
  909    }
  910}
  911
  912impl From<&PeerId> for CollaboratorId {
  913    fn from(peer_id: &PeerId) -> Self {
  914        CollaboratorId::PeerId(*peer_id)
  915    }
  916}
  917
  918#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
  919struct Follower {
  920    project_id: Option<u64>,
  921    peer_id: PeerId,
  922}
  923
  924impl AppState {
  925    #[track_caller]
  926    pub fn global(cx: &App) -> Weak<Self> {
  927        cx.global::<GlobalAppState>().0.clone()
  928    }
  929    pub fn try_global(cx: &App) -> Option<Weak<Self>> {
  930        cx.try_global::<GlobalAppState>()
  931            .map(|state| state.0.clone())
  932    }
  933    pub fn set_global(state: Weak<AppState>, cx: &mut App) {
  934        cx.set_global(GlobalAppState(state));
  935    }
  936
  937    #[cfg(any(test, feature = "test-support"))]
  938    pub fn test(cx: &mut App) -> Arc<Self> {
  939        use node_runtime::NodeRuntime;
  940        use session::Session;
  941        use settings::SettingsStore;
  942
  943        if !cx.has_global::<SettingsStore>() {
  944            let settings_store = SettingsStore::test(cx);
  945            cx.set_global(settings_store);
  946        }
  947
  948        let fs = fs::FakeFs::new(cx.background_executor().clone());
  949        let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
  950        let clock = Arc::new(clock::FakeSystemClock::new());
  951        let http_client = http_client::FakeHttpClient::with_404_response();
  952        let client = Client::new(clock, http_client, cx);
  953        let session = cx.new(|cx| AppSession::new(Session::test(), cx));
  954        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
  955        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
  956
  957        theme::init(theme::LoadThemes::JustBase, cx);
  958        client::init(&client, cx);
  959        crate::init_settings(cx);
  960
  961        Arc::new(Self {
  962            client,
  963            fs,
  964            languages,
  965            user_store,
  966            workspace_store,
  967            node_runtime: NodeRuntime::unavailable(),
  968            build_window_options: |_, _| Default::default(),
  969            session,
  970        })
  971    }
  972}
  973
  974struct DelayedDebouncedEditAction {
  975    task: Option<Task<()>>,
  976    cancel_channel: Option<oneshot::Sender<()>>,
  977}
  978
  979impl DelayedDebouncedEditAction {
  980    fn new() -> DelayedDebouncedEditAction {
  981        DelayedDebouncedEditAction {
  982            task: None,
  983            cancel_channel: None,
  984        }
  985    }
  986
  987    fn fire_new<F>(
  988        &mut self,
  989        delay: Duration,
  990        window: &mut Window,
  991        cx: &mut Context<Workspace>,
  992        func: F,
  993    ) where
  994        F: 'static
  995            + Send
  996            + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
  997    {
  998        if let Some(channel) = self.cancel_channel.take() {
  999            _ = channel.send(());
 1000        }
 1001
 1002        let (sender, mut receiver) = oneshot::channel::<()>();
 1003        self.cancel_channel = Some(sender);
 1004
 1005        let previous_task = self.task.take();
 1006        self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
 1007            let mut timer = cx.background_executor().timer(delay).fuse();
 1008            if let Some(previous_task) = previous_task {
 1009                previous_task.await;
 1010            }
 1011
 1012            futures::select_biased! {
 1013                _ = receiver => return,
 1014                    _ = timer => {}
 1015            }
 1016
 1017            if let Some(result) = workspace
 1018                .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
 1019                .log_err()
 1020            {
 1021                result.await.log_err();
 1022            }
 1023        }));
 1024    }
 1025}
 1026
 1027pub enum Event {
 1028    PaneAdded(Entity<Pane>),
 1029    PaneRemoved,
 1030    ItemAdded {
 1031        item: Box<dyn ItemHandle>,
 1032    },
 1033    ItemRemoved,
 1034    ActiveItemChanged,
 1035    UserSavedItem {
 1036        pane: WeakEntity<Pane>,
 1037        item: Box<dyn WeakItemHandle>,
 1038        save_intent: SaveIntent,
 1039    },
 1040    ContactRequestedJoin(u64),
 1041    WorkspaceCreated(WeakEntity<Workspace>),
 1042    OpenBundledFile {
 1043        text: Cow<'static, str>,
 1044        title: &'static str,
 1045        language: &'static str,
 1046    },
 1047    ZoomChanged,
 1048    ModalOpened,
 1049    ClearActivityIndicator,
 1050}
 1051
 1052#[derive(Debug)]
 1053pub enum OpenVisible {
 1054    All,
 1055    None,
 1056    OnlyFiles,
 1057    OnlyDirectories,
 1058}
 1059
 1060enum WorkspaceLocation {
 1061    // Valid local paths or SSH project to serialize
 1062    Location(SerializedWorkspaceLocation, PathList),
 1063    // No valid location found hence clear session id
 1064    DetachFromSession,
 1065    // No valid location found to serialize
 1066    None,
 1067}
 1068
 1069type PromptForNewPath = Box<
 1070    dyn Fn(
 1071        &mut Workspace,
 1072        DirectoryLister,
 1073        &mut Window,
 1074        &mut Context<Workspace>,
 1075    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1076>;
 1077
 1078type PromptForOpenPath = Box<
 1079    dyn Fn(
 1080        &mut Workspace,
 1081        DirectoryLister,
 1082        &mut Window,
 1083        &mut Context<Workspace>,
 1084    ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
 1085>;
 1086
 1087#[derive(Default)]
 1088struct DispatchingKeystrokes {
 1089    dispatched: HashSet<Vec<Keystroke>>,
 1090    queue: VecDeque<Keystroke>,
 1091    task: Option<Shared<Task<()>>>,
 1092}
 1093
 1094/// Collects everything project-related for a certain window opened.
 1095/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
 1096///
 1097/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
 1098/// The `Workspace` owns everybody's state and serves as a default, "global context",
 1099/// that can be used to register a global action to be triggered from any place in the window.
 1100pub struct Workspace {
 1101    weak_self: WeakEntity<Self>,
 1102    workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
 1103    zoomed: Option<AnyWeakView>,
 1104    previous_dock_drag_coordinates: Option<Point<Pixels>>,
 1105    zoomed_position: Option<DockPosition>,
 1106    center: PaneGroup,
 1107    left_dock: Entity<Dock>,
 1108    bottom_dock: Entity<Dock>,
 1109    right_dock: Entity<Dock>,
 1110    panes: Vec<Entity<Pane>>,
 1111    panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
 1112    active_pane: Entity<Pane>,
 1113    last_active_center_pane: Option<WeakEntity<Pane>>,
 1114    last_active_view_id: Option<proto::ViewId>,
 1115    status_bar: Entity<StatusBar>,
 1116    modal_layer: Entity<ModalLayer>,
 1117    toast_layer: Entity<ToastLayer>,
 1118    titlebar_item: Option<AnyView>,
 1119    notifications: Notifications,
 1120    suppressed_notifications: HashSet<NotificationId>,
 1121    project: Entity<Project>,
 1122    follower_states: HashMap<CollaboratorId, FollowerState>,
 1123    last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
 1124    window_edited: bool,
 1125    last_window_title: Option<String>,
 1126    dirty_items: HashMap<EntityId, Subscription>,
 1127    active_call: Option<(Entity<ActiveCall>, Vec<Subscription>)>,
 1128    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 1129    database_id: Option<WorkspaceId>,
 1130    app_state: Arc<AppState>,
 1131    dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
 1132    _subscriptions: Vec<Subscription>,
 1133    _apply_leader_updates: Task<Result<()>>,
 1134    _observe_current_user: Task<Result<()>>,
 1135    _schedule_serialize_workspace: Option<Task<()>>,
 1136    _schedule_serialize_ssh_paths: Option<Task<()>>,
 1137    pane_history_timestamp: Arc<AtomicUsize>,
 1138    bounds: Bounds<Pixels>,
 1139    pub centered_layout: bool,
 1140    bounds_save_task_queued: Option<Task<()>>,
 1141    on_prompt_for_new_path: Option<PromptForNewPath>,
 1142    on_prompt_for_open_path: Option<PromptForOpenPath>,
 1143    terminal_provider: Option<Box<dyn TerminalProvider>>,
 1144    debugger_provider: Option<Arc<dyn DebuggerProvider>>,
 1145    serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
 1146    _items_serializer: Task<Result<()>>,
 1147    session_id: Option<String>,
 1148    scheduled_tasks: Vec<Task<()>>,
 1149}
 1150
 1151impl EventEmitter<Event> for Workspace {}
 1152
 1153#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 1154pub struct ViewId {
 1155    pub creator: CollaboratorId,
 1156    pub id: u64,
 1157}
 1158
 1159pub struct FollowerState {
 1160    center_pane: Entity<Pane>,
 1161    dock_pane: Option<Entity<Pane>>,
 1162    active_view_id: Option<ViewId>,
 1163    items_by_leader_view_id: HashMap<ViewId, FollowerView>,
 1164}
 1165
 1166struct FollowerView {
 1167    view: Box<dyn FollowableItemHandle>,
 1168    location: Option<proto::PanelId>,
 1169}
 1170
 1171impl Workspace {
 1172    const DEFAULT_PADDING: f32 = 0.2;
 1173    const MAX_PADDING: f32 = 0.4;
 1174
 1175    pub fn new(
 1176        workspace_id: Option<WorkspaceId>,
 1177        project: Entity<Project>,
 1178        app_state: Arc<AppState>,
 1179        window: &mut Window,
 1180        cx: &mut Context<Self>,
 1181    ) -> Self {
 1182        cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
 1183            match event {
 1184                project::Event::RemoteIdChanged(_) => {
 1185                    this.update_window_title(window, cx);
 1186                }
 1187
 1188                project::Event::CollaboratorLeft(peer_id) => {
 1189                    this.collaborator_left(*peer_id, window, cx);
 1190                }
 1191
 1192                project::Event::WorktreeRemoved(_) | project::Event::WorktreeAdded(_) => {
 1193                    this.update_window_title(window, cx);
 1194                    this.serialize_workspace(window, cx);
 1195                    // This event could be triggered by `AddFolderToProject` or `RemoveFromProject`.
 1196                    this.update_history(cx);
 1197                }
 1198
 1199                project::Event::DisconnectedFromHost => {
 1200                    this.update_window_edited(window, cx);
 1201                    let leaders_to_unfollow =
 1202                        this.follower_states.keys().copied().collect::<Vec<_>>();
 1203                    for leader_id in leaders_to_unfollow {
 1204                        this.unfollow(leader_id, window, cx);
 1205                    }
 1206                }
 1207
 1208                project::Event::DisconnectedFromSshRemote => {
 1209                    this.update_window_edited(window, cx);
 1210                }
 1211
 1212                project::Event::Closed => {
 1213                    window.remove_window();
 1214                }
 1215
 1216                project::Event::DeletedEntry(_, entry_id) => {
 1217                    for pane in this.panes.iter() {
 1218                        pane.update(cx, |pane, cx| {
 1219                            pane.handle_deleted_project_item(*entry_id, window, cx)
 1220                        });
 1221                    }
 1222                }
 1223
 1224                project::Event::Toast {
 1225                    notification_id,
 1226                    message,
 1227                } => this.show_notification(
 1228                    NotificationId::named(notification_id.clone()),
 1229                    cx,
 1230                    |cx| cx.new(|cx| MessageNotification::new(message.clone(), cx)),
 1231                ),
 1232
 1233                project::Event::HideToast { notification_id } => {
 1234                    this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
 1235                }
 1236
 1237                project::Event::LanguageServerPrompt(request) => {
 1238                    struct LanguageServerPrompt;
 1239
 1240                    let mut hasher = DefaultHasher::new();
 1241                    request.lsp_name.as_str().hash(&mut hasher);
 1242                    let id = hasher.finish();
 1243
 1244                    this.show_notification(
 1245                        NotificationId::composite::<LanguageServerPrompt>(id as usize),
 1246                        cx,
 1247                        |cx| {
 1248                            cx.new(|cx| {
 1249                                notifications::LanguageServerPrompt::new(request.clone(), cx)
 1250                            })
 1251                        },
 1252                    );
 1253                }
 1254
 1255                project::Event::AgentLocationChanged => {
 1256                    this.handle_agent_location_changed(window, cx)
 1257                }
 1258
 1259                _ => {}
 1260            }
 1261            cx.notify()
 1262        })
 1263        .detach();
 1264
 1265        cx.subscribe_in(
 1266            &project.read(cx).breakpoint_store(),
 1267            window,
 1268            |workspace, _, event, window, cx| match event {
 1269                BreakpointStoreEvent::BreakpointsUpdated(_, _)
 1270                | BreakpointStoreEvent::BreakpointsCleared(_) => {
 1271                    workspace.serialize_workspace(window, cx);
 1272                }
 1273                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 1274            },
 1275        )
 1276        .detach();
 1277
 1278        cx.on_focus_lost(window, |this, window, cx| {
 1279            let focus_handle = this.focus_handle(cx);
 1280            window.focus(&focus_handle);
 1281        })
 1282        .detach();
 1283
 1284        let weak_handle = cx.entity().downgrade();
 1285        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 1286
 1287        let center_pane = cx.new(|cx| {
 1288            let mut center_pane = Pane::new(
 1289                weak_handle.clone(),
 1290                project.clone(),
 1291                pane_history_timestamp.clone(),
 1292                None,
 1293                NewFile.boxed_clone(),
 1294                window,
 1295                cx,
 1296            );
 1297            center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 1298            center_pane
 1299        });
 1300        cx.subscribe_in(&center_pane, window, Self::handle_pane_event)
 1301            .detach();
 1302
 1303        window.focus(&center_pane.focus_handle(cx));
 1304
 1305        cx.emit(Event::PaneAdded(center_pane.clone()));
 1306
 1307        let window_handle = window.window_handle().downcast::<Workspace>().unwrap();
 1308        app_state.workspace_store.update(cx, |store, _| {
 1309            store.workspaces.insert(window_handle);
 1310        });
 1311
 1312        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 1313        let mut connection_status = app_state.client.status();
 1314        let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
 1315            current_user.next().await;
 1316            connection_status.next().await;
 1317            let mut stream =
 1318                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 1319
 1320            while stream.recv().await.is_some() {
 1321                this.update(cx, |_, cx| cx.notify())?;
 1322            }
 1323            anyhow::Ok(())
 1324        });
 1325
 1326        // All leader updates are enqueued and then processed in a single task, so
 1327        // that each asynchronous operation can be run in order.
 1328        let (leader_updates_tx, mut leader_updates_rx) =
 1329            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 1330        let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
 1331            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 1332                Self::process_leader_update(&this, leader_id, update, cx)
 1333                    .await
 1334                    .log_err();
 1335            }
 1336
 1337            Ok(())
 1338        });
 1339
 1340        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 1341        let modal_layer = cx.new(|_| ModalLayer::new());
 1342        let toast_layer = cx.new(|_| ToastLayer::new());
 1343        cx.subscribe(
 1344            &modal_layer,
 1345            |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
 1346                cx.emit(Event::ModalOpened);
 1347            },
 1348        )
 1349        .detach();
 1350
 1351        let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
 1352        let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
 1353        let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
 1354        let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
 1355        let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
 1356        let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
 1357        let status_bar = cx.new(|cx| {
 1358            let mut status_bar = StatusBar::new(&center_pane.clone(), window, cx);
 1359            status_bar.add_left_item(left_dock_buttons, window, cx);
 1360            status_bar.add_right_item(right_dock_buttons, window, cx);
 1361            status_bar.add_right_item(bottom_dock_buttons, window, cx);
 1362            status_bar
 1363        });
 1364
 1365        let session_id = app_state.session.read(cx).id().to_owned();
 1366
 1367        let mut active_call = None;
 1368        if let Some(call) = ActiveCall::try_global(cx) {
 1369            let subscriptions = vec![cx.subscribe_in(&call, window, Self::on_active_call_event)];
 1370            active_call = Some((call, subscriptions));
 1371        }
 1372
 1373        let (serializable_items_tx, serializable_items_rx) =
 1374            mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
 1375        let _items_serializer = cx.spawn_in(window, async move |this, cx| {
 1376            Self::serialize_items(&this, serializable_items_rx, cx).await
 1377        });
 1378
 1379        let subscriptions = vec![
 1380            cx.observe_window_activation(window, Self::on_window_activation_changed),
 1381            cx.observe_window_bounds(window, move |this, window, cx| {
 1382                if this.bounds_save_task_queued.is_some() {
 1383                    return;
 1384                }
 1385                this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
 1386                    cx.background_executor()
 1387                        .timer(Duration::from_millis(100))
 1388                        .await;
 1389                    this.update_in(cx, |this, window, cx| {
 1390                        if let Some(display) = window.display(cx)
 1391                            && let Ok(display_uuid) = display.uuid()
 1392                        {
 1393                            let window_bounds = window.inner_window_bounds();
 1394                            if let Some(database_id) = workspace_id {
 1395                                cx.background_executor()
 1396                                    .spawn(DB.set_window_open_status(
 1397                                        database_id,
 1398                                        SerializedWindowBounds(window_bounds),
 1399                                        display_uuid,
 1400                                    ))
 1401                                    .detach_and_log_err(cx);
 1402                            }
 1403                        }
 1404                        this.bounds_save_task_queued.take();
 1405                    })
 1406                    .ok();
 1407                }));
 1408                cx.notify();
 1409            }),
 1410            cx.observe_window_appearance(window, |_, window, cx| {
 1411                let window_appearance = window.appearance();
 1412
 1413                *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
 1414
 1415                ThemeSettings::reload_current_theme(cx);
 1416                ThemeSettings::reload_current_icon_theme(cx);
 1417            }),
 1418            cx.on_release(move |this, cx| {
 1419                this.app_state.workspace_store.update(cx, move |store, _| {
 1420                    store.workspaces.remove(&window_handle.clone());
 1421                })
 1422            }),
 1423        ];
 1424
 1425        cx.defer_in(window, |this, window, cx| {
 1426            this.update_window_title(window, cx);
 1427            this.show_initial_notifications(cx);
 1428        });
 1429        Workspace {
 1430            weak_self: weak_handle.clone(),
 1431            zoomed: None,
 1432            zoomed_position: None,
 1433            previous_dock_drag_coordinates: None,
 1434            center: PaneGroup::new(center_pane.clone()),
 1435            panes: vec![center_pane.clone()],
 1436            panes_by_item: Default::default(),
 1437            active_pane: center_pane.clone(),
 1438            last_active_center_pane: Some(center_pane.downgrade()),
 1439            last_active_view_id: None,
 1440            status_bar,
 1441            modal_layer,
 1442            toast_layer,
 1443            titlebar_item: None,
 1444            notifications: Notifications::default(),
 1445            suppressed_notifications: HashSet::default(),
 1446            left_dock,
 1447            bottom_dock,
 1448            right_dock,
 1449            project: project.clone(),
 1450            follower_states: Default::default(),
 1451            last_leaders_by_pane: Default::default(),
 1452            dispatching_keystrokes: Default::default(),
 1453            window_edited: false,
 1454            last_window_title: None,
 1455            dirty_items: Default::default(),
 1456            active_call,
 1457            database_id: workspace_id,
 1458            app_state,
 1459            _observe_current_user,
 1460            _apply_leader_updates,
 1461            _schedule_serialize_workspace: None,
 1462            _schedule_serialize_ssh_paths: None,
 1463            leader_updates_tx,
 1464            _subscriptions: subscriptions,
 1465            pane_history_timestamp,
 1466            workspace_actions: Default::default(),
 1467            // This data will be incorrect, but it will be overwritten by the time it needs to be used.
 1468            bounds: Default::default(),
 1469            centered_layout: false,
 1470            bounds_save_task_queued: None,
 1471            on_prompt_for_new_path: None,
 1472            on_prompt_for_open_path: None,
 1473            terminal_provider: None,
 1474            debugger_provider: None,
 1475            serializable_items_tx,
 1476            _items_serializer,
 1477            session_id: Some(session_id),
 1478
 1479            scheduled_tasks: Vec::new(),
 1480        }
 1481    }
 1482
 1483    pub fn new_local(
 1484        abs_paths: Vec<PathBuf>,
 1485        app_state: Arc<AppState>,
 1486        requesting_window: Option<WindowHandle<Workspace>>,
 1487        env: Option<HashMap<String, String>>,
 1488        cx: &mut App,
 1489    ) -> Task<
 1490        anyhow::Result<(
 1491            WindowHandle<Workspace>,
 1492            Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
 1493        )>,
 1494    > {
 1495        let project_handle = Project::local(
 1496            app_state.client.clone(),
 1497            app_state.node_runtime.clone(),
 1498            app_state.user_store.clone(),
 1499            app_state.languages.clone(),
 1500            app_state.fs.clone(),
 1501            env,
 1502            cx,
 1503        );
 1504
 1505        cx.spawn(async move |cx| {
 1506            let mut paths_to_open = Vec::with_capacity(abs_paths.len());
 1507            for path in abs_paths.into_iter() {
 1508                if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
 1509                    paths_to_open.push(canonical)
 1510                } else {
 1511                    paths_to_open.push(path)
 1512                }
 1513            }
 1514
 1515            let serialized_workspace =
 1516                persistence::DB.workspace_for_roots(paths_to_open.as_slice());
 1517
 1518            if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
 1519                paths_to_open = paths.paths().to_vec();
 1520                if !paths.is_lexicographically_ordered() {
 1521                    project_handle
 1522                        .update(cx, |project, cx| {
 1523                            project.set_worktrees_reordered(true, cx);
 1524                        })
 1525                        .log_err();
 1526                }
 1527            }
 1528
 1529            // Get project paths for all of the abs_paths
 1530            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 1531                Vec::with_capacity(paths_to_open.len());
 1532
 1533            for path in paths_to_open.into_iter() {
 1534                if let Some((_, project_entry)) = cx
 1535                    .update(|cx| {
 1536                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 1537                    })?
 1538                    .await
 1539                    .log_err()
 1540                {
 1541                    project_paths.push((path, Some(project_entry)));
 1542                } else {
 1543                    project_paths.push((path, None));
 1544                }
 1545            }
 1546
 1547            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 1548                serialized_workspace.id
 1549            } else {
 1550                DB.next_id().await.unwrap_or_else(|_| Default::default())
 1551            };
 1552
 1553            let toolchains = DB.toolchains(workspace_id).await?;
 1554
 1555            for (toolchain, worktree_id, path) in toolchains {
 1556                let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
 1557                if !app_state.fs.is_file(toolchain_path.as_path()).await {
 1558                    continue;
 1559                }
 1560
 1561                project_handle
 1562                    .update(cx, |this, cx| {
 1563                        this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
 1564                    })?
 1565                    .await;
 1566            }
 1567            let window = if let Some(window) = requesting_window {
 1568                let centered_layout = serialized_workspace
 1569                    .as_ref()
 1570                    .map(|w| w.centered_layout)
 1571                    .unwrap_or(false);
 1572
 1573                cx.update_window(window.into(), |_, window, cx| {
 1574                    window.replace_root(cx, |window, cx| {
 1575                        let mut workspace = Workspace::new(
 1576                            Some(workspace_id),
 1577                            project_handle.clone(),
 1578                            app_state.clone(),
 1579                            window,
 1580                            cx,
 1581                        );
 1582
 1583                        workspace.centered_layout = centered_layout;
 1584                        workspace
 1585                    });
 1586                })?;
 1587                window
 1588            } else {
 1589                let window_bounds_override = window_bounds_env_override();
 1590
 1591                let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
 1592                    (Some(WindowBounds::Windowed(bounds)), None)
 1593                } else {
 1594                    let restorable_bounds = serialized_workspace
 1595                        .as_ref()
 1596                        .and_then(|workspace| Some((workspace.display?, workspace.window_bounds?)))
 1597                        .or_else(|| {
 1598                            let (display, window_bounds) = DB.last_window().log_err()?;
 1599                            Some((display?, window_bounds?))
 1600                        });
 1601
 1602                    if let Some((serialized_display, serialized_status)) = restorable_bounds {
 1603                        (Some(serialized_status.0), Some(serialized_display))
 1604                    } else {
 1605                        (None, None)
 1606                    }
 1607                };
 1608
 1609                // Use the serialized workspace to construct the new window
 1610                let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx))?;
 1611                options.window_bounds = window_bounds;
 1612                let centered_layout = serialized_workspace
 1613                    .as_ref()
 1614                    .map(|w| w.centered_layout)
 1615                    .unwrap_or(false);
 1616                cx.open_window(options, {
 1617                    let app_state = app_state.clone();
 1618                    let project_handle = project_handle.clone();
 1619                    move |window, cx| {
 1620                        cx.new(|cx| {
 1621                            let mut workspace = Workspace::new(
 1622                                Some(workspace_id),
 1623                                project_handle,
 1624                                app_state,
 1625                                window,
 1626                                cx,
 1627                            );
 1628                            workspace.centered_layout = centered_layout;
 1629                            workspace
 1630                        })
 1631                    }
 1632                })?
 1633            };
 1634
 1635            notify_if_database_failed(window, cx);
 1636            let opened_items = window
 1637                .update(cx, |_workspace, window, cx| {
 1638                    open_items(serialized_workspace, project_paths, window, cx)
 1639                })?
 1640                .await
 1641                .unwrap_or_default();
 1642
 1643            window
 1644                .update(cx, |workspace, window, cx| {
 1645                    window.activate_window();
 1646                    workspace.update_history(cx);
 1647                })
 1648                .log_err();
 1649            Ok((window, opened_items))
 1650        })
 1651    }
 1652
 1653    pub fn weak_handle(&self) -> WeakEntity<Self> {
 1654        self.weak_self.clone()
 1655    }
 1656
 1657    pub fn left_dock(&self) -> &Entity<Dock> {
 1658        &self.left_dock
 1659    }
 1660
 1661    pub fn bottom_dock(&self) -> &Entity<Dock> {
 1662        &self.bottom_dock
 1663    }
 1664
 1665    pub fn set_bottom_dock_layout(
 1666        &mut self,
 1667        layout: BottomDockLayout,
 1668        window: &mut Window,
 1669        cx: &mut Context<Self>,
 1670    ) {
 1671        let fs = self.project().read(cx).fs();
 1672        settings::update_settings_file::<WorkspaceSettings>(fs.clone(), cx, move |content, _cx| {
 1673            content.bottom_dock_layout = Some(layout);
 1674        });
 1675
 1676        cx.notify();
 1677        self.serialize_workspace(window, cx);
 1678    }
 1679
 1680    pub fn right_dock(&self) -> &Entity<Dock> {
 1681        &self.right_dock
 1682    }
 1683
 1684    pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
 1685        [&self.left_dock, &self.bottom_dock, &self.right_dock]
 1686    }
 1687
 1688    pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
 1689        match position {
 1690            DockPosition::Left => &self.left_dock,
 1691            DockPosition::Bottom => &self.bottom_dock,
 1692            DockPosition::Right => &self.right_dock,
 1693        }
 1694    }
 1695
 1696    pub fn is_edited(&self) -> bool {
 1697        self.window_edited
 1698    }
 1699
 1700    pub fn add_panel<T: Panel>(
 1701        &mut self,
 1702        panel: Entity<T>,
 1703        window: &mut Window,
 1704        cx: &mut Context<Self>,
 1705    ) {
 1706        let focus_handle = panel.panel_focus_handle(cx);
 1707        cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
 1708            .detach();
 1709
 1710        let dock_position = panel.position(window, cx);
 1711        let dock = self.dock_at_position(dock_position);
 1712
 1713        dock.update(cx, |dock, cx| {
 1714            dock.add_panel(panel, self.weak_self.clone(), window, cx)
 1715        });
 1716    }
 1717
 1718    pub fn status_bar(&self) -> &Entity<StatusBar> {
 1719        &self.status_bar
 1720    }
 1721
 1722    pub fn app_state(&self) -> &Arc<AppState> {
 1723        &self.app_state
 1724    }
 1725
 1726    pub fn user_store(&self) -> &Entity<UserStore> {
 1727        &self.app_state.user_store
 1728    }
 1729
 1730    pub fn project(&self) -> &Entity<Project> {
 1731        &self.project
 1732    }
 1733
 1734    pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
 1735        let mut history: HashMap<EntityId, usize> = HashMap::default();
 1736
 1737        for pane_handle in &self.panes {
 1738            let pane = pane_handle.read(cx);
 1739
 1740            for entry in pane.activation_history() {
 1741                history.insert(
 1742                    entry.entity_id,
 1743                    history
 1744                        .get(&entry.entity_id)
 1745                        .cloned()
 1746                        .unwrap_or(0)
 1747                        .max(entry.timestamp),
 1748                );
 1749            }
 1750        }
 1751
 1752        history
 1753    }
 1754
 1755    pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
 1756        let mut recent_item: Option<Entity<T>> = None;
 1757        let mut recent_timestamp = 0;
 1758        for pane_handle in &self.panes {
 1759            let pane = pane_handle.read(cx);
 1760            let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
 1761                pane.items().map(|item| (item.item_id(), item)).collect();
 1762            for entry in pane.activation_history() {
 1763                if entry.timestamp > recent_timestamp
 1764                    && let Some(&item) = item_map.get(&entry.entity_id)
 1765                    && let Some(typed_item) = item.act_as::<T>(cx)
 1766                {
 1767                    recent_timestamp = entry.timestamp;
 1768                    recent_item = Some(typed_item);
 1769                }
 1770            }
 1771        }
 1772        recent_item
 1773    }
 1774
 1775    pub fn recent_navigation_history_iter(
 1776        &self,
 1777        cx: &App,
 1778    ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> {
 1779        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 1780        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 1781
 1782        for pane in &self.panes {
 1783            let pane = pane.read(cx);
 1784
 1785            pane.nav_history()
 1786                .for_each_entry(cx, |entry, (project_path, fs_path)| {
 1787                    if let Some(fs_path) = &fs_path {
 1788                        abs_paths_opened
 1789                            .entry(fs_path.clone())
 1790                            .or_default()
 1791                            .insert(project_path.clone());
 1792                    }
 1793                    let timestamp = entry.timestamp;
 1794                    match history.entry(project_path) {
 1795                        hash_map::Entry::Occupied(mut entry) => {
 1796                            let (_, old_timestamp) = entry.get();
 1797                            if &timestamp > old_timestamp {
 1798                                entry.insert((fs_path, timestamp));
 1799                            }
 1800                        }
 1801                        hash_map::Entry::Vacant(entry) => {
 1802                            entry.insert((fs_path, timestamp));
 1803                        }
 1804                    }
 1805                });
 1806
 1807            if let Some(item) = pane.active_item()
 1808                && let Some(project_path) = item.project_path(cx)
 1809            {
 1810                let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
 1811
 1812                if let Some(fs_path) = &fs_path {
 1813                    abs_paths_opened
 1814                        .entry(fs_path.clone())
 1815                        .or_default()
 1816                        .insert(project_path.clone());
 1817                }
 1818
 1819                history.insert(project_path, (fs_path, std::usize::MAX));
 1820            }
 1821        }
 1822
 1823        history
 1824            .into_iter()
 1825            .sorted_by_key(|(_, (_, order))| *order)
 1826            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 1827            .rev()
 1828            .filter(move |(history_path, abs_path)| {
 1829                let latest_project_path_opened = abs_path
 1830                    .as_ref()
 1831                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 1832                    .and_then(|project_paths| {
 1833                        project_paths
 1834                            .iter()
 1835                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 1836                    });
 1837
 1838                latest_project_path_opened.is_none_or(|path| path == history_path)
 1839            })
 1840    }
 1841
 1842    pub fn recent_navigation_history(
 1843        &self,
 1844        limit: Option<usize>,
 1845        cx: &App,
 1846    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 1847        self.recent_navigation_history_iter(cx)
 1848            .take(limit.unwrap_or(usize::MAX))
 1849            .collect()
 1850    }
 1851
 1852    fn navigate_history(
 1853        &mut self,
 1854        pane: WeakEntity<Pane>,
 1855        mode: NavigationMode,
 1856        window: &mut Window,
 1857        cx: &mut Context<Workspace>,
 1858    ) -> Task<Result<()>> {
 1859        let to_load = if let Some(pane) = pane.upgrade() {
 1860            pane.update(cx, |pane, cx| {
 1861                window.focus(&pane.focus_handle(cx));
 1862                loop {
 1863                    // Retrieve the weak item handle from the history.
 1864                    let entry = pane.nav_history_mut().pop(mode, cx)?;
 1865
 1866                    // If the item is still present in this pane, then activate it.
 1867                    if let Some(index) = entry
 1868                        .item
 1869                        .upgrade()
 1870                        .and_then(|v| pane.index_for_item(v.as_ref()))
 1871                    {
 1872                        let prev_active_item_index = pane.active_item_index();
 1873                        pane.nav_history_mut().set_mode(mode);
 1874                        pane.activate_item(index, true, true, window, cx);
 1875                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 1876
 1877                        let mut navigated = prev_active_item_index != pane.active_item_index();
 1878                        if let Some(data) = entry.data {
 1879                            navigated |= pane.active_item()?.navigate(data, window, cx);
 1880                        }
 1881
 1882                        if navigated {
 1883                            break None;
 1884                        }
 1885                    } else {
 1886                        // If the item is no longer present in this pane, then retrieve its
 1887                        // path info in order to reopen it.
 1888                        break pane
 1889                            .nav_history()
 1890                            .path_for_item(entry.item.id())
 1891                            .map(|(project_path, abs_path)| (project_path, abs_path, entry));
 1892                    }
 1893                }
 1894            })
 1895        } else {
 1896            None
 1897        };
 1898
 1899        if let Some((project_path, abs_path, entry)) = to_load {
 1900            // If the item was no longer present, then load it again from its previous path, first try the local path
 1901            let open_by_project_path = self.load_path(project_path.clone(), window, cx);
 1902
 1903            cx.spawn_in(window, async move  |workspace, cx| {
 1904                let open_by_project_path = open_by_project_path.await;
 1905                let mut navigated = false;
 1906                match open_by_project_path
 1907                    .with_context(|| format!("Navigating to {project_path:?}"))
 1908                {
 1909                    Ok((project_entry_id, build_item)) => {
 1910                        let prev_active_item_id = pane.update(cx, |pane, _| {
 1911                            pane.nav_history_mut().set_mode(mode);
 1912                            pane.active_item().map(|p| p.item_id())
 1913                        })?;
 1914
 1915                        pane.update_in(cx, |pane, window, cx| {
 1916                            let item = pane.open_item(
 1917                                project_entry_id,
 1918                                project_path,
 1919                                true,
 1920                                entry.is_preview,
 1921                                true,
 1922                                None,
 1923                                window, cx,
 1924                                build_item,
 1925                            );
 1926                            navigated |= Some(item.item_id()) != prev_active_item_id;
 1927                            pane.nav_history_mut().set_mode(NavigationMode::Normal);
 1928                            if let Some(data) = entry.data {
 1929                                navigated |= item.navigate(data, window, cx);
 1930                            }
 1931                        })?;
 1932                    }
 1933                    Err(open_by_project_path_e) => {
 1934                        // Fall back to opening by abs path, in case an external file was opened and closed,
 1935                        // and its worktree is now dropped
 1936                        if let Some(abs_path) = abs_path {
 1937                            let prev_active_item_id = pane.update(cx, |pane, _| {
 1938                                pane.nav_history_mut().set_mode(mode);
 1939                                pane.active_item().map(|p| p.item_id())
 1940                            })?;
 1941                            let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
 1942                                workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
 1943                            })?;
 1944                            match open_by_abs_path
 1945                                .await
 1946                                .with_context(|| format!("Navigating to {abs_path:?}"))
 1947                            {
 1948                                Ok(item) => {
 1949                                    pane.update_in(cx, |pane, window, cx| {
 1950                                        navigated |= Some(item.item_id()) != prev_active_item_id;
 1951                                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 1952                                        if let Some(data) = entry.data {
 1953                                            navigated |= item.navigate(data, window, cx);
 1954                                        }
 1955                                    })?;
 1956                                }
 1957                                Err(open_by_abs_path_e) => {
 1958                                    log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
 1959                                }
 1960                            }
 1961                        }
 1962                    }
 1963                }
 1964
 1965                if !navigated {
 1966                    workspace
 1967                        .update_in(cx, |workspace, window, cx| {
 1968                            Self::navigate_history(workspace, pane, mode, window, cx)
 1969                        })?
 1970                        .await?;
 1971                }
 1972
 1973                Ok(())
 1974            })
 1975        } else {
 1976            Task::ready(Ok(()))
 1977        }
 1978    }
 1979
 1980    pub fn go_back(
 1981        &mut self,
 1982        pane: WeakEntity<Pane>,
 1983        window: &mut Window,
 1984        cx: &mut Context<Workspace>,
 1985    ) -> Task<Result<()>> {
 1986        self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
 1987    }
 1988
 1989    pub fn go_forward(
 1990        &mut self,
 1991        pane: WeakEntity<Pane>,
 1992        window: &mut Window,
 1993        cx: &mut Context<Workspace>,
 1994    ) -> Task<Result<()>> {
 1995        self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
 1996    }
 1997
 1998    pub fn reopen_closed_item(
 1999        &mut self,
 2000        window: &mut Window,
 2001        cx: &mut Context<Workspace>,
 2002    ) -> Task<Result<()>> {
 2003        self.navigate_history(
 2004            self.active_pane().downgrade(),
 2005            NavigationMode::ReopeningClosedItem,
 2006            window,
 2007            cx,
 2008        )
 2009    }
 2010
 2011    pub fn client(&self) -> &Arc<Client> {
 2012        &self.app_state.client
 2013    }
 2014
 2015    pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
 2016        self.titlebar_item = Some(item);
 2017        cx.notify();
 2018    }
 2019
 2020    pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
 2021        self.on_prompt_for_new_path = Some(prompt)
 2022    }
 2023
 2024    pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
 2025        self.on_prompt_for_open_path = Some(prompt)
 2026    }
 2027
 2028    pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
 2029        self.terminal_provider = Some(Box::new(provider));
 2030    }
 2031
 2032    pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
 2033        self.debugger_provider = Some(Arc::new(provider));
 2034    }
 2035
 2036    pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
 2037        self.debugger_provider.clone()
 2038    }
 2039
 2040    pub fn prompt_for_open_path(
 2041        &mut self,
 2042        path_prompt_options: PathPromptOptions,
 2043        lister: DirectoryLister,
 2044        window: &mut Window,
 2045        cx: &mut Context<Self>,
 2046    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2047        if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
 2048            let prompt = self.on_prompt_for_open_path.take().unwrap();
 2049            let rx = prompt(self, lister, window, cx);
 2050            self.on_prompt_for_open_path = Some(prompt);
 2051            rx
 2052        } else {
 2053            let (tx, rx) = oneshot::channel();
 2054            let abs_path = cx.prompt_for_paths(path_prompt_options);
 2055
 2056            cx.spawn_in(window, async move |workspace, cx| {
 2057                let Ok(result) = abs_path.await else {
 2058                    return Ok(());
 2059                };
 2060
 2061                match result {
 2062                    Ok(result) => {
 2063                        tx.send(result).ok();
 2064                    }
 2065                    Err(err) => {
 2066                        let rx = workspace.update_in(cx, |workspace, window, cx| {
 2067                            workspace.show_portal_error(err.to_string(), cx);
 2068                            let prompt = workspace.on_prompt_for_open_path.take().unwrap();
 2069                            let rx = prompt(workspace, lister, window, cx);
 2070                            workspace.on_prompt_for_open_path = Some(prompt);
 2071                            rx
 2072                        })?;
 2073                        if let Ok(path) = rx.await {
 2074                            tx.send(path).ok();
 2075                        }
 2076                    }
 2077                };
 2078                anyhow::Ok(())
 2079            })
 2080            .detach();
 2081
 2082            rx
 2083        }
 2084    }
 2085
 2086    pub fn prompt_for_new_path(
 2087        &mut self,
 2088        lister: DirectoryLister,
 2089        suggested_name: Option<String>,
 2090        window: &mut Window,
 2091        cx: &mut Context<Self>,
 2092    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
 2093        if self.project.read(cx).is_via_collab()
 2094            || self.project.read(cx).is_via_remote_server()
 2095            || !WorkspaceSettings::get_global(cx).use_system_path_prompts
 2096        {
 2097            let prompt = self.on_prompt_for_new_path.take().unwrap();
 2098            let rx = prompt(self, lister, window, cx);
 2099            self.on_prompt_for_new_path = Some(prompt);
 2100            return rx;
 2101        }
 2102
 2103        let (tx, rx) = oneshot::channel();
 2104        cx.spawn_in(window, async move |workspace, cx| {
 2105            let abs_path = workspace.update(cx, |workspace, cx| {
 2106                let relative_to = workspace
 2107                    .most_recent_active_path(cx)
 2108                    .and_then(|p| p.parent().map(|p| p.to_path_buf()))
 2109                    .or_else(|| {
 2110                        let project = workspace.project.read(cx);
 2111                        project.visible_worktrees(cx).find_map(|worktree| {
 2112                            Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
 2113                        })
 2114                    })
 2115                    .or_else(std::env::home_dir)
 2116                    .unwrap_or_else(|| PathBuf::from(""));
 2117                cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
 2118            })?;
 2119            let abs_path = match abs_path.await? {
 2120                Ok(path) => path,
 2121                Err(err) => {
 2122                    let rx = workspace.update_in(cx, |workspace, window, cx| {
 2123                        workspace.show_portal_error(err.to_string(), cx);
 2124
 2125                        let prompt = workspace.on_prompt_for_new_path.take().unwrap();
 2126                        let rx = prompt(workspace, lister, window, cx);
 2127                        workspace.on_prompt_for_new_path = Some(prompt);
 2128                        rx
 2129                    })?;
 2130                    if let Ok(path) = rx.await {
 2131                        tx.send(path).ok();
 2132                    }
 2133                    return anyhow::Ok(());
 2134                }
 2135            };
 2136
 2137            tx.send(abs_path.map(|path| vec![path])).ok();
 2138            anyhow::Ok(())
 2139        })
 2140        .detach();
 2141
 2142        rx
 2143    }
 2144
 2145    pub fn titlebar_item(&self) -> Option<AnyView> {
 2146        self.titlebar_item.clone()
 2147    }
 2148
 2149    /// Call the given callback with a workspace whose project is local.
 2150    ///
 2151    /// If the given workspace has a local project, then it will be passed
 2152    /// to the callback. Otherwise, a new empty window will be created.
 2153    pub fn with_local_workspace<T, F>(
 2154        &mut self,
 2155        window: &mut Window,
 2156        cx: &mut Context<Self>,
 2157        callback: F,
 2158    ) -> Task<Result<T>>
 2159    where
 2160        T: 'static,
 2161        F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
 2162    {
 2163        if self.project.read(cx).is_local() {
 2164            Task::ready(Ok(callback(self, window, cx)))
 2165        } else {
 2166            let env = self.project.read(cx).cli_environment(cx);
 2167            let task = Self::new_local(Vec::new(), self.app_state.clone(), None, env, cx);
 2168            cx.spawn_in(window, async move |_vh, cx| {
 2169                let (workspace, _) = task.await?;
 2170                workspace.update(cx, callback)
 2171            })
 2172        }
 2173    }
 2174
 2175    pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2176        self.project.read(cx).worktrees(cx)
 2177    }
 2178
 2179    pub fn visible_worktrees<'a>(
 2180        &self,
 2181        cx: &'a App,
 2182    ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
 2183        self.project.read(cx).visible_worktrees(cx)
 2184    }
 2185
 2186    #[cfg(any(test, feature = "test-support"))]
 2187    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
 2188        let futures = self
 2189            .worktrees(cx)
 2190            .filter_map(|worktree| worktree.read(cx).as_local())
 2191            .map(|worktree| worktree.scan_complete())
 2192            .collect::<Vec<_>>();
 2193        async move {
 2194            for future in futures {
 2195                future.await;
 2196            }
 2197        }
 2198    }
 2199
 2200    pub fn close_global(cx: &mut App) {
 2201        cx.defer(|cx| {
 2202            cx.windows().iter().find(|window| {
 2203                window
 2204                    .update(cx, |_, window, _| {
 2205                        if window.is_window_active() {
 2206                            //This can only get called when the window's project connection has been lost
 2207                            //so we don't need to prompt the user for anything and instead just close the window
 2208                            window.remove_window();
 2209                            true
 2210                        } else {
 2211                            false
 2212                        }
 2213                    })
 2214                    .unwrap_or(false)
 2215            });
 2216        });
 2217    }
 2218
 2219    pub fn close_window(&mut self, _: &CloseWindow, window: &mut Window, cx: &mut Context<Self>) {
 2220        let prepare = self.prepare_to_close(CloseIntent::CloseWindow, window, cx);
 2221        cx.spawn_in(window, async move |_, cx| {
 2222            if prepare.await? {
 2223                cx.update(|window, _cx| window.remove_window())?;
 2224            }
 2225            anyhow::Ok(())
 2226        })
 2227        .detach_and_log_err(cx)
 2228    }
 2229
 2230    pub fn move_focused_panel_to_next_position(
 2231        &mut self,
 2232        _: &MoveFocusedPanelToNextPosition,
 2233        window: &mut Window,
 2234        cx: &mut Context<Self>,
 2235    ) {
 2236        let docks = self.all_docks();
 2237        let active_dock = docks
 2238            .into_iter()
 2239            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 2240
 2241        if let Some(dock) = active_dock {
 2242            dock.update(cx, |dock, cx| {
 2243                let active_panel = dock
 2244                    .active_panel()
 2245                    .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
 2246
 2247                if let Some(panel) = active_panel {
 2248                    panel.move_to_next_position(window, cx);
 2249                }
 2250            })
 2251        }
 2252    }
 2253
 2254    pub fn prepare_to_close(
 2255        &mut self,
 2256        close_intent: CloseIntent,
 2257        window: &mut Window,
 2258        cx: &mut Context<Self>,
 2259    ) -> Task<Result<bool>> {
 2260        let active_call = self.active_call().cloned();
 2261
 2262        // On Linux and Windows, closing the last window should restore the last workspace.
 2263        let save_last_workspace = cfg!(not(target_os = "macos"))
 2264            && close_intent != CloseIntent::ReplaceWindow
 2265            && cx.windows().len() == 1;
 2266
 2267        cx.spawn_in(window, async move |this, cx| {
 2268            let workspace_count = cx.update(|_window, cx| {
 2269                cx.windows()
 2270                    .iter()
 2271                    .filter(|window| window.downcast::<Workspace>().is_some())
 2272                    .count()
 2273            })?;
 2274
 2275            if let Some(active_call) = active_call
 2276                && workspace_count == 1
 2277                && active_call.read_with(cx, |call, _| call.room().is_some())?
 2278            {
 2279                if close_intent == CloseIntent::CloseWindow {
 2280                    let answer = cx.update(|window, cx| {
 2281                        window.prompt(
 2282                            PromptLevel::Warning,
 2283                            "Do you want to leave the current call?",
 2284                            None,
 2285                            &["Close window and hang up", "Cancel"],
 2286                            cx,
 2287                        )
 2288                    })?;
 2289
 2290                    if answer.await.log_err() == Some(1) {
 2291                        return anyhow::Ok(false);
 2292                    } else {
 2293                        active_call
 2294                            .update(cx, |call, cx| call.hang_up(cx))?
 2295                            .await
 2296                            .log_err();
 2297                    }
 2298                }
 2299                if close_intent == CloseIntent::ReplaceWindow {
 2300                    _ = active_call.update(cx, |this, cx| {
 2301                        let workspace = cx
 2302                            .windows()
 2303                            .iter()
 2304                            .filter_map(|window| window.downcast::<Workspace>())
 2305                            .next()
 2306                            .unwrap();
 2307                        let project = workspace.read(cx)?.project.clone();
 2308                        if project.read(cx).is_shared() {
 2309                            this.unshare_project(project, cx)?;
 2310                        }
 2311                        Ok::<_, anyhow::Error>(())
 2312                    })?;
 2313                }
 2314            }
 2315
 2316            let save_result = this
 2317                .update_in(cx, |this, window, cx| {
 2318                    this.save_all_internal(SaveIntent::Close, window, cx)
 2319                })?
 2320                .await;
 2321
 2322            // If we're not quitting, but closing, we remove the workspace from
 2323            // the current session.
 2324            if close_intent != CloseIntent::Quit
 2325                && !save_last_workspace
 2326                && save_result.as_ref().is_ok_and(|&res| res)
 2327            {
 2328                this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
 2329                    .await;
 2330            }
 2331
 2332            save_result
 2333        })
 2334    }
 2335
 2336    fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
 2337        self.save_all_internal(
 2338            action.save_intent.unwrap_or(SaveIntent::SaveAll),
 2339            window,
 2340            cx,
 2341        )
 2342        .detach_and_log_err(cx);
 2343    }
 2344
 2345    fn send_keystrokes(
 2346        &mut self,
 2347        action: &SendKeystrokes,
 2348        window: &mut Window,
 2349        cx: &mut Context<Self>,
 2350    ) {
 2351        let keystrokes: Vec<Keystroke> = action
 2352            .0
 2353            .split(' ')
 2354            .flat_map(|k| Keystroke::parse(k).log_err())
 2355            .collect();
 2356        let _ = self.send_keystrokes_impl(keystrokes, window, cx);
 2357    }
 2358
 2359    pub fn send_keystrokes_impl(
 2360        &mut self,
 2361        keystrokes: Vec<Keystroke>,
 2362        window: &mut Window,
 2363        cx: &mut Context<Self>,
 2364    ) -> Shared<Task<()>> {
 2365        let mut state = self.dispatching_keystrokes.borrow_mut();
 2366        if !state.dispatched.insert(keystrokes.clone()) {
 2367            cx.propagate();
 2368            return state.task.clone().unwrap();
 2369        }
 2370
 2371        state.queue.extend(keystrokes);
 2372
 2373        let keystrokes = self.dispatching_keystrokes.clone();
 2374        if state.task.is_none() {
 2375            state.task = Some(
 2376                window
 2377                    .spawn(cx, async move |cx| {
 2378                        // limit to 100 keystrokes to avoid infinite recursion.
 2379                        for _ in 0..100 {
 2380                            let mut state = keystrokes.borrow_mut();
 2381                            let Some(keystroke) = state.queue.pop_front() else {
 2382                                state.dispatched.clear();
 2383                                state.task.take();
 2384                                return;
 2385                            };
 2386                            drop(state);
 2387                            cx.update(|window, cx| {
 2388                                let focused = window.focused(cx);
 2389                                window.dispatch_keystroke(keystroke.clone(), cx);
 2390                                if window.focused(cx) != focused {
 2391                                    // dispatch_keystroke may cause the focus to change.
 2392                                    // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
 2393                                    // And we need that to happen before the next keystroke to keep vim mode happy...
 2394                                    // (Note that the tests always do this implicitly, so you must manually test with something like:
 2395                                    //   "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
 2396                                    // )
 2397                                    window.draw(cx).clear();
 2398                                }
 2399                            })
 2400                            .ok();
 2401                        }
 2402
 2403                        *keystrokes.borrow_mut() = Default::default();
 2404                        log::error!("over 100 keystrokes passed to send_keystrokes");
 2405                    })
 2406                    .shared(),
 2407            );
 2408        }
 2409        state.task.clone().unwrap()
 2410    }
 2411
 2412    fn save_all_internal(
 2413        &mut self,
 2414        mut save_intent: SaveIntent,
 2415        window: &mut Window,
 2416        cx: &mut Context<Self>,
 2417    ) -> Task<Result<bool>> {
 2418        if self.project.read(cx).is_disconnected(cx) {
 2419            return Task::ready(Ok(true));
 2420        }
 2421        let dirty_items = self
 2422            .panes
 2423            .iter()
 2424            .flat_map(|pane| {
 2425                pane.read(cx).items().filter_map(|item| {
 2426                    if item.is_dirty(cx) {
 2427                        item.tab_content_text(0, cx);
 2428                        Some((pane.downgrade(), item.boxed_clone()))
 2429                    } else {
 2430                        None
 2431                    }
 2432                })
 2433            })
 2434            .collect::<Vec<_>>();
 2435
 2436        let project = self.project.clone();
 2437        cx.spawn_in(window, async move |workspace, cx| {
 2438            let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
 2439                let (serialize_tasks, remaining_dirty_items) =
 2440                    workspace.update_in(cx, |workspace, window, cx| {
 2441                        let mut remaining_dirty_items = Vec::new();
 2442                        let mut serialize_tasks = Vec::new();
 2443                        for (pane, item) in dirty_items {
 2444                            if let Some(task) = item
 2445                                .to_serializable_item_handle(cx)
 2446                                .and_then(|handle| handle.serialize(workspace, true, window, cx))
 2447                            {
 2448                                serialize_tasks.push(task);
 2449                            } else {
 2450                                remaining_dirty_items.push((pane, item));
 2451                            }
 2452                        }
 2453                        (serialize_tasks, remaining_dirty_items)
 2454                    })?;
 2455
 2456                futures::future::try_join_all(serialize_tasks).await?;
 2457
 2458                if remaining_dirty_items.len() > 1 {
 2459                    let answer = workspace.update_in(cx, |_, window, cx| {
 2460                        let detail = Pane::file_names_for_prompt(
 2461                            &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
 2462                            cx,
 2463                        );
 2464                        window.prompt(
 2465                            PromptLevel::Warning,
 2466                            "Do you want to save all changes in the following files?",
 2467                            Some(&detail),
 2468                            &["Save all", "Discard all", "Cancel"],
 2469                            cx,
 2470                        )
 2471                    })?;
 2472                    match answer.await.log_err() {
 2473                        Some(0) => save_intent = SaveIntent::SaveAll,
 2474                        Some(1) => save_intent = SaveIntent::Skip,
 2475                        Some(2) => return Ok(false),
 2476                        _ => {}
 2477                    }
 2478                }
 2479
 2480                remaining_dirty_items
 2481            } else {
 2482                dirty_items
 2483            };
 2484
 2485            for (pane, item) in dirty_items {
 2486                let (singleton, project_entry_ids) =
 2487                    cx.update(|_, cx| (item.is_singleton(cx), item.project_entry_ids(cx)))?;
 2488                if (singleton || !project_entry_ids.is_empty())
 2489                    && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
 2490                {
 2491                    return Ok(false);
 2492                }
 2493            }
 2494            Ok(true)
 2495        })
 2496    }
 2497
 2498    pub fn open_workspace_for_paths(
 2499        &mut self,
 2500        replace_current_window: bool,
 2501        paths: Vec<PathBuf>,
 2502        window: &mut Window,
 2503        cx: &mut Context<Self>,
 2504    ) -> Task<Result<()>> {
 2505        let window_handle = window.window_handle().downcast::<Self>();
 2506        let is_remote = self.project.read(cx).is_via_collab();
 2507        let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
 2508        let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
 2509
 2510        let window_to_replace = if replace_current_window {
 2511            window_handle
 2512        } else if is_remote || has_worktree || has_dirty_items {
 2513            None
 2514        } else {
 2515            window_handle
 2516        };
 2517        let app_state = self.app_state.clone();
 2518
 2519        cx.spawn(async move |_, cx| {
 2520            cx.update(|cx| {
 2521                open_paths(
 2522                    &paths,
 2523                    app_state,
 2524                    OpenOptions {
 2525                        replace_window: window_to_replace,
 2526                        ..Default::default()
 2527                    },
 2528                    cx,
 2529                )
 2530            })?
 2531            .await?;
 2532            Ok(())
 2533        })
 2534    }
 2535
 2536    #[allow(clippy::type_complexity)]
 2537    pub fn open_paths(
 2538        &mut self,
 2539        mut abs_paths: Vec<PathBuf>,
 2540        options: OpenOptions,
 2541        pane: Option<WeakEntity<Pane>>,
 2542        window: &mut Window,
 2543        cx: &mut Context<Self>,
 2544    ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
 2545        let fs = self.app_state.fs.clone();
 2546
 2547        // Sort the paths to ensure we add worktrees for parents before their children.
 2548        abs_paths.sort_unstable();
 2549        cx.spawn_in(window, async move |this, cx| {
 2550            let mut tasks = Vec::with_capacity(abs_paths.len());
 2551
 2552            for abs_path in &abs_paths {
 2553                let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
 2554                    OpenVisible::All => Some(true),
 2555                    OpenVisible::None => Some(false),
 2556                    OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
 2557                        Some(Some(metadata)) => Some(!metadata.is_dir),
 2558                        Some(None) => Some(true),
 2559                        None => None,
 2560                    },
 2561                    OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
 2562                        Some(Some(metadata)) => Some(metadata.is_dir),
 2563                        Some(None) => Some(false),
 2564                        None => None,
 2565                    },
 2566                };
 2567                let project_path = match visible {
 2568                    Some(visible) => match this
 2569                        .update(cx, |this, cx| {
 2570                            Workspace::project_path_for_path(
 2571                                this.project.clone(),
 2572                                abs_path,
 2573                                visible,
 2574                                cx,
 2575                            )
 2576                        })
 2577                        .log_err()
 2578                    {
 2579                        Some(project_path) => project_path.await.log_err(),
 2580                        None => None,
 2581                    },
 2582                    None => None,
 2583                };
 2584
 2585                let this = this.clone();
 2586                let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
 2587                let fs = fs.clone();
 2588                let pane = pane.clone();
 2589                let task = cx.spawn(async move |cx| {
 2590                    let (worktree, project_path) = project_path?;
 2591                    if fs.is_dir(&abs_path).await {
 2592                        this.update(cx, |workspace, cx| {
 2593                            let worktree = worktree.read(cx);
 2594                            let worktree_abs_path = worktree.abs_path();
 2595                            let entry_id = if abs_path.as_ref() == worktree_abs_path.as_ref() {
 2596                                worktree.root_entry()
 2597                            } else {
 2598                                abs_path
 2599                                    .strip_prefix(worktree_abs_path.as_ref())
 2600                                    .ok()
 2601                                    .and_then(|relative_path| {
 2602                                        worktree.entry_for_path(relative_path)
 2603                                    })
 2604                            }
 2605                            .map(|entry| entry.id);
 2606                            if let Some(entry_id) = entry_id {
 2607                                workspace.project.update(cx, |_, cx| {
 2608                                    cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
 2609                                })
 2610                            }
 2611                        })
 2612                        .ok()?;
 2613                        None
 2614                    } else {
 2615                        Some(
 2616                            this.update_in(cx, |this, window, cx| {
 2617                                this.open_path(
 2618                                    project_path,
 2619                                    pane,
 2620                                    options.focus.unwrap_or(true),
 2621                                    window,
 2622                                    cx,
 2623                                )
 2624                            })
 2625                            .ok()?
 2626                            .await,
 2627                        )
 2628                    }
 2629                });
 2630                tasks.push(task);
 2631            }
 2632
 2633            futures::future::join_all(tasks).await
 2634        })
 2635    }
 2636
 2637    pub fn open_resolved_path(
 2638        &mut self,
 2639        path: ResolvedPath,
 2640        window: &mut Window,
 2641        cx: &mut Context<Self>,
 2642    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 2643        match path {
 2644            ResolvedPath::ProjectPath { project_path, .. } => {
 2645                self.open_path(project_path, None, true, window, cx)
 2646            }
 2647            ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
 2648                path,
 2649                OpenOptions {
 2650                    visible: Some(OpenVisible::None),
 2651                    ..Default::default()
 2652                },
 2653                window,
 2654                cx,
 2655            ),
 2656        }
 2657    }
 2658
 2659    pub fn absolute_path_of_worktree(
 2660        &self,
 2661        worktree_id: WorktreeId,
 2662        cx: &mut Context<Self>,
 2663    ) -> Option<PathBuf> {
 2664        self.project
 2665            .read(cx)
 2666            .worktree_for_id(worktree_id, cx)
 2667            // TODO: use `abs_path` or `root_dir`
 2668            .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
 2669    }
 2670
 2671    fn add_folder_to_project(
 2672        &mut self,
 2673        _: &AddFolderToProject,
 2674        window: &mut Window,
 2675        cx: &mut Context<Self>,
 2676    ) {
 2677        let project = self.project.read(cx);
 2678        if project.is_via_collab() {
 2679            self.show_error(
 2680                &anyhow!("You cannot add folders to someone else's project"),
 2681                cx,
 2682            );
 2683            return;
 2684        }
 2685        let paths = self.prompt_for_open_path(
 2686            PathPromptOptions {
 2687                files: false,
 2688                directories: true,
 2689                multiple: true,
 2690                prompt: None,
 2691            },
 2692            DirectoryLister::Project(self.project.clone()),
 2693            window,
 2694            cx,
 2695        );
 2696        cx.spawn_in(window, async move |this, cx| {
 2697            if let Some(paths) = paths.await.log_err().flatten() {
 2698                let results = this
 2699                    .update_in(cx, |this, window, cx| {
 2700                        this.open_paths(
 2701                            paths,
 2702                            OpenOptions {
 2703                                visible: Some(OpenVisible::All),
 2704                                ..Default::default()
 2705                            },
 2706                            None,
 2707                            window,
 2708                            cx,
 2709                        )
 2710                    })?
 2711                    .await;
 2712                for result in results.into_iter().flatten() {
 2713                    result.log_err();
 2714                }
 2715            }
 2716            anyhow::Ok(())
 2717        })
 2718        .detach_and_log_err(cx);
 2719    }
 2720
 2721    pub fn project_path_for_path(
 2722        project: Entity<Project>,
 2723        abs_path: &Path,
 2724        visible: bool,
 2725        cx: &mut App,
 2726    ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
 2727        let entry = project.update(cx, |project, cx| {
 2728            project.find_or_create_worktree(abs_path, visible, cx)
 2729        });
 2730        cx.spawn(async move |cx| {
 2731            let (worktree, path) = entry.await?;
 2732            let worktree_id = worktree.read_with(cx, |t, _| t.id())?;
 2733            Ok((
 2734                worktree,
 2735                ProjectPath {
 2736                    worktree_id,
 2737                    path: path.into(),
 2738                },
 2739            ))
 2740        })
 2741    }
 2742
 2743    pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
 2744        self.panes.iter().flat_map(|pane| pane.read(cx).items())
 2745    }
 2746
 2747    pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
 2748        self.items_of_type(cx).max_by_key(|item| item.item_id())
 2749    }
 2750
 2751    pub fn items_of_type<'a, T: Item>(
 2752        &'a self,
 2753        cx: &'a App,
 2754    ) -> impl 'a + Iterator<Item = Entity<T>> {
 2755        self.panes
 2756            .iter()
 2757            .flat_map(|pane| pane.read(cx).items_of_type())
 2758    }
 2759
 2760    pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
 2761        self.active_pane().read(cx).active_item()
 2762    }
 2763
 2764    pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
 2765        let item = self.active_item(cx)?;
 2766        item.to_any().downcast::<I>().ok()
 2767    }
 2768
 2769    fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
 2770        self.active_item(cx).and_then(|item| item.project_path(cx))
 2771    }
 2772
 2773    pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
 2774        self.recent_navigation_history_iter(cx)
 2775            .filter_map(|(path, abs_path)| {
 2776                let worktree = self
 2777                    .project
 2778                    .read(cx)
 2779                    .worktree_for_id(path.worktree_id, cx)?;
 2780                if worktree.read(cx).is_visible() {
 2781                    abs_path
 2782                } else {
 2783                    None
 2784                }
 2785            })
 2786            .next()
 2787    }
 2788
 2789    pub fn save_active_item(
 2790        &mut self,
 2791        save_intent: SaveIntent,
 2792        window: &mut Window,
 2793        cx: &mut App,
 2794    ) -> Task<Result<()>> {
 2795        let project = self.project.clone();
 2796        let pane = self.active_pane();
 2797        let item = pane.read(cx).active_item();
 2798        let pane = pane.downgrade();
 2799
 2800        window.spawn(cx, async move |cx| {
 2801            if let Some(item) = item {
 2802                Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
 2803                    .await
 2804                    .map(|_| ())
 2805            } else {
 2806                Ok(())
 2807            }
 2808        })
 2809    }
 2810
 2811    pub fn close_inactive_items_and_panes(
 2812        &mut self,
 2813        action: &CloseInactiveTabsAndPanes,
 2814        window: &mut Window,
 2815        cx: &mut Context<Self>,
 2816    ) {
 2817        if let Some(task) = self.close_all_internal(
 2818            true,
 2819            action.save_intent.unwrap_or(SaveIntent::Close),
 2820            window,
 2821            cx,
 2822        ) {
 2823            task.detach_and_log_err(cx)
 2824        }
 2825    }
 2826
 2827    pub fn close_all_items_and_panes(
 2828        &mut self,
 2829        action: &CloseAllItemsAndPanes,
 2830        window: &mut Window,
 2831        cx: &mut Context<Self>,
 2832    ) {
 2833        if let Some(task) = self.close_all_internal(
 2834            false,
 2835            action.save_intent.unwrap_or(SaveIntent::Close),
 2836            window,
 2837            cx,
 2838        ) {
 2839            task.detach_and_log_err(cx)
 2840        }
 2841    }
 2842
 2843    fn close_all_internal(
 2844        &mut self,
 2845        retain_active_pane: bool,
 2846        save_intent: SaveIntent,
 2847        window: &mut Window,
 2848        cx: &mut Context<Self>,
 2849    ) -> Option<Task<Result<()>>> {
 2850        let current_pane = self.active_pane();
 2851
 2852        let mut tasks = Vec::new();
 2853
 2854        if retain_active_pane {
 2855            let current_pane_close = current_pane.update(cx, |pane, cx| {
 2856                pane.close_other_items(
 2857                    &CloseOtherItems {
 2858                        save_intent: None,
 2859                        close_pinned: false,
 2860                    },
 2861                    None,
 2862                    window,
 2863                    cx,
 2864                )
 2865            });
 2866
 2867            tasks.push(current_pane_close);
 2868        }
 2869
 2870        for pane in self.panes() {
 2871            if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
 2872                continue;
 2873            }
 2874
 2875            let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
 2876                pane.close_all_items(
 2877                    &CloseAllItems {
 2878                        save_intent: Some(save_intent),
 2879                        close_pinned: false,
 2880                    },
 2881                    window,
 2882                    cx,
 2883                )
 2884            });
 2885
 2886            tasks.push(close_pane_items)
 2887        }
 2888
 2889        if tasks.is_empty() {
 2890            None
 2891        } else {
 2892            Some(cx.spawn_in(window, async move |_, _| {
 2893                for task in tasks {
 2894                    task.await?
 2895                }
 2896                Ok(())
 2897            }))
 2898        }
 2899    }
 2900
 2901    pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
 2902        self.dock_at_position(position).read(cx).is_open()
 2903    }
 2904
 2905    pub fn toggle_dock(
 2906        &mut self,
 2907        dock_side: DockPosition,
 2908        window: &mut Window,
 2909        cx: &mut Context<Self>,
 2910    ) {
 2911        let dock = self.dock_at_position(dock_side);
 2912        let mut focus_center = false;
 2913        let mut reveal_dock = false;
 2914        dock.update(cx, |dock, cx| {
 2915            let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
 2916            let was_visible = dock.is_open() && !other_is_zoomed;
 2917            dock.set_open(!was_visible, window, cx);
 2918
 2919            if dock.active_panel().is_none() {
 2920                let Some(panel_ix) = dock
 2921                    .first_enabled_panel_idx(cx)
 2922                    .log_with_level(log::Level::Info)
 2923                else {
 2924                    return;
 2925                };
 2926                dock.activate_panel(panel_ix, window, cx);
 2927            }
 2928
 2929            if let Some(active_panel) = dock.active_panel() {
 2930                if was_visible {
 2931                    if active_panel
 2932                        .panel_focus_handle(cx)
 2933                        .contains_focused(window, cx)
 2934                    {
 2935                        focus_center = true;
 2936                    }
 2937                } else {
 2938                    let focus_handle = &active_panel.panel_focus_handle(cx);
 2939                    window.focus(focus_handle);
 2940                    reveal_dock = true;
 2941                }
 2942            }
 2943        });
 2944
 2945        if reveal_dock {
 2946            self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
 2947        }
 2948
 2949        if focus_center {
 2950            self.active_pane
 2951                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
 2952        }
 2953
 2954        cx.notify();
 2955        self.serialize_workspace(window, cx);
 2956    }
 2957
 2958    fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
 2959        self.all_docks().into_iter().find(|&dock| {
 2960            dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
 2961        })
 2962    }
 2963
 2964    fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 2965        if let Some(dock) = self.active_dock(window, cx) {
 2966            dock.update(cx, |dock, cx| {
 2967                dock.set_open(false, window, cx);
 2968            });
 2969            return true;
 2970        }
 2971        false
 2972    }
 2973
 2974    pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2975        for dock in self.all_docks() {
 2976            dock.update(cx, |dock, cx| {
 2977                dock.set_open(false, window, cx);
 2978            });
 2979        }
 2980
 2981        cx.focus_self(window);
 2982        cx.notify();
 2983        self.serialize_workspace(window, cx);
 2984    }
 2985
 2986    /// Transfer focus to the panel of the given type.
 2987    pub fn focus_panel<T: Panel>(
 2988        &mut self,
 2989        window: &mut Window,
 2990        cx: &mut Context<Self>,
 2991    ) -> Option<Entity<T>> {
 2992        let panel = self.focus_or_unfocus_panel::<T>(window, cx, |_, _, _| true)?;
 2993        panel.to_any().downcast().ok()
 2994    }
 2995
 2996    /// Focus the panel of the given type if it isn't already focused. If it is
 2997    /// already focused, then transfer focus back to the workspace center.
 2998    pub fn toggle_panel_focus<T: Panel>(
 2999        &mut self,
 3000        window: &mut Window,
 3001        cx: &mut Context<Self>,
 3002    ) -> bool {
 3003        let mut did_focus_panel = false;
 3004        self.focus_or_unfocus_panel::<T>(window, cx, |panel, window, cx| {
 3005            did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
 3006            did_focus_panel
 3007        });
 3008        did_focus_panel
 3009    }
 3010
 3011    pub fn activate_panel_for_proto_id(
 3012        &mut self,
 3013        panel_id: PanelId,
 3014        window: &mut Window,
 3015        cx: &mut Context<Self>,
 3016    ) -> Option<Arc<dyn PanelHandle>> {
 3017        let mut panel = None;
 3018        for dock in self.all_docks() {
 3019            if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
 3020                panel = dock.update(cx, |dock, cx| {
 3021                    dock.activate_panel(panel_index, window, cx);
 3022                    dock.set_open(true, window, cx);
 3023                    dock.active_panel().cloned()
 3024                });
 3025                break;
 3026            }
 3027        }
 3028
 3029        if panel.is_some() {
 3030            cx.notify();
 3031            self.serialize_workspace(window, cx);
 3032        }
 3033
 3034        panel
 3035    }
 3036
 3037    /// Focus or unfocus the given panel type, depending on the given callback.
 3038    fn focus_or_unfocus_panel<T: Panel>(
 3039        &mut self,
 3040        window: &mut Window,
 3041        cx: &mut Context<Self>,
 3042        mut should_focus: impl FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
 3043    ) -> Option<Arc<dyn PanelHandle>> {
 3044        let mut result_panel = None;
 3045        let mut serialize = false;
 3046        for dock in self.all_docks() {
 3047            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3048                let mut focus_center = false;
 3049                let panel = dock.update(cx, |dock, cx| {
 3050                    dock.activate_panel(panel_index, window, cx);
 3051
 3052                    let panel = dock.active_panel().cloned();
 3053                    if let Some(panel) = panel.as_ref() {
 3054                        if should_focus(&**panel, window, cx) {
 3055                            dock.set_open(true, window, cx);
 3056                            panel.panel_focus_handle(cx).focus(window);
 3057                        } else {
 3058                            focus_center = true;
 3059                        }
 3060                    }
 3061                    panel
 3062                });
 3063
 3064                if focus_center {
 3065                    self.active_pane
 3066                        .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
 3067                }
 3068
 3069                result_panel = panel;
 3070                serialize = true;
 3071                break;
 3072            }
 3073        }
 3074
 3075        if serialize {
 3076            self.serialize_workspace(window, cx);
 3077        }
 3078
 3079        cx.notify();
 3080        result_panel
 3081    }
 3082
 3083    /// Open the panel of the given type
 3084    pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3085        for dock in self.all_docks() {
 3086            if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
 3087                dock.update(cx, |dock, cx| {
 3088                    dock.activate_panel(panel_index, window, cx);
 3089                    dock.set_open(true, window, cx);
 3090                });
 3091            }
 3092        }
 3093    }
 3094
 3095    pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
 3096        self.all_docks()
 3097            .iter()
 3098            .find_map(|dock| dock.read(cx).panel::<T>())
 3099    }
 3100
 3101    fn dismiss_zoomed_items_to_reveal(
 3102        &mut self,
 3103        dock_to_reveal: Option<DockPosition>,
 3104        window: &mut Window,
 3105        cx: &mut Context<Self>,
 3106    ) {
 3107        // If a center pane is zoomed, unzoom it.
 3108        for pane in &self.panes {
 3109            if pane != &self.active_pane || dock_to_reveal.is_some() {
 3110                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 3111            }
 3112        }
 3113
 3114        // If another dock is zoomed, hide it.
 3115        let mut focus_center = false;
 3116        for dock in self.all_docks() {
 3117            dock.update(cx, |dock, cx| {
 3118                if Some(dock.position()) != dock_to_reveal
 3119                    && let Some(panel) = dock.active_panel()
 3120                    && panel.is_zoomed(window, cx)
 3121                {
 3122                    focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
 3123                    dock.set_open(false, window, cx);
 3124                }
 3125            });
 3126        }
 3127
 3128        if focus_center {
 3129            self.active_pane
 3130                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)))
 3131        }
 3132
 3133        if self.zoomed_position != dock_to_reveal {
 3134            self.zoomed = None;
 3135            self.zoomed_position = None;
 3136            cx.emit(Event::ZoomChanged);
 3137        }
 3138
 3139        cx.notify();
 3140    }
 3141
 3142    fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 3143        let pane = cx.new(|cx| {
 3144            let mut pane = Pane::new(
 3145                self.weak_handle(),
 3146                self.project.clone(),
 3147                self.pane_history_timestamp.clone(),
 3148                None,
 3149                NewFile.boxed_clone(),
 3150                window,
 3151                cx,
 3152            );
 3153            pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
 3154            pane
 3155        });
 3156        cx.subscribe_in(&pane, window, Self::handle_pane_event)
 3157            .detach();
 3158        self.panes.push(pane.clone());
 3159
 3160        window.focus(&pane.focus_handle(cx));
 3161
 3162        cx.emit(Event::PaneAdded(pane.clone()));
 3163        pane
 3164    }
 3165
 3166    pub fn add_item_to_center(
 3167        &mut self,
 3168        item: Box<dyn ItemHandle>,
 3169        window: &mut Window,
 3170        cx: &mut Context<Self>,
 3171    ) -> bool {
 3172        if let Some(center_pane) = self.last_active_center_pane.clone() {
 3173            if let Some(center_pane) = center_pane.upgrade() {
 3174                center_pane.update(cx, |pane, cx| {
 3175                    pane.add_item(item, true, true, None, window, cx)
 3176                });
 3177                true
 3178            } else {
 3179                false
 3180            }
 3181        } else {
 3182            false
 3183        }
 3184    }
 3185
 3186    pub fn add_item_to_active_pane(
 3187        &mut self,
 3188        item: Box<dyn ItemHandle>,
 3189        destination_index: Option<usize>,
 3190        focus_item: bool,
 3191        window: &mut Window,
 3192        cx: &mut App,
 3193    ) {
 3194        self.add_item(
 3195            self.active_pane.clone(),
 3196            item,
 3197            destination_index,
 3198            false,
 3199            focus_item,
 3200            window,
 3201            cx,
 3202        )
 3203    }
 3204
 3205    pub fn add_item(
 3206        &mut self,
 3207        pane: Entity<Pane>,
 3208        item: Box<dyn ItemHandle>,
 3209        destination_index: Option<usize>,
 3210        activate_pane: bool,
 3211        focus_item: bool,
 3212        window: &mut Window,
 3213        cx: &mut App,
 3214    ) {
 3215        if let Some(text) = item.telemetry_event_text(cx) {
 3216            telemetry::event!(text);
 3217        }
 3218
 3219        pane.update(cx, |pane, cx| {
 3220            pane.add_item(
 3221                item,
 3222                activate_pane,
 3223                focus_item,
 3224                destination_index,
 3225                window,
 3226                cx,
 3227            )
 3228        });
 3229    }
 3230
 3231    pub fn split_item(
 3232        &mut self,
 3233        split_direction: SplitDirection,
 3234        item: Box<dyn ItemHandle>,
 3235        window: &mut Window,
 3236        cx: &mut Context<Self>,
 3237    ) {
 3238        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
 3239        self.add_item(new_pane, item, None, true, true, window, cx);
 3240    }
 3241
 3242    pub fn open_abs_path(
 3243        &mut self,
 3244        abs_path: PathBuf,
 3245        options: OpenOptions,
 3246        window: &mut Window,
 3247        cx: &mut Context<Self>,
 3248    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3249        cx.spawn_in(window, async move |workspace, cx| {
 3250            let open_paths_task_result = workspace
 3251                .update_in(cx, |workspace, window, cx| {
 3252                    workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
 3253                })
 3254                .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
 3255                .await;
 3256            anyhow::ensure!(
 3257                open_paths_task_result.len() == 1,
 3258                "open abs path {abs_path:?} task returned incorrect number of results"
 3259            );
 3260            match open_paths_task_result
 3261                .into_iter()
 3262                .next()
 3263                .expect("ensured single task result")
 3264            {
 3265                Some(open_result) => {
 3266                    open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
 3267                }
 3268                None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
 3269            }
 3270        })
 3271    }
 3272
 3273    pub fn split_abs_path(
 3274        &mut self,
 3275        abs_path: PathBuf,
 3276        visible: bool,
 3277        window: &mut Window,
 3278        cx: &mut Context<Self>,
 3279    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3280        let project_path_task =
 3281            Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
 3282        cx.spawn_in(window, async move |this, cx| {
 3283            let (_, path) = project_path_task.await?;
 3284            this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
 3285                .await
 3286        })
 3287    }
 3288
 3289    pub fn open_path(
 3290        &mut self,
 3291        path: impl Into<ProjectPath>,
 3292        pane: Option<WeakEntity<Pane>>,
 3293        focus_item: bool,
 3294        window: &mut Window,
 3295        cx: &mut App,
 3296    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3297        self.open_path_preview(path, pane, focus_item, false, true, window, cx)
 3298    }
 3299
 3300    pub fn open_path_preview(
 3301        &mut self,
 3302        path: impl Into<ProjectPath>,
 3303        pane: Option<WeakEntity<Pane>>,
 3304        focus_item: bool,
 3305        allow_preview: bool,
 3306        activate: bool,
 3307        window: &mut Window,
 3308        cx: &mut App,
 3309    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3310        let pane = pane.unwrap_or_else(|| {
 3311            self.last_active_center_pane.clone().unwrap_or_else(|| {
 3312                self.panes
 3313                    .first()
 3314                    .expect("There must be an active pane")
 3315                    .downgrade()
 3316            })
 3317        });
 3318
 3319        let project_path = path.into();
 3320        let task = self.load_path(project_path.clone(), window, cx);
 3321        window.spawn(cx, async move |cx| {
 3322            let (project_entry_id, build_item) = task.await?;
 3323
 3324            pane.update_in(cx, |pane, window, cx| {
 3325                pane.open_item(
 3326                    project_entry_id,
 3327                    project_path,
 3328                    focus_item,
 3329                    allow_preview,
 3330                    activate,
 3331                    None,
 3332                    window,
 3333                    cx,
 3334                    build_item,
 3335                )
 3336            })
 3337        })
 3338    }
 3339
 3340    pub fn split_path(
 3341        &mut self,
 3342        path: impl Into<ProjectPath>,
 3343        window: &mut Window,
 3344        cx: &mut Context<Self>,
 3345    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3346        self.split_path_preview(path, false, None, window, cx)
 3347    }
 3348
 3349    pub fn split_path_preview(
 3350        &mut self,
 3351        path: impl Into<ProjectPath>,
 3352        allow_preview: bool,
 3353        split_direction: Option<SplitDirection>,
 3354        window: &mut Window,
 3355        cx: &mut Context<Self>,
 3356    ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
 3357        let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
 3358            self.panes
 3359                .first()
 3360                .expect("There must be an active pane")
 3361                .downgrade()
 3362        });
 3363
 3364        if let Member::Pane(center_pane) = &self.center.root
 3365            && center_pane.read(cx).items_len() == 0
 3366        {
 3367            return self.open_path(path, Some(pane), true, window, cx);
 3368        }
 3369
 3370        let project_path = path.into();
 3371        let task = self.load_path(project_path.clone(), window, cx);
 3372        cx.spawn_in(window, async move |this, cx| {
 3373            let (project_entry_id, build_item) = task.await?;
 3374            this.update_in(cx, move |this, window, cx| -> Option<_> {
 3375                let pane = pane.upgrade()?;
 3376                let new_pane = this.split_pane(
 3377                    pane,
 3378                    split_direction.unwrap_or(SplitDirection::Right),
 3379                    window,
 3380                    cx,
 3381                );
 3382                new_pane.update(cx, |new_pane, cx| {
 3383                    Some(new_pane.open_item(
 3384                        project_entry_id,
 3385                        project_path,
 3386                        true,
 3387                        allow_preview,
 3388                        true,
 3389                        None,
 3390                        window,
 3391                        cx,
 3392                        build_item,
 3393                    ))
 3394                })
 3395            })
 3396            .map(|option| option.context("pane was dropped"))?
 3397        })
 3398    }
 3399
 3400    fn load_path(
 3401        &mut self,
 3402        path: ProjectPath,
 3403        window: &mut Window,
 3404        cx: &mut App,
 3405    ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
 3406        let registry = cx.default_global::<ProjectItemRegistry>().clone();
 3407        registry.open_path(self.project(), &path, window, cx)
 3408    }
 3409
 3410    pub fn find_project_item<T>(
 3411        &self,
 3412        pane: &Entity<Pane>,
 3413        project_item: &Entity<T::Item>,
 3414        cx: &App,
 3415    ) -> Option<Entity<T>>
 3416    where
 3417        T: ProjectItem,
 3418    {
 3419        use project::ProjectItem as _;
 3420        let project_item = project_item.read(cx);
 3421        let entry_id = project_item.entry_id(cx);
 3422        let project_path = project_item.project_path(cx);
 3423
 3424        let mut item = None;
 3425        if let Some(entry_id) = entry_id {
 3426            item = pane.read(cx).item_for_entry(entry_id, cx);
 3427        }
 3428        if item.is_none()
 3429            && let Some(project_path) = project_path
 3430        {
 3431            item = pane.read(cx).item_for_path(project_path, cx);
 3432        }
 3433
 3434        item.and_then(|item| item.downcast::<T>())
 3435    }
 3436
 3437    pub fn is_project_item_open<T>(
 3438        &self,
 3439        pane: &Entity<Pane>,
 3440        project_item: &Entity<T::Item>,
 3441        cx: &App,
 3442    ) -> bool
 3443    where
 3444        T: ProjectItem,
 3445    {
 3446        self.find_project_item::<T>(pane, project_item, cx)
 3447            .is_some()
 3448    }
 3449
 3450    pub fn open_project_item<T>(
 3451        &mut self,
 3452        pane: Entity<Pane>,
 3453        project_item: Entity<T::Item>,
 3454        activate_pane: bool,
 3455        focus_item: bool,
 3456        window: &mut Window,
 3457        cx: &mut Context<Self>,
 3458    ) -> Entity<T>
 3459    where
 3460        T: ProjectItem,
 3461    {
 3462        if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
 3463            self.activate_item(&item, activate_pane, focus_item, window, cx);
 3464            return item;
 3465        }
 3466
 3467        let item = pane.update(cx, |pane, cx| {
 3468            cx.new(|cx| {
 3469                T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
 3470            })
 3471        });
 3472        let item_id = item.item_id();
 3473        let mut destination_index = None;
 3474        pane.update(cx, |pane, cx| {
 3475            if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation
 3476                && let Some(preview_item_id) = pane.preview_item_id()
 3477                && preview_item_id != item_id
 3478            {
 3479                destination_index = pane.close_current_preview_item(window, cx);
 3480            }
 3481            pane.set_preview_item_id(Some(item.item_id()), cx)
 3482        });
 3483
 3484        self.add_item(
 3485            pane,
 3486            Box::new(item.clone()),
 3487            destination_index,
 3488            activate_pane,
 3489            focus_item,
 3490            window,
 3491            cx,
 3492        );
 3493        item
 3494    }
 3495
 3496    pub fn open_shared_screen(
 3497        &mut self,
 3498        peer_id: PeerId,
 3499        window: &mut Window,
 3500        cx: &mut Context<Self>,
 3501    ) {
 3502        if let Some(shared_screen) =
 3503            self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
 3504        {
 3505            self.active_pane.update(cx, |pane, cx| {
 3506                pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
 3507            });
 3508        }
 3509    }
 3510
 3511    pub fn activate_item(
 3512        &mut self,
 3513        item: &dyn ItemHandle,
 3514        activate_pane: bool,
 3515        focus_item: bool,
 3516        window: &mut Window,
 3517        cx: &mut App,
 3518    ) -> bool {
 3519        let result = self.panes.iter().find_map(|pane| {
 3520            pane.read(cx)
 3521                .index_for_item(item)
 3522                .map(|ix| (pane.clone(), ix))
 3523        });
 3524        if let Some((pane, ix)) = result {
 3525            pane.update(cx, |pane, cx| {
 3526                pane.activate_item(ix, activate_pane, focus_item, window, cx)
 3527            });
 3528            true
 3529        } else {
 3530            false
 3531        }
 3532    }
 3533
 3534    fn activate_pane_at_index(
 3535        &mut self,
 3536        action: &ActivatePane,
 3537        window: &mut Window,
 3538        cx: &mut Context<Self>,
 3539    ) {
 3540        let panes = self.center.panes();
 3541        if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
 3542            window.focus(&pane.focus_handle(cx));
 3543        } else {
 3544            self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx);
 3545        }
 3546    }
 3547
 3548    fn move_item_to_pane_at_index(
 3549        &mut self,
 3550        action: &MoveItemToPane,
 3551        window: &mut Window,
 3552        cx: &mut Context<Self>,
 3553    ) {
 3554        let panes = self.center.panes();
 3555        let destination = match panes.get(action.destination) {
 3556            Some(&destination) => destination.clone(),
 3557            None => {
 3558                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 3559                    return;
 3560                }
 3561                let direction = SplitDirection::Right;
 3562                let split_off_pane = self
 3563                    .find_pane_in_direction(direction, cx)
 3564                    .unwrap_or_else(|| self.active_pane.clone());
 3565                let new_pane = self.add_pane(window, cx);
 3566                if self
 3567                    .center
 3568                    .split(&split_off_pane, &new_pane, direction)
 3569                    .log_err()
 3570                    .is_none()
 3571                {
 3572                    return;
 3573                };
 3574                new_pane
 3575            }
 3576        };
 3577
 3578        if action.clone {
 3579            clone_active_item(
 3580                self.database_id(),
 3581                &self.active_pane,
 3582                &destination,
 3583                action.focus,
 3584                window,
 3585                cx,
 3586            )
 3587        } else {
 3588            move_active_item(
 3589                &self.active_pane,
 3590                &destination,
 3591                action.focus,
 3592                true,
 3593                window,
 3594                cx,
 3595            )
 3596        }
 3597    }
 3598
 3599    pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
 3600        let panes = self.center.panes();
 3601        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 3602            let next_ix = (ix + 1) % panes.len();
 3603            let next_pane = panes[next_ix].clone();
 3604            window.focus(&next_pane.focus_handle(cx));
 3605        }
 3606    }
 3607
 3608    pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
 3609        let panes = self.center.panes();
 3610        if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
 3611            let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
 3612            let prev_pane = panes[prev_ix].clone();
 3613            window.focus(&prev_pane.focus_handle(cx));
 3614        }
 3615    }
 3616
 3617    pub fn activate_pane_in_direction(
 3618        &mut self,
 3619        direction: SplitDirection,
 3620        window: &mut Window,
 3621        cx: &mut App,
 3622    ) {
 3623        use ActivateInDirectionTarget as Target;
 3624        enum Origin {
 3625            LeftDock,
 3626            RightDock,
 3627            BottomDock,
 3628            Center,
 3629        }
 3630
 3631        let origin: Origin = [
 3632            (&self.left_dock, Origin::LeftDock),
 3633            (&self.right_dock, Origin::RightDock),
 3634            (&self.bottom_dock, Origin::BottomDock),
 3635        ]
 3636        .into_iter()
 3637        .find_map(|(dock, origin)| {
 3638            if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
 3639                Some(origin)
 3640            } else {
 3641                None
 3642            }
 3643        })
 3644        .unwrap_or(Origin::Center);
 3645
 3646        let get_last_active_pane = || {
 3647            let pane = self
 3648                .last_active_center_pane
 3649                .clone()
 3650                .unwrap_or_else(|| {
 3651                    self.panes
 3652                        .first()
 3653                        .expect("There must be an active pane")
 3654                        .downgrade()
 3655                })
 3656                .upgrade()?;
 3657            (pane.read(cx).items_len() != 0).then_some(pane)
 3658        };
 3659
 3660        let try_dock =
 3661            |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
 3662
 3663        let target = match (origin, direction) {
 3664            // We're in the center, so we first try to go to a different pane,
 3665            // otherwise try to go to a dock.
 3666            (Origin::Center, direction) => {
 3667                if let Some(pane) = self.find_pane_in_direction(direction, cx) {
 3668                    Some(Target::Pane(pane))
 3669                } else {
 3670                    match direction {
 3671                        SplitDirection::Up => None,
 3672                        SplitDirection::Down => try_dock(&self.bottom_dock),
 3673                        SplitDirection::Left => try_dock(&self.left_dock),
 3674                        SplitDirection::Right => try_dock(&self.right_dock),
 3675                    }
 3676                }
 3677            }
 3678
 3679            (Origin::LeftDock, SplitDirection::Right) => {
 3680                if let Some(last_active_pane) = get_last_active_pane() {
 3681                    Some(Target::Pane(last_active_pane))
 3682                } else {
 3683                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
 3684                }
 3685            }
 3686
 3687            (Origin::LeftDock, SplitDirection::Down)
 3688            | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
 3689
 3690            (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
 3691            (Origin::BottomDock, SplitDirection::Left) => try_dock(&self.left_dock),
 3692            (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
 3693
 3694            (Origin::RightDock, SplitDirection::Left) => {
 3695                if let Some(last_active_pane) = get_last_active_pane() {
 3696                    Some(Target::Pane(last_active_pane))
 3697                } else {
 3698                    try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
 3699                }
 3700            }
 3701
 3702            _ => None,
 3703        };
 3704
 3705        match target {
 3706            Some(ActivateInDirectionTarget::Pane(pane)) => {
 3707                let pane = pane.read(cx);
 3708                if let Some(item) = pane.active_item() {
 3709                    item.item_focus_handle(cx).focus(window);
 3710                } else {
 3711                    log::error!(
 3712                        "Could not find a focus target when in switching focus in {direction} direction for a pane",
 3713                    );
 3714                }
 3715            }
 3716            Some(ActivateInDirectionTarget::Dock(dock)) => {
 3717                // Defer this to avoid a panic when the dock's active panel is already on the stack.
 3718                window.defer(cx, move |window, cx| {
 3719                    let dock = dock.read(cx);
 3720                    if let Some(panel) = dock.active_panel() {
 3721                        panel.panel_focus_handle(cx).focus(window);
 3722                    } else {
 3723                        log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
 3724                    }
 3725                })
 3726            }
 3727            None => {}
 3728        }
 3729    }
 3730
 3731    pub fn move_item_to_pane_in_direction(
 3732        &mut self,
 3733        action: &MoveItemToPaneInDirection,
 3734        window: &mut Window,
 3735        cx: &mut Context<Self>,
 3736    ) {
 3737        let destination = match self.find_pane_in_direction(action.direction, cx) {
 3738            Some(destination) => destination,
 3739            None => {
 3740                if !action.clone && self.active_pane.read(cx).items_len() < 2 {
 3741                    return;
 3742                }
 3743                let new_pane = self.add_pane(window, cx);
 3744                if self
 3745                    .center
 3746                    .split(&self.active_pane, &new_pane, action.direction)
 3747                    .log_err()
 3748                    .is_none()
 3749                {
 3750                    return;
 3751                };
 3752                new_pane
 3753            }
 3754        };
 3755
 3756        if action.clone {
 3757            clone_active_item(
 3758                self.database_id(),
 3759                &self.active_pane,
 3760                &destination,
 3761                action.focus,
 3762                window,
 3763                cx,
 3764            )
 3765        } else {
 3766            move_active_item(
 3767                &self.active_pane,
 3768                &destination,
 3769                action.focus,
 3770                true,
 3771                window,
 3772                cx,
 3773            );
 3774        }
 3775    }
 3776
 3777    pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
 3778        self.center.bounding_box_for_pane(pane)
 3779    }
 3780
 3781    pub fn find_pane_in_direction(
 3782        &mut self,
 3783        direction: SplitDirection,
 3784        cx: &App,
 3785    ) -> Option<Entity<Pane>> {
 3786        self.center
 3787            .find_pane_in_direction(&self.active_pane, direction, cx)
 3788            .cloned()
 3789    }
 3790
 3791    pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
 3792        if let Some(to) = self.find_pane_in_direction(direction, cx) {
 3793            self.center.swap(&self.active_pane, &to);
 3794            cx.notify();
 3795        }
 3796    }
 3797
 3798    pub fn resize_pane(
 3799        &mut self,
 3800        axis: gpui::Axis,
 3801        amount: Pixels,
 3802        window: &mut Window,
 3803        cx: &mut Context<Self>,
 3804    ) {
 3805        let docks = self.all_docks();
 3806        let active_dock = docks
 3807            .into_iter()
 3808            .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
 3809
 3810        if let Some(dock) = active_dock {
 3811            let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
 3812                return;
 3813            };
 3814            match dock.read(cx).position() {
 3815                DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
 3816                DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
 3817                DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
 3818            }
 3819        } else {
 3820            self.center
 3821                .resize(&self.active_pane, axis, amount, &self.bounds);
 3822        }
 3823        cx.notify();
 3824    }
 3825
 3826    pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
 3827        self.center.reset_pane_sizes();
 3828        cx.notify();
 3829    }
 3830
 3831    fn handle_pane_focused(
 3832        &mut self,
 3833        pane: Entity<Pane>,
 3834        window: &mut Window,
 3835        cx: &mut Context<Self>,
 3836    ) {
 3837        // This is explicitly hoisted out of the following check for pane identity as
 3838        // terminal panel panes are not registered as a center panes.
 3839        self.status_bar.update(cx, |status_bar, cx| {
 3840            status_bar.set_active_pane(&pane, window, cx);
 3841        });
 3842        if self.active_pane != pane {
 3843            self.set_active_pane(&pane, window, cx);
 3844        }
 3845
 3846        if self.last_active_center_pane.is_none() {
 3847            self.last_active_center_pane = Some(pane.downgrade());
 3848        }
 3849
 3850        self.dismiss_zoomed_items_to_reveal(None, window, cx);
 3851        if pane.read(cx).is_zoomed() {
 3852            self.zoomed = Some(pane.downgrade().into());
 3853        } else {
 3854            self.zoomed = None;
 3855        }
 3856        self.zoomed_position = None;
 3857        cx.emit(Event::ZoomChanged);
 3858        self.update_active_view_for_followers(window, cx);
 3859        pane.update(cx, |pane, _| {
 3860            pane.track_alternate_file_items();
 3861        });
 3862
 3863        cx.notify();
 3864    }
 3865
 3866    fn set_active_pane(
 3867        &mut self,
 3868        pane: &Entity<Pane>,
 3869        window: &mut Window,
 3870        cx: &mut Context<Self>,
 3871    ) {
 3872        self.active_pane = pane.clone();
 3873        self.active_item_path_changed(window, cx);
 3874        self.last_active_center_pane = Some(pane.downgrade());
 3875    }
 3876
 3877    fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3878        self.update_active_view_for_followers(window, cx);
 3879    }
 3880
 3881    fn handle_pane_event(
 3882        &mut self,
 3883        pane: &Entity<Pane>,
 3884        event: &pane::Event,
 3885        window: &mut Window,
 3886        cx: &mut Context<Self>,
 3887    ) {
 3888        let mut serialize_workspace = true;
 3889        match event {
 3890            pane::Event::AddItem { item } => {
 3891                item.added_to_pane(self, pane.clone(), window, cx);
 3892                cx.emit(Event::ItemAdded {
 3893                    item: item.boxed_clone(),
 3894                });
 3895            }
 3896            pane::Event::Split(direction) => {
 3897                self.split_and_clone(pane.clone(), *direction, window, cx);
 3898            }
 3899            pane::Event::JoinIntoNext => {
 3900                self.join_pane_into_next(pane.clone(), window, cx);
 3901            }
 3902            pane::Event::JoinAll => {
 3903                self.join_all_panes(window, cx);
 3904            }
 3905            pane::Event::Remove { focus_on_pane } => {
 3906                self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
 3907            }
 3908            pane::Event::ActivateItem {
 3909                local,
 3910                focus_changed,
 3911            } => {
 3912                window.invalidate_character_coordinates();
 3913
 3914                pane.update(cx, |pane, _| {
 3915                    pane.track_alternate_file_items();
 3916                });
 3917                if *local {
 3918                    self.unfollow_in_pane(pane, window, cx);
 3919                }
 3920                serialize_workspace = *focus_changed || pane != self.active_pane();
 3921                if pane == self.active_pane() {
 3922                    self.active_item_path_changed(window, cx);
 3923                    self.update_active_view_for_followers(window, cx);
 3924                } else if *local {
 3925                    self.set_active_pane(pane, window, cx);
 3926                }
 3927            }
 3928            pane::Event::UserSavedItem { item, save_intent } => {
 3929                cx.emit(Event::UserSavedItem {
 3930                    pane: pane.downgrade(),
 3931                    item: item.boxed_clone(),
 3932                    save_intent: *save_intent,
 3933                });
 3934                serialize_workspace = false;
 3935            }
 3936            pane::Event::ChangeItemTitle => {
 3937                if *pane == self.active_pane {
 3938                    self.active_item_path_changed(window, cx);
 3939                }
 3940                serialize_workspace = false;
 3941            }
 3942            pane::Event::RemoveItem { .. } => {}
 3943            pane::Event::RemovedItem { item } => {
 3944                cx.emit(Event::ActiveItemChanged);
 3945                self.update_window_edited(window, cx);
 3946                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
 3947                    && entry.get().entity_id() == pane.entity_id()
 3948                {
 3949                    entry.remove();
 3950                }
 3951            }
 3952            pane::Event::Focus => {
 3953                window.invalidate_character_coordinates();
 3954                self.handle_pane_focused(pane.clone(), window, cx);
 3955            }
 3956            pane::Event::ZoomIn => {
 3957                if *pane == self.active_pane {
 3958                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
 3959                    if pane.read(cx).has_focus(window, cx) {
 3960                        self.zoomed = Some(pane.downgrade().into());
 3961                        self.zoomed_position = None;
 3962                        cx.emit(Event::ZoomChanged);
 3963                    }
 3964                    cx.notify();
 3965                }
 3966            }
 3967            pane::Event::ZoomOut => {
 3968                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
 3969                if self.zoomed_position.is_none() {
 3970                    self.zoomed = None;
 3971                    cx.emit(Event::ZoomChanged);
 3972                }
 3973                cx.notify();
 3974            }
 3975            pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
 3976        }
 3977
 3978        if serialize_workspace {
 3979            self.serialize_workspace(window, cx);
 3980        }
 3981    }
 3982
 3983    pub fn unfollow_in_pane(
 3984        &mut self,
 3985        pane: &Entity<Pane>,
 3986        window: &mut Window,
 3987        cx: &mut Context<Workspace>,
 3988    ) -> Option<CollaboratorId> {
 3989        let leader_id = self.leader_for_pane(pane)?;
 3990        self.unfollow(leader_id, window, cx);
 3991        Some(leader_id)
 3992    }
 3993
 3994    pub fn split_pane(
 3995        &mut self,
 3996        pane_to_split: Entity<Pane>,
 3997        split_direction: SplitDirection,
 3998        window: &mut Window,
 3999        cx: &mut Context<Self>,
 4000    ) -> Entity<Pane> {
 4001        let new_pane = self.add_pane(window, cx);
 4002        self.center
 4003            .split(&pane_to_split, &new_pane, split_direction)
 4004            .unwrap();
 4005        cx.notify();
 4006        new_pane
 4007    }
 4008
 4009    pub fn split_and_clone(
 4010        &mut self,
 4011        pane: Entity<Pane>,
 4012        direction: SplitDirection,
 4013        window: &mut Window,
 4014        cx: &mut Context<Self>,
 4015    ) -> Option<Entity<Pane>> {
 4016        let item = pane.read(cx).active_item()?;
 4017        let maybe_pane_handle =
 4018            if let Some(clone) = item.clone_on_split(self.database_id(), window, cx) {
 4019                let new_pane = self.add_pane(window, cx);
 4020                new_pane.update(cx, |pane, cx| {
 4021                    pane.add_item(clone, true, true, None, window, cx)
 4022                });
 4023                self.center.split(&pane, &new_pane, direction).unwrap();
 4024                Some(new_pane)
 4025            } else {
 4026                None
 4027            };
 4028        cx.notify();
 4029        maybe_pane_handle
 4030    }
 4031
 4032    pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4033        let active_item = self.active_pane.read(cx).active_item();
 4034        for pane in &self.panes {
 4035            join_pane_into_active(&self.active_pane, pane, window, cx);
 4036        }
 4037        if let Some(active_item) = active_item {
 4038            self.activate_item(active_item.as_ref(), true, true, window, cx);
 4039        }
 4040        cx.notify();
 4041    }
 4042
 4043    pub fn join_pane_into_next(
 4044        &mut self,
 4045        pane: Entity<Pane>,
 4046        window: &mut Window,
 4047        cx: &mut Context<Self>,
 4048    ) {
 4049        let next_pane = self
 4050            .find_pane_in_direction(SplitDirection::Right, cx)
 4051            .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
 4052            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 4053            .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
 4054        let Some(next_pane) = next_pane else {
 4055            return;
 4056        };
 4057        move_all_items(&pane, &next_pane, window, cx);
 4058        cx.notify();
 4059    }
 4060
 4061    fn remove_pane(
 4062        &mut self,
 4063        pane: Entity<Pane>,
 4064        focus_on: Option<Entity<Pane>>,
 4065        window: &mut Window,
 4066        cx: &mut Context<Self>,
 4067    ) {
 4068        if self.center.remove(&pane).unwrap() {
 4069            self.force_remove_pane(&pane, &focus_on, window, cx);
 4070            self.unfollow_in_pane(&pane, window, cx);
 4071            self.last_leaders_by_pane.remove(&pane.downgrade());
 4072            for removed_item in pane.read(cx).items() {
 4073                self.panes_by_item.remove(&removed_item.item_id());
 4074            }
 4075
 4076            cx.notify();
 4077        } else {
 4078            self.active_item_path_changed(window, cx);
 4079        }
 4080        cx.emit(Event::PaneRemoved);
 4081    }
 4082
 4083    pub fn panes(&self) -> &[Entity<Pane>] {
 4084        &self.panes
 4085    }
 4086
 4087    pub fn active_pane(&self) -> &Entity<Pane> {
 4088        &self.active_pane
 4089    }
 4090
 4091    pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
 4092        for dock in self.all_docks() {
 4093            if dock.focus_handle(cx).contains_focused(window, cx)
 4094                && let Some(pane) = dock
 4095                    .read(cx)
 4096                    .active_panel()
 4097                    .and_then(|panel| panel.pane(cx))
 4098            {
 4099                return pane;
 4100            }
 4101        }
 4102        self.active_pane().clone()
 4103    }
 4104
 4105    pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
 4106        self.find_pane_in_direction(SplitDirection::Right, cx)
 4107            .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
 4108            .unwrap_or_else(|| {
 4109                self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
 4110            })
 4111    }
 4112
 4113    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
 4114        let weak_pane = self.panes_by_item.get(&handle.item_id())?;
 4115        weak_pane.upgrade()
 4116    }
 4117
 4118    fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
 4119        self.follower_states.retain(|leader_id, state| {
 4120            if *leader_id == CollaboratorId::PeerId(peer_id) {
 4121                for item in state.items_by_leader_view_id.values() {
 4122                    item.view.set_leader_id(None, window, cx);
 4123                }
 4124                false
 4125            } else {
 4126                true
 4127            }
 4128        });
 4129        cx.notify();
 4130    }
 4131
 4132    pub fn start_following(
 4133        &mut self,
 4134        leader_id: impl Into<CollaboratorId>,
 4135        window: &mut Window,
 4136        cx: &mut Context<Self>,
 4137    ) -> Option<Task<Result<()>>> {
 4138        let leader_id = leader_id.into();
 4139        let pane = self.active_pane().clone();
 4140
 4141        self.last_leaders_by_pane
 4142            .insert(pane.downgrade(), leader_id);
 4143        self.unfollow(leader_id, window, cx);
 4144        self.unfollow_in_pane(&pane, window, cx);
 4145        self.follower_states.insert(
 4146            leader_id,
 4147            FollowerState {
 4148                center_pane: pane.clone(),
 4149                dock_pane: None,
 4150                active_view_id: None,
 4151                items_by_leader_view_id: Default::default(),
 4152            },
 4153        );
 4154        cx.notify();
 4155
 4156        match leader_id {
 4157            CollaboratorId::PeerId(leader_peer_id) => {
 4158                let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
 4159                let project_id = self.project.read(cx).remote_id();
 4160                let request = self.app_state.client.request(proto::Follow {
 4161                    room_id,
 4162                    project_id,
 4163                    leader_id: Some(leader_peer_id),
 4164                });
 4165
 4166                Some(cx.spawn_in(window, async move |this, cx| {
 4167                    let response = request.await?;
 4168                    this.update(cx, |this, _| {
 4169                        let state = this
 4170                            .follower_states
 4171                            .get_mut(&leader_id)
 4172                            .context("following interrupted")?;
 4173                        state.active_view_id = response
 4174                            .active_view
 4175                            .as_ref()
 4176                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 4177                        anyhow::Ok(())
 4178                    })??;
 4179                    if let Some(view) = response.active_view {
 4180                        Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
 4181                    }
 4182                    this.update_in(cx, |this, window, cx| {
 4183                        this.leader_updated(leader_id, window, cx)
 4184                    })?;
 4185                    Ok(())
 4186                }))
 4187            }
 4188            CollaboratorId::Agent => {
 4189                self.leader_updated(leader_id, window, cx)?;
 4190                Some(Task::ready(Ok(())))
 4191            }
 4192        }
 4193    }
 4194
 4195    pub fn follow_next_collaborator(
 4196        &mut self,
 4197        _: &FollowNextCollaborator,
 4198        window: &mut Window,
 4199        cx: &mut Context<Self>,
 4200    ) {
 4201        let collaborators = self.project.read(cx).collaborators();
 4202        let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
 4203            let mut collaborators = collaborators.keys().copied();
 4204            for peer_id in collaborators.by_ref() {
 4205                if CollaboratorId::PeerId(peer_id) == leader_id {
 4206                    break;
 4207                }
 4208            }
 4209            collaborators.next().map(CollaboratorId::PeerId)
 4210        } else if let Some(last_leader_id) =
 4211            self.last_leaders_by_pane.get(&self.active_pane.downgrade())
 4212        {
 4213            match last_leader_id {
 4214                CollaboratorId::PeerId(peer_id) => {
 4215                    if collaborators.contains_key(peer_id) {
 4216                        Some(*last_leader_id)
 4217                    } else {
 4218                        None
 4219                    }
 4220                }
 4221                CollaboratorId::Agent => Some(CollaboratorId::Agent),
 4222            }
 4223        } else {
 4224            None
 4225        };
 4226
 4227        let pane = self.active_pane.clone();
 4228        let Some(leader_id) = next_leader_id.or_else(|| {
 4229            Some(CollaboratorId::PeerId(
 4230                collaborators.keys().copied().next()?,
 4231            ))
 4232        }) else {
 4233            return;
 4234        };
 4235        if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
 4236            return;
 4237        }
 4238        if let Some(task) = self.start_following(leader_id, window, cx) {
 4239            task.detach_and_log_err(cx)
 4240        }
 4241    }
 4242
 4243    pub fn follow(
 4244        &mut self,
 4245        leader_id: impl Into<CollaboratorId>,
 4246        window: &mut Window,
 4247        cx: &mut Context<Self>,
 4248    ) {
 4249        let leader_id = leader_id.into();
 4250
 4251        if let CollaboratorId::PeerId(peer_id) = leader_id {
 4252            let Some(room) = ActiveCall::global(cx).read(cx).room() else {
 4253                return;
 4254            };
 4255            let room = room.read(cx);
 4256            let Some(remote_participant) = room.remote_participant_for_peer_id(peer_id) else {
 4257                return;
 4258            };
 4259
 4260            let project = self.project.read(cx);
 4261
 4262            let other_project_id = match remote_participant.location {
 4263                call::ParticipantLocation::External => None,
 4264                call::ParticipantLocation::UnsharedProject => None,
 4265                call::ParticipantLocation::SharedProject { project_id } => {
 4266                    if Some(project_id) == project.remote_id() {
 4267                        None
 4268                    } else {
 4269                        Some(project_id)
 4270                    }
 4271                }
 4272            };
 4273
 4274            // if they are active in another project, follow there.
 4275            if let Some(project_id) = other_project_id {
 4276                let app_state = self.app_state.clone();
 4277                crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
 4278                    .detach_and_log_err(cx);
 4279            }
 4280        }
 4281
 4282        // if you're already following, find the right pane and focus it.
 4283        if let Some(follower_state) = self.follower_states.get(&leader_id) {
 4284            window.focus(&follower_state.pane().focus_handle(cx));
 4285
 4286            return;
 4287        }
 4288
 4289        // Otherwise, follow.
 4290        if let Some(task) = self.start_following(leader_id, window, cx) {
 4291            task.detach_and_log_err(cx)
 4292        }
 4293    }
 4294
 4295    pub fn unfollow(
 4296        &mut self,
 4297        leader_id: impl Into<CollaboratorId>,
 4298        window: &mut Window,
 4299        cx: &mut Context<Self>,
 4300    ) -> Option<()> {
 4301        cx.notify();
 4302
 4303        let leader_id = leader_id.into();
 4304        let state = self.follower_states.remove(&leader_id)?;
 4305        for (_, item) in state.items_by_leader_view_id {
 4306            item.view.set_leader_id(None, window, cx);
 4307        }
 4308
 4309        if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
 4310            let project_id = self.project.read(cx).remote_id();
 4311            let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
 4312            self.app_state
 4313                .client
 4314                .send(proto::Unfollow {
 4315                    room_id,
 4316                    project_id,
 4317                    leader_id: Some(leader_peer_id),
 4318                })
 4319                .log_err();
 4320        }
 4321
 4322        Some(())
 4323    }
 4324
 4325    pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
 4326        self.follower_states.contains_key(&id.into())
 4327    }
 4328
 4329    fn active_item_path_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4330        cx.emit(Event::ActiveItemChanged);
 4331        let active_entry = self.active_project_path(cx);
 4332        self.project
 4333            .update(cx, |project, cx| project.set_active_path(active_entry, cx));
 4334
 4335        self.update_window_title(window, cx);
 4336    }
 4337
 4338    fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
 4339        let project = self.project().read(cx);
 4340        let mut title = String::new();
 4341
 4342        for (i, name) in project.worktree_root_names(cx).enumerate() {
 4343            if i > 0 {
 4344                title.push_str(", ");
 4345            }
 4346            title.push_str(name);
 4347        }
 4348
 4349        if title.is_empty() {
 4350            title = "empty project".to_string();
 4351        }
 4352
 4353        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
 4354            let filename = path
 4355                .path
 4356                .file_name()
 4357                .map(|s| s.to_string_lossy())
 4358                .or_else(|| {
 4359                    Some(Cow::Borrowed(
 4360                        project
 4361                            .worktree_for_id(path.worktree_id, cx)?
 4362                            .read(cx)
 4363                            .root_name(),
 4364                    ))
 4365                });
 4366
 4367            if let Some(filename) = filename {
 4368                title.push_str("");
 4369                title.push_str(filename.as_ref());
 4370            }
 4371        }
 4372
 4373        if project.is_via_collab() {
 4374            title.push_str("");
 4375        } else if project.is_shared() {
 4376            title.push_str("");
 4377        }
 4378
 4379        if let Some(last_title) = self.last_window_title.as_ref()
 4380            && &title == last_title
 4381        {
 4382            return;
 4383        }
 4384        window.set_window_title(&title);
 4385        SystemWindowTabController::update_tab_title(
 4386            cx,
 4387            window.window_handle().window_id(),
 4388            SharedString::from(&title),
 4389        );
 4390        self.last_window_title = Some(title);
 4391    }
 4392
 4393    fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
 4394        let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
 4395        if is_edited != self.window_edited {
 4396            self.window_edited = is_edited;
 4397            window.set_window_edited(self.window_edited)
 4398        }
 4399    }
 4400
 4401    fn update_item_dirty_state(
 4402        &mut self,
 4403        item: &dyn ItemHandle,
 4404        window: &mut Window,
 4405        cx: &mut App,
 4406    ) {
 4407        let is_dirty = item.is_dirty(cx);
 4408        let item_id = item.item_id();
 4409        let was_dirty = self.dirty_items.contains_key(&item_id);
 4410        if is_dirty == was_dirty {
 4411            return;
 4412        }
 4413        if was_dirty {
 4414            self.dirty_items.remove(&item_id);
 4415            self.update_window_edited(window, cx);
 4416            return;
 4417        }
 4418        if let Some(window_handle) = window.window_handle().downcast::<Self>() {
 4419            let s = item.on_release(
 4420                cx,
 4421                Box::new(move |cx| {
 4422                    window_handle
 4423                        .update(cx, |this, window, cx| {
 4424                            this.dirty_items.remove(&item_id);
 4425                            this.update_window_edited(window, cx)
 4426                        })
 4427                        .ok();
 4428                }),
 4429            );
 4430            self.dirty_items.insert(item_id, s);
 4431            self.update_window_edited(window, cx);
 4432        }
 4433    }
 4434
 4435    fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
 4436        if self.notifications.is_empty() {
 4437            None
 4438        } else {
 4439            Some(
 4440                div()
 4441                    .absolute()
 4442                    .right_3()
 4443                    .bottom_3()
 4444                    .w_112()
 4445                    .h_full()
 4446                    .flex()
 4447                    .flex_col()
 4448                    .justify_end()
 4449                    .gap_2()
 4450                    .children(
 4451                        self.notifications
 4452                            .iter()
 4453                            .map(|(_, notification)| notification.clone().into_any()),
 4454                    ),
 4455            )
 4456        }
 4457    }
 4458
 4459    // RPC handlers
 4460
 4461    fn active_view_for_follower(
 4462        &self,
 4463        follower_project_id: Option<u64>,
 4464        window: &mut Window,
 4465        cx: &mut Context<Self>,
 4466    ) -> Option<proto::View> {
 4467        let (item, panel_id) = self.active_item_for_followers(window, cx);
 4468        let item = item?;
 4469        let leader_id = self
 4470            .pane_for(&*item)
 4471            .and_then(|pane| self.leader_for_pane(&pane));
 4472        let leader_peer_id = match leader_id {
 4473            Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 4474            Some(CollaboratorId::Agent) | None => None,
 4475        };
 4476
 4477        let item_handle = item.to_followable_item_handle(cx)?;
 4478        let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
 4479        let variant = item_handle.to_state_proto(window, cx)?;
 4480
 4481        if item_handle.is_project_item(window, cx)
 4482            && (follower_project_id.is_none()
 4483                || follower_project_id != self.project.read(cx).remote_id())
 4484        {
 4485            return None;
 4486        }
 4487
 4488        Some(proto::View {
 4489            id: id.to_proto(),
 4490            leader_id: leader_peer_id,
 4491            variant: Some(variant),
 4492            panel_id: panel_id.map(|id| id as i32),
 4493        })
 4494    }
 4495
 4496    fn handle_follow(
 4497        &mut self,
 4498        follower_project_id: Option<u64>,
 4499        window: &mut Window,
 4500        cx: &mut Context<Self>,
 4501    ) -> proto::FollowResponse {
 4502        let active_view = self.active_view_for_follower(follower_project_id, window, cx);
 4503
 4504        cx.notify();
 4505        proto::FollowResponse {
 4506            // TODO: Remove after version 0.145.x stabilizes.
 4507            active_view_id: active_view.as_ref().and_then(|view| view.id.clone()),
 4508            views: active_view.iter().cloned().collect(),
 4509            active_view,
 4510        }
 4511    }
 4512
 4513    fn handle_update_followers(
 4514        &mut self,
 4515        leader_id: PeerId,
 4516        message: proto::UpdateFollowers,
 4517        _window: &mut Window,
 4518        _cx: &mut Context<Self>,
 4519    ) {
 4520        self.leader_updates_tx
 4521            .unbounded_send((leader_id, message))
 4522            .ok();
 4523    }
 4524
 4525    async fn process_leader_update(
 4526        this: &WeakEntity<Self>,
 4527        leader_id: PeerId,
 4528        update: proto::UpdateFollowers,
 4529        cx: &mut AsyncWindowContext,
 4530    ) -> Result<()> {
 4531        match update.variant.context("invalid update")? {
 4532            proto::update_followers::Variant::CreateView(view) => {
 4533                let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
 4534                let should_add_view = this.update(cx, |this, _| {
 4535                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 4536                        anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
 4537                    } else {
 4538                        anyhow::Ok(false)
 4539                    }
 4540                })??;
 4541
 4542                if should_add_view {
 4543                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 4544                }
 4545            }
 4546            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
 4547                let should_add_view = this.update(cx, |this, _| {
 4548                    if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
 4549                        state.active_view_id = update_active_view
 4550                            .view
 4551                            .as_ref()
 4552                            .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
 4553
 4554                        if state.active_view_id.is_some_and(|view_id| {
 4555                            !state.items_by_leader_view_id.contains_key(&view_id)
 4556                        }) {
 4557                            anyhow::Ok(true)
 4558                        } else {
 4559                            anyhow::Ok(false)
 4560                        }
 4561                    } else {
 4562                        anyhow::Ok(false)
 4563                    }
 4564                })??;
 4565
 4566                if should_add_view && let Some(view) = update_active_view.view {
 4567                    Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
 4568                }
 4569            }
 4570            proto::update_followers::Variant::UpdateView(update_view) => {
 4571                let variant = update_view.variant.context("missing update view variant")?;
 4572                let id = update_view.id.context("missing update view id")?;
 4573                let mut tasks = Vec::new();
 4574                this.update_in(cx, |this, window, cx| {
 4575                    let project = this.project.clone();
 4576                    if let Some(state) = this.follower_states.get(&leader_id.into()) {
 4577                        let view_id = ViewId::from_proto(id.clone())?;
 4578                        if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
 4579                            tasks.push(item.view.apply_update_proto(
 4580                                &project,
 4581                                variant.clone(),
 4582                                window,
 4583                                cx,
 4584                            ));
 4585                        }
 4586                    }
 4587                    anyhow::Ok(())
 4588                })??;
 4589                try_join_all(tasks).await.log_err();
 4590            }
 4591        }
 4592        this.update_in(cx, |this, window, cx| {
 4593            this.leader_updated(leader_id, window, cx)
 4594        })?;
 4595        Ok(())
 4596    }
 4597
 4598    async fn add_view_from_leader(
 4599        this: WeakEntity<Self>,
 4600        leader_id: PeerId,
 4601        view: &proto::View,
 4602        cx: &mut AsyncWindowContext,
 4603    ) -> Result<()> {
 4604        let this = this.upgrade().context("workspace dropped")?;
 4605
 4606        let Some(id) = view.id.clone() else {
 4607            anyhow::bail!("no id for view");
 4608        };
 4609        let id = ViewId::from_proto(id)?;
 4610        let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
 4611
 4612        let pane = this.update(cx, |this, _cx| {
 4613            let state = this
 4614                .follower_states
 4615                .get(&leader_id.into())
 4616                .context("stopped following")?;
 4617            anyhow::Ok(state.pane().clone())
 4618        })??;
 4619        let existing_item = pane.update_in(cx, |pane, window, cx| {
 4620            let client = this.read(cx).client().clone();
 4621            pane.items().find_map(|item| {
 4622                let item = item.to_followable_item_handle(cx)?;
 4623                if item.remote_id(&client, window, cx) == Some(id) {
 4624                    Some(item)
 4625                } else {
 4626                    None
 4627                }
 4628            })
 4629        })?;
 4630        let item = if let Some(existing_item) = existing_item {
 4631            existing_item
 4632        } else {
 4633            let variant = view.variant.clone();
 4634            anyhow::ensure!(variant.is_some(), "missing view variant");
 4635
 4636            let task = cx.update(|window, cx| {
 4637                FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
 4638            })?;
 4639
 4640            let Some(task) = task else {
 4641                anyhow::bail!(
 4642                    "failed to construct view from leader (maybe from a different version of zed?)"
 4643                );
 4644            };
 4645
 4646            let mut new_item = task.await?;
 4647            pane.update_in(cx, |pane, window, cx| {
 4648                let mut item_to_remove = None;
 4649                for (ix, item) in pane.items().enumerate() {
 4650                    if let Some(item) = item.to_followable_item_handle(cx) {
 4651                        match new_item.dedup(item.as_ref(), window, cx) {
 4652                            Some(item::Dedup::KeepExisting) => {
 4653                                new_item =
 4654                                    item.boxed_clone().to_followable_item_handle(cx).unwrap();
 4655                                break;
 4656                            }
 4657                            Some(item::Dedup::ReplaceExisting) => {
 4658                                item_to_remove = Some((ix, item.item_id()));
 4659                                break;
 4660                            }
 4661                            None => {}
 4662                        }
 4663                    }
 4664                }
 4665
 4666                if let Some((ix, id)) = item_to_remove {
 4667                    pane.remove_item(id, false, false, window, cx);
 4668                    pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
 4669                }
 4670            })?;
 4671
 4672            new_item
 4673        };
 4674
 4675        this.update_in(cx, |this, window, cx| {
 4676            let state = this.follower_states.get_mut(&leader_id.into())?;
 4677            item.set_leader_id(Some(leader_id.into()), window, cx);
 4678            state.items_by_leader_view_id.insert(
 4679                id,
 4680                FollowerView {
 4681                    view: item,
 4682                    location: panel_id,
 4683                },
 4684            );
 4685
 4686            Some(())
 4687        })?;
 4688
 4689        Ok(())
 4690    }
 4691
 4692    fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4693        let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
 4694            return;
 4695        };
 4696
 4697        if let Some(agent_location) = self.project.read(cx).agent_location() {
 4698            let buffer_entity_id = agent_location.buffer.entity_id();
 4699            let view_id = ViewId {
 4700                creator: CollaboratorId::Agent,
 4701                id: buffer_entity_id.as_u64(),
 4702            };
 4703            follower_state.active_view_id = Some(view_id);
 4704
 4705            let item = match follower_state.items_by_leader_view_id.entry(view_id) {
 4706                hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
 4707                hash_map::Entry::Vacant(entry) => {
 4708                    let existing_view =
 4709                        follower_state
 4710                            .center_pane
 4711                            .read(cx)
 4712                            .items()
 4713                            .find_map(|item| {
 4714                                let item = item.to_followable_item_handle(cx)?;
 4715                                if item.is_singleton(cx)
 4716                                    && item.project_item_model_ids(cx).as_slice()
 4717                                        == [buffer_entity_id]
 4718                                {
 4719                                    Some(item)
 4720                                } else {
 4721                                    None
 4722                                }
 4723                            });
 4724                    let view = existing_view.or_else(|| {
 4725                        agent_location.buffer.upgrade().and_then(|buffer| {
 4726                            cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
 4727                                registry.build_item(buffer, self.project.clone(), None, window, cx)
 4728                            })?
 4729                            .to_followable_item_handle(cx)
 4730                        })
 4731                    });
 4732
 4733                    view.map(|view| {
 4734                        entry.insert(FollowerView {
 4735                            view,
 4736                            location: None,
 4737                        })
 4738                    })
 4739                }
 4740            };
 4741
 4742            if let Some(item) = item {
 4743                item.view
 4744                    .set_leader_id(Some(CollaboratorId::Agent), window, cx);
 4745                item.view
 4746                    .update_agent_location(agent_location.position, window, cx);
 4747            }
 4748        } else {
 4749            follower_state.active_view_id = None;
 4750        }
 4751
 4752        self.leader_updated(CollaboratorId::Agent, window, cx);
 4753    }
 4754
 4755    pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
 4756        let mut is_project_item = true;
 4757        let mut update = proto::UpdateActiveView::default();
 4758        if window.is_window_active() {
 4759            let (active_item, panel_id) = self.active_item_for_followers(window, cx);
 4760
 4761            if let Some(item) = active_item
 4762                && item.item_focus_handle(cx).contains_focused(window, cx)
 4763            {
 4764                let leader_id = self
 4765                    .pane_for(&*item)
 4766                    .and_then(|pane| self.leader_for_pane(&pane));
 4767                let leader_peer_id = match leader_id {
 4768                    Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
 4769                    Some(CollaboratorId::Agent) | None => None,
 4770                };
 4771
 4772                if let Some(item) = item.to_followable_item_handle(cx) {
 4773                    let id = item
 4774                        .remote_id(&self.app_state.client, window, cx)
 4775                        .map(|id| id.to_proto());
 4776
 4777                    if let Some(id) = id
 4778                        && let Some(variant) = item.to_state_proto(window, cx)
 4779                    {
 4780                        let view = Some(proto::View {
 4781                            id: id.clone(),
 4782                            leader_id: leader_peer_id,
 4783                            variant: Some(variant),
 4784                            panel_id: panel_id.map(|id| id as i32),
 4785                        });
 4786
 4787                        is_project_item = item.is_project_item(window, cx);
 4788                        update = proto::UpdateActiveView {
 4789                            view,
 4790                            // TODO: Remove after version 0.145.x stabilizes.
 4791                            id,
 4792                            leader_id: leader_peer_id,
 4793                        };
 4794                    };
 4795                }
 4796            }
 4797        }
 4798
 4799        let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
 4800        if active_view_id != self.last_active_view_id.as_ref() {
 4801            self.last_active_view_id = active_view_id.cloned();
 4802            self.update_followers(
 4803                is_project_item,
 4804                proto::update_followers::Variant::UpdateActiveView(update),
 4805                window,
 4806                cx,
 4807            );
 4808        }
 4809    }
 4810
 4811    fn active_item_for_followers(
 4812        &self,
 4813        window: &mut Window,
 4814        cx: &mut App,
 4815    ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
 4816        let mut active_item = None;
 4817        let mut panel_id = None;
 4818        for dock in self.all_docks() {
 4819            if dock.focus_handle(cx).contains_focused(window, cx)
 4820                && let Some(panel) = dock.read(cx).active_panel()
 4821                && let Some(pane) = panel.pane(cx)
 4822                && let Some(item) = pane.read(cx).active_item()
 4823            {
 4824                active_item = Some(item);
 4825                panel_id = panel.remote_id();
 4826                break;
 4827            }
 4828        }
 4829
 4830        if active_item.is_none() {
 4831            active_item = self.active_pane().read(cx).active_item();
 4832        }
 4833        (active_item, panel_id)
 4834    }
 4835
 4836    fn update_followers(
 4837        &self,
 4838        project_only: bool,
 4839        update: proto::update_followers::Variant,
 4840        _: &mut Window,
 4841        cx: &mut App,
 4842    ) -> Option<()> {
 4843        // If this update only applies to for followers in the current project,
 4844        // then skip it unless this project is shared. If it applies to all
 4845        // followers, regardless of project, then set `project_id` to none,
 4846        // indicating that it goes to all followers.
 4847        let project_id = if project_only {
 4848            Some(self.project.read(cx).remote_id()?)
 4849        } else {
 4850            None
 4851        };
 4852        self.app_state().workspace_store.update(cx, |store, cx| {
 4853            store.update_followers(project_id, update, cx)
 4854        })
 4855    }
 4856
 4857    pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
 4858        self.follower_states.iter().find_map(|(leader_id, state)| {
 4859            if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
 4860                Some(*leader_id)
 4861            } else {
 4862                None
 4863            }
 4864        })
 4865    }
 4866
 4867    fn leader_updated(
 4868        &mut self,
 4869        leader_id: impl Into<CollaboratorId>,
 4870        window: &mut Window,
 4871        cx: &mut Context<Self>,
 4872    ) -> Option<Box<dyn ItemHandle>> {
 4873        cx.notify();
 4874
 4875        let leader_id = leader_id.into();
 4876        let (panel_id, item) = match leader_id {
 4877            CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
 4878            CollaboratorId::Agent => (None, self.active_item_for_agent()?),
 4879        };
 4880
 4881        let state = self.follower_states.get(&leader_id)?;
 4882        let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
 4883        let pane;
 4884        if let Some(panel_id) = panel_id {
 4885            pane = self
 4886                .activate_panel_for_proto_id(panel_id, window, cx)?
 4887                .pane(cx)?;
 4888            let state = self.follower_states.get_mut(&leader_id)?;
 4889            state.dock_pane = Some(pane.clone());
 4890        } else {
 4891            pane = state.center_pane.clone();
 4892            let state = self.follower_states.get_mut(&leader_id)?;
 4893            if let Some(dock_pane) = state.dock_pane.take() {
 4894                transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
 4895            }
 4896        }
 4897
 4898        pane.update(cx, |pane, cx| {
 4899            let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
 4900            if let Some(index) = pane.index_for_item(item.as_ref()) {
 4901                pane.activate_item(index, false, false, window, cx);
 4902            } else {
 4903                pane.add_item(item.boxed_clone(), false, false, None, window, cx)
 4904            }
 4905
 4906            if focus_active_item {
 4907                pane.focus_active_item(window, cx)
 4908            }
 4909        });
 4910
 4911        Some(item)
 4912    }
 4913
 4914    fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
 4915        let state = self.follower_states.get(&CollaboratorId::Agent)?;
 4916        let active_view_id = state.active_view_id?;
 4917        Some(
 4918            state
 4919                .items_by_leader_view_id
 4920                .get(&active_view_id)?
 4921                .view
 4922                .boxed_clone(),
 4923        )
 4924    }
 4925
 4926    fn active_item_for_peer(
 4927        &self,
 4928        peer_id: PeerId,
 4929        window: &mut Window,
 4930        cx: &mut Context<Self>,
 4931    ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
 4932        let call = self.active_call()?;
 4933        let room = call.read(cx).room()?.read(cx);
 4934        let participant = room.remote_participant_for_peer_id(peer_id)?;
 4935        let leader_in_this_app;
 4936        let leader_in_this_project;
 4937        match participant.location {
 4938            call::ParticipantLocation::SharedProject { project_id } => {
 4939                leader_in_this_app = true;
 4940                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
 4941            }
 4942            call::ParticipantLocation::UnsharedProject => {
 4943                leader_in_this_app = true;
 4944                leader_in_this_project = false;
 4945            }
 4946            call::ParticipantLocation::External => {
 4947                leader_in_this_app = false;
 4948                leader_in_this_project = false;
 4949            }
 4950        };
 4951        let state = self.follower_states.get(&peer_id.into())?;
 4952        let mut item_to_activate = None;
 4953        if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
 4954            if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
 4955                && (leader_in_this_project || !item.view.is_project_item(window, cx))
 4956            {
 4957                item_to_activate = Some((item.location, item.view.boxed_clone()));
 4958            }
 4959        } else if let Some(shared_screen) =
 4960            self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
 4961        {
 4962            item_to_activate = Some((None, Box::new(shared_screen)));
 4963        }
 4964        item_to_activate
 4965    }
 4966
 4967    fn shared_screen_for_peer(
 4968        &self,
 4969        peer_id: PeerId,
 4970        pane: &Entity<Pane>,
 4971        window: &mut Window,
 4972        cx: &mut App,
 4973    ) -> Option<Entity<SharedScreen>> {
 4974        let call = self.active_call()?;
 4975        let room = call.read(cx).room()?.clone();
 4976        let participant = room.read(cx).remote_participant_for_peer_id(peer_id)?;
 4977        let track = participant.video_tracks.values().next()?.clone();
 4978        let user = participant.user.clone();
 4979
 4980        for item in pane.read(cx).items_of_type::<SharedScreen>() {
 4981            if item.read(cx).peer_id == peer_id {
 4982                return Some(item);
 4983            }
 4984        }
 4985
 4986        Some(cx.new(|cx| SharedScreen::new(track, peer_id, user.clone(), room.clone(), window, cx)))
 4987    }
 4988
 4989    pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4990        if window.is_window_active() {
 4991            self.update_active_view_for_followers(window, cx);
 4992
 4993            if let Some(database_id) = self.database_id {
 4994                cx.background_spawn(persistence::DB.update_timestamp(database_id))
 4995                    .detach();
 4996            }
 4997        } else {
 4998            for pane in &self.panes {
 4999                pane.update(cx, |pane, cx| {
 5000                    if let Some(item) = pane.active_item() {
 5001                        item.workspace_deactivated(window, cx);
 5002                    }
 5003                    for item in pane.items() {
 5004                        if matches!(
 5005                            item.workspace_settings(cx).autosave,
 5006                            AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
 5007                        ) {
 5008                            Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
 5009                                .detach_and_log_err(cx);
 5010                        }
 5011                    }
 5012                });
 5013            }
 5014        }
 5015    }
 5016
 5017    pub fn active_call(&self) -> Option<&Entity<ActiveCall>> {
 5018        self.active_call.as_ref().map(|(call, _)| call)
 5019    }
 5020
 5021    fn on_active_call_event(
 5022        &mut self,
 5023        _: &Entity<ActiveCall>,
 5024        event: &call::room::Event,
 5025        window: &mut Window,
 5026        cx: &mut Context<Self>,
 5027    ) {
 5028        match event {
 5029            call::room::Event::ParticipantLocationChanged { participant_id }
 5030            | call::room::Event::RemoteVideoTracksChanged { participant_id } => {
 5031                self.leader_updated(participant_id, window, cx);
 5032            }
 5033            _ => {}
 5034        }
 5035    }
 5036
 5037    pub fn database_id(&self) -> Option<WorkspaceId> {
 5038        self.database_id
 5039    }
 5040
 5041    pub fn session_id(&self) -> Option<String> {
 5042        self.session_id.clone()
 5043    }
 5044
 5045    pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
 5046        let project = self.project().read(cx);
 5047        project
 5048            .visible_worktrees(cx)
 5049            .map(|worktree| worktree.read(cx).abs_path())
 5050            .collect::<Vec<_>>()
 5051    }
 5052
 5053    fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
 5054        match member {
 5055            Member::Axis(PaneAxis { members, .. }) => {
 5056                for child in members.iter() {
 5057                    self.remove_panes(child.clone(), window, cx)
 5058                }
 5059            }
 5060            Member::Pane(pane) => {
 5061                self.force_remove_pane(&pane, &None, window, cx);
 5062            }
 5063        }
 5064    }
 5065
 5066    fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
 5067        self.session_id.take();
 5068        self.serialize_workspace_internal(window, cx)
 5069    }
 5070
 5071    fn force_remove_pane(
 5072        &mut self,
 5073        pane: &Entity<Pane>,
 5074        focus_on: &Option<Entity<Pane>>,
 5075        window: &mut Window,
 5076        cx: &mut Context<Workspace>,
 5077    ) {
 5078        self.panes.retain(|p| p != pane);
 5079        if let Some(focus_on) = focus_on {
 5080            focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
 5081        } else if self.active_pane() == pane {
 5082            self.panes
 5083                .last()
 5084                .unwrap()
 5085                .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx)));
 5086        }
 5087        if self.last_active_center_pane == Some(pane.downgrade()) {
 5088            self.last_active_center_pane = None;
 5089        }
 5090        cx.notify();
 5091    }
 5092
 5093    fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5094        if self._schedule_serialize_workspace.is_none() {
 5095            self._schedule_serialize_workspace =
 5096                Some(cx.spawn_in(window, async move |this, cx| {
 5097                    cx.background_executor()
 5098                        .timer(SERIALIZATION_THROTTLE_TIME)
 5099                        .await;
 5100                    this.update_in(cx, |this, window, cx| {
 5101                        this.serialize_workspace_internal(window, cx).detach();
 5102                        this._schedule_serialize_workspace.take();
 5103                    })
 5104                    .log_err();
 5105                }));
 5106        }
 5107    }
 5108
 5109    fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
 5110        let Some(database_id) = self.database_id() else {
 5111            return Task::ready(());
 5112        };
 5113
 5114        fn serialize_pane_handle(
 5115            pane_handle: &Entity<Pane>,
 5116            window: &mut Window,
 5117            cx: &mut App,
 5118        ) -> SerializedPane {
 5119            let (items, active, pinned_count) = {
 5120                let pane = pane_handle.read(cx);
 5121                let active_item_id = pane.active_item().map(|item| item.item_id());
 5122                (
 5123                    pane.items()
 5124                        .filter_map(|handle| {
 5125                            let handle = handle.to_serializable_item_handle(cx)?;
 5126
 5127                            Some(SerializedItem {
 5128                                kind: Arc::from(handle.serialized_item_kind()),
 5129                                item_id: handle.item_id().as_u64(),
 5130                                active: Some(handle.item_id()) == active_item_id,
 5131                                preview: pane.is_active_preview_item(handle.item_id()),
 5132                            })
 5133                        })
 5134                        .collect::<Vec<_>>(),
 5135                    pane.has_focus(window, cx),
 5136                    pane.pinned_count(),
 5137                )
 5138            };
 5139
 5140            SerializedPane::new(items, active, pinned_count)
 5141        }
 5142
 5143        fn build_serialized_pane_group(
 5144            pane_group: &Member,
 5145            window: &mut Window,
 5146            cx: &mut App,
 5147        ) -> SerializedPaneGroup {
 5148            match pane_group {
 5149                Member::Axis(PaneAxis {
 5150                    axis,
 5151                    members,
 5152                    flexes,
 5153                    bounding_boxes: _,
 5154                }) => SerializedPaneGroup::Group {
 5155                    axis: SerializedAxis(*axis),
 5156                    children: members
 5157                        .iter()
 5158                        .map(|member| build_serialized_pane_group(member, window, cx))
 5159                        .collect::<Vec<_>>(),
 5160                    flexes: Some(flexes.lock().clone()),
 5161                },
 5162                Member::Pane(pane_handle) => {
 5163                    SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
 5164                }
 5165            }
 5166        }
 5167
 5168        fn build_serialized_docks(
 5169            this: &Workspace,
 5170            window: &mut Window,
 5171            cx: &mut App,
 5172        ) -> DockStructure {
 5173            let left_dock = this.left_dock.read(cx);
 5174            let left_visible = left_dock.is_open();
 5175            let left_active_panel = left_dock
 5176                .active_panel()
 5177                .map(|panel| panel.persistent_name().to_string());
 5178            let left_dock_zoom = left_dock
 5179                .active_panel()
 5180                .map(|panel| panel.is_zoomed(window, cx))
 5181                .unwrap_or(false);
 5182
 5183            let right_dock = this.right_dock.read(cx);
 5184            let right_visible = right_dock.is_open();
 5185            let right_active_panel = right_dock
 5186                .active_panel()
 5187                .map(|panel| panel.persistent_name().to_string());
 5188            let right_dock_zoom = right_dock
 5189                .active_panel()
 5190                .map(|panel| panel.is_zoomed(window, cx))
 5191                .unwrap_or(false);
 5192
 5193            let bottom_dock = this.bottom_dock.read(cx);
 5194            let bottom_visible = bottom_dock.is_open();
 5195            let bottom_active_panel = bottom_dock
 5196                .active_panel()
 5197                .map(|panel| panel.persistent_name().to_string());
 5198            let bottom_dock_zoom = bottom_dock
 5199                .active_panel()
 5200                .map(|panel| panel.is_zoomed(window, cx))
 5201                .unwrap_or(false);
 5202
 5203            DockStructure {
 5204                left: DockData {
 5205                    visible: left_visible,
 5206                    active_panel: left_active_panel,
 5207                    zoom: left_dock_zoom,
 5208                },
 5209                right: DockData {
 5210                    visible: right_visible,
 5211                    active_panel: right_active_panel,
 5212                    zoom: right_dock_zoom,
 5213                },
 5214                bottom: DockData {
 5215                    visible: bottom_visible,
 5216                    active_panel: bottom_active_panel,
 5217                    zoom: bottom_dock_zoom,
 5218                },
 5219            }
 5220        }
 5221
 5222        match self.serialize_workspace_location(cx) {
 5223            WorkspaceLocation::Location(location, paths) => {
 5224                let breakpoints = self.project.update(cx, |project, cx| {
 5225                    project
 5226                        .breakpoint_store()
 5227                        .read(cx)
 5228                        .all_source_breakpoints(cx)
 5229                });
 5230
 5231                let center_group = build_serialized_pane_group(&self.center.root, window, cx);
 5232                let docks = build_serialized_docks(self, window, cx);
 5233                let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
 5234                let serialized_workspace = SerializedWorkspace {
 5235                    id: database_id,
 5236                    location,
 5237                    paths,
 5238                    center_group,
 5239                    window_bounds,
 5240                    display: Default::default(),
 5241                    docks,
 5242                    centered_layout: self.centered_layout,
 5243                    session_id: self.session_id.clone(),
 5244                    breakpoints,
 5245                    window_id: Some(window.window_handle().window_id().as_u64()),
 5246                };
 5247
 5248                window.spawn(cx, async move |_| {
 5249                    persistence::DB.save_workspace(serialized_workspace).await;
 5250                })
 5251            }
 5252            WorkspaceLocation::DetachFromSession => window.spawn(cx, async move |_| {
 5253                persistence::DB
 5254                    .set_session_id(database_id, None)
 5255                    .await
 5256                    .log_err();
 5257            }),
 5258            WorkspaceLocation::None => Task::ready(()),
 5259        }
 5260    }
 5261
 5262    fn serialize_workspace_location(&self, cx: &App) -> WorkspaceLocation {
 5263        let paths = PathList::new(&self.root_paths(cx));
 5264        if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
 5265            WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
 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_remote_project_with_new_connection(
 7279    window: WindowHandle<Workspace>,
 7280    connection_options: RemoteConnectionOptions,
 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_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 7290
 7291        let session = match cx
 7292            .update(|cx| {
 7293                remote::RemoteClient::new(
 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_remote_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_remote_project_with_existing_connection(
 7333    connection_options: RemoteConnectionOptions,
 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_remote_project(connection_options.clone(), paths.clone(), cx).await?;
 7343
 7344        open_remote_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_remote_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_remote_project(
 7445    connection_options: RemoteConnectionOptions,
 7446    paths: Vec<PathBuf>,
 7447    cx: &AsyncApp,
 7448) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
 7449    cx.background_spawn(async move {
 7450        let remote_connection_id = persistence::DB
 7451            .get_or_create_remote_connection(connection_options)
 7452            .await?;
 7453
 7454        let serialized_workspace =
 7455            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 7456
 7457        let workspace_id = if let Some(workspace_id) =
 7458            serialized_workspace.as_ref().map(|workspace| workspace.id)
 7459        {
 7460            workspace_id
 7461        } else {
 7462            persistence::DB.next_id().await?
 7463        };
 7464
 7465        Ok((workspace_id, serialized_workspace))
 7466    })
 7467}
 7468
 7469pub fn join_in_room_project(
 7470    project_id: u64,
 7471    follow_user_id: u64,
 7472    app_state: Arc<AppState>,
 7473    cx: &mut App,
 7474) -> Task<Result<()>> {
 7475    let windows = cx.windows();
 7476    cx.spawn(async move |cx| {
 7477        let existing_workspace = windows.into_iter().find_map(|window_handle| {
 7478            window_handle
 7479                .downcast::<Workspace>()
 7480                .and_then(|window_handle| {
 7481                    window_handle
 7482                        .update(cx, |workspace, _window, cx| {
 7483                            if workspace.project().read(cx).remote_id() == Some(project_id) {
 7484                                Some(window_handle)
 7485                            } else {
 7486                                None
 7487                            }
 7488                        })
 7489                        .unwrap_or(None)
 7490                })
 7491        });
 7492
 7493        let workspace = if let Some(existing_workspace) = existing_workspace {
 7494            existing_workspace
 7495        } else {
 7496            let active_call = cx.update(|cx| ActiveCall::global(cx))?;
 7497            let room = active_call
 7498                .read_with(cx, |call, _| call.room().cloned())?
 7499                .context("not in a call")?;
 7500            let project = room
 7501                .update(cx, |room, cx| {
 7502                    room.join_project(
 7503                        project_id,
 7504                        app_state.languages.clone(),
 7505                        app_state.fs.clone(),
 7506                        cx,
 7507                    )
 7508                })?
 7509                .await?;
 7510
 7511            let window_bounds_override = window_bounds_env_override();
 7512            cx.update(|cx| {
 7513                let mut options = (app_state.build_window_options)(None, cx);
 7514                options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
 7515                cx.open_window(options, |window, cx| {
 7516                    cx.new(|cx| {
 7517                        Workspace::new(Default::default(), project, app_state.clone(), window, cx)
 7518                    })
 7519                })
 7520            })??
 7521        };
 7522
 7523        workspace.update(cx, |workspace, window, cx| {
 7524            cx.activate(true);
 7525            window.activate_window();
 7526
 7527            if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
 7528                let follow_peer_id = room
 7529                    .read(cx)
 7530                    .remote_participants()
 7531                    .iter()
 7532                    .find(|(_, participant)| participant.user.id == follow_user_id)
 7533                    .map(|(_, p)| p.peer_id)
 7534                    .or_else(|| {
 7535                        // If we couldn't follow the given user, follow the host instead.
 7536                        let collaborator = workspace
 7537                            .project()
 7538                            .read(cx)
 7539                            .collaborators()
 7540                            .values()
 7541                            .find(|collaborator| collaborator.is_host)?;
 7542                        Some(collaborator.peer_id)
 7543                    });
 7544
 7545                if let Some(follow_peer_id) = follow_peer_id {
 7546                    workspace.follow(follow_peer_id, window, cx);
 7547                }
 7548            }
 7549        })?;
 7550
 7551        anyhow::Ok(())
 7552    })
 7553}
 7554
 7555pub fn reload(cx: &mut App) {
 7556    let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
 7557    let mut workspace_windows = cx
 7558        .windows()
 7559        .into_iter()
 7560        .filter_map(|window| window.downcast::<Workspace>())
 7561        .collect::<Vec<_>>();
 7562
 7563    // If multiple windows have unsaved changes, and need a save prompt,
 7564    // prompt in the active window before switching to a different window.
 7565    workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
 7566
 7567    let mut prompt = None;
 7568    if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
 7569        prompt = window
 7570            .update(cx, |_, window, cx| {
 7571                window.prompt(
 7572                    PromptLevel::Info,
 7573                    "Are you sure you want to restart?",
 7574                    None,
 7575                    &["Restart", "Cancel"],
 7576                    cx,
 7577                )
 7578            })
 7579            .ok();
 7580    }
 7581
 7582    cx.spawn(async move |cx| {
 7583        if let Some(prompt) = prompt {
 7584            let answer = prompt.await?;
 7585            if answer != 0 {
 7586                return Ok(());
 7587            }
 7588        }
 7589
 7590        // If the user cancels any save prompt, then keep the app open.
 7591        for window in workspace_windows {
 7592            if let Ok(should_close) = window.update(cx, |workspace, window, cx| {
 7593                workspace.prepare_to_close(CloseIntent::Quit, window, cx)
 7594            }) && !should_close.await?
 7595            {
 7596                return Ok(());
 7597            }
 7598        }
 7599        cx.update(|cx| cx.restart())
 7600    })
 7601    .detach_and_log_err(cx);
 7602}
 7603
 7604fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
 7605    let mut parts = value.split(',');
 7606    let x: usize = parts.next()?.parse().ok()?;
 7607    let y: usize = parts.next()?.parse().ok()?;
 7608    Some(point(px(x as f32), px(y as f32)))
 7609}
 7610
 7611fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
 7612    let mut parts = value.split(',');
 7613    let width: usize = parts.next()?.parse().ok()?;
 7614    let height: usize = parts.next()?.parse().ok()?;
 7615    Some(size(px(width as f32), px(height as f32)))
 7616}
 7617
 7618/// Add client-side decorations (rounded corners, shadows, resize handling) when appropriate.
 7619pub fn client_side_decorations(
 7620    element: impl IntoElement,
 7621    window: &mut Window,
 7622    cx: &mut App,
 7623) -> Stateful<Div> {
 7624    const BORDER_SIZE: Pixels = px(1.0);
 7625    let decorations = window.window_decorations();
 7626
 7627    match decorations {
 7628        Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
 7629        Decorations::Server => window.set_client_inset(px(0.0)),
 7630    }
 7631
 7632    struct GlobalResizeEdge(ResizeEdge);
 7633    impl Global for GlobalResizeEdge {}
 7634
 7635    div()
 7636        .id("window-backdrop")
 7637        .bg(transparent_black())
 7638        .map(|div| match decorations {
 7639            Decorations::Server => div,
 7640            Decorations::Client { tiling, .. } => div
 7641                .when(!(tiling.top || tiling.right), |div| {
 7642                    div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7643                })
 7644                .when(!(tiling.top || tiling.left), |div| {
 7645                    div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7646                })
 7647                .when(!(tiling.bottom || tiling.right), |div| {
 7648                    div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7649                })
 7650                .when(!(tiling.bottom || tiling.left), |div| {
 7651                    div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7652                })
 7653                .when(!tiling.top, |div| {
 7654                    div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7655                })
 7656                .when(!tiling.bottom, |div| {
 7657                    div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7658                })
 7659                .when(!tiling.left, |div| {
 7660                    div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7661                })
 7662                .when(!tiling.right, |div| {
 7663                    div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
 7664                })
 7665                .on_mouse_move(move |e, window, cx| {
 7666                    let size = window.window_bounds().get_bounds().size;
 7667                    let pos = e.position;
 7668
 7669                    let new_edge =
 7670                        resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
 7671
 7672                    let edge = cx.try_global::<GlobalResizeEdge>();
 7673                    if new_edge != edge.map(|edge| edge.0) {
 7674                        window
 7675                            .window_handle()
 7676                            .update(cx, |workspace, _, cx| {
 7677                                cx.notify(workspace.entity_id());
 7678                            })
 7679                            .ok();
 7680                    }
 7681                })
 7682                .on_mouse_down(MouseButton::Left, move |e, window, _| {
 7683                    let size = window.window_bounds().get_bounds().size;
 7684                    let pos = e.position;
 7685
 7686                    let edge = match resize_edge(
 7687                        pos,
 7688                        theme::CLIENT_SIDE_DECORATION_SHADOW,
 7689                        size,
 7690                        tiling,
 7691                    ) {
 7692                        Some(value) => value,
 7693                        None => return,
 7694                    };
 7695
 7696                    window.start_window_resize(edge);
 7697                }),
 7698        })
 7699        .size_full()
 7700        .child(
 7701            div()
 7702                .cursor(CursorStyle::Arrow)
 7703                .map(|div| match decorations {
 7704                    Decorations::Server => div,
 7705                    Decorations::Client { tiling } => div
 7706                        .border_color(cx.theme().colors().border)
 7707                        .when(!(tiling.top || tiling.right), |div| {
 7708                            div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7709                        })
 7710                        .when(!(tiling.top || tiling.left), |div| {
 7711                            div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7712                        })
 7713                        .when(!(tiling.bottom || tiling.right), |div| {
 7714                            div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7715                        })
 7716                        .when(!(tiling.bottom || tiling.left), |div| {
 7717                            div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING)
 7718                        })
 7719                        .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
 7720                        .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
 7721                        .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
 7722                        .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
 7723                        .when(!tiling.is_tiled(), |div| {
 7724                            div.shadow(vec![gpui::BoxShadow {
 7725                                color: Hsla {
 7726                                    h: 0.,
 7727                                    s: 0.,
 7728                                    l: 0.,
 7729                                    a: 0.4,
 7730                                },
 7731                                blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
 7732                                spread_radius: px(0.),
 7733                                offset: point(px(0.0), px(0.0)),
 7734                            }])
 7735                        }),
 7736                })
 7737                .on_mouse_move(|_e, _, cx| {
 7738                    cx.stop_propagation();
 7739                })
 7740                .size_full()
 7741                .child(element),
 7742        )
 7743        .map(|div| match decorations {
 7744            Decorations::Server => div,
 7745            Decorations::Client { tiling, .. } => div.child(
 7746                canvas(
 7747                    |_bounds, window, _| {
 7748                        window.insert_hitbox(
 7749                            Bounds::new(
 7750                                point(px(0.0), px(0.0)),
 7751                                window.window_bounds().get_bounds().size,
 7752                            ),
 7753                            HitboxBehavior::Normal,
 7754                        )
 7755                    },
 7756                    move |_bounds, hitbox, window, cx| {
 7757                        let mouse = window.mouse_position();
 7758                        let size = window.window_bounds().get_bounds().size;
 7759                        let Some(edge) =
 7760                            resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
 7761                        else {
 7762                            return;
 7763                        };
 7764                        cx.set_global(GlobalResizeEdge(edge));
 7765                        window.set_cursor_style(
 7766                            match edge {
 7767                                ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
 7768                                ResizeEdge::Left | ResizeEdge::Right => {
 7769                                    CursorStyle::ResizeLeftRight
 7770                                }
 7771                                ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
 7772                                    CursorStyle::ResizeUpLeftDownRight
 7773                                }
 7774                                ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
 7775                                    CursorStyle::ResizeUpRightDownLeft
 7776                                }
 7777                            },
 7778                            &hitbox,
 7779                        );
 7780                    },
 7781                )
 7782                .size_full()
 7783                .absolute(),
 7784            ),
 7785        })
 7786}
 7787
 7788fn resize_edge(
 7789    pos: Point<Pixels>,
 7790    shadow_size: Pixels,
 7791    window_size: Size<Pixels>,
 7792    tiling: Tiling,
 7793) -> Option<ResizeEdge> {
 7794    let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
 7795    if bounds.contains(&pos) {
 7796        return None;
 7797    }
 7798
 7799    let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
 7800    let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
 7801    if !tiling.top && top_left_bounds.contains(&pos) {
 7802        return Some(ResizeEdge::TopLeft);
 7803    }
 7804
 7805    let top_right_bounds = Bounds::new(
 7806        Point::new(window_size.width - corner_size.width, px(0.)),
 7807        corner_size,
 7808    );
 7809    if !tiling.top && top_right_bounds.contains(&pos) {
 7810        return Some(ResizeEdge::TopRight);
 7811    }
 7812
 7813    let bottom_left_bounds = Bounds::new(
 7814        Point::new(px(0.), window_size.height - corner_size.height),
 7815        corner_size,
 7816    );
 7817    if !tiling.bottom && bottom_left_bounds.contains(&pos) {
 7818        return Some(ResizeEdge::BottomLeft);
 7819    }
 7820
 7821    let bottom_right_bounds = Bounds::new(
 7822        Point::new(
 7823            window_size.width - corner_size.width,
 7824            window_size.height - corner_size.height,
 7825        ),
 7826        corner_size,
 7827    );
 7828    if !tiling.bottom && bottom_right_bounds.contains(&pos) {
 7829        return Some(ResizeEdge::BottomRight);
 7830    }
 7831
 7832    if !tiling.top && pos.y < shadow_size {
 7833        Some(ResizeEdge::Top)
 7834    } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
 7835        Some(ResizeEdge::Bottom)
 7836    } else if !tiling.left && pos.x < shadow_size {
 7837        Some(ResizeEdge::Left)
 7838    } else if !tiling.right && pos.x > window_size.width - shadow_size {
 7839        Some(ResizeEdge::Right)
 7840    } else {
 7841        None
 7842    }
 7843}
 7844
 7845fn join_pane_into_active(
 7846    active_pane: &Entity<Pane>,
 7847    pane: &Entity<Pane>,
 7848    window: &mut Window,
 7849    cx: &mut App,
 7850) {
 7851    if pane == active_pane {
 7852    } else if pane.read(cx).items_len() == 0 {
 7853        pane.update(cx, |_, cx| {
 7854            cx.emit(pane::Event::Remove {
 7855                focus_on_pane: None,
 7856            });
 7857        })
 7858    } else {
 7859        move_all_items(pane, active_pane, window, cx);
 7860    }
 7861}
 7862
 7863fn move_all_items(
 7864    from_pane: &Entity<Pane>,
 7865    to_pane: &Entity<Pane>,
 7866    window: &mut Window,
 7867    cx: &mut App,
 7868) {
 7869    let destination_is_different = from_pane != to_pane;
 7870    let mut moved_items = 0;
 7871    for (item_ix, item_handle) in from_pane
 7872        .read(cx)
 7873        .items()
 7874        .enumerate()
 7875        .map(|(ix, item)| (ix, item.clone()))
 7876        .collect::<Vec<_>>()
 7877    {
 7878        let ix = item_ix - moved_items;
 7879        if destination_is_different {
 7880            // Close item from previous pane
 7881            from_pane.update(cx, |source, cx| {
 7882                source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
 7883            });
 7884            moved_items += 1;
 7885        }
 7886
 7887        // This automatically removes duplicate items in the pane
 7888        to_pane.update(cx, |destination, cx| {
 7889            destination.add_item(item_handle, true, true, None, window, cx);
 7890            window.focus(&destination.focus_handle(cx))
 7891        });
 7892    }
 7893}
 7894
 7895pub fn move_item(
 7896    source: &Entity<Pane>,
 7897    destination: &Entity<Pane>,
 7898    item_id_to_move: EntityId,
 7899    destination_index: usize,
 7900    activate: bool,
 7901    window: &mut Window,
 7902    cx: &mut App,
 7903) {
 7904    let Some((item_ix, item_handle)) = source
 7905        .read(cx)
 7906        .items()
 7907        .enumerate()
 7908        .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
 7909        .map(|(ix, item)| (ix, item.clone()))
 7910    else {
 7911        // Tab was closed during drag
 7912        return;
 7913    };
 7914
 7915    if source != destination {
 7916        // Close item from previous pane
 7917        source.update(cx, |source, cx| {
 7918            source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
 7919        });
 7920    }
 7921
 7922    // This automatically removes duplicate items in the pane
 7923    destination.update(cx, |destination, cx| {
 7924        destination.add_item_inner(
 7925            item_handle,
 7926            activate,
 7927            activate,
 7928            activate,
 7929            Some(destination_index),
 7930            window,
 7931            cx,
 7932        );
 7933        if activate {
 7934            window.focus(&destination.focus_handle(cx))
 7935        }
 7936    });
 7937}
 7938
 7939pub fn move_active_item(
 7940    source: &Entity<Pane>,
 7941    destination: &Entity<Pane>,
 7942    focus_destination: bool,
 7943    close_if_empty: bool,
 7944    window: &mut Window,
 7945    cx: &mut App,
 7946) {
 7947    if source == destination {
 7948        return;
 7949    }
 7950    let Some(active_item) = source.read(cx).active_item() else {
 7951        return;
 7952    };
 7953    source.update(cx, |source_pane, cx| {
 7954        let item_id = active_item.item_id();
 7955        source_pane.remove_item(item_id, false, close_if_empty, window, cx);
 7956        destination.update(cx, |target_pane, cx| {
 7957            target_pane.add_item(
 7958                active_item,
 7959                focus_destination,
 7960                focus_destination,
 7961                Some(target_pane.items_len()),
 7962                window,
 7963                cx,
 7964            );
 7965        });
 7966    });
 7967}
 7968
 7969pub fn clone_active_item(
 7970    workspace_id: Option<WorkspaceId>,
 7971    source: &Entity<Pane>,
 7972    destination: &Entity<Pane>,
 7973    focus_destination: bool,
 7974    window: &mut Window,
 7975    cx: &mut App,
 7976) {
 7977    if source == destination {
 7978        return;
 7979    }
 7980    let Some(active_item) = source.read(cx).active_item() else {
 7981        return;
 7982    };
 7983    destination.update(cx, |target_pane, cx| {
 7984        let Some(clone) = active_item.clone_on_split(workspace_id, window, cx) else {
 7985            return;
 7986        };
 7987        target_pane.add_item(
 7988            clone,
 7989            focus_destination,
 7990            focus_destination,
 7991            Some(target_pane.items_len()),
 7992            window,
 7993            cx,
 7994        );
 7995    });
 7996}
 7997
 7998#[derive(Debug)]
 7999pub struct WorkspacePosition {
 8000    pub window_bounds: Option<WindowBounds>,
 8001    pub display: Option<Uuid>,
 8002    pub centered_layout: bool,
 8003}
 8004
 8005pub fn remote_workspace_position_from_db(
 8006    connection_options: RemoteConnectionOptions,
 8007    paths_to_open: &[PathBuf],
 8008    cx: &App,
 8009) -> Task<Result<WorkspacePosition>> {
 8010    let paths = paths_to_open.to_vec();
 8011
 8012    cx.background_spawn(async move {
 8013        let remote_connection_id = persistence::DB
 8014            .get_or_create_remote_connection(connection_options)
 8015            .await
 8016            .context("fetching serialized ssh project")?;
 8017        let serialized_workspace =
 8018            persistence::DB.remote_workspace_for_roots(&paths, remote_connection_id);
 8019
 8020        let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
 8021            (Some(WindowBounds::Windowed(bounds)), None)
 8022        } else {
 8023            let restorable_bounds = serialized_workspace
 8024                .as_ref()
 8025                .and_then(|workspace| Some((workspace.display?, workspace.window_bounds?)))
 8026                .or_else(|| {
 8027                    let (display, window_bounds) = DB.last_window().log_err()?;
 8028                    Some((display?, window_bounds?))
 8029                });
 8030
 8031            if let Some((serialized_display, serialized_status)) = restorable_bounds {
 8032                (Some(serialized_status.0), Some(serialized_display))
 8033            } else {
 8034                (None, None)
 8035            }
 8036        };
 8037
 8038        let centered_layout = serialized_workspace
 8039            .as_ref()
 8040            .map(|w| w.centered_layout)
 8041            .unwrap_or(false);
 8042
 8043        Ok(WorkspacePosition {
 8044            window_bounds,
 8045            display,
 8046            centered_layout,
 8047        })
 8048    })
 8049}
 8050
 8051pub fn with_active_or_new_workspace(
 8052    cx: &mut App,
 8053    f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
 8054) {
 8055    match cx.active_window().and_then(|w| w.downcast::<Workspace>()) {
 8056        Some(workspace) => {
 8057            cx.defer(move |cx| {
 8058                workspace
 8059                    .update(cx, |workspace, window, cx| f(workspace, window, cx))
 8060                    .log_err();
 8061            });
 8062        }
 8063        None => {
 8064            let app_state = AppState::global(cx);
 8065            if let Some(app_state) = app_state.upgrade() {
 8066                open_new(
 8067                    OpenOptions::default(),
 8068                    app_state,
 8069                    cx,
 8070                    move |workspace, window, cx| f(workspace, window, cx),
 8071                )
 8072                .detach_and_log_err(cx);
 8073            }
 8074        }
 8075    }
 8076}
 8077
 8078#[cfg(test)]
 8079mod tests {
 8080    use std::{cell::RefCell, rc::Rc};
 8081
 8082    use super::*;
 8083    use crate::{
 8084        dock::{PanelEvent, test::TestPanel},
 8085        item::{
 8086            ItemEvent,
 8087            test::{TestItem, TestProjectItem},
 8088        },
 8089    };
 8090    use fs::FakeFs;
 8091    use gpui::{
 8092        DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
 8093        UpdateGlobal, VisualTestContext, px,
 8094    };
 8095    use project::{Project, ProjectEntryId};
 8096    use serde_json::json;
 8097    use settings::SettingsStore;
 8098
 8099    #[gpui::test]
 8100    async fn test_tab_disambiguation(cx: &mut TestAppContext) {
 8101        init_test(cx);
 8102
 8103        let fs = FakeFs::new(cx.executor());
 8104        let project = Project::test(fs, [], cx).await;
 8105        let (workspace, cx) =
 8106            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8107
 8108        // Adding an item with no ambiguity renders the tab without detail.
 8109        let item1 = cx.new(|cx| {
 8110            let mut item = TestItem::new(cx);
 8111            item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
 8112            item
 8113        });
 8114        workspace.update_in(cx, |workspace, window, cx| {
 8115            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8116        });
 8117        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
 8118
 8119        // Adding an item that creates ambiguity increases the level of detail on
 8120        // both tabs.
 8121        let item2 = cx.new_window_entity(|_window, cx| {
 8122            let mut item = TestItem::new(cx);
 8123            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 8124            item
 8125        });
 8126        workspace.update_in(cx, |workspace, window, cx| {
 8127            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8128        });
 8129        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8130        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8131
 8132        // Adding an item that creates ambiguity increases the level of detail only
 8133        // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
 8134        // we stop at the highest detail available.
 8135        let item3 = cx.new(|cx| {
 8136            let mut item = TestItem::new(cx);
 8137            item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
 8138            item
 8139        });
 8140        workspace.update_in(cx, |workspace, window, cx| {
 8141            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8142        });
 8143        item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
 8144        item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 8145        item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
 8146    }
 8147
 8148    #[gpui::test]
 8149    async fn test_tracking_active_path(cx: &mut TestAppContext) {
 8150        init_test(cx);
 8151
 8152        let fs = FakeFs::new(cx.executor());
 8153        fs.insert_tree(
 8154            "/root1",
 8155            json!({
 8156                "one.txt": "",
 8157                "two.txt": "",
 8158            }),
 8159        )
 8160        .await;
 8161        fs.insert_tree(
 8162            "/root2",
 8163            json!({
 8164                "three.txt": "",
 8165            }),
 8166        )
 8167        .await;
 8168
 8169        let project = Project::test(fs, ["root1".as_ref()], cx).await;
 8170        let (workspace, cx) =
 8171            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8172        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8173        let worktree_id = project.update(cx, |project, cx| {
 8174            project.worktrees(cx).next().unwrap().read(cx).id()
 8175        });
 8176
 8177        let item1 = cx.new(|cx| {
 8178            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
 8179        });
 8180        let item2 = cx.new(|cx| {
 8181            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
 8182        });
 8183
 8184        // Add an item to an empty pane
 8185        workspace.update_in(cx, |workspace, window, cx| {
 8186            workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
 8187        });
 8188        project.update(cx, |project, cx| {
 8189            assert_eq!(
 8190                project.active_entry(),
 8191                project
 8192                    .entry_for_path(&(worktree_id, "one.txt").into(), cx)
 8193                    .map(|e| e.id)
 8194            );
 8195        });
 8196        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 8197
 8198        // Add a second item to a non-empty pane
 8199        workspace.update_in(cx, |workspace, window, cx| {
 8200            workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
 8201        });
 8202        assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
 8203        project.update(cx, |project, cx| {
 8204            assert_eq!(
 8205                project.active_entry(),
 8206                project
 8207                    .entry_for_path(&(worktree_id, "two.txt").into(), cx)
 8208                    .map(|e| e.id)
 8209            );
 8210        });
 8211
 8212        // Close the active item
 8213        pane.update_in(cx, |pane, window, cx| {
 8214            pane.close_active_item(&Default::default(), window, cx)
 8215        })
 8216        .await
 8217        .unwrap();
 8218        assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
 8219        project.update(cx, |project, cx| {
 8220            assert_eq!(
 8221                project.active_entry(),
 8222                project
 8223                    .entry_for_path(&(worktree_id, "one.txt").into(), cx)
 8224                    .map(|e| e.id)
 8225            );
 8226        });
 8227
 8228        // Add a project folder
 8229        project
 8230            .update(cx, |project, cx| {
 8231                project.find_or_create_worktree("root2", true, cx)
 8232            })
 8233            .await
 8234            .unwrap();
 8235        assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
 8236
 8237        // Remove a project folder
 8238        project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
 8239        assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
 8240    }
 8241
 8242    #[gpui::test]
 8243    async fn test_close_window(cx: &mut TestAppContext) {
 8244        init_test(cx);
 8245
 8246        let fs = FakeFs::new(cx.executor());
 8247        fs.insert_tree("/root", json!({ "one": "" })).await;
 8248
 8249        let project = Project::test(fs, ["root".as_ref()], cx).await;
 8250        let (workspace, cx) =
 8251            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8252
 8253        // When there are no dirty items, there's nothing to do.
 8254        let item1 = cx.new(TestItem::new);
 8255        workspace.update_in(cx, |w, window, cx| {
 8256            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
 8257        });
 8258        let task = workspace.update_in(cx, |w, window, cx| {
 8259            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8260        });
 8261        assert!(task.await.unwrap());
 8262
 8263        // When there are dirty untitled items, prompt to save each one. If the user
 8264        // cancels any prompt, then abort.
 8265        let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
 8266        let item3 = cx.new(|cx| {
 8267            TestItem::new(cx)
 8268                .with_dirty(true)
 8269                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8270        });
 8271        workspace.update_in(cx, |w, window, cx| {
 8272            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8273            w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8274        });
 8275        let task = workspace.update_in(cx, |w, window, cx| {
 8276            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8277        });
 8278        cx.executor().run_until_parked();
 8279        cx.simulate_prompt_answer("Cancel"); // cancel save all
 8280        cx.executor().run_until_parked();
 8281        assert!(!cx.has_pending_prompt());
 8282        assert!(!task.await.unwrap());
 8283    }
 8284
 8285    #[gpui::test]
 8286    async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
 8287        init_test(cx);
 8288
 8289        // Register TestItem as a serializable item
 8290        cx.update(|cx| {
 8291            register_serializable_item::<TestItem>(cx);
 8292        });
 8293
 8294        let fs = FakeFs::new(cx.executor());
 8295        fs.insert_tree("/root", json!({ "one": "" })).await;
 8296
 8297        let project = Project::test(fs, ["root".as_ref()], cx).await;
 8298        let (workspace, cx) =
 8299            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8300
 8301        // When there are dirty untitled items, but they can serialize, then there is no prompt.
 8302        let item1 = cx.new(|cx| {
 8303            TestItem::new(cx)
 8304                .with_dirty(true)
 8305                .with_serialize(|| Some(Task::ready(Ok(()))))
 8306        });
 8307        let item2 = cx.new(|cx| {
 8308            TestItem::new(cx)
 8309                .with_dirty(true)
 8310                .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8311                .with_serialize(|| Some(Task::ready(Ok(()))))
 8312        });
 8313        workspace.update_in(cx, |w, window, cx| {
 8314            w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8315            w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8316        });
 8317        let task = workspace.update_in(cx, |w, window, cx| {
 8318            w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
 8319        });
 8320        assert!(task.await.unwrap());
 8321    }
 8322
 8323    #[gpui::test]
 8324    async fn test_close_pane_items(cx: &mut TestAppContext) {
 8325        init_test(cx);
 8326
 8327        let fs = FakeFs::new(cx.executor());
 8328
 8329        let project = Project::test(fs, None, cx).await;
 8330        let (workspace, cx) =
 8331            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8332
 8333        let item1 = cx.new(|cx| {
 8334            TestItem::new(cx)
 8335                .with_dirty(true)
 8336                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 8337        });
 8338        let item2 = cx.new(|cx| {
 8339            TestItem::new(cx)
 8340                .with_dirty(true)
 8341                .with_conflict(true)
 8342                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 8343        });
 8344        let item3 = cx.new(|cx| {
 8345            TestItem::new(cx)
 8346                .with_dirty(true)
 8347                .with_conflict(true)
 8348                .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
 8349        });
 8350        let item4 = cx.new(|cx| {
 8351            TestItem::new(cx).with_dirty(true).with_project_items(&[{
 8352                let project_item = TestProjectItem::new_untitled(cx);
 8353                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 8354                project_item
 8355            }])
 8356        });
 8357        let pane = workspace.update_in(cx, |workspace, window, cx| {
 8358            workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
 8359            workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
 8360            workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
 8361            workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
 8362            workspace.active_pane().clone()
 8363        });
 8364
 8365        let close_items = pane.update_in(cx, |pane, window, cx| {
 8366            pane.activate_item(1, true, true, window, cx);
 8367            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 8368            let item1_id = item1.item_id();
 8369            let item3_id = item3.item_id();
 8370            let item4_id = item4.item_id();
 8371            pane.close_items(window, cx, SaveIntent::Close, move |id| {
 8372                [item1_id, item3_id, item4_id].contains(&id)
 8373            })
 8374        });
 8375        cx.executor().run_until_parked();
 8376
 8377        assert!(cx.has_pending_prompt());
 8378        cx.simulate_prompt_answer("Save all");
 8379
 8380        cx.executor().run_until_parked();
 8381
 8382        // Item 1 is saved. There's a prompt to save item 3.
 8383        pane.update(cx, |pane, cx| {
 8384            assert_eq!(item1.read(cx).save_count, 1);
 8385            assert_eq!(item1.read(cx).save_as_count, 0);
 8386            assert_eq!(item1.read(cx).reload_count, 0);
 8387            assert_eq!(pane.items_len(), 3);
 8388            assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
 8389        });
 8390        assert!(cx.has_pending_prompt());
 8391
 8392        // Cancel saving item 3.
 8393        cx.simulate_prompt_answer("Discard");
 8394        cx.executor().run_until_parked();
 8395
 8396        // Item 3 is reloaded. There's a prompt to save item 4.
 8397        pane.update(cx, |pane, cx| {
 8398            assert_eq!(item3.read(cx).save_count, 0);
 8399            assert_eq!(item3.read(cx).save_as_count, 0);
 8400            assert_eq!(item3.read(cx).reload_count, 1);
 8401            assert_eq!(pane.items_len(), 2);
 8402            assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
 8403        });
 8404
 8405        // There's a prompt for a path for item 4.
 8406        cx.simulate_new_path_selection(|_| Some(Default::default()));
 8407        close_items.await.unwrap();
 8408
 8409        // The requested items are closed.
 8410        pane.update(cx, |pane, cx| {
 8411            assert_eq!(item4.read(cx).save_count, 0);
 8412            assert_eq!(item4.read(cx).save_as_count, 1);
 8413            assert_eq!(item4.read(cx).reload_count, 0);
 8414            assert_eq!(pane.items_len(), 1);
 8415            assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
 8416        });
 8417    }
 8418
 8419    #[gpui::test]
 8420    async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
 8421        init_test(cx);
 8422
 8423        let fs = FakeFs::new(cx.executor());
 8424        let project = Project::test(fs, [], cx).await;
 8425        let (workspace, cx) =
 8426            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8427
 8428        // Create several workspace items with single project entries, and two
 8429        // workspace items with multiple project entries.
 8430        let single_entry_items = (0..=4)
 8431            .map(|project_entry_id| {
 8432                cx.new(|cx| {
 8433                    TestItem::new(cx)
 8434                        .with_dirty(true)
 8435                        .with_project_items(&[dirty_project_item(
 8436                            project_entry_id,
 8437                            &format!("{project_entry_id}.txt"),
 8438                            cx,
 8439                        )])
 8440                })
 8441            })
 8442            .collect::<Vec<_>>();
 8443        let item_2_3 = cx.new(|cx| {
 8444            TestItem::new(cx)
 8445                .with_dirty(true)
 8446                .with_singleton(false)
 8447                .with_project_items(&[
 8448                    single_entry_items[2].read(cx).project_items[0].clone(),
 8449                    single_entry_items[3].read(cx).project_items[0].clone(),
 8450                ])
 8451        });
 8452        let item_3_4 = cx.new(|cx| {
 8453            TestItem::new(cx)
 8454                .with_dirty(true)
 8455                .with_singleton(false)
 8456                .with_project_items(&[
 8457                    single_entry_items[3].read(cx).project_items[0].clone(),
 8458                    single_entry_items[4].read(cx).project_items[0].clone(),
 8459                ])
 8460        });
 8461
 8462        // Create two panes that contain the following project entries:
 8463        //   left pane:
 8464        //     multi-entry items:   (2, 3)
 8465        //     single-entry items:  0, 2, 3, 4
 8466        //   right pane:
 8467        //     single-entry items:  4, 1
 8468        //     multi-entry items:   (3, 4)
 8469        let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
 8470            let left_pane = workspace.active_pane().clone();
 8471            workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
 8472            workspace.add_item_to_active_pane(
 8473                single_entry_items[0].boxed_clone(),
 8474                None,
 8475                true,
 8476                window,
 8477                cx,
 8478            );
 8479            workspace.add_item_to_active_pane(
 8480                single_entry_items[2].boxed_clone(),
 8481                None,
 8482                true,
 8483                window,
 8484                cx,
 8485            );
 8486            workspace.add_item_to_active_pane(
 8487                single_entry_items[3].boxed_clone(),
 8488                None,
 8489                true,
 8490                window,
 8491                cx,
 8492            );
 8493            workspace.add_item_to_active_pane(
 8494                single_entry_items[4].boxed_clone(),
 8495                None,
 8496                true,
 8497                window,
 8498                cx,
 8499            );
 8500
 8501            let right_pane = workspace
 8502                .split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx)
 8503                .unwrap();
 8504
 8505            right_pane.update(cx, |pane, cx| {
 8506                pane.add_item(
 8507                    single_entry_items[1].boxed_clone(),
 8508                    true,
 8509                    true,
 8510                    None,
 8511                    window,
 8512                    cx,
 8513                );
 8514                pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
 8515            });
 8516
 8517            (left_pane, right_pane)
 8518        });
 8519
 8520        cx.focus(&right_pane);
 8521
 8522        let mut close = right_pane.update_in(cx, |pane, window, cx| {
 8523            pane.close_all_items(&CloseAllItems::default(), window, cx)
 8524                .unwrap()
 8525        });
 8526        cx.executor().run_until_parked();
 8527
 8528        let msg = cx.pending_prompt().unwrap().0;
 8529        assert!(msg.contains("1.txt"));
 8530        assert!(!msg.contains("2.txt"));
 8531        assert!(!msg.contains("3.txt"));
 8532        assert!(!msg.contains("4.txt"));
 8533
 8534        cx.simulate_prompt_answer("Cancel");
 8535        close.await;
 8536
 8537        left_pane
 8538            .update_in(cx, |left_pane, window, cx| {
 8539                left_pane.close_item_by_id(
 8540                    single_entry_items[3].entity_id(),
 8541                    SaveIntent::Skip,
 8542                    window,
 8543                    cx,
 8544                )
 8545            })
 8546            .await
 8547            .unwrap();
 8548
 8549        close = right_pane.update_in(cx, |pane, window, cx| {
 8550            pane.close_all_items(&CloseAllItems::default(), window, cx)
 8551                .unwrap()
 8552        });
 8553        cx.executor().run_until_parked();
 8554
 8555        let details = cx.pending_prompt().unwrap().1;
 8556        assert!(details.contains("1.txt"));
 8557        assert!(!details.contains("2.txt"));
 8558        assert!(details.contains("3.txt"));
 8559        // ideally this assertion could be made, but today we can only
 8560        // save whole items not project items, so the orphaned item 3 causes
 8561        // 4 to be saved too.
 8562        // assert!(!details.contains("4.txt"));
 8563
 8564        cx.simulate_prompt_answer("Save all");
 8565
 8566        cx.executor().run_until_parked();
 8567        close.await;
 8568        right_pane.read_with(cx, |pane, _| {
 8569            assert_eq!(pane.items_len(), 0);
 8570        });
 8571    }
 8572
 8573    #[gpui::test]
 8574    async fn test_autosave(cx: &mut gpui::TestAppContext) {
 8575        init_test(cx);
 8576
 8577        let fs = FakeFs::new(cx.executor());
 8578        let project = Project::test(fs, [], cx).await;
 8579        let (workspace, cx) =
 8580            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8581        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8582
 8583        let item = cx.new(|cx| {
 8584            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8585        });
 8586        let item_id = item.entity_id();
 8587        workspace.update_in(cx, |workspace, window, cx| {
 8588            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 8589        });
 8590
 8591        // Autosave on window change.
 8592        item.update(cx, |item, cx| {
 8593            SettingsStore::update_global(cx, |settings, cx| {
 8594                settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 8595                    settings.autosave = Some(AutosaveSetting::OnWindowChange);
 8596                })
 8597            });
 8598            item.is_dirty = true;
 8599        });
 8600
 8601        // Deactivating the window saves the file.
 8602        cx.deactivate_window();
 8603        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 8604
 8605        // Re-activating the window doesn't save the file.
 8606        cx.update(|window, _| window.activate_window());
 8607        cx.executor().run_until_parked();
 8608        item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
 8609
 8610        // Autosave on focus change.
 8611        item.update_in(cx, |item, window, cx| {
 8612            cx.focus_self(window);
 8613            SettingsStore::update_global(cx, |settings, cx| {
 8614                settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 8615                    settings.autosave = Some(AutosaveSetting::OnFocusChange);
 8616                })
 8617            });
 8618            item.is_dirty = true;
 8619        });
 8620
 8621        // Blurring the item saves the file.
 8622        item.update_in(cx, |_, window, _| window.blur());
 8623        cx.executor().run_until_parked();
 8624        item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
 8625
 8626        // Deactivating the window still saves the file.
 8627        item.update_in(cx, |item, window, cx| {
 8628            cx.focus_self(window);
 8629            item.is_dirty = true;
 8630        });
 8631        cx.deactivate_window();
 8632        item.update(cx, |item, _| assert_eq!(item.save_count, 3));
 8633
 8634        // Autosave after delay.
 8635        item.update(cx, |item, cx| {
 8636            SettingsStore::update_global(cx, |settings, cx| {
 8637                settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 8638                    settings.autosave = Some(AutosaveSetting::AfterDelay { milliseconds: 500 });
 8639                })
 8640            });
 8641            item.is_dirty = true;
 8642            cx.emit(ItemEvent::Edit);
 8643        });
 8644
 8645        // Delay hasn't fully expired, so the file is still dirty and unsaved.
 8646        cx.executor().advance_clock(Duration::from_millis(250));
 8647        item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
 8648
 8649        // After delay expires, the file is saved.
 8650        cx.executor().advance_clock(Duration::from_millis(250));
 8651        item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
 8652
 8653        // Autosave on focus change, ensuring closing the tab counts as such.
 8654        item.update(cx, |item, cx| {
 8655            SettingsStore::update_global(cx, |settings, cx| {
 8656                settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 8657                    settings.autosave = Some(AutosaveSetting::OnFocusChange);
 8658                })
 8659            });
 8660            item.is_dirty = true;
 8661            for project_item in &mut item.project_items {
 8662                project_item.update(cx, |project_item, _| project_item.is_dirty = true);
 8663            }
 8664        });
 8665
 8666        pane.update_in(cx, |pane, window, cx| {
 8667            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 8668        })
 8669        .await
 8670        .unwrap();
 8671        assert!(!cx.has_pending_prompt());
 8672        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 8673
 8674        // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
 8675        workspace.update_in(cx, |workspace, window, cx| {
 8676            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 8677        });
 8678        item.update_in(cx, |item, window, cx| {
 8679            item.project_items[0].update(cx, |item, _| {
 8680                item.entry_id = None;
 8681            });
 8682            item.is_dirty = true;
 8683            window.blur();
 8684        });
 8685        cx.run_until_parked();
 8686        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 8687
 8688        // Ensure autosave is prevented for deleted files also when closing the buffer.
 8689        let _close_items = pane.update_in(cx, |pane, window, cx| {
 8690            pane.close_items(window, cx, SaveIntent::Close, move |id| id == item_id)
 8691        });
 8692        cx.run_until_parked();
 8693        assert!(cx.has_pending_prompt());
 8694        item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
 8695    }
 8696
 8697    #[gpui::test]
 8698    async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
 8699        init_test(cx);
 8700
 8701        let fs = FakeFs::new(cx.executor());
 8702
 8703        let project = Project::test(fs, [], cx).await;
 8704        let (workspace, cx) =
 8705            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8706
 8707        let item = cx.new(|cx| {
 8708            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
 8709        });
 8710        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8711        let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
 8712        let toolbar_notify_count = Rc::new(RefCell::new(0));
 8713
 8714        workspace.update_in(cx, |workspace, window, cx| {
 8715            workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
 8716            let toolbar_notification_count = toolbar_notify_count.clone();
 8717            cx.observe_in(&toolbar, window, move |_, _, _, _| {
 8718                *toolbar_notification_count.borrow_mut() += 1
 8719            })
 8720            .detach();
 8721        });
 8722
 8723        pane.read_with(cx, |pane, _| {
 8724            assert!(!pane.can_navigate_backward());
 8725            assert!(!pane.can_navigate_forward());
 8726        });
 8727
 8728        item.update_in(cx, |item, _, cx| {
 8729            item.set_state("one".to_string(), cx);
 8730        });
 8731
 8732        // Toolbar must be notified to re-render the navigation buttons
 8733        assert_eq!(*toolbar_notify_count.borrow(), 1);
 8734
 8735        pane.read_with(cx, |pane, _| {
 8736            assert!(pane.can_navigate_backward());
 8737            assert!(!pane.can_navigate_forward());
 8738        });
 8739
 8740        workspace
 8741            .update_in(cx, |workspace, window, cx| {
 8742                workspace.go_back(pane.downgrade(), window, cx)
 8743            })
 8744            .await
 8745            .unwrap();
 8746
 8747        assert_eq!(*toolbar_notify_count.borrow(), 2);
 8748        pane.read_with(cx, |pane, _| {
 8749            assert!(!pane.can_navigate_backward());
 8750            assert!(pane.can_navigate_forward());
 8751        });
 8752    }
 8753
 8754    #[gpui::test]
 8755    async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
 8756        init_test(cx);
 8757        let fs = FakeFs::new(cx.executor());
 8758
 8759        let project = Project::test(fs, [], cx).await;
 8760        let (workspace, cx) =
 8761            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8762
 8763        let panel = workspace.update_in(cx, |workspace, window, cx| {
 8764            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
 8765            workspace.add_panel(panel.clone(), window, cx);
 8766
 8767            workspace
 8768                .right_dock()
 8769                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
 8770
 8771            panel
 8772        });
 8773
 8774        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 8775        pane.update_in(cx, |pane, window, cx| {
 8776            let item = cx.new(TestItem::new);
 8777            pane.add_item(Box::new(item), true, true, None, window, cx);
 8778        });
 8779
 8780        // Transfer focus from center to panel
 8781        workspace.update_in(cx, |workspace, window, cx| {
 8782            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 8783        });
 8784
 8785        workspace.update_in(cx, |workspace, window, cx| {
 8786            assert!(workspace.right_dock().read(cx).is_open());
 8787            assert!(!panel.is_zoomed(window, cx));
 8788            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8789        });
 8790
 8791        // Transfer focus from panel to center
 8792        workspace.update_in(cx, |workspace, window, cx| {
 8793            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 8794        });
 8795
 8796        workspace.update_in(cx, |workspace, window, cx| {
 8797            assert!(workspace.right_dock().read(cx).is_open());
 8798            assert!(!panel.is_zoomed(window, cx));
 8799            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8800        });
 8801
 8802        // Close the dock
 8803        workspace.update_in(cx, |workspace, window, cx| {
 8804            workspace.toggle_dock(DockPosition::Right, window, cx);
 8805        });
 8806
 8807        workspace.update_in(cx, |workspace, window, cx| {
 8808            assert!(!workspace.right_dock().read(cx).is_open());
 8809            assert!(!panel.is_zoomed(window, cx));
 8810            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8811        });
 8812
 8813        // Open the dock
 8814        workspace.update_in(cx, |workspace, window, cx| {
 8815            workspace.toggle_dock(DockPosition::Right, window, cx);
 8816        });
 8817
 8818        workspace.update_in(cx, |workspace, window, cx| {
 8819            assert!(workspace.right_dock().read(cx).is_open());
 8820            assert!(!panel.is_zoomed(window, cx));
 8821            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8822        });
 8823
 8824        // Focus and zoom panel
 8825        panel.update_in(cx, |panel, window, cx| {
 8826            cx.focus_self(window);
 8827            panel.set_zoomed(true, window, cx)
 8828        });
 8829
 8830        workspace.update_in(cx, |workspace, window, cx| {
 8831            assert!(workspace.right_dock().read(cx).is_open());
 8832            assert!(panel.is_zoomed(window, cx));
 8833            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8834        });
 8835
 8836        // Transfer focus to the center closes the dock
 8837        workspace.update_in(cx, |workspace, window, cx| {
 8838            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 8839        });
 8840
 8841        workspace.update_in(cx, |workspace, window, cx| {
 8842            assert!(!workspace.right_dock().read(cx).is_open());
 8843            assert!(panel.is_zoomed(window, cx));
 8844            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8845        });
 8846
 8847        // Transferring focus back to the panel keeps it zoomed
 8848        workspace.update_in(cx, |workspace, window, cx| {
 8849            workspace.toggle_panel_focus::<TestPanel>(window, cx);
 8850        });
 8851
 8852        workspace.update_in(cx, |workspace, window, cx| {
 8853            assert!(workspace.right_dock().read(cx).is_open());
 8854            assert!(panel.is_zoomed(window, cx));
 8855            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8856        });
 8857
 8858        // Close the dock while it is zoomed
 8859        workspace.update_in(cx, |workspace, window, cx| {
 8860            workspace.toggle_dock(DockPosition::Right, window, cx)
 8861        });
 8862
 8863        workspace.update_in(cx, |workspace, window, cx| {
 8864            assert!(!workspace.right_dock().read(cx).is_open());
 8865            assert!(panel.is_zoomed(window, cx));
 8866            assert!(workspace.zoomed.is_none());
 8867            assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8868        });
 8869
 8870        // Opening the dock, when it's zoomed, retains focus
 8871        workspace.update_in(cx, |workspace, window, cx| {
 8872            workspace.toggle_dock(DockPosition::Right, window, cx)
 8873        });
 8874
 8875        workspace.update_in(cx, |workspace, window, cx| {
 8876            assert!(workspace.right_dock().read(cx).is_open());
 8877            assert!(panel.is_zoomed(window, cx));
 8878            assert!(workspace.zoomed.is_some());
 8879            assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
 8880        });
 8881
 8882        // Unzoom and close the panel, zoom the active pane.
 8883        panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
 8884        workspace.update_in(cx, |workspace, window, cx| {
 8885            workspace.toggle_dock(DockPosition::Right, window, cx)
 8886        });
 8887        pane.update_in(cx, |pane, window, cx| {
 8888            pane.toggle_zoom(&Default::default(), window, cx)
 8889        });
 8890
 8891        // Opening a dock unzooms the pane.
 8892        workspace.update_in(cx, |workspace, window, cx| {
 8893            workspace.toggle_dock(DockPosition::Right, window, cx)
 8894        });
 8895        workspace.update_in(cx, |workspace, window, cx| {
 8896            let pane = pane.read(cx);
 8897            assert!(!pane.is_zoomed());
 8898            assert!(!pane.focus_handle(cx).is_focused(window));
 8899            assert!(workspace.right_dock().read(cx).is_open());
 8900            assert!(workspace.zoomed.is_none());
 8901        });
 8902    }
 8903
 8904    #[gpui::test]
 8905    async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
 8906        init_test(cx);
 8907
 8908        let fs = FakeFs::new(cx.executor());
 8909
 8910        let project = Project::test(fs, None, cx).await;
 8911        let (workspace, cx) =
 8912            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 8913
 8914        // Let's arrange the panes like this:
 8915        //
 8916        // +-----------------------+
 8917        // |         top           |
 8918        // +------+--------+-------+
 8919        // | left | center | right |
 8920        // +------+--------+-------+
 8921        // |        bottom         |
 8922        // +-----------------------+
 8923
 8924        let top_item = cx.new(|cx| {
 8925            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
 8926        });
 8927        let bottom_item = cx.new(|cx| {
 8928            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
 8929        });
 8930        let left_item = cx.new(|cx| {
 8931            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
 8932        });
 8933        let right_item = cx.new(|cx| {
 8934            TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
 8935        });
 8936        let center_item = cx.new(|cx| {
 8937            TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
 8938        });
 8939
 8940        let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 8941            let top_pane_id = workspace.active_pane().entity_id();
 8942            workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
 8943            workspace.split_pane(
 8944                workspace.active_pane().clone(),
 8945                SplitDirection::Down,
 8946                window,
 8947                cx,
 8948            );
 8949            top_pane_id
 8950        });
 8951        let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 8952            let bottom_pane_id = workspace.active_pane().entity_id();
 8953            workspace.add_item_to_active_pane(
 8954                Box::new(bottom_item.clone()),
 8955                None,
 8956                false,
 8957                window,
 8958                cx,
 8959            );
 8960            workspace.split_pane(
 8961                workspace.active_pane().clone(),
 8962                SplitDirection::Up,
 8963                window,
 8964                cx,
 8965            );
 8966            bottom_pane_id
 8967        });
 8968        let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 8969            let left_pane_id = workspace.active_pane().entity_id();
 8970            workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
 8971            workspace.split_pane(
 8972                workspace.active_pane().clone(),
 8973                SplitDirection::Right,
 8974                window,
 8975                cx,
 8976            );
 8977            left_pane_id
 8978        });
 8979        let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 8980            let right_pane_id = workspace.active_pane().entity_id();
 8981            workspace.add_item_to_active_pane(
 8982                Box::new(right_item.clone()),
 8983                None,
 8984                false,
 8985                window,
 8986                cx,
 8987            );
 8988            workspace.split_pane(
 8989                workspace.active_pane().clone(),
 8990                SplitDirection::Left,
 8991                window,
 8992                cx,
 8993            );
 8994            right_pane_id
 8995        });
 8996        let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
 8997            let center_pane_id = workspace.active_pane().entity_id();
 8998            workspace.add_item_to_active_pane(
 8999                Box::new(center_item.clone()),
 9000                None,
 9001                false,
 9002                window,
 9003                cx,
 9004            );
 9005            center_pane_id
 9006        });
 9007        cx.executor().run_until_parked();
 9008
 9009        workspace.update_in(cx, |workspace, window, cx| {
 9010            assert_eq!(center_pane_id, workspace.active_pane().entity_id());
 9011
 9012            // Join into next from center pane into right
 9013            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9014        });
 9015
 9016        workspace.update_in(cx, |workspace, window, cx| {
 9017            let active_pane = workspace.active_pane();
 9018            assert_eq!(right_pane_id, active_pane.entity_id());
 9019            assert_eq!(2, active_pane.read(cx).items_len());
 9020            let item_ids_in_pane =
 9021                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9022            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9023            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9024
 9025            // Join into next from right pane into bottom
 9026            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9027        });
 9028
 9029        workspace.update_in(cx, |workspace, window, cx| {
 9030            let active_pane = workspace.active_pane();
 9031            assert_eq!(bottom_pane_id, active_pane.entity_id());
 9032            assert_eq!(3, active_pane.read(cx).items_len());
 9033            let item_ids_in_pane =
 9034                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9035            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9036            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9037            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 9038
 9039            // Join into next from bottom pane into left
 9040            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9041        });
 9042
 9043        workspace.update_in(cx, |workspace, window, cx| {
 9044            let active_pane = workspace.active_pane();
 9045            assert_eq!(left_pane_id, active_pane.entity_id());
 9046            assert_eq!(4, active_pane.read(cx).items_len());
 9047            let item_ids_in_pane =
 9048                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9049            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9050            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9051            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 9052            assert!(item_ids_in_pane.contains(&left_item.item_id()));
 9053
 9054            // Join into next from left pane into top
 9055            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
 9056        });
 9057
 9058        workspace.update_in(cx, |workspace, window, cx| {
 9059            let active_pane = workspace.active_pane();
 9060            assert_eq!(top_pane_id, active_pane.entity_id());
 9061            assert_eq!(5, active_pane.read(cx).items_len());
 9062            let item_ids_in_pane =
 9063                HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
 9064            assert!(item_ids_in_pane.contains(&center_item.item_id()));
 9065            assert!(item_ids_in_pane.contains(&right_item.item_id()));
 9066            assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
 9067            assert!(item_ids_in_pane.contains(&left_item.item_id()));
 9068            assert!(item_ids_in_pane.contains(&top_item.item_id()));
 9069
 9070            // Single pane left: no-op
 9071            workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
 9072        });
 9073
 9074        workspace.update(cx, |workspace, _cx| {
 9075            let active_pane = workspace.active_pane();
 9076            assert_eq!(top_pane_id, active_pane.entity_id());
 9077        });
 9078    }
 9079
 9080    fn add_an_item_to_active_pane(
 9081        cx: &mut VisualTestContext,
 9082        workspace: &Entity<Workspace>,
 9083        item_id: u64,
 9084    ) -> Entity<TestItem> {
 9085        let item = cx.new(|cx| {
 9086            TestItem::new(cx).with_project_items(&[TestProjectItem::new(
 9087                item_id,
 9088                "item{item_id}.txt",
 9089                cx,
 9090            )])
 9091        });
 9092        workspace.update_in(cx, |workspace, window, cx| {
 9093            workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
 9094        });
 9095        item
 9096    }
 9097
 9098    fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
 9099        workspace.update_in(cx, |workspace, window, cx| {
 9100            workspace.split_pane(
 9101                workspace.active_pane().clone(),
 9102                SplitDirection::Right,
 9103                window,
 9104                cx,
 9105            )
 9106        })
 9107    }
 9108
 9109    #[gpui::test]
 9110    async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
 9111        init_test(cx);
 9112        let fs = FakeFs::new(cx.executor());
 9113        let project = Project::test(fs, None, cx).await;
 9114        let (workspace, cx) =
 9115            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9116
 9117        add_an_item_to_active_pane(cx, &workspace, 1);
 9118        split_pane(cx, &workspace);
 9119        add_an_item_to_active_pane(cx, &workspace, 2);
 9120        split_pane(cx, &workspace); // empty pane
 9121        split_pane(cx, &workspace);
 9122        let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
 9123
 9124        cx.executor().run_until_parked();
 9125
 9126        workspace.update(cx, |workspace, cx| {
 9127            let num_panes = workspace.panes().len();
 9128            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
 9129            let active_item = workspace
 9130                .active_pane()
 9131                .read(cx)
 9132                .active_item()
 9133                .expect("item is in focus");
 9134
 9135            assert_eq!(num_panes, 4);
 9136            assert_eq!(num_items_in_current_pane, 1);
 9137            assert_eq!(active_item.item_id(), last_item.item_id());
 9138        });
 9139
 9140        workspace.update_in(cx, |workspace, window, cx| {
 9141            workspace.join_all_panes(window, cx);
 9142        });
 9143
 9144        workspace.update(cx, |workspace, cx| {
 9145            let num_panes = workspace.panes().len();
 9146            let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
 9147            let active_item = workspace
 9148                .active_pane()
 9149                .read(cx)
 9150                .active_item()
 9151                .expect("item is in focus");
 9152
 9153            assert_eq!(num_panes, 1);
 9154            assert_eq!(num_items_in_current_pane, 3);
 9155            assert_eq!(active_item.item_id(), last_item.item_id());
 9156        });
 9157    }
 9158    struct TestModal(FocusHandle);
 9159
 9160    impl TestModal {
 9161        fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
 9162            Self(cx.focus_handle())
 9163        }
 9164    }
 9165
 9166    impl EventEmitter<DismissEvent> for TestModal {}
 9167
 9168    impl Focusable for TestModal {
 9169        fn focus_handle(&self, _cx: &App) -> FocusHandle {
 9170            self.0.clone()
 9171        }
 9172    }
 9173
 9174    impl ModalView for TestModal {}
 9175
 9176    impl Render for TestModal {
 9177        fn render(
 9178            &mut self,
 9179            _window: &mut Window,
 9180            _cx: &mut Context<TestModal>,
 9181        ) -> impl IntoElement {
 9182            div().track_focus(&self.0)
 9183        }
 9184    }
 9185
 9186    #[gpui::test]
 9187    async fn test_panels(cx: &mut gpui::TestAppContext) {
 9188        init_test(cx);
 9189        let fs = FakeFs::new(cx.executor());
 9190
 9191        let project = Project::test(fs, [], cx).await;
 9192        let (workspace, cx) =
 9193            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9194
 9195        let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
 9196            let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, cx));
 9197            workspace.add_panel(panel_1.clone(), window, cx);
 9198            workspace.toggle_dock(DockPosition::Left, window, cx);
 9199            let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
 9200            workspace.add_panel(panel_2.clone(), window, cx);
 9201            workspace.toggle_dock(DockPosition::Right, window, cx);
 9202
 9203            let left_dock = workspace.left_dock();
 9204            assert_eq!(
 9205                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9206                panel_1.panel_id()
 9207            );
 9208            assert_eq!(
 9209                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9210                panel_1.size(window, cx)
 9211            );
 9212
 9213            left_dock.update(cx, |left_dock, cx| {
 9214                left_dock.resize_active_panel(Some(px(1337.)), window, cx)
 9215            });
 9216            assert_eq!(
 9217                workspace
 9218                    .right_dock()
 9219                    .read(cx)
 9220                    .visible_panel()
 9221                    .unwrap()
 9222                    .panel_id(),
 9223                panel_2.panel_id(),
 9224            );
 9225
 9226            (panel_1, panel_2)
 9227        });
 9228
 9229        // Move panel_1 to the right
 9230        panel_1.update_in(cx, |panel_1, window, cx| {
 9231            panel_1.set_position(DockPosition::Right, window, cx)
 9232        });
 9233
 9234        workspace.update_in(cx, |workspace, window, cx| {
 9235            // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
 9236            // Since it was the only panel on the left, the left dock should now be closed.
 9237            assert!(!workspace.left_dock().read(cx).is_open());
 9238            assert!(workspace.left_dock().read(cx).visible_panel().is_none());
 9239            let right_dock = workspace.right_dock();
 9240            assert_eq!(
 9241                right_dock.read(cx).visible_panel().unwrap().panel_id(),
 9242                panel_1.panel_id()
 9243            );
 9244            assert_eq!(
 9245                right_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9246                px(1337.)
 9247            );
 9248
 9249            // Now we move panel_2 to the left
 9250            panel_2.set_position(DockPosition::Left, window, cx);
 9251        });
 9252
 9253        workspace.update(cx, |workspace, cx| {
 9254            // Since panel_2 was not visible on the right, we don't open the left dock.
 9255            assert!(!workspace.left_dock().read(cx).is_open());
 9256            // And the right dock is unaffected in its displaying of panel_1
 9257            assert!(workspace.right_dock().read(cx).is_open());
 9258            assert_eq!(
 9259                workspace
 9260                    .right_dock()
 9261                    .read(cx)
 9262                    .visible_panel()
 9263                    .unwrap()
 9264                    .panel_id(),
 9265                panel_1.panel_id(),
 9266            );
 9267        });
 9268
 9269        // Move panel_1 back to the left
 9270        panel_1.update_in(cx, |panel_1, window, cx| {
 9271            panel_1.set_position(DockPosition::Left, window, cx)
 9272        });
 9273
 9274        workspace.update_in(cx, |workspace, window, cx| {
 9275            // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
 9276            let left_dock = workspace.left_dock();
 9277            assert!(left_dock.read(cx).is_open());
 9278            assert_eq!(
 9279                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9280                panel_1.panel_id()
 9281            );
 9282            assert_eq!(
 9283                left_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9284                px(1337.)
 9285            );
 9286            // And the right dock should be closed as it no longer has any panels.
 9287            assert!(!workspace.right_dock().read(cx).is_open());
 9288
 9289            // Now we move panel_1 to the bottom
 9290            panel_1.set_position(DockPosition::Bottom, window, cx);
 9291        });
 9292
 9293        workspace.update_in(cx, |workspace, window, cx| {
 9294            // Since panel_1 was visible on the left, we close the left dock.
 9295            assert!(!workspace.left_dock().read(cx).is_open());
 9296            // The bottom dock is sized based on the panel's default size,
 9297            // since the panel orientation changed from vertical to horizontal.
 9298            let bottom_dock = workspace.bottom_dock();
 9299            assert_eq!(
 9300                bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
 9301                panel_1.size(window, cx),
 9302            );
 9303            // Close bottom dock and move panel_1 back to the left.
 9304            bottom_dock.update(cx, |bottom_dock, cx| {
 9305                bottom_dock.set_open(false, window, cx)
 9306            });
 9307            panel_1.set_position(DockPosition::Left, window, cx);
 9308        });
 9309
 9310        // Emit activated event on panel 1
 9311        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
 9312
 9313        // Now the left dock is open and panel_1 is active and focused.
 9314        workspace.update_in(cx, |workspace, window, cx| {
 9315            let left_dock = workspace.left_dock();
 9316            assert!(left_dock.read(cx).is_open());
 9317            assert_eq!(
 9318                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9319                panel_1.panel_id(),
 9320            );
 9321            assert!(panel_1.focus_handle(cx).is_focused(window));
 9322        });
 9323
 9324        // Emit closed event on panel 2, which is not active
 9325        panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
 9326
 9327        // Wo don't close the left dock, because panel_2 wasn't the active panel
 9328        workspace.update(cx, |workspace, cx| {
 9329            let left_dock = workspace.left_dock();
 9330            assert!(left_dock.read(cx).is_open());
 9331            assert_eq!(
 9332                left_dock.read(cx).visible_panel().unwrap().panel_id(),
 9333                panel_1.panel_id(),
 9334            );
 9335        });
 9336
 9337        // Emitting a ZoomIn event shows the panel as zoomed.
 9338        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
 9339        workspace.read_with(cx, |workspace, _| {
 9340            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9341            assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
 9342        });
 9343
 9344        // Move panel to another dock while it is zoomed
 9345        panel_1.update_in(cx, |panel, window, cx| {
 9346            panel.set_position(DockPosition::Right, window, cx)
 9347        });
 9348        workspace.read_with(cx, |workspace, _| {
 9349            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9350
 9351            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
 9352        });
 9353
 9354        // This is a helper for getting a:
 9355        // - valid focus on an element,
 9356        // - that isn't a part of the panes and panels system of the Workspace,
 9357        // - and doesn't trigger the 'on_focus_lost' API.
 9358        let focus_other_view = {
 9359            let workspace = workspace.clone();
 9360            move |cx: &mut VisualTestContext| {
 9361                workspace.update_in(cx, |workspace, window, cx| {
 9362                    if workspace.active_modal::<TestModal>(cx).is_some() {
 9363                        workspace.toggle_modal(window, cx, TestModal::new);
 9364                        workspace.toggle_modal(window, cx, TestModal::new);
 9365                    } else {
 9366                        workspace.toggle_modal(window, cx, TestModal::new);
 9367                    }
 9368                })
 9369            }
 9370        };
 9371
 9372        // If focus is transferred to another view that's not a panel or another pane, we still show
 9373        // the panel as zoomed.
 9374        focus_other_view(cx);
 9375        workspace.read_with(cx, |workspace, _| {
 9376            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9377            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
 9378        });
 9379
 9380        // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
 9381        workspace.update_in(cx, |_workspace, window, cx| {
 9382            cx.focus_self(window);
 9383        });
 9384        workspace.read_with(cx, |workspace, _| {
 9385            assert_eq!(workspace.zoomed, None);
 9386            assert_eq!(workspace.zoomed_position, None);
 9387        });
 9388
 9389        // If focus is transferred again to another view that's not a panel or a pane, we won't
 9390        // show the panel as zoomed because it wasn't zoomed before.
 9391        focus_other_view(cx);
 9392        workspace.read_with(cx, |workspace, _| {
 9393            assert_eq!(workspace.zoomed, None);
 9394            assert_eq!(workspace.zoomed_position, None);
 9395        });
 9396
 9397        // When the panel is activated, it is zoomed again.
 9398        cx.dispatch_action(ToggleRightDock);
 9399        workspace.read_with(cx, |workspace, _| {
 9400            assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
 9401            assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
 9402        });
 9403
 9404        // Emitting a ZoomOut event unzooms the panel.
 9405        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
 9406        workspace.read_with(cx, |workspace, _| {
 9407            assert_eq!(workspace.zoomed, None);
 9408            assert_eq!(workspace.zoomed_position, None);
 9409        });
 9410
 9411        // Emit closed event on panel 1, which is active
 9412        panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
 9413
 9414        // Now the left dock is closed, because panel_1 was the active panel
 9415        workspace.update(cx, |workspace, cx| {
 9416            let right_dock = workspace.right_dock();
 9417            assert!(!right_dock.read(cx).is_open());
 9418        });
 9419    }
 9420
 9421    #[gpui::test]
 9422    async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
 9423        init_test(cx);
 9424
 9425        let fs = FakeFs::new(cx.background_executor.clone());
 9426        let project = Project::test(fs, [], cx).await;
 9427        let (workspace, cx) =
 9428            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9429        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9430
 9431        let dirty_regular_buffer = cx.new(|cx| {
 9432            TestItem::new(cx)
 9433                .with_dirty(true)
 9434                .with_label("1.txt")
 9435                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9436        });
 9437        let dirty_regular_buffer_2 = cx.new(|cx| {
 9438            TestItem::new(cx)
 9439                .with_dirty(true)
 9440                .with_label("2.txt")
 9441                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 9442        });
 9443        let dirty_multi_buffer_with_both = cx.new(|cx| {
 9444            TestItem::new(cx)
 9445                .with_dirty(true)
 9446                .with_singleton(false)
 9447                .with_label("Fake Project Search")
 9448                .with_project_items(&[
 9449                    dirty_regular_buffer.read(cx).project_items[0].clone(),
 9450                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
 9451                ])
 9452        });
 9453        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
 9454        workspace.update_in(cx, |workspace, window, cx| {
 9455            workspace.add_item(
 9456                pane.clone(),
 9457                Box::new(dirty_regular_buffer.clone()),
 9458                None,
 9459                false,
 9460                false,
 9461                window,
 9462                cx,
 9463            );
 9464            workspace.add_item(
 9465                pane.clone(),
 9466                Box::new(dirty_regular_buffer_2.clone()),
 9467                None,
 9468                false,
 9469                false,
 9470                window,
 9471                cx,
 9472            );
 9473            workspace.add_item(
 9474                pane.clone(),
 9475                Box::new(dirty_multi_buffer_with_both.clone()),
 9476                None,
 9477                false,
 9478                false,
 9479                window,
 9480                cx,
 9481            );
 9482        });
 9483
 9484        pane.update_in(cx, |pane, window, cx| {
 9485            pane.activate_item(2, true, true, window, cx);
 9486            assert_eq!(
 9487                pane.active_item().unwrap().item_id(),
 9488                multi_buffer_with_both_files_id,
 9489                "Should select the multi buffer in the pane"
 9490            );
 9491        });
 9492        let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
 9493            pane.close_other_items(
 9494                &CloseOtherItems {
 9495                    save_intent: Some(SaveIntent::Save),
 9496                    close_pinned: true,
 9497                },
 9498                None,
 9499                window,
 9500                cx,
 9501            )
 9502        });
 9503        cx.background_executor.run_until_parked();
 9504        assert!(!cx.has_pending_prompt());
 9505        close_all_but_multi_buffer_task
 9506            .await
 9507            .expect("Closing all buffers but the multi buffer failed");
 9508        pane.update(cx, |pane, cx| {
 9509            assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
 9510            assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
 9511            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
 9512            assert_eq!(pane.items_len(), 1);
 9513            assert_eq!(
 9514                pane.active_item().unwrap().item_id(),
 9515                multi_buffer_with_both_files_id,
 9516                "Should have only the multi buffer left in the pane"
 9517            );
 9518            assert!(
 9519                dirty_multi_buffer_with_both.read(cx).is_dirty,
 9520                "The multi buffer containing the unsaved buffer should still be dirty"
 9521            );
 9522        });
 9523
 9524        dirty_regular_buffer.update(cx, |buffer, cx| {
 9525            buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
 9526        });
 9527
 9528        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
 9529            pane.close_active_item(
 9530                &CloseActiveItem {
 9531                    save_intent: Some(SaveIntent::Close),
 9532                    close_pinned: false,
 9533                },
 9534                window,
 9535                cx,
 9536            )
 9537        });
 9538        cx.background_executor.run_until_parked();
 9539        assert!(
 9540            cx.has_pending_prompt(),
 9541            "Dirty multi buffer should prompt a save dialog"
 9542        );
 9543        cx.simulate_prompt_answer("Save");
 9544        cx.background_executor.run_until_parked();
 9545        close_multi_buffer_task
 9546            .await
 9547            .expect("Closing the multi buffer failed");
 9548        pane.update(cx, |pane, cx| {
 9549            assert_eq!(
 9550                dirty_multi_buffer_with_both.read(cx).save_count,
 9551                1,
 9552                "Multi buffer item should get be saved"
 9553            );
 9554            // Test impl does not save inner items, so we do not assert them
 9555            assert_eq!(
 9556                pane.items_len(),
 9557                0,
 9558                "No more items should be left in the pane"
 9559            );
 9560            assert!(pane.active_item().is_none());
 9561        });
 9562    }
 9563
 9564    #[gpui::test]
 9565    async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
 9566        cx: &mut TestAppContext,
 9567    ) {
 9568        init_test(cx);
 9569
 9570        let fs = FakeFs::new(cx.background_executor.clone());
 9571        let project = Project::test(fs, [], cx).await;
 9572        let (workspace, cx) =
 9573            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9574        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9575
 9576        let dirty_regular_buffer = cx.new(|cx| {
 9577            TestItem::new(cx)
 9578                .with_dirty(true)
 9579                .with_label("1.txt")
 9580                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9581        });
 9582        let dirty_regular_buffer_2 = cx.new(|cx| {
 9583            TestItem::new(cx)
 9584                .with_dirty(true)
 9585                .with_label("2.txt")
 9586                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
 9587        });
 9588        let clear_regular_buffer = cx.new(|cx| {
 9589            TestItem::new(cx)
 9590                .with_label("3.txt")
 9591                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
 9592        });
 9593
 9594        let dirty_multi_buffer_with_both = cx.new(|cx| {
 9595            TestItem::new(cx)
 9596                .with_dirty(true)
 9597                .with_singleton(false)
 9598                .with_label("Fake Project Search")
 9599                .with_project_items(&[
 9600                    dirty_regular_buffer.read(cx).project_items[0].clone(),
 9601                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
 9602                    clear_regular_buffer.read(cx).project_items[0].clone(),
 9603                ])
 9604        });
 9605        let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
 9606        workspace.update_in(cx, |workspace, window, cx| {
 9607            workspace.add_item(
 9608                pane.clone(),
 9609                Box::new(dirty_regular_buffer.clone()),
 9610                None,
 9611                false,
 9612                false,
 9613                window,
 9614                cx,
 9615            );
 9616            workspace.add_item(
 9617                pane.clone(),
 9618                Box::new(dirty_multi_buffer_with_both.clone()),
 9619                None,
 9620                false,
 9621                false,
 9622                window,
 9623                cx,
 9624            );
 9625        });
 9626
 9627        pane.update_in(cx, |pane, window, cx| {
 9628            pane.activate_item(1, true, true, window, cx);
 9629            assert_eq!(
 9630                pane.active_item().unwrap().item_id(),
 9631                multi_buffer_with_both_files_id,
 9632                "Should select the multi buffer in the pane"
 9633            );
 9634        });
 9635        let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
 9636            pane.close_active_item(
 9637                &CloseActiveItem {
 9638                    save_intent: None,
 9639                    close_pinned: false,
 9640                },
 9641                window,
 9642                cx,
 9643            )
 9644        });
 9645        cx.background_executor.run_until_parked();
 9646        assert!(
 9647            cx.has_pending_prompt(),
 9648            "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
 9649        );
 9650    }
 9651
 9652    /// Tests that when `close_on_file_delete` is enabled, files are automatically
 9653    /// closed when they are deleted from disk.
 9654    #[gpui::test]
 9655    async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
 9656        init_test(cx);
 9657
 9658        // Enable the close_on_disk_deletion setting
 9659        cx.update_global(|store: &mut SettingsStore, cx| {
 9660            store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 9661                settings.close_on_file_delete = Some(true);
 9662            });
 9663        });
 9664
 9665        let fs = FakeFs::new(cx.background_executor.clone());
 9666        let project = Project::test(fs, [], cx).await;
 9667        let (workspace, cx) =
 9668            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9669        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9670
 9671        // Create a test item that simulates a file
 9672        let item = cx.new(|cx| {
 9673            TestItem::new(cx)
 9674                .with_label("test.txt")
 9675                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
 9676        });
 9677
 9678        // Add item to workspace
 9679        workspace.update_in(cx, |workspace, window, cx| {
 9680            workspace.add_item(
 9681                pane.clone(),
 9682                Box::new(item.clone()),
 9683                None,
 9684                false,
 9685                false,
 9686                window,
 9687                cx,
 9688            );
 9689        });
 9690
 9691        // Verify the item is in the pane
 9692        pane.read_with(cx, |pane, _| {
 9693            assert_eq!(pane.items().count(), 1);
 9694        });
 9695
 9696        // Simulate file deletion by setting the item's deleted state
 9697        item.update(cx, |item, _| {
 9698            item.set_has_deleted_file(true);
 9699        });
 9700
 9701        // Emit UpdateTab event to trigger the close behavior
 9702        cx.run_until_parked();
 9703        item.update(cx, |_, cx| {
 9704            cx.emit(ItemEvent::UpdateTab);
 9705        });
 9706
 9707        // Allow the close operation to complete
 9708        cx.run_until_parked();
 9709
 9710        // Verify the item was automatically closed
 9711        pane.read_with(cx, |pane, _| {
 9712            assert_eq!(
 9713                pane.items().count(),
 9714                0,
 9715                "Item should be automatically closed when file is deleted"
 9716            );
 9717        });
 9718    }
 9719
 9720    /// Tests that when `close_on_file_delete` is disabled (default), files remain
 9721    /// open with a strikethrough when they are deleted from disk.
 9722    #[gpui::test]
 9723    async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
 9724        init_test(cx);
 9725
 9726        // Ensure close_on_disk_deletion is disabled (default)
 9727        cx.update_global(|store: &mut SettingsStore, cx| {
 9728            store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 9729                settings.close_on_file_delete = Some(false);
 9730            });
 9731        });
 9732
 9733        let fs = FakeFs::new(cx.background_executor.clone());
 9734        let project = Project::test(fs, [], cx).await;
 9735        let (workspace, cx) =
 9736            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9737        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9738
 9739        // Create a test item that simulates a file
 9740        let item = cx.new(|cx| {
 9741            TestItem::new(cx)
 9742                .with_label("test.txt")
 9743                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
 9744        });
 9745
 9746        // Add item to workspace
 9747        workspace.update_in(cx, |workspace, window, cx| {
 9748            workspace.add_item(
 9749                pane.clone(),
 9750                Box::new(item.clone()),
 9751                None,
 9752                false,
 9753                false,
 9754                window,
 9755                cx,
 9756            );
 9757        });
 9758
 9759        // Verify the item is in the pane
 9760        pane.read_with(cx, |pane, _| {
 9761            assert_eq!(pane.items().count(), 1);
 9762        });
 9763
 9764        // Simulate file deletion
 9765        item.update(cx, |item, _| {
 9766            item.set_has_deleted_file(true);
 9767        });
 9768
 9769        // Emit UpdateTab event
 9770        cx.run_until_parked();
 9771        item.update(cx, |_, cx| {
 9772            cx.emit(ItemEvent::UpdateTab);
 9773        });
 9774
 9775        // Allow any potential close operation to complete
 9776        cx.run_until_parked();
 9777
 9778        // Verify the item remains open (with strikethrough)
 9779        pane.read_with(cx, |pane, _| {
 9780            assert_eq!(
 9781                pane.items().count(),
 9782                1,
 9783                "Item should remain open when close_on_disk_deletion is disabled"
 9784            );
 9785        });
 9786
 9787        // Verify the item shows as deleted
 9788        item.read_with(cx, |item, _| {
 9789            assert!(
 9790                item.has_deleted_file,
 9791                "Item should be marked as having deleted file"
 9792            );
 9793        });
 9794    }
 9795
 9796    /// Tests that dirty files are not automatically closed when deleted from disk,
 9797    /// even when `close_on_file_delete` is enabled. This ensures users don't lose
 9798    /// unsaved changes without being prompted.
 9799    #[gpui::test]
 9800    async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
 9801        init_test(cx);
 9802
 9803        // Enable the close_on_file_delete setting
 9804        cx.update_global(|store: &mut SettingsStore, cx| {
 9805            store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 9806                settings.close_on_file_delete = Some(true);
 9807            });
 9808        });
 9809
 9810        let fs = FakeFs::new(cx.background_executor.clone());
 9811        let project = Project::test(fs, [], cx).await;
 9812        let (workspace, cx) =
 9813            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9814        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9815
 9816        // Create a dirty test item
 9817        let item = cx.new(|cx| {
 9818            TestItem::new(cx)
 9819                .with_dirty(true)
 9820                .with_label("test.txt")
 9821                .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
 9822        });
 9823
 9824        // Add item to workspace
 9825        workspace.update_in(cx, |workspace, window, cx| {
 9826            workspace.add_item(
 9827                pane.clone(),
 9828                Box::new(item.clone()),
 9829                None,
 9830                false,
 9831                false,
 9832                window,
 9833                cx,
 9834            );
 9835        });
 9836
 9837        // Simulate file deletion
 9838        item.update(cx, |item, _| {
 9839            item.set_has_deleted_file(true);
 9840        });
 9841
 9842        // Emit UpdateTab event to trigger the close behavior
 9843        cx.run_until_parked();
 9844        item.update(cx, |_, cx| {
 9845            cx.emit(ItemEvent::UpdateTab);
 9846        });
 9847
 9848        // Allow any potential close operation to complete
 9849        cx.run_until_parked();
 9850
 9851        // Verify the item remains open (dirty files are not auto-closed)
 9852        pane.read_with(cx, |pane, _| {
 9853            assert_eq!(
 9854                pane.items().count(),
 9855                1,
 9856                "Dirty items should not be automatically closed even when file is deleted"
 9857            );
 9858        });
 9859
 9860        // Verify the item is marked as deleted and still dirty
 9861        item.read_with(cx, |item, _| {
 9862            assert!(
 9863                item.has_deleted_file,
 9864                "Item should be marked as having deleted file"
 9865            );
 9866            assert!(item.is_dirty, "Item should still be dirty");
 9867        });
 9868    }
 9869
 9870    /// Tests that navigation history is cleaned up when files are auto-closed
 9871    /// due to deletion from disk.
 9872    #[gpui::test]
 9873    async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
 9874        init_test(cx);
 9875
 9876        // Enable the close_on_file_delete setting
 9877        cx.update_global(|store: &mut SettingsStore, cx| {
 9878            store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
 9879                settings.close_on_file_delete = Some(true);
 9880            });
 9881        });
 9882
 9883        let fs = FakeFs::new(cx.background_executor.clone());
 9884        let project = Project::test(fs, [], cx).await;
 9885        let (workspace, cx) =
 9886            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9887        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9888
 9889        // Create test items
 9890        let item1 = cx.new(|cx| {
 9891            TestItem::new(cx)
 9892                .with_label("test1.txt")
 9893                .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
 9894        });
 9895        let item1_id = item1.item_id();
 9896
 9897        let item2 = cx.new(|cx| {
 9898            TestItem::new(cx)
 9899                .with_label("test2.txt")
 9900                .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
 9901        });
 9902
 9903        // Add items to workspace
 9904        workspace.update_in(cx, |workspace, window, cx| {
 9905            workspace.add_item(
 9906                pane.clone(),
 9907                Box::new(item1.clone()),
 9908                None,
 9909                false,
 9910                false,
 9911                window,
 9912                cx,
 9913            );
 9914            workspace.add_item(
 9915                pane.clone(),
 9916                Box::new(item2.clone()),
 9917                None,
 9918                false,
 9919                false,
 9920                window,
 9921                cx,
 9922            );
 9923        });
 9924
 9925        // Activate item1 to ensure it gets navigation entries
 9926        pane.update_in(cx, |pane, window, cx| {
 9927            pane.activate_item(0, true, true, window, cx);
 9928        });
 9929
 9930        // Switch to item2 and back to create navigation history
 9931        pane.update_in(cx, |pane, window, cx| {
 9932            pane.activate_item(1, true, true, window, cx);
 9933        });
 9934        cx.run_until_parked();
 9935
 9936        pane.update_in(cx, |pane, window, cx| {
 9937            pane.activate_item(0, true, true, window, cx);
 9938        });
 9939        cx.run_until_parked();
 9940
 9941        // Simulate file deletion for item1
 9942        item1.update(cx, |item, _| {
 9943            item.set_has_deleted_file(true);
 9944        });
 9945
 9946        // Emit UpdateTab event to trigger the close behavior
 9947        item1.update(cx, |_, cx| {
 9948            cx.emit(ItemEvent::UpdateTab);
 9949        });
 9950        cx.run_until_parked();
 9951
 9952        // Verify item1 was closed
 9953        pane.read_with(cx, |pane, _| {
 9954            assert_eq!(
 9955                pane.items().count(),
 9956                1,
 9957                "Should have 1 item remaining after auto-close"
 9958            );
 9959        });
 9960
 9961        // Check navigation history after close
 9962        let has_item = pane.read_with(cx, |pane, cx| {
 9963            let mut has_item = false;
 9964            pane.nav_history().for_each_entry(cx, |entry, _| {
 9965                if entry.item.id() == item1_id {
 9966                    has_item = true;
 9967                }
 9968            });
 9969            has_item
 9970        });
 9971
 9972        assert!(
 9973            !has_item,
 9974            "Navigation history should not contain closed item entries"
 9975        );
 9976    }
 9977
 9978    #[gpui::test]
 9979    async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
 9980        cx: &mut TestAppContext,
 9981    ) {
 9982        init_test(cx);
 9983
 9984        let fs = FakeFs::new(cx.background_executor.clone());
 9985        let project = Project::test(fs, [], cx).await;
 9986        let (workspace, cx) =
 9987            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
 9988        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
 9989
 9990        let dirty_regular_buffer = cx.new(|cx| {
 9991            TestItem::new(cx)
 9992                .with_dirty(true)
 9993                .with_label("1.txt")
 9994                .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
 9995        });
 9996        let dirty_regular_buffer_2 = cx.new(|cx| {
 9997            TestItem::new(cx)
 9998                .with_dirty(true)
 9999                .with_label("2.txt")
10000                .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10001        });
10002        let clear_regular_buffer = cx.new(|cx| {
10003            TestItem::new(cx)
10004                .with_label("3.txt")
10005                .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
10006        });
10007
10008        let dirty_multi_buffer = cx.new(|cx| {
10009            TestItem::new(cx)
10010                .with_dirty(true)
10011                .with_singleton(false)
10012                .with_label("Fake Project Search")
10013                .with_project_items(&[
10014                    dirty_regular_buffer.read(cx).project_items[0].clone(),
10015                    dirty_regular_buffer_2.read(cx).project_items[0].clone(),
10016                    clear_regular_buffer.read(cx).project_items[0].clone(),
10017                ])
10018        });
10019        workspace.update_in(cx, |workspace, window, cx| {
10020            workspace.add_item(
10021                pane.clone(),
10022                Box::new(dirty_regular_buffer.clone()),
10023                None,
10024                false,
10025                false,
10026                window,
10027                cx,
10028            );
10029            workspace.add_item(
10030                pane.clone(),
10031                Box::new(dirty_regular_buffer_2.clone()),
10032                None,
10033                false,
10034                false,
10035                window,
10036                cx,
10037            );
10038            workspace.add_item(
10039                pane.clone(),
10040                Box::new(dirty_multi_buffer.clone()),
10041                None,
10042                false,
10043                false,
10044                window,
10045                cx,
10046            );
10047        });
10048
10049        pane.update_in(cx, |pane, window, cx| {
10050            pane.activate_item(2, true, true, window, cx);
10051            assert_eq!(
10052                pane.active_item().unwrap().item_id(),
10053                dirty_multi_buffer.item_id(),
10054                "Should select the multi buffer in the pane"
10055            );
10056        });
10057        let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
10058            pane.close_active_item(
10059                &CloseActiveItem {
10060                    save_intent: None,
10061                    close_pinned: false,
10062                },
10063                window,
10064                cx,
10065            )
10066        });
10067        cx.background_executor.run_until_parked();
10068        assert!(
10069            !cx.has_pending_prompt(),
10070            "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
10071        );
10072        close_multi_buffer_task
10073            .await
10074            .expect("Closing multi buffer failed");
10075        pane.update(cx, |pane, cx| {
10076            assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
10077            assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
10078            assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
10079            assert_eq!(
10080                pane.items()
10081                    .map(|item| item.item_id())
10082                    .sorted()
10083                    .collect::<Vec<_>>(),
10084                vec![
10085                    dirty_regular_buffer.item_id(),
10086                    dirty_regular_buffer_2.item_id(),
10087                ],
10088                "Should have no multi buffer left in the pane"
10089            );
10090            assert!(dirty_regular_buffer.read(cx).is_dirty);
10091            assert!(dirty_regular_buffer_2.read(cx).is_dirty);
10092        });
10093    }
10094
10095    #[gpui::test]
10096    async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
10097        init_test(cx);
10098        let fs = FakeFs::new(cx.executor());
10099        let project = Project::test(fs, [], cx).await;
10100        let (workspace, cx) =
10101            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10102
10103        // Add a new panel to the right dock, opening the dock and setting the
10104        // focus to the new panel.
10105        let panel = workspace.update_in(cx, |workspace, window, cx| {
10106            let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, cx));
10107            workspace.add_panel(panel.clone(), window, cx);
10108
10109            workspace
10110                .right_dock()
10111                .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
10112
10113            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10114
10115            panel
10116        });
10117
10118        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10119        // panel to the next valid position which, in this case, is the left
10120        // dock.
10121        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10122        workspace.update(cx, |workspace, cx| {
10123            assert!(workspace.left_dock().read(cx).is_open());
10124            assert_eq!(panel.read(cx).position, DockPosition::Left);
10125        });
10126
10127        // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
10128        // panel to the next valid position which, in this case, is the bottom
10129        // dock.
10130        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10131        workspace.update(cx, |workspace, cx| {
10132            assert!(workspace.bottom_dock().read(cx).is_open());
10133            assert_eq!(panel.read(cx).position, DockPosition::Bottom);
10134        });
10135
10136        // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
10137        // around moving the panel to its initial position, the right dock.
10138        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10139        workspace.update(cx, |workspace, cx| {
10140            assert!(workspace.right_dock().read(cx).is_open());
10141            assert_eq!(panel.read(cx).position, DockPosition::Right);
10142        });
10143
10144        // Remove focus from the panel, ensuring that, if the panel is not
10145        // focused, the `MoveFocusedPanelToNextPosition` action does not update
10146        // the panel's position, so the panel is still in the right dock.
10147        workspace.update_in(cx, |workspace, window, cx| {
10148            workspace.toggle_panel_focus::<TestPanel>(window, cx);
10149        });
10150
10151        cx.dispatch_action(MoveFocusedPanelToNextPosition);
10152        workspace.update(cx, |workspace, cx| {
10153            assert!(workspace.right_dock().read(cx).is_open());
10154            assert_eq!(panel.read(cx).position, DockPosition::Right);
10155        });
10156    }
10157
10158    #[gpui::test]
10159    async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
10160        init_test(cx);
10161
10162        let fs = FakeFs::new(cx.executor());
10163        let project = Project::test(fs, [], cx).await;
10164        let (workspace, cx) =
10165            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10166
10167        let item_1 = cx.new(|cx| {
10168            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10169        });
10170        workspace.update_in(cx, |workspace, window, cx| {
10171            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10172            workspace.move_item_to_pane_in_direction(
10173                &MoveItemToPaneInDirection {
10174                    direction: SplitDirection::Right,
10175                    focus: true,
10176                    clone: false,
10177                },
10178                window,
10179                cx,
10180            );
10181            workspace.move_item_to_pane_at_index(
10182                &MoveItemToPane {
10183                    destination: 3,
10184                    focus: true,
10185                    clone: false,
10186                },
10187                window,
10188                cx,
10189            );
10190
10191            assert_eq!(workspace.panes.len(), 1, "No new panes were created");
10192            assert_eq!(
10193                pane_items_paths(&workspace.active_pane, cx),
10194                vec!["first.txt".to_string()],
10195                "Single item was not moved anywhere"
10196            );
10197        });
10198
10199        let item_2 = cx.new(|cx| {
10200            TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
10201        });
10202        workspace.update_in(cx, |workspace, window, cx| {
10203            workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
10204            assert_eq!(
10205                pane_items_paths(&workspace.panes[0], cx),
10206                vec!["first.txt".to_string(), "second.txt".to_string()],
10207            );
10208            workspace.move_item_to_pane_in_direction(
10209                &MoveItemToPaneInDirection {
10210                    direction: SplitDirection::Right,
10211                    focus: true,
10212                    clone: false,
10213                },
10214                window,
10215                cx,
10216            );
10217
10218            assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
10219            assert_eq!(
10220                pane_items_paths(&workspace.panes[0], cx),
10221                vec!["first.txt".to_string()],
10222                "After moving, one item should be left in the original pane"
10223            );
10224            assert_eq!(
10225                pane_items_paths(&workspace.panes[1], cx),
10226                vec!["second.txt".to_string()],
10227                "New item should have been moved to the new pane"
10228            );
10229        });
10230
10231        let item_3 = cx.new(|cx| {
10232            TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
10233        });
10234        workspace.update_in(cx, |workspace, window, cx| {
10235            let original_pane = workspace.panes[0].clone();
10236            workspace.set_active_pane(&original_pane, window, cx);
10237            workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
10238            assert_eq!(workspace.panes.len(), 2, "No new panes were created");
10239            assert_eq!(
10240                pane_items_paths(&workspace.active_pane, cx),
10241                vec!["first.txt".to_string(), "third.txt".to_string()],
10242                "New pane should be ready to move one item out"
10243            );
10244
10245            workspace.move_item_to_pane_at_index(
10246                &MoveItemToPane {
10247                    destination: 3,
10248                    focus: true,
10249                    clone: false,
10250                },
10251                window,
10252                cx,
10253            );
10254            assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
10255            assert_eq!(
10256                pane_items_paths(&workspace.active_pane, cx),
10257                vec!["first.txt".to_string()],
10258                "After moving, one item should be left in the original pane"
10259            );
10260            assert_eq!(
10261                pane_items_paths(&workspace.panes[1], cx),
10262                vec!["second.txt".to_string()],
10263                "Previously created pane should be unchanged"
10264            );
10265            assert_eq!(
10266                pane_items_paths(&workspace.panes[2], cx),
10267                vec!["third.txt".to_string()],
10268                "New item should have been moved to the new pane"
10269            );
10270        });
10271    }
10272
10273    #[gpui::test]
10274    async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
10275        init_test(cx);
10276
10277        let fs = FakeFs::new(cx.executor());
10278        let project = Project::test(fs, [], cx).await;
10279        let (workspace, cx) =
10280            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10281
10282        let item_1 = cx.new(|cx| {
10283            TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
10284        });
10285        workspace.update_in(cx, |workspace, window, cx| {
10286            workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
10287            workspace.move_item_to_pane_in_direction(
10288                &MoveItemToPaneInDirection {
10289                    direction: SplitDirection::Right,
10290                    focus: true,
10291                    clone: true,
10292                },
10293                window,
10294                cx,
10295            );
10296            workspace.move_item_to_pane_at_index(
10297                &MoveItemToPane {
10298                    destination: 3,
10299                    focus: true,
10300                    clone: true,
10301                },
10302                window,
10303                cx,
10304            );
10305
10306            assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
10307            for pane in workspace.panes() {
10308                assert_eq!(
10309                    pane_items_paths(pane, cx),
10310                    vec!["first.txt".to_string()],
10311                    "Single item exists in all panes"
10312                );
10313            }
10314        });
10315
10316        // verify that the active pane has been updated after waiting for the
10317        // pane focus event to fire and resolve
10318        workspace.read_with(cx, |workspace, _app| {
10319            assert_eq!(
10320                workspace.active_pane(),
10321                &workspace.panes[2],
10322                "The third pane should be the active one: {:?}",
10323                workspace.panes
10324            );
10325        })
10326    }
10327
10328    mod register_project_item_tests {
10329
10330        use super::*;
10331
10332        // View
10333        struct TestPngItemView {
10334            focus_handle: FocusHandle,
10335        }
10336        // Model
10337        struct TestPngItem {}
10338
10339        impl project::ProjectItem for TestPngItem {
10340            fn try_open(
10341                _project: &Entity<Project>,
10342                path: &ProjectPath,
10343                cx: &mut App,
10344            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
10345                if path.path.extension().unwrap() == "png" {
10346                    Some(cx.spawn(async move |cx| cx.new(|_| TestPngItem {})))
10347                } else {
10348                    None
10349                }
10350            }
10351
10352            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
10353                None
10354            }
10355
10356            fn project_path(&self, _: &App) -> Option<ProjectPath> {
10357                None
10358            }
10359
10360            fn is_dirty(&self) -> bool {
10361                false
10362            }
10363        }
10364
10365        impl Item for TestPngItemView {
10366            type Event = ();
10367            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10368                "".into()
10369            }
10370        }
10371        impl EventEmitter<()> for TestPngItemView {}
10372        impl Focusable for TestPngItemView {
10373            fn focus_handle(&self, _cx: &App) -> FocusHandle {
10374                self.focus_handle.clone()
10375            }
10376        }
10377
10378        impl Render for TestPngItemView {
10379            fn render(
10380                &mut self,
10381                _window: &mut Window,
10382                _cx: &mut Context<Self>,
10383            ) -> impl IntoElement {
10384                Empty
10385            }
10386        }
10387
10388        impl ProjectItem for TestPngItemView {
10389            type Item = TestPngItem;
10390
10391            fn for_project_item(
10392                _project: Entity<Project>,
10393                _pane: Option<&Pane>,
10394                _item: Entity<Self::Item>,
10395                _: &mut Window,
10396                cx: &mut Context<Self>,
10397            ) -> Self
10398            where
10399                Self: Sized,
10400            {
10401                Self {
10402                    focus_handle: cx.focus_handle(),
10403                }
10404            }
10405        }
10406
10407        // View
10408        struct TestIpynbItemView {
10409            focus_handle: FocusHandle,
10410        }
10411        // Model
10412        struct TestIpynbItem {}
10413
10414        impl project::ProjectItem for TestIpynbItem {
10415            fn try_open(
10416                _project: &Entity<Project>,
10417                path: &ProjectPath,
10418                cx: &mut App,
10419            ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
10420                if path.path.extension().unwrap() == "ipynb" {
10421                    Some(cx.spawn(async move |cx| cx.new(|_| TestIpynbItem {})))
10422                } else {
10423                    None
10424                }
10425            }
10426
10427            fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
10428                None
10429            }
10430
10431            fn project_path(&self, _: &App) -> Option<ProjectPath> {
10432                None
10433            }
10434
10435            fn is_dirty(&self) -> bool {
10436                false
10437            }
10438        }
10439
10440        impl Item for TestIpynbItemView {
10441            type Event = ();
10442            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10443                "".into()
10444            }
10445        }
10446        impl EventEmitter<()> for TestIpynbItemView {}
10447        impl Focusable for TestIpynbItemView {
10448            fn focus_handle(&self, _cx: &App) -> FocusHandle {
10449                self.focus_handle.clone()
10450            }
10451        }
10452
10453        impl Render for TestIpynbItemView {
10454            fn render(
10455                &mut self,
10456                _window: &mut Window,
10457                _cx: &mut Context<Self>,
10458            ) -> impl IntoElement {
10459                Empty
10460            }
10461        }
10462
10463        impl ProjectItem for TestIpynbItemView {
10464            type Item = TestIpynbItem;
10465
10466            fn for_project_item(
10467                _project: Entity<Project>,
10468                _pane: Option<&Pane>,
10469                _item: Entity<Self::Item>,
10470                _: &mut Window,
10471                cx: &mut Context<Self>,
10472            ) -> Self
10473            where
10474                Self: Sized,
10475            {
10476                Self {
10477                    focus_handle: cx.focus_handle(),
10478                }
10479            }
10480        }
10481
10482        struct TestAlternatePngItemView {
10483            focus_handle: FocusHandle,
10484        }
10485
10486        impl Item for TestAlternatePngItemView {
10487            type Event = ();
10488            fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
10489                "".into()
10490            }
10491        }
10492
10493        impl EventEmitter<()> for TestAlternatePngItemView {}
10494        impl Focusable for TestAlternatePngItemView {
10495            fn focus_handle(&self, _cx: &App) -> FocusHandle {
10496                self.focus_handle.clone()
10497            }
10498        }
10499
10500        impl Render for TestAlternatePngItemView {
10501            fn render(
10502                &mut self,
10503                _window: &mut Window,
10504                _cx: &mut Context<Self>,
10505            ) -> impl IntoElement {
10506                Empty
10507            }
10508        }
10509
10510        impl ProjectItem for TestAlternatePngItemView {
10511            type Item = TestPngItem;
10512
10513            fn for_project_item(
10514                _project: Entity<Project>,
10515                _pane: Option<&Pane>,
10516                _item: Entity<Self::Item>,
10517                _: &mut Window,
10518                cx: &mut Context<Self>,
10519            ) -> Self
10520            where
10521                Self: Sized,
10522            {
10523                Self {
10524                    focus_handle: cx.focus_handle(),
10525                }
10526            }
10527        }
10528
10529        #[gpui::test]
10530        async fn test_register_project_item(cx: &mut TestAppContext) {
10531            init_test(cx);
10532
10533            cx.update(|cx| {
10534                register_project_item::<TestPngItemView>(cx);
10535                register_project_item::<TestIpynbItemView>(cx);
10536            });
10537
10538            let fs = FakeFs::new(cx.executor());
10539            fs.insert_tree(
10540                "/root1",
10541                json!({
10542                    "one.png": "BINARYDATAHERE",
10543                    "two.ipynb": "{ totally a notebook }",
10544                    "three.txt": "editing text, sure why not?"
10545                }),
10546            )
10547            .await;
10548
10549            let project = Project::test(fs, ["root1".as_ref()], cx).await;
10550            let (workspace, cx) =
10551                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10552
10553            let worktree_id = project.update(cx, |project, cx| {
10554                project.worktrees(cx).next().unwrap().read(cx).id()
10555            });
10556
10557            let handle = workspace
10558                .update_in(cx, |workspace, window, cx| {
10559                    let project_path = (worktree_id, "one.png");
10560                    workspace.open_path(project_path, None, true, window, cx)
10561                })
10562                .await
10563                .unwrap();
10564
10565            // Now we can check if the handle we got back errored or not
10566            assert_eq!(
10567                handle.to_any().entity_type(),
10568                TypeId::of::<TestPngItemView>()
10569            );
10570
10571            let handle = workspace
10572                .update_in(cx, |workspace, window, cx| {
10573                    let project_path = (worktree_id, "two.ipynb");
10574                    workspace.open_path(project_path, None, true, window, cx)
10575                })
10576                .await
10577                .unwrap();
10578
10579            assert_eq!(
10580                handle.to_any().entity_type(),
10581                TypeId::of::<TestIpynbItemView>()
10582            );
10583
10584            let handle = workspace
10585                .update_in(cx, |workspace, window, cx| {
10586                    let project_path = (worktree_id, "three.txt");
10587                    workspace.open_path(project_path, None, true, window, cx)
10588                })
10589                .await;
10590            assert!(handle.is_err());
10591        }
10592
10593        #[gpui::test]
10594        async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
10595            init_test(cx);
10596
10597            cx.update(|cx| {
10598                register_project_item::<TestPngItemView>(cx);
10599                register_project_item::<TestAlternatePngItemView>(cx);
10600            });
10601
10602            let fs = FakeFs::new(cx.executor());
10603            fs.insert_tree(
10604                "/root1",
10605                json!({
10606                    "one.png": "BINARYDATAHERE",
10607                    "two.ipynb": "{ totally a notebook }",
10608                    "three.txt": "editing text, sure why not?"
10609                }),
10610            )
10611            .await;
10612            let project = Project::test(fs, ["root1".as_ref()], cx).await;
10613            let (workspace, cx) =
10614                cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10615            let worktree_id = project.update(cx, |project, cx| {
10616                project.worktrees(cx).next().unwrap().read(cx).id()
10617            });
10618
10619            let handle = workspace
10620                .update_in(cx, |workspace, window, cx| {
10621                    let project_path = (worktree_id, "one.png");
10622                    workspace.open_path(project_path, None, true, window, cx)
10623                })
10624                .await
10625                .unwrap();
10626
10627            // This _must_ be the second item registered
10628            assert_eq!(
10629                handle.to_any().entity_type(),
10630                TypeId::of::<TestAlternatePngItemView>()
10631            );
10632
10633            let handle = workspace
10634                .update_in(cx, |workspace, window, cx| {
10635                    let project_path = (worktree_id, "three.txt");
10636                    workspace.open_path(project_path, None, true, window, cx)
10637                })
10638                .await;
10639            assert!(handle.is_err());
10640        }
10641    }
10642
10643    fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
10644        pane.read(cx)
10645            .items()
10646            .flat_map(|item| {
10647                item.project_paths(cx)
10648                    .into_iter()
10649                    .map(|path| path.path.to_string_lossy().to_string())
10650            })
10651            .collect()
10652    }
10653
10654    pub fn init_test(cx: &mut TestAppContext) {
10655        cx.update(|cx| {
10656            let settings_store = SettingsStore::test(cx);
10657            cx.set_global(settings_store);
10658            theme::init(theme::LoadThemes::JustBase, cx);
10659            language::init(cx);
10660            crate::init_settings(cx);
10661            Project::init_settings(cx);
10662        });
10663    }
10664
10665    fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
10666        let item = TestProjectItem::new(id, path, cx);
10667        item.update(cx, |item, _| {
10668            item.is_dirty = true;
10669        });
10670        item
10671    }
10672}