workspace.rs

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