workspace.rs

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