workspace.rs

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