workspace.rs

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