workspace2.rs

   1#![allow(unused_variables, dead_code, unused_mut)]
   2// todo!() this is to make transition easier.
   3
   4pub mod dock;
   5pub mod item;
   6pub mod notifications;
   7pub mod pane;
   8pub mod pane_group;
   9mod persistence;
  10pub mod searchable;
  11// todo!()
  12// pub mod shared_screen;
  13mod modal_layer;
  14mod status_bar;
  15mod toolbar;
  16mod workspace_settings;
  17
  18pub use crate::persistence::{
  19    model::{
  20        DockData, DockStructure, ItemId, SerializedItem, SerializedPane, SerializedPaneGroup,
  21        SerializedWorkspace,
  22    },
  23    WorkspaceDb,
  24};
  25use anyhow::{anyhow, Context as _, Result};
  26use call2::ActiveCall;
  27use client2::{
  28    proto::{self, PeerId},
  29    Client, TypedEnvelope, UserStore,
  30};
  31use collections::{hash_map, HashMap, HashSet};
  32use dock::{Dock, DockPosition, Panel, PanelButtons, PanelHandle as _};
  33use futures::{
  34    channel::{mpsc, oneshot},
  35    future::try_join_all,
  36    Future, FutureExt, StreamExt,
  37};
  38use gpui::{
  39    actions, div, point, rems, size, Action, AnyModel, AnyView, AnyWeakView, AppContext,
  40    AsyncAppContext, AsyncWindowContext, Bounds, Component, Div, Entity, EntityId, EventEmitter,
  41    FocusHandle, GlobalPixels, KeyContext, Model, ModelContext, ParentElement, Point, Render, Size,
  42    StatefulInteractive, StatelessInteractive, StatelessInteractivity, Styled, Subscription, Task,
  43    View, ViewContext, VisualContext, WeakView, WindowBounds, WindowContext, WindowHandle,
  44    WindowOptions,
  45};
  46use item::{FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, ProjectItem};
  47use itertools::Itertools;
  48use language2::LanguageRegistry;
  49use lazy_static::lazy_static;
  50pub use modal_layer::*;
  51use node_runtime::NodeRuntime;
  52use notifications::{simple_message_notification::MessageNotification, NotificationHandle};
  53pub use pane::*;
  54pub use pane_group::*;
  55use persistence::{model::WorkspaceLocation, DB};
  56use postage::stream::Stream;
  57use project2::{Project, ProjectEntryId, ProjectPath, Worktree};
  58use serde::Deserialize;
  59use settings2::Settings;
  60use status_bar::StatusBar;
  61pub use status_bar::StatusItemView;
  62use std::{
  63    any::TypeId,
  64    borrow::Cow,
  65    env,
  66    path::{Path, PathBuf},
  67    sync::{atomic::AtomicUsize, Arc},
  68    time::Duration,
  69};
  70use theme2::ActiveTheme;
  71pub use toolbar::{ToolbarItemLocation, ToolbarItemView};
  72use ui::{h_stack, Button, ButtonVariant, Label, LabelColor};
  73use util::ResultExt;
  74use uuid::Uuid;
  75use workspace_settings::{AutosaveSetting, WorkspaceSettings};
  76
  77lazy_static! {
  78    static ref ZED_WINDOW_SIZE: Option<Size<GlobalPixels>> = env::var("ZED_WINDOW_SIZE")
  79        .ok()
  80        .as_deref()
  81        .and_then(parse_pixel_size_env_var);
  82    static ref ZED_WINDOW_POSITION: Option<Point<GlobalPixels>> = env::var("ZED_WINDOW_POSITION")
  83        .ok()
  84        .as_deref()
  85        .and_then(parse_pixel_position_env_var);
  86}
  87
  88// #[derive(Clone, PartialEq)]
  89// pub struct RemoveWorktreeFromProject(pub WorktreeId);
  90
  91actions!(
  92    Open,
  93    NewFile,
  94    NewWindow,
  95    CloseWindow,
  96    CloseInactiveTabsAndPanes,
  97    AddFolderToProject,
  98    Unfollow,
  99    SaveAs,
 100    ReloadActiveItem,
 101    ActivatePreviousPane,
 102    ActivateNextPane,
 103    FollowNextCollaborator,
 104    NewTerminal,
 105    NewCenterTerminal,
 106    ToggleTerminalFocus,
 107    NewSearch,
 108    Feedback,
 109    Restart,
 110    Welcome,
 111    ToggleZoom,
 112    ToggleLeftDock,
 113    ToggleRightDock,
 114    ToggleBottomDock,
 115    CloseAllDocks,
 116);
 117
 118// #[derive(Clone, PartialEq)]
 119// pub struct OpenPaths {
 120//     pub paths: Vec<PathBuf>,
 121// }
 122
 123// #[derive(Clone, Deserialize, PartialEq)]
 124// pub struct ActivatePane(pub usize);
 125
 126// #[derive(Clone, Deserialize, PartialEq)]
 127// pub struct ActivatePaneInDirection(pub SplitDirection);
 128
 129// #[derive(Clone, Deserialize, PartialEq)]
 130// pub struct SwapPaneInDirection(pub SplitDirection);
 131
 132// #[derive(Clone, Deserialize, PartialEq)]
 133// pub struct NewFileInDirection(pub SplitDirection);
 134
 135// #[derive(Clone, PartialEq, Debug, Deserialize)]
 136// #[serde(rename_all = "camelCase")]
 137// pub struct SaveAll {
 138//     pub save_intent: Option<SaveIntent>,
 139// }
 140
 141// #[derive(Clone, PartialEq, Debug, Deserialize)]
 142// #[serde(rename_all = "camelCase")]
 143// pub struct Save {
 144//     pub save_intent: Option<SaveIntent>,
 145// }
 146
 147// #[derive(Clone, PartialEq, Debug, Deserialize, Default)]
 148// #[serde(rename_all = "camelCase")]
 149// pub struct CloseAllItemsAndPanes {
 150//     pub save_intent: Option<SaveIntent>,
 151// }
 152
 153#[derive(Deserialize)]
 154pub struct Toast {
 155    id: usize,
 156    msg: Cow<'static, str>,
 157    #[serde(skip)]
 158    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut WindowContext)>)>,
 159}
 160
 161impl Toast {
 162    pub fn new<I: Into<Cow<'static, str>>>(id: usize, msg: I) -> Self {
 163        Toast {
 164            id,
 165            msg: msg.into(),
 166            on_click: None,
 167        }
 168    }
 169
 170    pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
 171    where
 172        M: Into<Cow<'static, str>>,
 173        F: Fn(&mut WindowContext) + 'static,
 174    {
 175        self.on_click = Some((message.into(), Arc::new(on_click)));
 176        self
 177    }
 178}
 179
 180impl PartialEq for Toast {
 181    fn eq(&self, other: &Self) -> bool {
 182        self.id == other.id
 183            && self.msg == other.msg
 184            && self.on_click.is_some() == other.on_click.is_some()
 185    }
 186}
 187
 188impl Clone for Toast {
 189    fn clone(&self) -> Self {
 190        Toast {
 191            id: self.id,
 192            msg: self.msg.to_owned(),
 193            on_click: self.on_click.clone(),
 194        }
 195    }
 196}
 197
 198// #[derive(Clone, Deserialize, PartialEq)]
 199// pub struct OpenTerminal {
 200//     pub working_directory: PathBuf,
 201// }
 202
 203// impl_actions!(
 204//     workspace,
 205//     [
 206//         ActivatePane,
 207//         ActivatePaneInDirection,
 208//         SwapPaneInDirection,
 209//         NewFileInDirection,
 210//         Toast,
 211//         OpenTerminal,
 212//         SaveAll,
 213//         Save,
 214//         CloseAllItemsAndPanes,
 215//     ]
 216// );
 217
 218pub type WorkspaceId = i64;
 219
 220pub fn init_settings(cx: &mut AppContext) {
 221    WorkspaceSettings::register(cx);
 222    ItemSettings::register(cx);
 223}
 224
 225pub fn init(app_state: Arc<AppState>, cx: &mut AppContext) {
 226    init_settings(cx);
 227    pane::init(cx);
 228    notifications::init(cx);
 229
 230    //     cx.add_global_action({
 231    //         let app_state = Arc::downgrade(&app_state);
 232    //         move |_: &Open, cx: &mut AppContext| {
 233    //             let mut paths = cx.prompt_for_paths(PathPromptOptions {
 234    //                 files: true,
 235    //                 directories: true,
 236    //                 multiple: true,
 237    //             });
 238
 239    //             if let Some(app_state) = app_state.upgrade() {
 240    //                 cx.spawn(move |mut cx| async move {
 241    //                     if let Some(paths) = paths.recv().await.flatten() {
 242    //                         cx.update(|cx| {
 243    //                             open_paths(&paths, &app_state, None, cx).detach_and_log_err(cx)
 244    //                         });
 245    //                     }
 246    //                 })
 247    //                 .detach();
 248    //             }
 249    //         }
 250    //     });
 251}
 252
 253type ProjectItemBuilders =
 254    HashMap<TypeId, fn(Model<Project>, AnyModel, &mut ViewContext<Pane>) -> Box<dyn ItemHandle>>;
 255pub fn register_project_item<I: ProjectItem>(cx: &mut AppContext) {
 256    let builders = cx.default_global::<ProjectItemBuilders>();
 257    builders.insert(TypeId::of::<I::Item>(), |project, model, cx| {
 258        let item = model.downcast::<I::Item>().unwrap();
 259        Box::new(cx.build_view(|cx| I::for_project_item(project, item, cx)))
 260    });
 261}
 262
 263type FollowableItemBuilder = fn(
 264    View<Pane>,
 265    View<Workspace>,
 266    ViewId,
 267    &mut Option<proto::view::Variant>,
 268    &mut AppContext,
 269) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>;
 270type FollowableItemBuilders = HashMap<
 271    TypeId,
 272    (
 273        FollowableItemBuilder,
 274        fn(&AnyView) -> Box<dyn FollowableItemHandle>,
 275    ),
 276>;
 277pub fn register_followable_item<I: FollowableItem>(cx: &mut AppContext) {
 278    let builders = cx.default_global::<FollowableItemBuilders>();
 279    builders.insert(
 280        TypeId::of::<I>(),
 281        (
 282            |pane, workspace, id, state, cx| {
 283                I::from_state_proto(pane, workspace, id, state, cx).map(|task| {
 284                    cx.foreground_executor()
 285                        .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
 286                })
 287            },
 288            |this| Box::new(this.clone().downcast::<I>().unwrap()),
 289        ),
 290    );
 291}
 292
 293type ItemDeserializers = HashMap<
 294    Arc<str>,
 295    fn(
 296        Model<Project>,
 297        WeakView<Workspace>,
 298        WorkspaceId,
 299        ItemId,
 300        &mut ViewContext<Pane>,
 301    ) -> Task<Result<Box<dyn ItemHandle>>>,
 302>;
 303pub fn register_deserializable_item<I: Item>(cx: &mut AppContext) {
 304    if let Some(serialized_item_kind) = I::serialized_item_kind() {
 305        let deserializers = cx.default_global::<ItemDeserializers>();
 306        deserializers.insert(
 307            Arc::from(serialized_item_kind),
 308            |project, workspace, workspace_id, item_id, cx| {
 309                let task = I::deserialize(project, workspace, workspace_id, item_id, cx);
 310                cx.foreground_executor()
 311                    .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 312            },
 313        );
 314    }
 315}
 316
 317pub struct AppState {
 318    pub languages: Arc<LanguageRegistry>,
 319    pub client: Arc<Client>,
 320    pub user_store: Model<UserStore>,
 321    pub workspace_store: Model<WorkspaceStore>,
 322    pub fs: Arc<dyn fs2::Fs>,
 323    pub build_window_options:
 324        fn(Option<WindowBounds>, Option<Uuid>, &mut AppContext) -> WindowOptions,
 325    pub initialize_workspace: fn(
 326        WeakView<Workspace>,
 327        bool,
 328        Arc<AppState>,
 329        AsyncWindowContext,
 330    ) -> Task<anyhow::Result<()>>,
 331    pub node_runtime: Arc<dyn NodeRuntime>,
 332}
 333
 334pub struct WorkspaceStore {
 335    workspaces: HashSet<WindowHandle<Workspace>>,
 336    followers: Vec<Follower>,
 337    client: Arc<Client>,
 338    _subscriptions: Vec<client2::Subscription>,
 339}
 340
 341#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 342struct Follower {
 343    project_id: Option<u64>,
 344    peer_id: PeerId,
 345}
 346
 347impl AppState {
 348    #[cfg(any(test, feature = "test-support"))]
 349    pub fn test(cx: &mut AppContext) -> Arc<Self> {
 350        use gpui::Context;
 351        use node_runtime::FakeNodeRuntime;
 352        use settings2::SettingsStore;
 353
 354        if !cx.has_global::<SettingsStore>() {
 355            let settings_store = SettingsStore::test(cx);
 356            cx.set_global(settings_store);
 357        }
 358
 359        let fs = fs2::FakeFs::new(cx.background_executor().clone());
 360        let languages = Arc::new(LanguageRegistry::test());
 361        let http_client = util::http::FakeHttpClient::with_404_response();
 362        let client = Client::new(http_client.clone(), cx);
 363        let user_store = cx.build_model(|cx| UserStore::new(client.clone(), http_client, cx));
 364        let workspace_store = cx.build_model(|cx| WorkspaceStore::new(client.clone(), cx));
 365
 366        theme2::init(cx);
 367        client2::init(&client, cx);
 368        crate::init_settings(cx);
 369
 370        Arc::new(Self {
 371            client,
 372            fs,
 373            languages,
 374            user_store,
 375            workspace_store,
 376            node_runtime: FakeNodeRuntime::new(),
 377            initialize_workspace: |_, _, _, _| Task::ready(Ok(())),
 378            build_window_options: |_, _, _| Default::default(),
 379        })
 380    }
 381}
 382
 383struct DelayedDebouncedEditAction {
 384    task: Option<Task<()>>,
 385    cancel_channel: Option<oneshot::Sender<()>>,
 386}
 387
 388impl DelayedDebouncedEditAction {
 389    fn new() -> DelayedDebouncedEditAction {
 390        DelayedDebouncedEditAction {
 391            task: None,
 392            cancel_channel: None,
 393        }
 394    }
 395
 396    fn fire_new<F>(&mut self, delay: Duration, cx: &mut ViewContext<Workspace>, func: F)
 397    where
 398        F: 'static + Send + FnOnce(&mut Workspace, &mut ViewContext<Workspace>) -> Task<Result<()>>,
 399    {
 400        if let Some(channel) = self.cancel_channel.take() {
 401            _ = channel.send(());
 402        }
 403
 404        let (sender, mut receiver) = oneshot::channel::<()>();
 405        self.cancel_channel = Some(sender);
 406
 407        let previous_task = self.task.take();
 408        self.task = Some(cx.spawn(move |workspace, mut cx| async move {
 409            let mut timer = cx.background_executor().timer(delay).fuse();
 410            if let Some(previous_task) = previous_task {
 411                previous_task.await;
 412            }
 413
 414            futures::select_biased! {
 415                _ = receiver => return,
 416                    _ = timer => {}
 417            }
 418
 419            if let Some(result) = workspace
 420                .update(&mut cx, |workspace, cx| (func)(workspace, cx))
 421                .log_err()
 422            {
 423                result.await.log_err();
 424            }
 425        }));
 426    }
 427}
 428
 429pub enum Event {
 430    PaneAdded(View<Pane>),
 431    ContactRequestedJoin(u64),
 432    WorkspaceCreated(WeakView<Workspace>),
 433}
 434
 435pub struct Workspace {
 436    weak_self: WeakView<Self>,
 437    focus_handle: FocusHandle,
 438    workspace_actions: Vec<
 439        Box<
 440            dyn Fn(
 441                Div<Workspace, StatelessInteractivity<Workspace>>,
 442            ) -> Div<Workspace, StatelessInteractivity<Workspace>>,
 443        >,
 444    >,
 445    zoomed: Option<AnyWeakView>,
 446    zoomed_position: Option<DockPosition>,
 447    center: PaneGroup,
 448    left_dock: View<Dock>,
 449    bottom_dock: View<Dock>,
 450    right_dock: View<Dock>,
 451    panes: Vec<View<Pane>>,
 452    panes_by_item: HashMap<EntityId, WeakView<Pane>>,
 453    active_pane: View<Pane>,
 454    last_active_center_pane: Option<WeakView<Pane>>,
 455    last_active_view_id: Option<proto::ViewId>,
 456    status_bar: View<StatusBar>,
 457    modal_layer: View<ModalLayer>,
 458    //     titlebar_item: Option<AnyViewHandle>,
 459    notifications: Vec<(TypeId, usize, Box<dyn NotificationHandle>)>,
 460    project: Model<Project>,
 461    follower_states: HashMap<View<Pane>, FollowerState>,
 462    last_leaders_by_pane: HashMap<WeakView<Pane>, PeerId>,
 463    window_edited: bool,
 464    active_call: Option<(Model<ActiveCall>, Vec<Subscription>)>,
 465    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 466    database_id: WorkspaceId,
 467    app_state: Arc<AppState>,
 468    subscriptions: Vec<Subscription>,
 469    _apply_leader_updates: Task<Result<()>>,
 470    _observe_current_user: Task<Result<()>>,
 471    _schedule_serialize: Option<Task<()>>,
 472    pane_history_timestamp: Arc<AtomicUsize>,
 473}
 474
 475#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 476pub struct ViewId {
 477    pub creator: PeerId,
 478    pub id: u64,
 479}
 480
 481#[derive(Default)]
 482struct FollowerState {
 483    leader_id: PeerId,
 484    active_view_id: Option<ViewId>,
 485    items_by_leader_view_id: HashMap<ViewId, Box<dyn FollowableItemHandle>>,
 486}
 487
 488enum WorkspaceBounds {}
 489
 490impl Workspace {
 491    pub fn new(
 492        workspace_id: WorkspaceId,
 493        project: Model<Project>,
 494        app_state: Arc<AppState>,
 495        cx: &mut ViewContext<Self>,
 496    ) -> Self {
 497        cx.observe(&project, |_, _, cx| cx.notify()).detach();
 498        cx.subscribe(&project, move |this, _, event, cx| {
 499            match event {
 500                project2::Event::RemoteIdChanged(_) => {
 501                    this.update_window_title(cx);
 502                }
 503
 504                project2::Event::CollaboratorLeft(peer_id) => {
 505                    this.collaborator_left(*peer_id, cx);
 506                }
 507
 508                project2::Event::WorktreeRemoved(_) | project2::Event::WorktreeAdded => {
 509                    this.update_window_title(cx);
 510                    this.serialize_workspace(cx);
 511                }
 512
 513                project2::Event::DisconnectedFromHost => {
 514                    this.update_window_edited(cx);
 515                    cx.blur();
 516                }
 517
 518                project2::Event::Closed => {
 519                    cx.remove_window();
 520                }
 521
 522                project2::Event::DeletedEntry(entry_id) => {
 523                    for pane in this.panes.iter() {
 524                        pane.update(cx, |pane, cx| {
 525                            pane.handle_deleted_project_item(*entry_id, cx)
 526                        });
 527                    }
 528                }
 529
 530                project2::Event::Notification(message) => this.show_notification(0, cx, |cx| {
 531                    cx.build_view(|_| MessageNotification::new(message.clone()))
 532                }),
 533
 534                _ => {}
 535            }
 536            cx.notify()
 537        })
 538        .detach();
 539
 540        let weak_handle = cx.view().downgrade();
 541        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 542
 543        let center_pane = cx.build_view(|cx| {
 544            Pane::new(
 545                weak_handle.clone(),
 546                project.clone(),
 547                pane_history_timestamp.clone(),
 548                cx,
 549            )
 550        });
 551        cx.subscribe(&center_pane, Self::handle_pane_event).detach();
 552        // todo!()
 553        // cx.focus(&center_pane);
 554        cx.emit(Event::PaneAdded(center_pane.clone()));
 555
 556        let window_handle = cx.window_handle().downcast::<Workspace>().unwrap();
 557        app_state.workspace_store.update(cx, |store, _| {
 558            store.workspaces.insert(window_handle);
 559        });
 560
 561        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 562        let mut connection_status = app_state.client.status();
 563        let _observe_current_user = cx.spawn(|this, mut cx| async move {
 564            current_user.next().await;
 565            connection_status.next().await;
 566            let mut stream =
 567                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 568
 569            while stream.recv().await.is_some() {
 570                this.update(&mut cx, |_, cx| cx.notify())?;
 571            }
 572            anyhow::Ok(())
 573        });
 574
 575        // All leader updates are enqueued and then processed in a single task, so
 576        // that each asynchronous operation can be run in order.
 577        let (leader_updates_tx, mut leader_updates_rx) =
 578            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 579        let _apply_leader_updates = cx.spawn(|this, mut cx| async move {
 580            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 581                Self::process_leader_update(&this, leader_id, update, &mut cx)
 582                    .await
 583                    .log_err();
 584            }
 585
 586            Ok(())
 587        });
 588
 589        cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
 590
 591        let left_dock = cx.build_view(|_| Dock::new(DockPosition::Left));
 592        let bottom_dock = cx.build_view(|_| Dock::new(DockPosition::Bottom));
 593        let right_dock = cx.build_view(|_| Dock::new(DockPosition::Right));
 594        let left_dock_buttons =
 595            cx.build_view(|cx| PanelButtons::new(left_dock.clone(), weak_handle.clone(), cx));
 596        let bottom_dock_buttons =
 597            cx.build_view(|cx| PanelButtons::new(bottom_dock.clone(), weak_handle.clone(), cx));
 598        let right_dock_buttons =
 599            cx.build_view(|cx| PanelButtons::new(right_dock.clone(), weak_handle.clone(), cx));
 600        let status_bar = cx.build_view(|cx| {
 601            let mut status_bar = StatusBar::new(&center_pane.clone(), cx);
 602            status_bar.add_left_item(left_dock_buttons, cx);
 603            status_bar.add_right_item(right_dock_buttons, cx);
 604            status_bar.add_right_item(bottom_dock_buttons, cx);
 605            status_bar
 606        });
 607
 608        let workspace_handle = cx.view().downgrade();
 609        let modal_layer = cx.build_view(|cx| ModalLayer::new());
 610
 611        // todo!()
 612        // cx.update_default_global::<DragAndDrop<Workspace>, _, _>(|drag_and_drop, _| {
 613        //     drag_and_drop.register_container(weak_handle.clone());
 614        // });
 615
 616        let mut active_call = None;
 617        if cx.has_global::<Model<ActiveCall>>() {
 618            let call = cx.global::<Model<ActiveCall>>().clone();
 619            let mut subscriptions = Vec::new();
 620            subscriptions.push(cx.subscribe(&call, Self::on_active_call_event));
 621            active_call = Some((call, subscriptions));
 622        }
 623
 624        let subscriptions = vec![
 625            cx.observe_window_activation(Self::on_window_activation_changed),
 626            cx.observe_window_bounds(move |_, cx| {
 627                if let Some(display) = cx.display() {
 628                    // Transform fixed bounds to be stored in terms of the containing display
 629                    let mut bounds = cx.window_bounds();
 630                    if let WindowBounds::Fixed(window_bounds) = &mut bounds {
 631                        let display_bounds = display.bounds();
 632                        window_bounds.origin.x -= display_bounds.origin.x;
 633                        window_bounds.origin.y -= display_bounds.origin.y;
 634                    }
 635
 636                    if let Some(display_uuid) = display.uuid().log_err() {
 637                        cx.background_executor()
 638                            .spawn(DB.set_window_bounds(workspace_id, bounds, display_uuid))
 639                            .detach_and_log_err(cx);
 640                    }
 641                }
 642                cx.notify();
 643            }),
 644            cx.observe(&left_dock, |this, _, cx| {
 645                this.serialize_workspace(cx);
 646                cx.notify();
 647            }),
 648            cx.observe(&bottom_dock, |this, _, cx| {
 649                this.serialize_workspace(cx);
 650                cx.notify();
 651            }),
 652            cx.observe(&right_dock, |this, _, cx| {
 653                this.serialize_workspace(cx);
 654                cx.notify();
 655            }),
 656        ];
 657
 658        cx.defer(|this, cx| this.update_window_title(cx));
 659        Workspace {
 660            weak_self: weak_handle.clone(),
 661            focus_handle: cx.focus_handle(),
 662            zoomed: None,
 663            zoomed_position: None,
 664            center: PaneGroup::new(center_pane.clone()),
 665            panes: vec![center_pane.clone()],
 666            panes_by_item: Default::default(),
 667            active_pane: center_pane.clone(),
 668            last_active_center_pane: Some(center_pane.downgrade()),
 669            last_active_view_id: None,
 670            status_bar,
 671            modal_layer,
 672            // titlebar_item: None,
 673            notifications: Default::default(),
 674            left_dock,
 675            bottom_dock,
 676            right_dock,
 677            project: project.clone(),
 678            follower_states: Default::default(),
 679            last_leaders_by_pane: Default::default(),
 680            window_edited: false,
 681            active_call,
 682            database_id: workspace_id,
 683            app_state,
 684            _observe_current_user,
 685            _apply_leader_updates,
 686            _schedule_serialize: None,
 687            leader_updates_tx,
 688            subscriptions,
 689            pane_history_timestamp,
 690            workspace_actions: Default::default(),
 691        }
 692    }
 693
 694    fn new_local(
 695        abs_paths: Vec<PathBuf>,
 696        app_state: Arc<AppState>,
 697        _requesting_window: Option<WindowHandle<Workspace>>,
 698        cx: &mut AppContext,
 699    ) -> Task<
 700        anyhow::Result<(
 701            WindowHandle<Workspace>,
 702            Vec<Option<Result<Box<dyn ItemHandle>, anyhow::Error>>>,
 703        )>,
 704    > {
 705        let project_handle = Project::local(
 706            app_state.client.clone(),
 707            app_state.node_runtime.clone(),
 708            app_state.user_store.clone(),
 709            app_state.languages.clone(),
 710            app_state.fs.clone(),
 711            cx,
 712        );
 713
 714        cx.spawn(|mut cx| async move {
 715            let serialized_workspace: Option<SerializedWorkspace> = None; //persistence::DB.workspace_for_roots(&abs_paths.as_slice());
 716
 717            let paths_to_open = Arc::new(abs_paths);
 718
 719            // Get project paths for all of the abs_paths
 720            let mut worktree_roots: HashSet<Arc<Path>> = Default::default();
 721            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 722                Vec::with_capacity(paths_to_open.len());
 723            for path in paths_to_open.iter().cloned() {
 724                if let Some((worktree, project_entry)) = cx
 725                    .update(|cx| {
 726                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 727                    })?
 728                    .await
 729                    .log_err()
 730                {
 731                    worktree_roots.extend(worktree.update(&mut cx, |tree, _| tree.abs_path()).ok());
 732                    project_paths.push((path, Some(project_entry)));
 733                } else {
 734                    project_paths.push((path, None));
 735                }
 736            }
 737
 738            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 739                serialized_workspace.id
 740            } else {
 741                DB.next_id().await.unwrap_or(0)
 742            };
 743
 744            // todo!()
 745            let window = /*if let Some(window) = requesting_window {
 746                cx.update_window(window.into(), |old_workspace, cx| {
 747                    cx.replace_root_view(|cx| {
 748                        Workspace::new(workspace_id, project_handle.clone(), app_state.clone(), cx)
 749                    });
 750                });
 751                window
 752                } else */ {
 753                let window_bounds_override = window_bounds_env_override(&cx);
 754                let (bounds, display) = if let Some(bounds) = window_bounds_override {
 755                    (Some(bounds), None)
 756                } else {
 757                    serialized_workspace
 758                        .as_ref()
 759                        .and_then(|serialized_workspace| {
 760                            let serialized_display = serialized_workspace.display?;
 761                            let mut bounds = serialized_workspace.bounds?;
 762
 763                            // Stored bounds are relative to the containing display.
 764                            // So convert back to global coordinates if that screen still exists
 765                            if let WindowBounds::Fixed(mut window_bounds) = bounds {
 766                                let screen =
 767                                    cx.update(|cx|
 768                                        cx.displays()
 769                                            .into_iter()
 770                                            .find(|display| display.uuid().ok() == Some(serialized_display))
 771                                    ).ok()??;
 772                                let screen_bounds = screen.bounds();
 773                                window_bounds.origin.x += screen_bounds.origin.x;
 774                                window_bounds.origin.y += screen_bounds.origin.y;
 775                                bounds = WindowBounds::Fixed(window_bounds);
 776                            }
 777
 778                            Some((bounds, serialized_display))
 779                        })
 780                        .unzip()
 781                };
 782
 783                // Use the serialized workspace to construct the new window
 784                let options =
 785                    cx.update(|cx| (app_state.build_window_options)(bounds, display, cx))?;
 786
 787                cx.open_window(options, {
 788                    let app_state = app_state.clone();
 789                    let workspace_id = workspace_id.clone();
 790                    let project_handle = project_handle.clone();
 791                    move |cx| {
 792                        cx.build_view(|cx| {
 793                            Workspace::new(workspace_id, project_handle, app_state, cx)
 794                        })
 795                    }
 796                })?
 797            };
 798
 799            // todo!() Ask how to do this
 800            let weak_view = window.update(&mut cx, |_, cx| cx.view().downgrade())?;
 801            let async_cx = window.update(&mut cx, |_, cx| cx.to_async())?;
 802
 803            (app_state.initialize_workspace)(
 804                weak_view,
 805                serialized_workspace.is_some(),
 806                app_state.clone(),
 807                async_cx,
 808            )
 809            .await
 810            .log_err();
 811
 812            window
 813                .update(&mut cx, |_, cx| cx.activate_window())
 814                .log_err();
 815
 816            notify_if_database_failed(window, &mut cx);
 817            let opened_items = window
 818                .update(&mut cx, |_workspace, cx| {
 819                    open_items(
 820                        serialized_workspace,
 821                        project_paths,
 822                        app_state,
 823                        cx,
 824                    )
 825                })?
 826                .await
 827                .unwrap_or_default();
 828
 829            Ok((window, opened_items))
 830        })
 831    }
 832
 833    pub fn weak_handle(&self) -> WeakView<Self> {
 834        self.weak_self.clone()
 835    }
 836
 837    pub fn left_dock(&self) -> &View<Dock> {
 838        &self.left_dock
 839    }
 840
 841    pub fn bottom_dock(&self) -> &View<Dock> {
 842        &self.bottom_dock
 843    }
 844
 845    pub fn right_dock(&self) -> &View<Dock> {
 846        &self.right_dock
 847    }
 848
 849    pub fn add_panel<T: Panel>(&mut self, panel: View<T>, cx: &mut ViewContext<Self>) {
 850        let dock = match panel.position(cx) {
 851            DockPosition::Left => &self.left_dock,
 852            DockPosition::Bottom => &self.bottom_dock,
 853            DockPosition::Right => &self.right_dock,
 854        };
 855
 856        dock.update(cx, |dock, cx| dock.add_panel(panel, cx));
 857    }
 858
 859    pub fn status_bar(&self) -> &View<StatusBar> {
 860        &self.status_bar
 861    }
 862
 863    pub fn app_state(&self) -> &Arc<AppState> {
 864        &self.app_state
 865    }
 866
 867    pub fn user_store(&self) -> &Model<UserStore> {
 868        &self.app_state.user_store
 869    }
 870
 871    pub fn project(&self) -> &Model<Project> {
 872        &self.project
 873    }
 874
 875    pub fn recent_navigation_history(
 876        &self,
 877        limit: Option<usize>,
 878        cx: &AppContext,
 879    ) -> Vec<(ProjectPath, Option<PathBuf>)> {
 880        let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
 881        let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
 882        for pane in &self.panes {
 883            let pane = pane.read(cx);
 884            pane.nav_history()
 885                .for_each_entry(cx, |entry, (project_path, fs_path)| {
 886                    if let Some(fs_path) = &fs_path {
 887                        abs_paths_opened
 888                            .entry(fs_path.clone())
 889                            .or_default()
 890                            .insert(project_path.clone());
 891                    }
 892                    let timestamp = entry.timestamp;
 893                    match history.entry(project_path) {
 894                        hash_map::Entry::Occupied(mut entry) => {
 895                            let (_, old_timestamp) = entry.get();
 896                            if &timestamp > old_timestamp {
 897                                entry.insert((fs_path, timestamp));
 898                            }
 899                        }
 900                        hash_map::Entry::Vacant(entry) => {
 901                            entry.insert((fs_path, timestamp));
 902                        }
 903                    }
 904                });
 905        }
 906
 907        history
 908            .into_iter()
 909            .sorted_by_key(|(_, (_, timestamp))| *timestamp)
 910            .map(|(project_path, (fs_path, _))| (project_path, fs_path))
 911            .rev()
 912            .filter(|(history_path, abs_path)| {
 913                let latest_project_path_opened = abs_path
 914                    .as_ref()
 915                    .and_then(|abs_path| abs_paths_opened.get(abs_path))
 916                    .and_then(|project_paths| {
 917                        project_paths
 918                            .iter()
 919                            .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
 920                    });
 921
 922                match latest_project_path_opened {
 923                    Some(latest_project_path_opened) => latest_project_path_opened == history_path,
 924                    None => true,
 925                }
 926            })
 927            .take(limit.unwrap_or(usize::MAX))
 928            .collect()
 929    }
 930
 931    fn navigate_history(
 932        &mut self,
 933        pane: WeakView<Pane>,
 934        mode: NavigationMode,
 935        cx: &mut ViewContext<Workspace>,
 936    ) -> Task<Result<()>> {
 937        let to_load = if let Some(pane) = pane.upgrade() {
 938            // todo!("focus")
 939            // cx.focus(&pane);
 940
 941            pane.update(cx, |pane, cx| {
 942                loop {
 943                    // Retrieve the weak item handle from the history.
 944                    let entry = pane.nav_history_mut().pop(mode, cx)?;
 945
 946                    // If the item is still present in this pane, then activate it.
 947                    if let Some(index) = entry
 948                        .item
 949                        .upgrade()
 950                        .and_then(|v| pane.index_for_item(v.as_ref()))
 951                    {
 952                        let prev_active_item_index = pane.active_item_index();
 953                        pane.nav_history_mut().set_mode(mode);
 954                        pane.activate_item(index, true, true, cx);
 955                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 956
 957                        let mut navigated = prev_active_item_index != pane.active_item_index();
 958                        if let Some(data) = entry.data {
 959                            navigated |= pane.active_item()?.navigate(data, cx);
 960                        }
 961
 962                        if navigated {
 963                            break None;
 964                        }
 965                    }
 966                    // If the item is no longer present in this pane, then retrieve its
 967                    // project path in order to reopen it.
 968                    else {
 969                        break pane
 970                            .nav_history()
 971                            .path_for_item(entry.item.id())
 972                            .map(|(project_path, _)| (project_path, entry));
 973                    }
 974                }
 975            })
 976        } else {
 977            None
 978        };
 979
 980        if let Some((project_path, entry)) = to_load {
 981            // If the item was no longer present, then load it again from its previous path.
 982            let task = self.load_path(project_path, cx);
 983            cx.spawn(|workspace, mut cx| async move {
 984                let task = task.await;
 985                let mut navigated = false;
 986                if let Some((project_entry_id, build_item)) = task.log_err() {
 987                    let prev_active_item_id = pane.update(&mut cx, |pane, _| {
 988                        pane.nav_history_mut().set_mode(mode);
 989                        pane.active_item().map(|p| p.id())
 990                    })?;
 991
 992                    pane.update(&mut cx, |pane, cx| {
 993                        let item = pane.open_item(project_entry_id, true, cx, build_item);
 994                        navigated |= Some(item.id()) != prev_active_item_id;
 995                        pane.nav_history_mut().set_mode(NavigationMode::Normal);
 996                        if let Some(data) = entry.data {
 997                            navigated |= item.navigate(data, cx);
 998                        }
 999                    })?;
1000                }
1001
1002                if !navigated {
1003                    workspace
1004                        .update(&mut cx, |workspace, cx| {
1005                            Self::navigate_history(workspace, pane, mode, cx)
1006                        })?
1007                        .await?;
1008                }
1009
1010                Ok(())
1011            })
1012        } else {
1013            Task::ready(Ok(()))
1014        }
1015    }
1016
1017    pub fn go_back(
1018        &mut self,
1019        pane: WeakView<Pane>,
1020        cx: &mut ViewContext<Workspace>,
1021    ) -> Task<Result<()>> {
1022        self.navigate_history(pane, NavigationMode::GoingBack, cx)
1023    }
1024
1025    pub fn go_forward(
1026        &mut self,
1027        pane: WeakView<Pane>,
1028        cx: &mut ViewContext<Workspace>,
1029    ) -> Task<Result<()>> {
1030        self.navigate_history(pane, NavigationMode::GoingForward, cx)
1031    }
1032
1033    pub fn reopen_closed_item(&mut self, cx: &mut ViewContext<Workspace>) -> Task<Result<()>> {
1034        self.navigate_history(
1035            self.active_pane().downgrade(),
1036            NavigationMode::ReopeningClosedItem,
1037            cx,
1038        )
1039    }
1040
1041    pub fn client(&self) -> &Client {
1042        &self.app_state.client
1043    }
1044
1045    // todo!()
1046    // pub fn set_titlebar_item(&mut self, item: AnyViewHandle, cx: &mut ViewContext<Self>) {
1047    //     self.titlebar_item = Some(item);
1048    //     cx.notify();
1049    // }
1050
1051    // pub fn titlebar_item(&self) -> Option<AnyViewHandle> {
1052    //     self.titlebar_item.clone()
1053    // }
1054
1055    //     /// Call the given callback with a workspace whose project is local.
1056    //     ///
1057    //     /// If the given workspace has a local project, then it will be passed
1058    //     /// to the callback. Otherwise, a new empty window will be created.
1059    //     pub fn with_local_workspace<T, F>(
1060    //         &mut self,
1061    //         cx: &mut ViewContext<Self>,
1062    //         callback: F,
1063    //     ) -> Task<Result<T>>
1064    //     where
1065    //         T: 'static,
1066    //         F: 'static + FnOnce(&mut Workspace, &mut ViewContext<Workspace>) -> T,
1067    //     {
1068    //         if self.project.read(cx).is_local() {
1069    //             Task::Ready(Some(Ok(callback(self, cx))))
1070    //         } else {
1071    //             let task = Self::new_local(Vec::new(), self.app_state.clone(), None, cx);
1072    //             cx.spawn(|_vh, mut cx| async move {
1073    //                 let (workspace, _) = task.await;
1074    //                 workspace.update(&mut cx, callback)
1075    //             })
1076    //         }
1077    //     }
1078
1079    pub fn worktrees<'a>(&self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Model<Worktree>> {
1080        self.project.read(cx).worktrees()
1081    }
1082
1083    pub fn visible_worktrees<'a>(
1084        &self,
1085        cx: &'a AppContext,
1086    ) -> impl 'a + Iterator<Item = Model<Worktree>> {
1087        self.project.read(cx).visible_worktrees(cx)
1088    }
1089
1090    pub fn worktree_scans_complete(&self, cx: &AppContext) -> impl Future<Output = ()> + 'static {
1091        let futures = self
1092            .worktrees(cx)
1093            .filter_map(|worktree| worktree.read(cx).as_local())
1094            .map(|worktree| worktree.scan_complete())
1095            .collect::<Vec<_>>();
1096        async move {
1097            for future in futures {
1098                future.await;
1099            }
1100        }
1101    }
1102
1103    //     pub fn close_global(_: &CloseWindow, cx: &mut AppContext) {
1104    //         cx.spawn(|mut cx| async move {
1105    //             let window = cx
1106    //                 .windows()
1107    //                 .into_iter()
1108    //                 .find(|window| window.is_active(&cx).unwrap_or(false));
1109    //             if let Some(window) = window {
1110    //                 //This can only get called when the window's project connection has been lost
1111    //                 //so we don't need to prompt the user for anything and instead just close the window
1112    //                 window.remove(&mut cx);
1113    //             }
1114    //         })
1115    //         .detach();
1116    //     }
1117
1118    //     pub fn close(
1119    //         &mut self,
1120    //         _: &CloseWindow,
1121    //         cx: &mut ViewContext<Self>,
1122    //     ) -> Option<Task<Result<()>>> {
1123    //         let window = cx.window();
1124    //         let prepare = self.prepare_to_close(false, cx);
1125    //         Some(cx.spawn(|_, mut cx| async move {
1126    //             if prepare.await? {
1127    //                 window.remove(&mut cx);
1128    //             }
1129    //             Ok(())
1130    //         }))
1131    //     }
1132
1133    pub fn prepare_to_close(
1134        &mut self,
1135        quitting: bool,
1136        cx: &mut ViewContext<Self>,
1137    ) -> Task<Result<bool>> {
1138        //todo!(saveing)
1139        // let active_call = self.active_call().cloned();
1140        // let window = cx.window();
1141
1142        cx.spawn(|this, mut cx| async move {
1143            // let workspace_count = cx
1144            //     .windows()
1145            //     .into_iter()
1146            //     .filter(|window| window.root_is::<Workspace>())
1147            //     .count();
1148
1149            // if let Some(active_call) = active_call {
1150            //     if !quitting
1151            //         && workspace_count == 1
1152            //         && active_call.read_with(&cx, |call, _| call.room().is_some())
1153            //     {
1154            //         let answer = window.prompt(
1155            //             PromptLevel::Warning,
1156            //             "Do you want to leave the current call?",
1157            //             &["Close window and hang up", "Cancel"],
1158            //             &mut cx,
1159            //         );
1160
1161            //         if let Some(mut answer) = answer {
1162            //             if answer.next().await == Some(1) {
1163            //                 return anyhow::Ok(false);
1164            //             } else {
1165            //                 active_call
1166            //                     .update(&mut cx, |call, cx| call.hang_up(cx))
1167            //                     .await
1168            //                     .log_err();
1169            //             }
1170            //         }
1171            //     }
1172            // }
1173
1174            Ok(
1175                false, // this
1176                      // .update(&mut cx, |this, cx| {
1177                      //     this.save_all_internal(SaveIntent::Close, cx)
1178                      // })?
1179                      // .await?
1180            )
1181        })
1182    }
1183
1184    //     fn save_all(
1185    //         &mut self,
1186    //         action: &SaveAll,
1187    //         cx: &mut ViewContext<Self>,
1188    //     ) -> Option<Task<Result<()>>> {
1189    //         let save_all =
1190    //             self.save_all_internal(action.save_intent.unwrap_or(SaveIntent::SaveAll), cx);
1191    //         Some(cx.foreground().spawn(async move {
1192    //             save_all.await?;
1193    //             Ok(())
1194    //         }))
1195    //     }
1196
1197    //     fn save_all_internal(
1198    //         &mut self,
1199    //         mut save_intent: SaveIntent,
1200    //         cx: &mut ViewContext<Self>,
1201    //     ) -> Task<Result<bool>> {
1202    //         if self.project.read(cx).is_read_only() {
1203    //             return Task::ready(Ok(true));
1204    //         }
1205    //         let dirty_items = self
1206    //             .panes
1207    //             .iter()
1208    //             .flat_map(|pane| {
1209    //                 pane.read(cx).items().filter_map(|item| {
1210    //                     if item.is_dirty(cx) {
1211    //                         Some((pane.downgrade(), item.boxed_clone()))
1212    //                     } else {
1213    //                         None
1214    //                     }
1215    //                 })
1216    //             })
1217    //             .collect::<Vec<_>>();
1218
1219    //         let project = self.project.clone();
1220    //         cx.spawn(|workspace, mut cx| async move {
1221    //             // Override save mode and display "Save all files" prompt
1222    //             if save_intent == SaveIntent::Close && dirty_items.len() > 1 {
1223    //                 let mut answer = workspace.update(&mut cx, |_, cx| {
1224    //                     let prompt = Pane::file_names_for_prompt(
1225    //                         &mut dirty_items.iter().map(|(_, handle)| handle),
1226    //                         dirty_items.len(),
1227    //                         cx,
1228    //                     );
1229    //                     cx.prompt(
1230    //                         PromptLevel::Warning,
1231    //                         &prompt,
1232    //                         &["Save all", "Discard all", "Cancel"],
1233    //                     )
1234    //                 })?;
1235    //                 match answer.next().await {
1236    //                     Some(0) => save_intent = SaveIntent::SaveAll,
1237    //                     Some(1) => save_intent = SaveIntent::Skip,
1238    //                     _ => {}
1239    //                 }
1240    //             }
1241    //             for (pane, item) in dirty_items {
1242    //                 let (singleton, project_entry_ids) =
1243    //                     cx.read(|cx| (item.is_singleton(cx), item.project_entry_ids(cx)));
1244    //                 if singleton || !project_entry_ids.is_empty() {
1245    //                     if let Some(ix) =
1246    //                         pane.read_with(&cx, |pane, _| pane.index_for_item(item.as_ref()))?
1247    //                     {
1248    //                         if !Pane::save_item(
1249    //                             project.clone(),
1250    //                             &pane,
1251    //                             ix,
1252    //                             &*item,
1253    //                             save_intent,
1254    //                             &mut cx,
1255    //                         )
1256    //                         .await?
1257    //                         {
1258    //                             return Ok(false);
1259    //                         }
1260    //                     }
1261    //                 }
1262    //             }
1263    //             Ok(true)
1264    //         })
1265    //     }
1266
1267    //     pub fn open(&mut self, _: &Open, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
1268    //         let mut paths = cx.prompt_for_paths(PathPromptOptions {
1269    //             files: true,
1270    //             directories: true,
1271    //             multiple: true,
1272    //         });
1273
1274    //         Some(cx.spawn(|this, mut cx| async move {
1275    //             if let Some(paths) = paths.recv().await.flatten() {
1276    //                 if let Some(task) = this
1277    //                     .update(&mut cx, |this, cx| this.open_workspace_for_paths(paths, cx))
1278    //                     .log_err()
1279    //                 {
1280    //                     task.await?
1281    //                 }
1282    //             }
1283    //             Ok(())
1284    //         }))
1285    //     }
1286
1287    //     pub fn open_workspace_for_paths(
1288    //         &mut self,
1289    //         paths: Vec<PathBuf>,
1290    //         cx: &mut ViewContext<Self>,
1291    //     ) -> Task<Result<()>> {
1292    //         let window = cx.window().downcast::<Self>();
1293    //         let is_remote = self.project.read(cx).is_remote();
1294    //         let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
1295    //         let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
1296    //         let close_task = if is_remote || has_worktree || has_dirty_items {
1297    //             None
1298    //         } else {
1299    //             Some(self.prepare_to_close(false, cx))
1300    //         };
1301    //         let app_state = self.app_state.clone();
1302
1303    //         cx.spawn(|_, mut cx| async move {
1304    //             let window_to_replace = if let Some(close_task) = close_task {
1305    //                 if !close_task.await? {
1306    //                     return Ok(());
1307    //                 }
1308    //                 window
1309    //             } else {
1310    //                 None
1311    //             };
1312    //             cx.update(|cx| open_paths(&paths, &app_state, window_to_replace, cx))
1313    //                 .await?;
1314    //             Ok(())
1315    //         })
1316    //     }
1317
1318    #[allow(clippy::type_complexity)]
1319    pub fn open_paths(
1320        &mut self,
1321        mut abs_paths: Vec<PathBuf>,
1322        visible: bool,
1323        cx: &mut ViewContext<Self>,
1324    ) -> Task<Vec<Option<Result<Box<dyn ItemHandle>, anyhow::Error>>>> {
1325        log::info!("open paths {abs_paths:?}");
1326
1327        let fs = self.app_state.fs.clone();
1328
1329        // Sort the paths to ensure we add worktrees for parents before their children.
1330        abs_paths.sort_unstable();
1331        cx.spawn(move |this, mut cx| async move {
1332            let mut tasks = Vec::with_capacity(abs_paths.len());
1333            for abs_path in &abs_paths {
1334                let project_path = match this
1335                    .update(&mut cx, |this, cx| {
1336                        Workspace::project_path_for_path(
1337                            this.project.clone(),
1338                            abs_path,
1339                            visible,
1340                            cx,
1341                        )
1342                    })
1343                    .log_err()
1344                {
1345                    Some(project_path) => project_path.await.log_err(),
1346                    None => None,
1347                };
1348
1349                let this = this.clone();
1350                let abs_path = abs_path.clone();
1351                let fs = fs.clone();
1352                let task = cx.spawn(move |mut cx| async move {
1353                    let (worktree, project_path) = project_path?;
1354                    if fs.is_file(&abs_path).await {
1355                        Some(
1356                            this.update(&mut cx, |this, cx| {
1357                                this.open_path(project_path, None, true, cx)
1358                            })
1359                            .log_err()?
1360                            .await,
1361                        )
1362                    } else {
1363                        this.update(&mut cx, |workspace, cx| {
1364                            let worktree = worktree.read(cx);
1365                            let worktree_abs_path = worktree.abs_path();
1366                            let entry_id = if abs_path == worktree_abs_path.as_ref() {
1367                                worktree.root_entry()
1368                            } else {
1369                                abs_path
1370                                    .strip_prefix(worktree_abs_path.as_ref())
1371                                    .ok()
1372                                    .and_then(|relative_path| {
1373                                        worktree.entry_for_path(relative_path)
1374                                    })
1375                            }
1376                            .map(|entry| entry.id);
1377                            if let Some(entry_id) = entry_id {
1378                                workspace.project.update(cx, |_, cx| {
1379                                    cx.emit(project2::Event::ActiveEntryChanged(Some(entry_id)));
1380                                })
1381                            }
1382                        })
1383                        .log_err()?;
1384                        None
1385                    }
1386                });
1387                tasks.push(task);
1388            }
1389
1390            futures::future::join_all(tasks).await
1391        })
1392    }
1393
1394    //     fn add_folder_to_project(&mut self, _: &AddFolderToProject, cx: &mut ViewContext<Self>) {
1395    //         let mut paths = cx.prompt_for_paths(PathPromptOptions {
1396    //             files: false,
1397    //             directories: true,
1398    //             multiple: true,
1399    //         });
1400    //         cx.spawn(|this, mut cx| async move {
1401    //             if let Some(paths) = paths.recv().await.flatten() {
1402    //                 let results = this
1403    //                     .update(&mut cx, |this, cx| this.open_paths(paths, true, cx))?
1404    //                     .await;
1405    //                 for result in results.into_iter().flatten() {
1406    //                     result.log_err();
1407    //                 }
1408    //             }
1409    //             anyhow::Ok(())
1410    //         })
1411    //         .detach_and_log_err(cx);
1412    //     }
1413
1414    fn project_path_for_path(
1415        project: Model<Project>,
1416        abs_path: &Path,
1417        visible: bool,
1418        cx: &mut AppContext,
1419    ) -> Task<Result<(Model<Worktree>, ProjectPath)>> {
1420        let entry = project.update(cx, |project, cx| {
1421            project.find_or_create_local_worktree(abs_path, visible, cx)
1422        });
1423        cx.spawn(|mut cx| async move {
1424            let (worktree, path) = entry.await?;
1425            let worktree_id = worktree.update(&mut cx, |t, _| t.id())?;
1426            Ok((
1427                worktree,
1428                ProjectPath {
1429                    worktree_id,
1430                    path: path.into(),
1431                },
1432            ))
1433        })
1434    }
1435
1436    pub fn items<'a>(
1437        &'a self,
1438        cx: &'a AppContext,
1439    ) -> impl 'a + Iterator<Item = &Box<dyn ItemHandle>> {
1440        self.panes.iter().flat_map(|pane| pane.read(cx).items())
1441    }
1442
1443    //     pub fn item_of_type<T: Item>(&self, cx: &AppContext) -> Option<View<T>> {
1444    //         self.items_of_type(cx).max_by_key(|item| item.id())
1445    //     }
1446
1447    //     pub fn items_of_type<'a, T: Item>(
1448    //         &'a self,
1449    //         cx: &'a AppContext,
1450    //     ) -> impl 'a + Iterator<Item = View<T>> {
1451    //         self.panes
1452    //             .iter()
1453    //             .flat_map(|pane| pane.read(cx).items_of_type())
1454    //     }
1455
1456    pub fn active_item(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
1457        self.active_pane().read(cx).active_item()
1458    }
1459
1460    fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> {
1461        self.active_item(cx).and_then(|item| item.project_path(cx))
1462    }
1463
1464    pub fn save_active_item(
1465        &mut self,
1466        save_intent: SaveIntent,
1467        cx: &mut ViewContext<Self>,
1468    ) -> Task<Result<()>> {
1469        let project = self.project.clone();
1470        let pane = self.active_pane();
1471        let item_ix = pane.read(cx).active_item_index();
1472        let item = pane.read(cx).active_item();
1473        let pane = pane.downgrade();
1474
1475        cx.spawn(|_, mut cx| async move {
1476            if let Some(item) = item {
1477                Pane::save_item(project, &pane, item_ix, item.as_ref(), save_intent, &mut cx)
1478                    .await
1479                    .map(|_| ())
1480            } else {
1481                Ok(())
1482            }
1483        })
1484    }
1485
1486    //     pub fn close_inactive_items_and_panes(
1487    //         &mut self,
1488    //         _: &CloseInactiveTabsAndPanes,
1489    //         cx: &mut ViewContext<Self>,
1490    //     ) -> Option<Task<Result<()>>> {
1491    //         self.close_all_internal(true, SaveIntent::Close, cx)
1492    //     }
1493
1494    //     pub fn close_all_items_and_panes(
1495    //         &mut self,
1496    //         action: &CloseAllItemsAndPanes,
1497    //         cx: &mut ViewContext<Self>,
1498    //     ) -> Option<Task<Result<()>>> {
1499    //         self.close_all_internal(false, action.save_intent.unwrap_or(SaveIntent::Close), cx)
1500    //     }
1501
1502    //     fn close_all_internal(
1503    //         &mut self,
1504    //         retain_active_pane: bool,
1505    //         save_intent: SaveIntent,
1506    //         cx: &mut ViewContext<Self>,
1507    //     ) -> Option<Task<Result<()>>> {
1508    //         let current_pane = self.active_pane();
1509
1510    //         let mut tasks = Vec::new();
1511
1512    //         if retain_active_pane {
1513    //             if let Some(current_pane_close) = current_pane.update(cx, |pane, cx| {
1514    //                 pane.close_inactive_items(&CloseInactiveItems, cx)
1515    //             }) {
1516    //                 tasks.push(current_pane_close);
1517    //             };
1518    //         }
1519
1520    //         for pane in self.panes() {
1521    //             if retain_active_pane && pane.id() == current_pane.id() {
1522    //                 continue;
1523    //             }
1524
1525    //             if let Some(close_pane_items) = pane.update(cx, |pane: &mut Pane, cx| {
1526    //                 pane.close_all_items(
1527    //                     &CloseAllItems {
1528    //                         save_intent: Some(save_intent),
1529    //                     },
1530    //                     cx,
1531    //                 )
1532    //             }) {
1533    //                 tasks.push(close_pane_items)
1534    //             }
1535    //         }
1536
1537    //         if tasks.is_empty() {
1538    //             None
1539    //         } else {
1540    //             Some(cx.spawn(|_, _| async move {
1541    //                 for task in tasks {
1542    //                     task.await?
1543    //                 }
1544    //                 Ok(())
1545    //             }))
1546    //         }
1547    //     }
1548
1549    pub fn toggle_dock(&mut self, dock_side: DockPosition, cx: &mut ViewContext<Self>) {
1550        let dock = match dock_side {
1551            DockPosition::Left => &self.left_dock,
1552            DockPosition::Bottom => &self.bottom_dock,
1553            DockPosition::Right => &self.right_dock,
1554        };
1555        let mut focus_center = false;
1556        let mut reveal_dock = false;
1557        dock.update(cx, |dock, cx| {
1558            let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
1559            let was_visible = dock.is_open() && !other_is_zoomed;
1560            dock.set_open(!was_visible, cx);
1561
1562            if let Some(active_panel) = dock.active_panel() {
1563                if was_visible {
1564                    if active_panel.has_focus(cx) {
1565                        focus_center = true;
1566                    }
1567                } else {
1568                    let focus_handle = &active_panel.focus_handle(cx);
1569                    cx.focus(focus_handle);
1570                    reveal_dock = true;
1571                }
1572            }
1573        });
1574
1575        if reveal_dock {
1576            self.dismiss_zoomed_items_to_reveal(Some(dock_side), cx);
1577        }
1578
1579        if focus_center {
1580            cx.focus(&self.focus_handle);
1581        }
1582
1583        cx.notify();
1584        self.serialize_workspace(cx);
1585    }
1586
1587    pub fn close_all_docks(&mut self, cx: &mut ViewContext<Self>) {
1588        let docks = [&self.left_dock, &self.bottom_dock, &self.right_dock];
1589
1590        for dock in docks {
1591            dock.update(cx, |dock, cx| {
1592                dock.set_open(false, cx);
1593            });
1594        }
1595
1596        // todo!("focus")
1597        // cx.focus_self();
1598        cx.notify();
1599        self.serialize_workspace(cx);
1600    }
1601
1602    //     /// Transfer focus to the panel of the given type.
1603    //     pub fn focus_panel<T: Panel>(&mut self, cx: &mut ViewContext<Self>) -> Option<View<T>> {
1604    //         self.focus_or_unfocus_panel::<T>(cx, |_, _| true)?
1605    //             .as_any()
1606    //             .clone()
1607    //             .downcast()
1608    //     }
1609
1610    //     /// Focus the panel of the given type if it isn't already focused. If it is
1611    //     /// already focused, then transfer focus back to the workspace center.
1612    //     pub fn toggle_panel_focus<T: Panel>(&mut self, cx: &mut ViewContext<Self>) {
1613    //         self.focus_or_unfocus_panel::<T>(cx, |panel, cx| !panel.has_focus(cx));
1614    //     }
1615
1616    //     /// Focus or unfocus the given panel type, depending on the given callback.
1617    //     fn focus_or_unfocus_panel<T: Panel>(
1618    //         &mut self,
1619    //         cx: &mut ViewContext<Self>,
1620    //         should_focus: impl Fn(&dyn PanelHandle, &mut ViewContext<Dock>) -> bool,
1621    //     ) -> Option<Rc<dyn PanelHandle>> {
1622    //         for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
1623    //             if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
1624    //                 let mut focus_center = false;
1625    //                 let mut reveal_dock = false;
1626    //                 let panel = dock.update(cx, |dock, cx| {
1627    //                     dock.activate_panel(panel_index, cx);
1628
1629    //                     let panel = dock.active_panel().cloned();
1630    //                     if let Some(panel) = panel.as_ref() {
1631    //                         if should_focus(&**panel, cx) {
1632    //                             dock.set_open(true, cx);
1633    //                             cx.focus(panel.as_any());
1634    //                             reveal_dock = true;
1635    //                         } else {
1636    //                             // if panel.is_zoomed(cx) {
1637    //                             //     dock.set_open(false, cx);
1638    //                             // }
1639    //                             focus_center = true;
1640    //                         }
1641    //                     }
1642    //                     panel
1643    //                 });
1644
1645    //                 if focus_center {
1646    //                     cx.focus_self();
1647    //                 }
1648
1649    //                 self.serialize_workspace(cx);
1650    //                 cx.notify();
1651    //                 return panel;
1652    //             }
1653    //         }
1654    //         None
1655    //     }
1656
1657    //     pub fn panel<T: Panel>(&self, cx: &WindowContext) -> Option<View<T>> {
1658    //         for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
1659    //             let dock = dock.read(cx);
1660    //             if let Some(panel) = dock.panel::<T>() {
1661    //                 return Some(panel);
1662    //             }
1663    //         }
1664    //         None
1665    //     }
1666
1667    fn zoom_out(&mut self, cx: &mut ViewContext<Self>) {
1668        for pane in &self.panes {
1669            pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
1670        }
1671
1672        self.left_dock.update(cx, |dock, cx| dock.zoom_out(cx));
1673        self.bottom_dock.update(cx, |dock, cx| dock.zoom_out(cx));
1674        self.right_dock.update(cx, |dock, cx| dock.zoom_out(cx));
1675        self.zoomed = None;
1676        self.zoomed_position = None;
1677
1678        cx.notify();
1679    }
1680
1681    //     #[cfg(any(test, feature = "test-support"))]
1682    //     pub fn zoomed_view(&self, cx: &AppContext) -> Option<AnyViewHandle> {
1683    //         self.zoomed.and_then(|view| view.upgrade(cx))
1684    //     }
1685
1686    fn dismiss_zoomed_items_to_reveal(
1687        &mut self,
1688        dock_to_reveal: Option<DockPosition>,
1689        cx: &mut ViewContext<Self>,
1690    ) {
1691        // If a center pane is zoomed, unzoom it.
1692        for pane in &self.panes {
1693            if pane != &self.active_pane || dock_to_reveal.is_some() {
1694                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
1695            }
1696        }
1697
1698        // If another dock is zoomed, hide it.
1699        let mut focus_center = false;
1700        for dock in [&self.left_dock, &self.right_dock, &self.bottom_dock] {
1701            dock.update(cx, |dock, cx| {
1702                if Some(dock.position()) != dock_to_reveal {
1703                    if let Some(panel) = dock.active_panel() {
1704                        if panel.is_zoomed(cx) {
1705                            focus_center |= panel.has_focus(cx);
1706                            dock.set_open(false, cx);
1707                        }
1708                    }
1709                }
1710            });
1711        }
1712
1713        if focus_center {
1714            cx.focus(&self.focus_handle);
1715        }
1716
1717        if self.zoomed_position != dock_to_reveal {
1718            self.zoomed = None;
1719            self.zoomed_position = None;
1720        }
1721
1722        cx.notify();
1723    }
1724
1725    fn add_pane(&mut self, cx: &mut ViewContext<Self>) -> View<Pane> {
1726        let pane = cx.build_view(|cx| {
1727            Pane::new(
1728                self.weak_handle(),
1729                self.project.clone(),
1730                self.pane_history_timestamp.clone(),
1731                cx,
1732            )
1733        });
1734        cx.subscribe(&pane, Self::handle_pane_event).detach();
1735        self.panes.push(pane.clone());
1736        // todo!()
1737        // cx.focus(&pane);
1738        cx.emit(Event::PaneAdded(pane.clone()));
1739        pane
1740    }
1741
1742    //     pub fn add_item_to_center(
1743    //         &mut self,
1744    //         item: Box<dyn ItemHandle>,
1745    //         cx: &mut ViewContext<Self>,
1746    //     ) -> bool {
1747    //         if let Some(center_pane) = self.last_active_center_pane.clone() {
1748    //             if let Some(center_pane) = center_pane.upgrade(cx) {
1749    //                 center_pane.update(cx, |pane, cx| pane.add_item(item, true, true, None, cx));
1750    //                 true
1751    //             } else {
1752    //                 false
1753    //             }
1754    //         } else {
1755    //             false
1756    //         }
1757    //     }
1758
1759    pub fn add_item(&mut self, item: Box<dyn ItemHandle>, cx: &mut ViewContext<Self>) {
1760        self.active_pane
1761            .update(cx, |pane, cx| pane.add_item(item, true, true, None, cx));
1762    }
1763
1764    pub fn split_item(
1765        &mut self,
1766        split_direction: SplitDirection,
1767        item: Box<dyn ItemHandle>,
1768        cx: &mut ViewContext<Self>,
1769    ) {
1770        let new_pane = self.split_pane(self.active_pane.clone(), split_direction, cx);
1771        new_pane.update(cx, move |new_pane, cx| {
1772            new_pane.add_item(item, true, true, None, cx)
1773        })
1774    }
1775
1776    //     pub fn open_abs_path(
1777    //         &mut self,
1778    //         abs_path: PathBuf,
1779    //         visible: bool,
1780    //         cx: &mut ViewContext<Self>,
1781    //     ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
1782    //         cx.spawn(|workspace, mut cx| async move {
1783    //             let open_paths_task_result = workspace
1784    //                 .update(&mut cx, |workspace, cx| {
1785    //                     workspace.open_paths(vec![abs_path.clone()], visible, cx)
1786    //                 })
1787    //                 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
1788    //                 .await;
1789    //             anyhow::ensure!(
1790    //                 open_paths_task_result.len() == 1,
1791    //                 "open abs path {abs_path:?} task returned incorrect number of results"
1792    //             );
1793    //             match open_paths_task_result
1794    //                 .into_iter()
1795    //                 .next()
1796    //                 .expect("ensured single task result")
1797    //             {
1798    //                 Some(open_result) => {
1799    //                     open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
1800    //                 }
1801    //                 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
1802    //             }
1803    //         })
1804    //     }
1805
1806    //     pub fn split_abs_path(
1807    //         &mut self,
1808    //         abs_path: PathBuf,
1809    //         visible: bool,
1810    //         cx: &mut ViewContext<Self>,
1811    //     ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
1812    //         let project_path_task =
1813    //             Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
1814    //         cx.spawn(|this, mut cx| async move {
1815    //             let (_, path) = project_path_task.await?;
1816    //             this.update(&mut cx, |this, cx| this.split_path(path, cx))?
1817    //                 .await
1818    //         })
1819    //     }
1820
1821    pub fn open_path(
1822        &mut self,
1823        path: impl Into<ProjectPath>,
1824        pane: Option<WeakView<Pane>>,
1825        focus_item: bool,
1826        cx: &mut ViewContext<Self>,
1827    ) -> Task<Result<Box<dyn ItemHandle>, anyhow::Error>> {
1828        let pane = pane.unwrap_or_else(|| {
1829            self.last_active_center_pane.clone().unwrap_or_else(|| {
1830                self.panes
1831                    .first()
1832                    .expect("There must be an active pane")
1833                    .downgrade()
1834            })
1835        });
1836
1837        let task = self.load_path(path.into(), cx);
1838        cx.spawn(move |_, mut cx| async move {
1839            let (project_entry_id, build_item) = task.await?;
1840            pane.update(&mut cx, |pane, cx| {
1841                pane.open_item(project_entry_id, focus_item, cx, build_item)
1842            })
1843        })
1844    }
1845
1846    //     pub fn split_path(
1847    //         &mut self,
1848    //         path: impl Into<ProjectPath>,
1849    //         cx: &mut ViewContext<Self>,
1850    //     ) -> Task<Result<Box<dyn ItemHandle>, anyhow::Error>> {
1851    //         let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
1852    //             self.panes
1853    //                 .first()
1854    //                 .expect("There must be an active pane")
1855    //                 .downgrade()
1856    //         });
1857
1858    //         if let Member::Pane(center_pane) = &self.center.root {
1859    //             if center_pane.read(cx).items_len() == 0 {
1860    //                 return self.open_path(path, Some(pane), true, cx);
1861    //             }
1862    //         }
1863
1864    //         let task = self.load_path(path.into(), cx);
1865    //         cx.spawn(|this, mut cx| async move {
1866    //             let (project_entry_id, build_item) = task.await?;
1867    //             this.update(&mut cx, move |this, cx| -> Option<_> {
1868    //                 let pane = pane.upgrade(cx)?;
1869    //                 let new_pane = this.split_pane(pane, SplitDirection::Right, cx);
1870    //                 new_pane.update(cx, |new_pane, cx| {
1871    //                     Some(new_pane.open_item(project_entry_id, true, cx, build_item))
1872    //                 })
1873    //             })
1874    //             .map(|option| option.ok_or_else(|| anyhow!("pane was dropped")))?
1875    //         })
1876    //     }
1877
1878    pub(crate) fn load_path(
1879        &mut self,
1880        path: ProjectPath,
1881        cx: &mut ViewContext<Self>,
1882    ) -> Task<
1883        Result<(
1884            ProjectEntryId,
1885            impl 'static + Send + FnOnce(&mut ViewContext<Pane>) -> Box<dyn ItemHandle>,
1886        )>,
1887    > {
1888        let project = self.project().clone();
1889        let project_item = project.update(cx, |project, cx| project.open_path(path, cx));
1890        cx.spawn(|_, mut cx| async move {
1891            let (project_entry_id, project_item) = project_item.await?;
1892            let build_item = cx.update(|_, cx| {
1893                cx.default_global::<ProjectItemBuilders>()
1894                    .get(&project_item.entity_type())
1895                    .ok_or_else(|| anyhow!("no item builder for project item"))
1896                    .cloned()
1897            })??;
1898            let build_item =
1899                move |cx: &mut ViewContext<Pane>| build_item(project, project_item, cx);
1900            Ok((project_entry_id, build_item))
1901        })
1902    }
1903
1904    pub fn open_project_item<T>(
1905        &mut self,
1906        project_item: Model<T::Item>,
1907        cx: &mut ViewContext<Self>,
1908    ) -> View<T>
1909    where
1910        T: ProjectItem,
1911    {
1912        use project2::Item as _;
1913
1914        let entry_id = project_item.read(cx).entry_id(cx);
1915        if let Some(item) = entry_id
1916            .and_then(|entry_id| self.active_pane().read(cx).item_for_entry(entry_id, cx))
1917            .and_then(|item| item.downcast())
1918        {
1919            self.activate_item(&item, cx);
1920            return item;
1921        }
1922
1923        let item =
1924            cx.build_view(|cx| T::for_project_item(self.project().clone(), project_item, cx));
1925        self.add_item(Box::new(item.clone()), cx);
1926        item
1927    }
1928
1929    pub fn split_project_item<T>(
1930        &mut self,
1931        project_item: Model<T::Item>,
1932        cx: &mut ViewContext<Self>,
1933    ) -> View<T>
1934    where
1935        T: ProjectItem,
1936    {
1937        use project2::Item as _;
1938
1939        let entry_id = project_item.read(cx).entry_id(cx);
1940        if let Some(item) = entry_id
1941            .and_then(|entry_id| self.active_pane().read(cx).item_for_entry(entry_id, cx))
1942            .and_then(|item| item.downcast())
1943        {
1944            self.activate_item(&item, cx);
1945            return item;
1946        }
1947
1948        let item =
1949            cx.build_view(|cx| T::for_project_item(self.project().clone(), project_item, cx));
1950        self.split_item(SplitDirection::Right, Box::new(item.clone()), cx);
1951        item
1952    }
1953
1954    //     pub fn open_shared_screen(&mut self, peer_id: PeerId, cx: &mut ViewContext<Self>) {
1955    //         if let Some(shared_screen) = self.shared_screen_for_peer(peer_id, &self.active_pane, cx) {
1956    //             self.active_pane.update(cx, |pane, cx| {
1957    //                 pane.add_item(Box::new(shared_screen), false, true, None, cx)
1958    //             });
1959    //         }
1960    //     }
1961
1962    pub fn activate_item(&mut self, item: &dyn ItemHandle, cx: &mut ViewContext<Self>) -> bool {
1963        let result = self.panes.iter().find_map(|pane| {
1964            pane.read(cx)
1965                .index_for_item(item)
1966                .map(|ix| (pane.clone(), ix))
1967        });
1968        if let Some((pane, ix)) = result {
1969            pane.update(cx, |pane, cx| pane.activate_item(ix, true, true, cx));
1970            true
1971        } else {
1972            false
1973        }
1974    }
1975
1976    //     fn activate_pane_at_index(&mut self, action: &ActivatePane, cx: &mut ViewContext<Self>) {
1977    //         let panes = self.center.panes();
1978    //         if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
1979    //             cx.focus(&pane);
1980    //         } else {
1981    //             self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, cx);
1982    //         }
1983    //     }
1984
1985    //     pub fn activate_next_pane(&mut self, cx: &mut ViewContext<Self>) {
1986    //         let panes = self.center.panes();
1987    //         if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
1988    //             let next_ix = (ix + 1) % panes.len();
1989    //             let next_pane = panes[next_ix].clone();
1990    //             cx.focus(&next_pane);
1991    //         }
1992    //     }
1993
1994    //     pub fn activate_previous_pane(&mut self, cx: &mut ViewContext<Self>) {
1995    //         let panes = self.center.panes();
1996    //         if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
1997    //             let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
1998    //             let prev_pane = panes[prev_ix].clone();
1999    //             cx.focus(&prev_pane);
2000    //         }
2001    //     }
2002
2003    //     pub fn activate_pane_in_direction(
2004    //         &mut self,
2005    //         direction: SplitDirection,
2006    //         cx: &mut ViewContext<Self>,
2007    //     ) {
2008    //         if let Some(pane) = self.find_pane_in_direction(direction, cx) {
2009    //             cx.focus(pane);
2010    //         }
2011    //     }
2012
2013    //     pub fn swap_pane_in_direction(
2014    //         &mut self,
2015    //         direction: SplitDirection,
2016    //         cx: &mut ViewContext<Self>,
2017    //     ) {
2018    //         if let Some(to) = self
2019    //             .find_pane_in_direction(direction, cx)
2020    //             .map(|pane| pane.clone())
2021    //         {
2022    //             self.center.swap(&self.active_pane.clone(), &to);
2023    //             cx.notify();
2024    //         }
2025    //     }
2026
2027    //     fn find_pane_in_direction(
2028    //         &mut self,
2029    //         direction: SplitDirection,
2030    //         cx: &mut ViewContext<Self>,
2031    //     ) -> Option<&View<Pane>> {
2032    //         let Some(bounding_box) = self.center.bounding_box_for_pane(&self.active_pane) else {
2033    //             return None;
2034    //         };
2035    //         let cursor = self.active_pane.read(cx).pixel_position_of_cursor(cx);
2036    //         let center = match cursor {
2037    //             Some(cursor) if bounding_box.contains_point(cursor) => cursor,
2038    //             _ => bounding_box.center(),
2039    //         };
2040
2041    //         let distance_to_next = theme::current(cx).workspace.pane_divider.width + 1.;
2042
2043    //         let target = match direction {
2044    //             SplitDirection::Left => vec2f(bounding_box.origin_x() - distance_to_next, center.y()),
2045    //             SplitDirection::Right => vec2f(bounding_box.max_x() + distance_to_next, center.y()),
2046    //             SplitDirection::Up => vec2f(center.x(), bounding_box.origin_y() - distance_to_next),
2047    //             SplitDirection::Down => vec2f(center.x(), bounding_box.max_y() + distance_to_next),
2048    //         };
2049    //         self.center.pane_at_pixel_position(target)
2050    //     }
2051
2052    fn handle_pane_focused(&mut self, pane: View<Pane>, cx: &mut ViewContext<Self>) {
2053        if self.active_pane != pane {
2054            self.active_pane = pane.clone();
2055            self.status_bar.update(cx, |status_bar, cx| {
2056                status_bar.set_active_pane(&self.active_pane, cx);
2057            });
2058            self.active_item_path_changed(cx);
2059            self.last_active_center_pane = Some(pane.downgrade());
2060        }
2061
2062        self.dismiss_zoomed_items_to_reveal(None, cx);
2063        if pane.read(cx).is_zoomed() {
2064            self.zoomed = Some(pane.downgrade().into());
2065        } else {
2066            self.zoomed = None;
2067        }
2068        self.zoomed_position = None;
2069        self.update_active_view_for_followers(cx);
2070
2071        cx.notify();
2072    }
2073
2074    fn handle_pane_event(
2075        &mut self,
2076        pane: View<Pane>,
2077        event: &pane::Event,
2078        cx: &mut ViewContext<Self>,
2079    ) {
2080        match event {
2081            pane::Event::AddItem { item } => item.added_to_pane(self, pane, cx),
2082            pane::Event::Split(direction) => {
2083                self.split_and_clone(pane, *direction, cx);
2084            }
2085            pane::Event::Remove => self.remove_pane(pane, cx),
2086            pane::Event::ActivateItem { local } => {
2087                if *local {
2088                    self.unfollow(&pane, cx);
2089                }
2090                if &pane == self.active_pane() {
2091                    self.active_item_path_changed(cx);
2092                }
2093            }
2094            pane::Event::ChangeItemTitle => {
2095                if pane == self.active_pane {
2096                    self.active_item_path_changed(cx);
2097                }
2098                self.update_window_edited(cx);
2099            }
2100            pane::Event::RemoveItem { item_id } => {
2101                self.update_window_edited(cx);
2102                if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(*item_id) {
2103                    if entry.get().entity_id() == pane.entity_id() {
2104                        entry.remove();
2105                    }
2106                }
2107            }
2108            pane::Event::Focus => {
2109                self.handle_pane_focused(pane.clone(), cx);
2110            }
2111            pane::Event::ZoomIn => {
2112                if pane == self.active_pane {
2113                    pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
2114                    if pane.read(cx).has_focus(cx) {
2115                        self.zoomed = Some(pane.downgrade().into());
2116                        self.zoomed_position = None;
2117                    }
2118                    cx.notify();
2119                }
2120            }
2121            pane::Event::ZoomOut => {
2122                pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
2123                if self.zoomed_position.is_none() {
2124                    self.zoomed = None;
2125                }
2126                cx.notify();
2127            }
2128        }
2129
2130        self.serialize_workspace(cx);
2131    }
2132
2133    pub fn split_pane(
2134        &mut self,
2135        pane_to_split: View<Pane>,
2136        split_direction: SplitDirection,
2137        cx: &mut ViewContext<Self>,
2138    ) -> View<Pane> {
2139        let new_pane = self.add_pane(cx);
2140        self.center
2141            .split(&pane_to_split, &new_pane, split_direction)
2142            .unwrap();
2143        cx.notify();
2144        new_pane
2145    }
2146
2147    pub fn split_and_clone(
2148        &mut self,
2149        pane: View<Pane>,
2150        direction: SplitDirection,
2151        cx: &mut ViewContext<Self>,
2152    ) -> Option<View<Pane>> {
2153        let item = pane.read(cx).active_item()?;
2154        let maybe_pane_handle = if let Some(clone) = item.clone_on_split(self.database_id(), cx) {
2155            let new_pane = self.add_pane(cx);
2156            new_pane.update(cx, |pane, cx| pane.add_item(clone, true, true, None, cx));
2157            self.center.split(&pane, &new_pane, direction).unwrap();
2158            Some(new_pane)
2159        } else {
2160            None
2161        };
2162        cx.notify();
2163        maybe_pane_handle
2164    }
2165
2166    pub fn split_pane_with_item(
2167        &mut self,
2168        pane_to_split: WeakView<Pane>,
2169        split_direction: SplitDirection,
2170        from: WeakView<Pane>,
2171        item_id_to_move: EntityId,
2172        cx: &mut ViewContext<Self>,
2173    ) {
2174        let Some(pane_to_split) = pane_to_split.upgrade() else {
2175            return;
2176        };
2177        let Some(from) = from.upgrade() else {
2178            return;
2179        };
2180
2181        let new_pane = self.add_pane(cx);
2182        self.move_item(from.clone(), new_pane.clone(), item_id_to_move, 0, cx);
2183        self.center
2184            .split(&pane_to_split, &new_pane, split_direction)
2185            .unwrap();
2186        cx.notify();
2187    }
2188
2189    pub fn split_pane_with_project_entry(
2190        &mut self,
2191        pane_to_split: WeakView<Pane>,
2192        split_direction: SplitDirection,
2193        project_entry: ProjectEntryId,
2194        cx: &mut ViewContext<Self>,
2195    ) -> Option<Task<Result<()>>> {
2196        let pane_to_split = pane_to_split.upgrade()?;
2197        let new_pane = self.add_pane(cx);
2198        self.center
2199            .split(&pane_to_split, &new_pane, split_direction)
2200            .unwrap();
2201
2202        let path = self.project.read(cx).path_for_entry(project_entry, cx)?;
2203        let task = self.open_path(path, Some(new_pane.downgrade()), true, cx);
2204        Some(cx.foreground_executor().spawn(async move {
2205            task.await?;
2206            Ok(())
2207        }))
2208    }
2209
2210    pub fn move_item(
2211        &mut self,
2212        source: View<Pane>,
2213        destination: View<Pane>,
2214        item_id_to_move: EntityId,
2215        destination_index: usize,
2216        cx: &mut ViewContext<Self>,
2217    ) {
2218        let item_to_move = source
2219            .read(cx)
2220            .items()
2221            .enumerate()
2222            .find(|(_, item_handle)| item_handle.id() == item_id_to_move);
2223
2224        if item_to_move.is_none() {
2225            log::warn!("Tried to move item handle which was not in `from` pane. Maybe tab was closed during drop");
2226            return;
2227        }
2228        let (item_ix, item_handle) = item_to_move.unwrap();
2229        let item_handle = item_handle.clone();
2230
2231        if source != destination {
2232            // Close item from previous pane
2233            source.update(cx, |source, cx| {
2234                source.remove_item(item_ix, false, cx);
2235            });
2236        }
2237
2238        // This automatically removes duplicate items in the pane
2239        destination.update(cx, |destination, cx| {
2240            destination.add_item(item_handle, true, true, Some(destination_index), cx);
2241            destination.focus(cx)
2242        });
2243    }
2244
2245    fn remove_pane(&mut self, pane: View<Pane>, cx: &mut ViewContext<Self>) {
2246        if self.center.remove(&pane).unwrap() {
2247            self.force_remove_pane(&pane, cx);
2248            self.unfollow(&pane, cx);
2249            self.last_leaders_by_pane.remove(&pane.downgrade());
2250            for removed_item in pane.read(cx).items() {
2251                self.panes_by_item.remove(&removed_item.id());
2252            }
2253
2254            cx.notify();
2255        } else {
2256            self.active_item_path_changed(cx);
2257        }
2258    }
2259
2260    pub fn panes(&self) -> &[View<Pane>] {
2261        &self.panes
2262    }
2263
2264    pub fn active_pane(&self) -> &View<Pane> {
2265        &self.active_pane
2266    }
2267
2268    fn collaborator_left(&mut self, peer_id: PeerId, cx: &mut ViewContext<Self>) {
2269        self.follower_states.retain(|_, state| {
2270            if state.leader_id == peer_id {
2271                for item in state.items_by_leader_view_id.values() {
2272                    item.set_leader_peer_id(None, cx);
2273                }
2274                false
2275            } else {
2276                true
2277            }
2278        });
2279        cx.notify();
2280    }
2281
2282    //     fn start_following(
2283    //         &mut self,
2284    //         leader_id: PeerId,
2285    //         cx: &mut ViewContext<Self>,
2286    //     ) -> Option<Task<Result<()>>> {
2287    //         let pane = self.active_pane().clone();
2288
2289    //         self.last_leaders_by_pane
2290    //             .insert(pane.downgrade(), leader_id);
2291    //         self.unfollow(&pane, cx);
2292    //         self.follower_states.insert(
2293    //             pane.clone(),
2294    //             FollowerState {
2295    //                 leader_id,
2296    //                 active_view_id: None,
2297    //                 items_by_leader_view_id: Default::default(),
2298    //             },
2299    //         );
2300    //         cx.notify();
2301
2302    //         let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
2303    //         let project_id = self.project.read(cx).remote_id();
2304    //         let request = self.app_state.client.request(proto::Follow {
2305    //             room_id,
2306    //             project_id,
2307    //             leader_id: Some(leader_id),
2308    //         });
2309
2310    //         Some(cx.spawn(|this, mut cx| async move {
2311    //             let response = request.await?;
2312    //             this.update(&mut cx, |this, _| {
2313    //                 let state = this
2314    //                     .follower_states
2315    //                     .get_mut(&pane)
2316    //                     .ok_or_else(|| anyhow!("following interrupted"))?;
2317    //                 state.active_view_id = if let Some(active_view_id) = response.active_view_id {
2318    //                     Some(ViewId::from_proto(active_view_id)?)
2319    //                 } else {
2320    //                     None
2321    //                 };
2322    //                 Ok::<_, anyhow::Error>(())
2323    //             })??;
2324    //             Self::add_views_from_leader(
2325    //                 this.clone(),
2326    //                 leader_id,
2327    //                 vec![pane],
2328    //                 response.views,
2329    //                 &mut cx,
2330    //             )
2331    //             .await?;
2332    //             this.update(&mut cx, |this, cx| this.leader_updated(leader_id, cx))?;
2333    //             Ok(())
2334    //         }))
2335    //     }
2336
2337    //     pub fn follow_next_collaborator(
2338    //         &mut self,
2339    //         _: &FollowNextCollaborator,
2340    //         cx: &mut ViewContext<Self>,
2341    //     ) -> Option<Task<Result<()>>> {
2342    //         let collaborators = self.project.read(cx).collaborators();
2343    //         let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
2344    //             let mut collaborators = collaborators.keys().copied();
2345    //             for peer_id in collaborators.by_ref() {
2346    //                 if peer_id == leader_id {
2347    //                     break;
2348    //                 }
2349    //             }
2350    //             collaborators.next()
2351    //         } else if let Some(last_leader_id) =
2352    //             self.last_leaders_by_pane.get(&self.active_pane.downgrade())
2353    //         {
2354    //             if collaborators.contains_key(last_leader_id) {
2355    //                 Some(*last_leader_id)
2356    //             } else {
2357    //                 None
2358    //             }
2359    //         } else {
2360    //             None
2361    //         };
2362
2363    //         let pane = self.active_pane.clone();
2364    //         let Some(leader_id) = next_leader_id.or_else(|| collaborators.keys().copied().next())
2365    //         else {
2366    //             return None;
2367    //         };
2368    //         if Some(leader_id) == self.unfollow(&pane, cx) {
2369    //             return None;
2370    //         }
2371    //         self.follow(leader_id, cx)
2372    //     }
2373
2374    //     pub fn follow(
2375    //         &mut self,
2376    //         leader_id: PeerId,
2377    //         cx: &mut ViewContext<Self>,
2378    //     ) -> Option<Task<Result<()>>> {
2379    //         let room = ActiveCall::global(cx).read(cx).room()?.read(cx);
2380    //         let project = self.project.read(cx);
2381
2382    //         let Some(remote_participant) = room.remote_participant_for_peer_id(leader_id) else {
2383    //             return None;
2384    //         };
2385
2386    //         let other_project_id = match remote_participant.location {
2387    //             call::ParticipantLocation::External => None,
2388    //             call::ParticipantLocation::UnsharedProject => None,
2389    //             call::ParticipantLocation::SharedProject { project_id } => {
2390    //                 if Some(project_id) == project.remote_id() {
2391    //                     None
2392    //                 } else {
2393    //                     Some(project_id)
2394    //                 }
2395    //             }
2396    //         };
2397
2398    //         // if they are active in another project, follow there.
2399    //         if let Some(project_id) = other_project_id {
2400    //             let app_state = self.app_state.clone();
2401    //             return Some(crate::join_remote_project(
2402    //                 project_id,
2403    //                 remote_participant.user.id,
2404    //                 app_state,
2405    //                 cx,
2406    //             ));
2407    //         }
2408
2409    //         // if you're already following, find the right pane and focus it.
2410    //         for (pane, state) in &self.follower_states {
2411    //             if leader_id == state.leader_id {
2412    //                 cx.focus(pane);
2413    //                 return None;
2414    //             }
2415    //         }
2416
2417    //         // Otherwise, follow.
2418    //         self.start_following(leader_id, cx)
2419    //     }
2420
2421    pub fn unfollow(&mut self, pane: &View<Pane>, cx: &mut ViewContext<Self>) -> Option<PeerId> {
2422        let state = self.follower_states.remove(pane)?;
2423        let leader_id = state.leader_id;
2424        for (_, item) in state.items_by_leader_view_id {
2425            item.set_leader_peer_id(None, cx);
2426        }
2427
2428        if self
2429            .follower_states
2430            .values()
2431            .all(|state| state.leader_id != state.leader_id)
2432        {
2433            let project_id = self.project.read(cx).remote_id();
2434            let room_id = self.active_call()?.read(cx).room()?.read(cx).id();
2435            self.app_state
2436                .client
2437                .send(proto::Unfollow {
2438                    room_id,
2439                    project_id,
2440                    leader_id: Some(leader_id),
2441                })
2442                .log_err();
2443        }
2444
2445        cx.notify();
2446        Some(leader_id)
2447    }
2448
2449    //     pub fn is_being_followed(&self, peer_id: PeerId) -> bool {
2450    //         self.follower_states
2451    //             .values()
2452    //             .any(|state| state.leader_id == peer_id)
2453    //     }
2454
2455    fn render_titlebar(&self, cx: &mut ViewContext<Self>) -> impl Component<Self> {
2456        h_stack()
2457            .id("titlebar")
2458            .justify_between()
2459            .when(
2460                !matches!(cx.window_bounds(), WindowBounds::Fullscreen),
2461                |s| s.pl_20(),
2462            )
2463            .w_full()
2464            .h(rems(1.75))
2465            .bg(cx.theme().colors().title_bar_background)
2466            .on_click(|_, event, cx| {
2467                if event.up.click_count == 2 {
2468                    cx.zoom_window();
2469                }
2470            })
2471            .child(
2472                h_stack()
2473                    // TODO - Add player menu
2474                    .child(
2475                        Button::new("player")
2476                            .variant(ButtonVariant::Ghost)
2477                            .color(Some(LabelColor::Player(0))),
2478                    )
2479                    // TODO - Add project menu
2480                    .child(Button::new("project_name").variant(ButtonVariant::Ghost))
2481                    // TODO - Add git menu
2482                    .child(
2483                        Button::new("branch_name")
2484                            .variant(ButtonVariant::Ghost)
2485                            .color(Some(LabelColor::Muted)),
2486                    ),
2487            ) // self.titlebar_item
2488            .child(h_stack().child(Label::new("Right side titlebar item")))
2489    }
2490
2491    fn active_item_path_changed(&mut self, cx: &mut ViewContext<Self>) {
2492        let active_entry = self.active_project_path(cx);
2493        self.project
2494            .update(cx, |project, cx| project.set_active_path(active_entry, cx));
2495        self.update_window_title(cx);
2496    }
2497
2498    fn update_window_title(&mut self, cx: &mut ViewContext<Self>) {
2499        let project = self.project().read(cx);
2500        let mut title = String::new();
2501
2502        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
2503            let filename = path
2504                .path
2505                .file_name()
2506                .map(|s| s.to_string_lossy())
2507                .or_else(|| {
2508                    Some(Cow::Borrowed(
2509                        project
2510                            .worktree_for_id(path.worktree_id, cx)?
2511                            .read(cx)
2512                            .root_name(),
2513                    ))
2514                });
2515
2516            if let Some(filename) = filename {
2517                title.push_str(filename.as_ref());
2518                title.push_str(" β€” ");
2519            }
2520        }
2521
2522        for (i, name) in project.worktree_root_names(cx).enumerate() {
2523            if i > 0 {
2524                title.push_str(", ");
2525            }
2526            title.push_str(name);
2527        }
2528
2529        if title.is_empty() {
2530            title = "empty project".to_string();
2531        }
2532
2533        if project.is_remote() {
2534            title.push_str(" ↙");
2535        } else if project.is_shared() {
2536            title.push_str(" β†—");
2537        }
2538
2539        // todo!()
2540        // cx.set_window_title(&title);
2541    }
2542
2543    fn update_window_edited(&mut self, cx: &mut ViewContext<Self>) {
2544        let is_edited = !self.project.read(cx).is_read_only()
2545            && self
2546                .items(cx)
2547                .any(|item| item.has_conflict(cx) || item.is_dirty(cx));
2548        if is_edited != self.window_edited {
2549            self.window_edited = is_edited;
2550            // todo!()
2551            // cx.set_window_edited(self.window_edited)
2552        }
2553    }
2554
2555    //     fn render_disconnected_overlay(
2556    //         &self,
2557    //         cx: &mut ViewContext<Workspace>,
2558    //     ) -> Option<AnyElement<Workspace>> {
2559    //         if self.project.read(cx).is_read_only() {
2560    //             enum DisconnectedOverlay {}
2561    //             Some(
2562    //                 MouseEventHandler::new::<DisconnectedOverlay, _>(0, cx, |_, cx| {
2563    //                     let theme = &theme::current(cx);
2564    //                     Label::new(
2565    //                         "Your connection to the remote project has been lost.",
2566    //                         theme.workspace.disconnected_overlay.text.clone(),
2567    //                     )
2568    //                     .aligned()
2569    //                     .contained()
2570    //                     .with_style(theme.workspace.disconnected_overlay.container)
2571    //                 })
2572    //                 .with_cursor_style(CursorStyle::Arrow)
2573    //                 .capture_all()
2574    //                 .into_any_named("disconnected overlay"),
2575    //             )
2576    //         } else {
2577    //             None
2578    //         }
2579    //     }
2580
2581    //     fn render_notifications(
2582    //         &self,
2583    //         theme: &theme::Workspace,
2584    //         cx: &AppContext,
2585    //     ) -> Option<AnyElement<Workspace>> {
2586    //         if self.notifications.is_empty() {
2587    //             None
2588    //         } else {
2589    //             Some(
2590    //                 Flex::column()
2591    //                     .with_children(self.notifications.iter().map(|(_, _, notification)| {
2592    //                         ChildView::new(notification.as_any(), cx)
2593    //                             .contained()
2594    //                             .with_style(theme.notification)
2595    //                     }))
2596    //                     .constrained()
2597    //                     .with_width(theme.notifications.width)
2598    //                     .contained()
2599    //                     .with_style(theme.notifications.container)
2600    //                     .aligned()
2601    //                     .bottom()
2602    //                     .right()
2603    //                     .into_any(),
2604    //             )
2605    //         }
2606    //     }
2607
2608    //     // RPC handlers
2609
2610    fn handle_follow(
2611        &mut self,
2612        _follower_project_id: Option<u64>,
2613        _cx: &mut ViewContext<Self>,
2614    ) -> proto::FollowResponse {
2615        todo!()
2616
2617        //     let client = &self.app_state.client;
2618        //     let project_id = self.project.read(cx).remote_id();
2619
2620        //     let active_view_id = self.active_item(cx).and_then(|i| {
2621        //         Some(
2622        //             i.to_followable_item_handle(cx)?
2623        //                 .remote_id(client, cx)?
2624        //                 .to_proto(),
2625        //         )
2626        //     });
2627
2628        //     cx.notify();
2629
2630        //     self.last_active_view_id = active_view_id.clone();
2631        //     proto::FollowResponse {
2632        //         active_view_id,
2633        //         views: self
2634        //             .panes()
2635        //             .iter()
2636        //             .flat_map(|pane| {
2637        //                 let leader_id = self.leader_for_pane(pane);
2638        //                 pane.read(cx).items().filter_map({
2639        //                     let cx = &cx;
2640        //                     move |item| {
2641        //                         let item = item.to_followable_item_handle(cx)?;
2642        //                         if (project_id.is_none() || project_id != follower_project_id)
2643        //                             && item.is_project_item(cx)
2644        //                         {
2645        //                             return None;
2646        //                         }
2647        //                         let id = item.remote_id(client, cx)?.to_proto();
2648        //                         let variant = item.to_state_proto(cx)?;
2649        //                         Some(proto::View {
2650        //                             id: Some(id),
2651        //                             leader_id,
2652        //                             variant: Some(variant),
2653        //                         })
2654        //                     }
2655        //                 })
2656        //             })
2657        //             .collect(),
2658        //     }
2659    }
2660
2661    fn handle_update_followers(
2662        &mut self,
2663        leader_id: PeerId,
2664        message: proto::UpdateFollowers,
2665        _cx: &mut ViewContext<Self>,
2666    ) {
2667        self.leader_updates_tx
2668            .unbounded_send((leader_id, message))
2669            .ok();
2670    }
2671
2672    async fn process_leader_update(
2673        this: &WeakView<Self>,
2674        leader_id: PeerId,
2675        update: proto::UpdateFollowers,
2676        cx: &mut AsyncWindowContext,
2677    ) -> Result<()> {
2678        match update.variant.ok_or_else(|| anyhow!("invalid update"))? {
2679            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
2680                this.update(cx, |this, _| {
2681                    for (_, state) in &mut this.follower_states {
2682                        if state.leader_id == leader_id {
2683                            state.active_view_id =
2684                                if let Some(active_view_id) = update_active_view.id.clone() {
2685                                    Some(ViewId::from_proto(active_view_id)?)
2686                                } else {
2687                                    None
2688                                };
2689                        }
2690                    }
2691                    anyhow::Ok(())
2692                })??;
2693            }
2694            proto::update_followers::Variant::UpdateView(update_view) => {
2695                let variant = update_view
2696                    .variant
2697                    .ok_or_else(|| anyhow!("missing update view variant"))?;
2698                let id = update_view
2699                    .id
2700                    .ok_or_else(|| anyhow!("missing update view id"))?;
2701                let mut tasks = Vec::new();
2702                this.update(cx, |this, cx| {
2703                    let project = this.project.clone();
2704                    for (_, state) in &mut this.follower_states {
2705                        if state.leader_id == leader_id {
2706                            let view_id = ViewId::from_proto(id.clone())?;
2707                            if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
2708                                tasks.push(item.apply_update_proto(&project, variant.clone(), cx));
2709                            }
2710                        }
2711                    }
2712                    anyhow::Ok(())
2713                })??;
2714                try_join_all(tasks).await.log_err();
2715            }
2716            proto::update_followers::Variant::CreateView(view) => {
2717                let panes = this.update(cx, |this, _| {
2718                    this.follower_states
2719                        .iter()
2720                        .filter_map(|(pane, state)| (state.leader_id == leader_id).then_some(pane))
2721                        .cloned()
2722                        .collect()
2723                })?;
2724                Self::add_views_from_leader(this.clone(), leader_id, panes, vec![view], cx).await?;
2725            }
2726        }
2727        this.update(cx, |this, cx| this.leader_updated(leader_id, cx))?;
2728        Ok(())
2729    }
2730
2731    async fn add_views_from_leader(
2732        this: WeakView<Self>,
2733        leader_id: PeerId,
2734        panes: Vec<View<Pane>>,
2735        views: Vec<proto::View>,
2736        cx: &mut AsyncWindowContext,
2737    ) -> Result<()> {
2738        let this = this.upgrade().context("workspace dropped")?;
2739
2740        let item_builders = cx.update(|_, cx| {
2741            cx.default_global::<FollowableItemBuilders>()
2742                .values()
2743                .map(|b| b.0)
2744                .collect::<Vec<_>>()
2745        })?;
2746
2747        let mut item_tasks_by_pane = HashMap::default();
2748        for pane in panes {
2749            let mut item_tasks = Vec::new();
2750            let mut leader_view_ids = Vec::new();
2751            for view in &views {
2752                let Some(id) = &view.id else { continue };
2753                let id = ViewId::from_proto(id.clone())?;
2754                let mut variant = view.variant.clone();
2755                if variant.is_none() {
2756                    Err(anyhow!("missing view variant"))?;
2757                }
2758                for build_item in &item_builders {
2759                    let task = cx.update(|_, cx| {
2760                        build_item(pane.clone(), this.clone(), id, &mut variant, cx)
2761                    })?;
2762                    if let Some(task) = task {
2763                        item_tasks.push(task);
2764                        leader_view_ids.push(id);
2765                        break;
2766                    } else {
2767                        assert!(variant.is_some());
2768                    }
2769                }
2770            }
2771
2772            item_tasks_by_pane.insert(pane, (item_tasks, leader_view_ids));
2773        }
2774
2775        for (pane, (item_tasks, leader_view_ids)) in item_tasks_by_pane {
2776            let items = futures::future::try_join_all(item_tasks).await?;
2777            this.update(cx, |this, cx| {
2778                let state = this.follower_states.get_mut(&pane)?;
2779                for (id, item) in leader_view_ids.into_iter().zip(items) {
2780                    item.set_leader_peer_id(Some(leader_id), cx);
2781                    state.items_by_leader_view_id.insert(id, item);
2782                }
2783
2784                Some(())
2785            })?;
2786        }
2787        Ok(())
2788    }
2789
2790    fn update_active_view_for_followers(&mut self, cx: &mut ViewContext<Self>) {
2791        let mut is_project_item = true;
2792        let mut update = proto::UpdateActiveView::default();
2793        if self.active_pane.read(cx).has_focus(cx) {
2794            let item = self
2795                .active_item(cx)
2796                .and_then(|item| item.to_followable_item_handle(cx));
2797            if let Some(item) = item {
2798                is_project_item = item.is_project_item(cx);
2799                update = proto::UpdateActiveView {
2800                    id: item
2801                        .remote_id(&self.app_state.client, cx)
2802                        .map(|id| id.to_proto()),
2803                    leader_id: self.leader_for_pane(&self.active_pane),
2804                };
2805            }
2806        }
2807
2808        if update.id != self.last_active_view_id {
2809            self.last_active_view_id = update.id.clone();
2810            self.update_followers(
2811                is_project_item,
2812                proto::update_followers::Variant::UpdateActiveView(update),
2813                cx,
2814            );
2815        }
2816    }
2817
2818    fn update_followers(
2819        &self,
2820        project_only: bool,
2821        update: proto::update_followers::Variant,
2822        cx: &mut WindowContext,
2823    ) -> Option<()> {
2824        let project_id = if project_only {
2825            self.project.read(cx).remote_id()
2826        } else {
2827            None
2828        };
2829        self.app_state().workspace_store.update(cx, |store, cx| {
2830            store.update_followers(project_id, update, cx)
2831        })
2832    }
2833
2834    pub fn leader_for_pane(&self, pane: &View<Pane>) -> Option<PeerId> {
2835        self.follower_states.get(pane).map(|state| state.leader_id)
2836    }
2837
2838    fn leader_updated(&mut self, leader_id: PeerId, cx: &mut ViewContext<Self>) -> Option<()> {
2839        cx.notify();
2840
2841        let call = self.active_call()?;
2842        let room = call.read(cx).room()?.read(cx);
2843        let participant = room.remote_participant_for_peer_id(leader_id)?;
2844        let mut items_to_activate = Vec::new();
2845
2846        let leader_in_this_app;
2847        let leader_in_this_project;
2848        match participant.location {
2849            call2::ParticipantLocation::SharedProject { project_id } => {
2850                leader_in_this_app = true;
2851                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
2852            }
2853            call2::ParticipantLocation::UnsharedProject => {
2854                leader_in_this_app = true;
2855                leader_in_this_project = false;
2856            }
2857            call2::ParticipantLocation::External => {
2858                leader_in_this_app = false;
2859                leader_in_this_project = false;
2860            }
2861        };
2862
2863        for (pane, state) in &self.follower_states {
2864            if state.leader_id != leader_id {
2865                continue;
2866            }
2867            if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
2868                if let Some(item) = state.items_by_leader_view_id.get(&active_view_id) {
2869                    if leader_in_this_project || !item.is_project_item(cx) {
2870                        items_to_activate.push((pane.clone(), item.boxed_clone()));
2871                    }
2872                } else {
2873                    log::warn!(
2874                        "unknown view id {:?} for leader {:?}",
2875                        active_view_id,
2876                        leader_id
2877                    );
2878                }
2879                continue;
2880            }
2881            // todo!()
2882            // if let Some(shared_screen) = self.shared_screen_for_peer(leader_id, pane, cx) {
2883            //     items_to_activate.push((pane.clone(), Box::new(shared_screen)));
2884            // }
2885        }
2886
2887        for (pane, item) in items_to_activate {
2888            let pane_was_focused = pane.read(cx).has_focus(cx);
2889            if let Some(index) = pane.update(cx, |pane, _| pane.index_for_item(item.as_ref())) {
2890                pane.update(cx, |pane, cx| pane.activate_item(index, false, false, cx));
2891            } else {
2892                pane.update(cx, |pane, cx| {
2893                    pane.add_item(item.boxed_clone(), false, false, None, cx)
2894                });
2895            }
2896
2897            if pane_was_focused {
2898                pane.update(cx, |pane, cx| pane.focus_active_item(cx));
2899            }
2900        }
2901
2902        None
2903    }
2904
2905    // todo!()
2906    //     fn shared_screen_for_peer(
2907    //         &self,
2908    //         peer_id: PeerId,
2909    //         pane: &View<Pane>,
2910    //         cx: &mut ViewContext<Self>,
2911    //     ) -> Option<View<SharedScreen>> {
2912    //         let call = self.active_call()?;
2913    //         let room = call.read(cx).room()?.read(cx);
2914    //         let participant = room.remote_participant_for_peer_id(peer_id)?;
2915    //         let track = participant.video_tracks.values().next()?.clone();
2916    //         let user = participant.user.clone();
2917
2918    //         for item in pane.read(cx).items_of_type::<SharedScreen>() {
2919    //             if item.read(cx).peer_id == peer_id {
2920    //                 return Some(item);
2921    //             }
2922    //         }
2923
2924    //         Some(cx.build_view(|cx| SharedScreen::new(&track, peer_id, user.clone(), cx)))
2925    //     }
2926
2927    pub fn on_window_activation_changed(&mut self, cx: &mut ViewContext<Self>) {
2928        if cx.is_window_active() {
2929            self.update_active_view_for_followers(cx);
2930            cx.background_executor()
2931                .spawn(persistence::DB.update_timestamp(self.database_id()))
2932                .detach();
2933        } else {
2934            for pane in &self.panes {
2935                pane.update(cx, |pane, cx| {
2936                    if let Some(item) = pane.active_item() {
2937                        item.workspace_deactivated(cx);
2938                    }
2939                    if matches!(
2940                        WorkspaceSettings::get_global(cx).autosave,
2941                        AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
2942                    ) {
2943                        for item in pane.items() {
2944                            Pane::autosave_item(item.as_ref(), self.project.clone(), cx)
2945                                .detach_and_log_err(cx);
2946                        }
2947                    }
2948                });
2949            }
2950        }
2951    }
2952
2953    fn active_call(&self) -> Option<&Model<ActiveCall>> {
2954        self.active_call.as_ref().map(|(call, _)| call)
2955    }
2956
2957    fn on_active_call_event(
2958        &mut self,
2959        _: Model<ActiveCall>,
2960        event: &call2::room::Event,
2961        cx: &mut ViewContext<Self>,
2962    ) {
2963        match event {
2964            call2::room::Event::ParticipantLocationChanged { participant_id }
2965            | call2::room::Event::RemoteVideoTracksChanged { participant_id } => {
2966                self.leader_updated(*participant_id, cx);
2967            }
2968            _ => {}
2969        }
2970    }
2971
2972    pub fn database_id(&self) -> WorkspaceId {
2973        self.database_id
2974    }
2975
2976    fn location(&self, cx: &AppContext) -> Option<WorkspaceLocation> {
2977        let project = self.project().read(cx);
2978
2979        if project.is_local() {
2980            Some(
2981                project
2982                    .visible_worktrees(cx)
2983                    .map(|worktree| worktree.read(cx).abs_path())
2984                    .collect::<Vec<_>>()
2985                    .into(),
2986            )
2987        } else {
2988            None
2989        }
2990    }
2991
2992    fn remove_panes(&mut self, member: Member, cx: &mut ViewContext<Workspace>) {
2993        match member {
2994            Member::Axis(PaneAxis { members, .. }) => {
2995                for child in members.iter() {
2996                    self.remove_panes(child.clone(), cx)
2997                }
2998            }
2999            Member::Pane(pane) => {
3000                self.force_remove_pane(&pane, cx);
3001            }
3002        }
3003    }
3004
3005    fn force_remove_pane(&mut self, pane: &View<Pane>, cx: &mut ViewContext<Workspace>) {
3006        self.panes.retain(|p| p != pane);
3007        if true {
3008            todo!()
3009            // cx.focus(self.panes.last().unwrap());
3010        }
3011        if self.last_active_center_pane == Some(pane.downgrade()) {
3012            self.last_active_center_pane = None;
3013        }
3014        cx.notify();
3015    }
3016
3017    //     fn schedule_serialize(&mut self, cx: &mut ViewContext<Self>) {
3018    //         self._schedule_serialize = Some(cx.spawn(|this, cx| async move {
3019    //             cx.background().timer(Duration::from_millis(100)).await;
3020    //             this.read_with(&cx, |this, cx| this.serialize_workspace(cx))
3021    //                 .ok();
3022    //         }));
3023    //     }
3024
3025    fn serialize_workspace(&self, cx: &mut ViewContext<Self>) {
3026        fn serialize_pane_handle(pane_handle: &View<Pane>, cx: &WindowContext) -> SerializedPane {
3027            let (items, active) = {
3028                let pane = pane_handle.read(cx);
3029                let active_item_id = pane.active_item().map(|item| item.id());
3030                (
3031                    pane.items()
3032                        .filter_map(|item_handle| {
3033                            Some(SerializedItem {
3034                                kind: Arc::from(item_handle.serialized_item_kind()?),
3035                                item_id: item_handle.id().as_u64() as usize,
3036                                active: Some(item_handle.id()) == active_item_id,
3037                            })
3038                        })
3039                        .collect::<Vec<_>>(),
3040                    pane.has_focus(cx),
3041                )
3042            };
3043
3044            SerializedPane::new(items, active)
3045        }
3046
3047        fn build_serialized_pane_group(
3048            pane_group: &Member,
3049            cx: &WindowContext,
3050        ) -> SerializedPaneGroup {
3051            match pane_group {
3052                Member::Axis(PaneAxis {
3053                    axis,
3054                    members,
3055                    flexes,
3056                    bounding_boxes: _,
3057                }) => SerializedPaneGroup::Group {
3058                    axis: *axis,
3059                    children: members
3060                        .iter()
3061                        .map(|member| build_serialized_pane_group(member, cx))
3062                        .collect::<Vec<_>>(),
3063                    flexes: Some(flexes.lock().clone()),
3064                },
3065                Member::Pane(pane_handle) => {
3066                    SerializedPaneGroup::Pane(serialize_pane_handle(&pane_handle, cx))
3067                }
3068            }
3069        }
3070
3071        fn build_serialized_docks(
3072            this: &Workspace,
3073            cx: &mut ViewContext<Workspace>,
3074        ) -> DockStructure {
3075            let left_dock = this.left_dock.read(cx);
3076            let left_visible = left_dock.is_open();
3077            let left_active_panel = left_dock
3078                .visible_panel()
3079                .and_then(|panel| Some(panel.persistent_name(cx).to_string()));
3080            let left_dock_zoom = left_dock
3081                .visible_panel()
3082                .map(|panel| panel.is_zoomed(cx))
3083                .unwrap_or(false);
3084
3085            let right_dock = this.right_dock.read(cx);
3086            let right_visible = right_dock.is_open();
3087            let right_active_panel = right_dock
3088                .visible_panel()
3089                .and_then(|panel| Some(panel.persistent_name(cx).to_string()));
3090            let right_dock_zoom = right_dock
3091                .visible_panel()
3092                .map(|panel| panel.is_zoomed(cx))
3093                .unwrap_or(false);
3094
3095            let bottom_dock = this.bottom_dock.read(cx);
3096            let bottom_visible = bottom_dock.is_open();
3097            let bottom_active_panel = bottom_dock
3098                .visible_panel()
3099                .and_then(|panel| Some(panel.persistent_name(cx).to_string()));
3100            let bottom_dock_zoom = bottom_dock
3101                .visible_panel()
3102                .map(|panel| panel.is_zoomed(cx))
3103                .unwrap_or(false);
3104
3105            DockStructure {
3106                left: DockData {
3107                    visible: left_visible,
3108                    active_panel: left_active_panel,
3109                    zoom: left_dock_zoom,
3110                },
3111                right: DockData {
3112                    visible: right_visible,
3113                    active_panel: right_active_panel,
3114                    zoom: right_dock_zoom,
3115                },
3116                bottom: DockData {
3117                    visible: bottom_visible,
3118                    active_panel: bottom_active_panel,
3119                    zoom: bottom_dock_zoom,
3120                },
3121            }
3122        }
3123
3124        if let Some(location) = self.location(cx) {
3125            // Load bearing special case:
3126            //  - with_local_workspace() relies on this to not have other stuff open
3127            //    when you open your log
3128            if !location.paths().is_empty() {
3129                let center_group = build_serialized_pane_group(&self.center.root, cx);
3130                let docks = build_serialized_docks(self, cx);
3131
3132                let serialized_workspace = SerializedWorkspace {
3133                    id: self.database_id,
3134                    location,
3135                    center_group,
3136                    bounds: Default::default(),
3137                    display: Default::default(),
3138                    docks,
3139                };
3140
3141                cx.spawn(|_, _| persistence::DB.save_workspace(serialized_workspace))
3142                    .detach();
3143            }
3144        }
3145    }
3146
3147    pub(crate) fn load_workspace(
3148        serialized_workspace: SerializedWorkspace,
3149        paths_to_open: Vec<Option<ProjectPath>>,
3150        cx: &mut ViewContext<Workspace>,
3151    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
3152        cx.spawn(|workspace, mut cx| async move {
3153            let (project, old_center_pane) = workspace.update(&mut cx, |workspace, _| {
3154                (
3155                    workspace.project().clone(),
3156                    workspace.last_active_center_pane.clone(),
3157                )
3158            })?;
3159
3160            let mut center_group = None;
3161            let mut center_items = None;
3162
3163            // Traverse the splits tree and add to things
3164            if let Some((group, active_pane, items)) = serialized_workspace
3165                .center_group
3166                .deserialize(
3167                    &project,
3168                    serialized_workspace.id,
3169                    workspace.clone(),
3170                    &mut cx,
3171                )
3172                .await
3173            {
3174                center_items = Some(items);
3175                center_group = Some((group, active_pane))
3176            }
3177
3178            let mut items_by_project_path = cx.update(|_, cx| {
3179                center_items
3180                    .unwrap_or_default()
3181                    .into_iter()
3182                    .filter_map(|item| {
3183                        let item = item?;
3184                        let project_path = item.project_path(cx)?;
3185                        Some((project_path, item))
3186                    })
3187                    .collect::<HashMap<_, _>>()
3188            })?;
3189
3190            let opened_items = paths_to_open
3191                .into_iter()
3192                .map(|path_to_open| {
3193                    path_to_open
3194                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
3195                })
3196                .collect::<Vec<_>>();
3197
3198            // Remove old panes from workspace panes list
3199            workspace.update(&mut cx, |workspace, cx| {
3200                if let Some((center_group, active_pane)) = center_group {
3201                    workspace.remove_panes(workspace.center.root.clone(), cx);
3202
3203                    // Swap workspace center group
3204                    workspace.center = PaneGroup::with_root(center_group);
3205
3206                    // Change the focus to the workspace first so that we retrigger focus in on the pane.
3207                    // todo!()
3208                    // cx.focus_self();
3209                    // if let Some(active_pane) = active_pane {
3210                    //     cx.focus(&active_pane);
3211                    // } else {
3212                    //     cx.focus(workspace.panes.last().unwrap());
3213                    // }
3214                } else {
3215                    // todo!()
3216                    // let old_center_handle = old_center_pane.and_then(|weak| weak.upgrade());
3217                    // if let Some(old_center_handle) = old_center_handle {
3218                    //     cx.focus(&old_center_handle)
3219                    // } else {
3220                    //     cx.focus_self()
3221                    // }
3222                }
3223
3224                let docks = serialized_workspace.docks;
3225                workspace.left_dock.update(cx, |dock, cx| {
3226                    dock.set_open(docks.left.visible, cx);
3227                    if let Some(active_panel) = docks.left.active_panel {
3228                        if let Some(ix) = dock.panel_index_for_ui_name(&active_panel, cx) {
3229                            dock.activate_panel(ix, cx);
3230                        }
3231                    }
3232                    dock.active_panel()
3233                        .map(|panel| panel.set_zoomed(docks.left.zoom, cx));
3234                    if docks.left.visible && docks.left.zoom {
3235                        // todo!()
3236                        // cx.focus_self()
3237                    }
3238                });
3239                // TODO: I think the bug is that setting zoom or active undoes the bottom zoom or something
3240                workspace.right_dock.update(cx, |dock, cx| {
3241                    dock.set_open(docks.right.visible, cx);
3242                    if let Some(active_panel) = docks.right.active_panel {
3243                        if let Some(ix) = dock.panel_index_for_ui_name(&active_panel, cx) {
3244                            dock.activate_panel(ix, cx);
3245                        }
3246                    }
3247                    dock.active_panel()
3248                        .map(|panel| panel.set_zoomed(docks.right.zoom, cx));
3249
3250                    if docks.right.visible && docks.right.zoom {
3251                        // todo!()
3252                        // cx.focus_self()
3253                    }
3254                });
3255                workspace.bottom_dock.update(cx, |dock, cx| {
3256                    dock.set_open(docks.bottom.visible, cx);
3257                    if let Some(active_panel) = docks.bottom.active_panel {
3258                        if let Some(ix) = dock.panel_index_for_ui_name(&active_panel, cx) {
3259                            dock.activate_panel(ix, cx);
3260                        }
3261                    }
3262
3263                    dock.active_panel()
3264                        .map(|panel| panel.set_zoomed(docks.bottom.zoom, cx));
3265
3266                    if docks.bottom.visible && docks.bottom.zoom {
3267                        // todo!()
3268                        // cx.focus_self()
3269                    }
3270                });
3271
3272                cx.notify();
3273            })?;
3274
3275            // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
3276            workspace.update(&mut cx, |workspace, cx| workspace.serialize_workspace(cx))?;
3277
3278            Ok(opened_items)
3279        })
3280    }
3281
3282    fn actions(div: Div<Self>) -> Div<Self> {
3283        div
3284            //     cx.add_async_action(Workspace::open);
3285            //     cx.add_async_action(Workspace::follow_next_collaborator);
3286            //     cx.add_async_action(Workspace::close);
3287            //     cx.add_async_action(Workspace::close_inactive_items_and_panes);
3288            //     cx.add_async_action(Workspace::close_all_items_and_panes);
3289            //     cx.add_global_action(Workspace::close_global);
3290            //     cx.add_global_action(restart);
3291            //     cx.add_async_action(Workspace::save_all);
3292            //     cx.add_action(Workspace::add_folder_to_project);
3293            //     cx.add_action(
3294            //         |workspace: &mut Workspace, _: &Unfollow, cx: &mut ViewContext<Workspace>| {
3295            //             let pane = workspace.active_pane().clone();
3296            //             workspace.unfollow(&pane, cx);
3297            //         },
3298            //     );
3299            //     cx.add_action(
3300            //         |workspace: &mut Workspace, action: &Save, cx: &mut ViewContext<Workspace>| {
3301            //             workspace
3302            //                 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), cx)
3303            //                 .detach_and_log_err(cx);
3304            //         },
3305            //     );
3306            //     cx.add_action(
3307            //         |workspace: &mut Workspace, _: &SaveAs, cx: &mut ViewContext<Workspace>| {
3308            //             workspace
3309            //                 .save_active_item(SaveIntent::SaveAs, cx)
3310            //                 .detach_and_log_err(cx);
3311            //         },
3312            //     );
3313            //     cx.add_action(|workspace: &mut Workspace, _: &ActivatePreviousPane, cx| {
3314            //         workspace.activate_previous_pane(cx)
3315            //     });
3316            //     cx.add_action(|workspace: &mut Workspace, _: &ActivateNextPane, cx| {
3317            //         workspace.activate_next_pane(cx)
3318            //     });
3319            //     cx.add_action(
3320            //         |workspace: &mut Workspace, action: &ActivatePaneInDirection, cx| {
3321            //             workspace.activate_pane_in_direction(action.0, cx)
3322            //         },
3323            //     );
3324            //     cx.add_action(
3325            //         |workspace: &mut Workspace, action: &SwapPaneInDirection, cx| {
3326            //             workspace.swap_pane_in_direction(action.0, cx)
3327            //         },
3328            //     );
3329            .on_action(|this, e: &ToggleLeftDock, cx| {
3330                println!("TOGGLING DOCK");
3331                this.toggle_dock(DockPosition::Left, cx);
3332            })
3333        //     cx.add_action(|workspace: &mut Workspace, _: &ToggleRightDock, cx| {
3334        //         workspace.toggle_dock(DockPosition::Right, cx);
3335        //     });
3336        //     cx.add_action(|workspace: &mut Workspace, _: &ToggleBottomDock, cx| {
3337        //         workspace.toggle_dock(DockPosition::Bottom, cx);
3338        //     });
3339        //     cx.add_action(|workspace: &mut Workspace, _: &CloseAllDocks, cx| {
3340        //         workspace.close_all_docks(cx);
3341        //     });
3342        //     cx.add_action(Workspace::activate_pane_at_index);
3343        //     cx.add_action(|workspace: &mut Workspace, _: &ReopenClosedItem, cx| {
3344        //         workspace.reopen_closed_item(cx).detach();
3345        //     });
3346        //     cx.add_action(|workspace: &mut Workspace, _: &GoBack, cx| {
3347        //         workspace
3348        //             .go_back(workspace.active_pane().downgrade(), cx)
3349        //             .detach();
3350        //     });
3351        //     cx.add_action(|workspace: &mut Workspace, _: &GoForward, cx| {
3352        //         workspace
3353        //             .go_forward(workspace.active_pane().downgrade(), cx)
3354        //             .detach();
3355        //     });
3356
3357        //     cx.add_action(|_: &mut Workspace, _: &install_cli::Install, cx| {
3358        //         cx.spawn(|workspace, mut cx| async move {
3359        //             let err = install_cli::install_cli(&cx)
3360        //                 .await
3361        //                 .context("Failed to create CLI symlink");
3362
3363        //             workspace.update(&mut cx, |workspace, cx| {
3364        //                 if matches!(err, Err(_)) {
3365        //                     err.notify_err(workspace, cx);
3366        //                 } else {
3367        //                     workspace.show_notification(1, cx, |cx| {
3368        //                         cx.build_view(|_| {
3369        //                             MessageNotification::new("Successfully installed the `zed` binary")
3370        //                         })
3371        //                     });
3372        //                 }
3373        //             })
3374        //         })
3375        //         .detach();
3376        //     });
3377    }
3378
3379    // todo!()
3380    //     #[cfg(any(test, feature = "test-support"))]
3381    //     pub fn test_new(project: ModelHandle<Project>, cx: &mut ViewContext<Self>) -> Self {
3382    //         use node_runtime::FakeNodeRuntime;
3383    #[cfg(any(test, feature = "test-support"))]
3384    pub fn test_new(project: Model<Project>, cx: &mut ViewContext<Self>) -> Self {
3385        use gpui::Context;
3386        use node_runtime::FakeNodeRuntime;
3387
3388        let client = project.read(cx).client();
3389        let user_store = project.read(cx).user_store();
3390
3391        let workspace_store = cx.build_model(|cx| WorkspaceStore::new(client.clone(), cx));
3392        let app_state = Arc::new(AppState {
3393            languages: project.read(cx).languages().clone(),
3394            workspace_store,
3395            client,
3396            user_store,
3397            fs: project.read(cx).fs().clone(),
3398            build_window_options: |_, _, _| Default::default(),
3399            initialize_workspace: |_, _, _, _| Task::ready(Ok(())),
3400            node_runtime: FakeNodeRuntime::new(),
3401        });
3402        Self::new(0, project, app_state, cx)
3403    }
3404
3405    //     fn render_dock(&self, position: DockPosition, cx: &WindowContext) -> Option<AnyElement<Self>> {
3406    //         let dock = match position {
3407    //             DockPosition::Left => &self.left_dock,
3408    //             DockPosition::Right => &self.right_dock,
3409    //             DockPosition::Bottom => &self.bottom_dock,
3410    //         };
3411    //         let active_panel = dock.read(cx).visible_panel()?;
3412    //         let element = if Some(active_panel.id()) == self.zoomed.as_ref().map(|zoomed| zoomed.id()) {
3413    //             dock.read(cx).render_placeholder(cx)
3414    //         } else {
3415    //             ChildView::new(dock, cx).into_any()
3416    //         };
3417
3418    //         Some(
3419    //             element
3420    //                 .constrained()
3421    //                 .dynamically(move |constraint, _, cx| match position {
3422    //                     DockPosition::Left | DockPosition::Right => SizeConstraint::new(
3423    //                         Vector2F::new(20., constraint.min.y()),
3424    //                         Vector2F::new(cx.window_size().x() * 0.8, constraint.max.y()),
3425    //                     ),
3426    //                     DockPosition::Bottom => SizeConstraint::new(
3427    //                         Vector2F::new(constraint.min.x(), 20.),
3428    //                         Vector2F::new(constraint.max.x(), cx.window_size().y() * 0.8),
3429    //                     ),
3430    //                 })
3431    //                 .into_any(),
3432    //         )
3433    //     }
3434    // }
3435    pub fn register_action<A: Action>(
3436        &mut self,
3437        callback: impl Fn(&mut Self, &A, &mut ViewContext<Self>) + 'static,
3438    ) {
3439        let callback = Arc::new(callback);
3440
3441        self.workspace_actions.push(Box::new(move |div| {
3442            let callback = callback.clone();
3443            div.on_action(move |workspace, event, cx| (callback.clone())(workspace, event, cx))
3444        }));
3445    }
3446
3447    fn add_workspace_actions_listeners(
3448        &self,
3449        mut div: Div<Workspace, StatelessInteractivity<Workspace>>,
3450    ) -> Div<Workspace, StatelessInteractivity<Workspace>> {
3451        for action in self.workspace_actions.iter() {
3452            div = (action)(div)
3453        }
3454        div
3455    }
3456
3457    pub fn toggle_modal<V: Modal, B>(&mut self, cx: &mut ViewContext<Self>, build: B)
3458    where
3459        B: FnOnce(&mut ViewContext<V>) -> V,
3460    {
3461        self.modal_layer
3462            .update(cx, |modal_layer, cx| modal_layer.toggle_modal(cx, build))
3463    }
3464}
3465
3466fn window_bounds_env_override(cx: &AsyncAppContext) -> Option<WindowBounds> {
3467    let display_origin = cx
3468        .update(|cx| Some(cx.displays().first()?.bounds().origin))
3469        .ok()??;
3470    ZED_WINDOW_POSITION
3471        .zip(*ZED_WINDOW_SIZE)
3472        .map(|(position, size)| {
3473            WindowBounds::Fixed(Bounds {
3474                origin: display_origin + position,
3475                size,
3476            })
3477        })
3478}
3479
3480fn open_items(
3481    serialized_workspace: Option<SerializedWorkspace>,
3482    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
3483    app_state: Arc<AppState>,
3484    cx: &mut ViewContext<Workspace>,
3485) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> {
3486    let restored_items = serialized_workspace.map(|serialized_workspace| {
3487        Workspace::load_workspace(
3488            serialized_workspace,
3489            project_paths_to_open
3490                .iter()
3491                .map(|(_, project_path)| project_path)
3492                .cloned()
3493                .collect(),
3494            cx,
3495        )
3496    });
3497
3498    cx.spawn(|workspace, mut cx| async move {
3499        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
3500
3501        if let Some(restored_items) = restored_items {
3502            let restored_items = restored_items.await?;
3503
3504            let restored_project_paths = restored_items
3505                .iter()
3506                .filter_map(|item| {
3507                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
3508                        .ok()
3509                        .flatten()
3510                })
3511                .collect::<HashSet<_>>();
3512
3513            for restored_item in restored_items {
3514                opened_items.push(restored_item.map(Ok));
3515            }
3516
3517            project_paths_to_open
3518                .iter_mut()
3519                .for_each(|(_, project_path)| {
3520                    if let Some(project_path_to_open) = project_path {
3521                        if restored_project_paths.contains(project_path_to_open) {
3522                            *project_path = None;
3523                        }
3524                    }
3525                });
3526        } else {
3527            for _ in 0..project_paths_to_open.len() {
3528                opened_items.push(None);
3529            }
3530        }
3531        assert!(opened_items.len() == project_paths_to_open.len());
3532
3533        let tasks =
3534            project_paths_to_open
3535                .into_iter()
3536                .enumerate()
3537                .map(|(i, (abs_path, project_path))| {
3538                    let workspace = workspace.clone();
3539                    cx.spawn(|mut cx| {
3540                        let fs = app_state.fs.clone();
3541                        async move {
3542                            let file_project_path = project_path?;
3543                            if fs.is_file(&abs_path).await {
3544                                Some((
3545                                    i,
3546                                    workspace
3547                                        .update(&mut cx, |workspace, cx| {
3548                                            workspace.open_path(file_project_path, None, true, cx)
3549                                        })
3550                                        .log_err()?
3551                                        .await,
3552                                ))
3553                            } else {
3554                                None
3555                            }
3556                        }
3557                    })
3558                });
3559
3560        let tasks = tasks.collect::<Vec<_>>();
3561
3562        let tasks = futures::future::join_all(tasks.into_iter());
3563        for maybe_opened_path in tasks.await.into_iter() {
3564            if let Some((i, path_open_result)) = maybe_opened_path {
3565                opened_items[i] = Some(path_open_result);
3566            }
3567        }
3568
3569        Ok(opened_items)
3570    })
3571}
3572
3573// todo!()
3574// fn notify_of_new_dock(workspace: &WeakView<Workspace>, cx: &mut AsyncAppContext) {
3575//     const NEW_PANEL_BLOG_POST: &str = "https://zed.dev/blog/new-panel-system";
3576//     const NEW_DOCK_HINT_KEY: &str = "show_new_dock_key";
3577//     const MESSAGE_ID: usize = 2;
3578
3579//     if workspace
3580//         .read_with(cx, |workspace, cx| {
3581//             workspace.has_shown_notification_once::<MessageNotification>(MESSAGE_ID, cx)
3582//         })
3583//         .unwrap_or(false)
3584//     {
3585//         return;
3586//     }
3587
3588//     if db::kvp::KEY_VALUE_STORE
3589//         .read_kvp(NEW_DOCK_HINT_KEY)
3590//         .ok()
3591//         .flatten()
3592//         .is_some()
3593//     {
3594//         if !workspace
3595//             .read_with(cx, |workspace, cx| {
3596//                 workspace.has_shown_notification_once::<MessageNotification>(MESSAGE_ID, cx)
3597//             })
3598//             .unwrap_or(false)
3599//         {
3600//             cx.update(|cx| {
3601//                 cx.update_global::<NotificationTracker, _, _>(|tracker, _| {
3602//                     let entry = tracker
3603//                         .entry(TypeId::of::<MessageNotification>())
3604//                         .or_default();
3605//                     if !entry.contains(&MESSAGE_ID) {
3606//                         entry.push(MESSAGE_ID);
3607//                     }
3608//                 });
3609//             });
3610//         }
3611
3612//         return;
3613//     }
3614
3615//     cx.spawn(|_| async move {
3616//         db::kvp::KEY_VALUE_STORE
3617//             .write_kvp(NEW_DOCK_HINT_KEY.to_string(), "seen".to_string())
3618//             .await
3619//             .ok();
3620//     })
3621//     .detach();
3622
3623//     workspace
3624//         .update(cx, |workspace, cx| {
3625//             workspace.show_notification_once(2, cx, |cx| {
3626//                 cx.build_view(|_| {
3627//                     MessageNotification::new_element(|text, _| {
3628//                         Text::new(
3629//                             "Looking for the dock? Try ctrl-`!\nshift-escape now zooms your pane.",
3630//                             text,
3631//                         )
3632//                         .with_custom_runs(vec![26..32, 34..46], |_, bounds, cx| {
3633//                             let code_span_background_color = settings::get::<ThemeSettings>(cx)
3634//                                 .theme
3635//                                 .editor
3636//                                 .document_highlight_read_background;
3637
3638//                             cx.scene().push_quad(gpui::Quad {
3639//                                 bounds,
3640//                                 background: Some(code_span_background_color),
3641//                                 border: Default::default(),
3642//                                 corner_radii: (2.0).into(),
3643//                             })
3644//                         })
3645//                         .into_any()
3646//                     })
3647//                     .with_click_message("Read more about the new panel system")
3648//                     .on_click(|cx| cx.platform().open_url(NEW_PANEL_BLOG_POST))
3649//                 })
3650//             })
3651//         })
3652//         .ok();
3653
3654fn notify_if_database_failed(workspace: WindowHandle<Workspace>, cx: &mut AsyncAppContext) {
3655    const REPORT_ISSUE_URL: &str ="https://github.com/zed-industries/community/issues/new?assignees=&labels=defect%2Ctriage&template=2_bug_report.yml";
3656
3657    workspace
3658        .update(cx, |workspace, cx| {
3659            if (*db2::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
3660                workspace.show_notification_once(0, cx, |cx| {
3661                    cx.build_view(|_| {
3662                        MessageNotification::new("Failed to load the database file.")
3663                            .with_click_message("Click to let us know about this error")
3664                            .on_click(|cx| cx.open_url(REPORT_ISSUE_URL))
3665                    })
3666                });
3667            }
3668        })
3669        .log_err();
3670}
3671
3672impl EventEmitter<Event> for Workspace {}
3673
3674impl Render for Workspace {
3675    type Element = Div<Self>;
3676
3677    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
3678        let mut context = KeyContext::default();
3679        context.add("Workspace");
3680
3681        self.add_workspace_actions_listeners(div())
3682            .context(context)
3683            .relative()
3684            .size_full()
3685            .flex()
3686            .flex_col()
3687            .font("Zed Sans")
3688            .gap_0()
3689            .justify_start()
3690            .items_start()
3691            .text_color(cx.theme().colors().text)
3692            .bg(cx.theme().colors().background)
3693            .child(self.render_titlebar(cx))
3694            .child(
3695                // todo! should this be a component a view?
3696                div()
3697                    .id("workspace")
3698                    .relative()
3699                    .flex_1()
3700                    .w_full()
3701                    .flex()
3702                    .overflow_hidden()
3703                    .border_t()
3704                    .border_b()
3705                    .border_color(cx.theme().colors().border)
3706                    .child(self.modal_layer.clone())
3707                    .child(
3708                        div()
3709                            .flex()
3710                            .flex_row()
3711                            .flex_1()
3712                            .h_full()
3713                            .child(div().flex().flex_1().child(self.left_dock.clone()))
3714                            .child(
3715                                div()
3716                                    .flex()
3717                                    .flex_col()
3718                                    .flex_1()
3719                                    .child(self.center.render(
3720                                        &self.project,
3721                                        &self.follower_states,
3722                                        self.active_call(),
3723                                        &self.active_pane,
3724                                        self.zoomed.as_ref(),
3725                                        &self.app_state,
3726                                        cx,
3727                                    ))
3728                                    .child(div().flex().flex_1().child(self.bottom_dock.clone())),
3729                            )
3730                            .child(div().flex().flex_1().child(self.right_dock.clone())),
3731                    ),
3732            )
3733            .child(self.status_bar.clone())
3734            // .when(self.debug.show_toast, |this| {
3735            //     this.child(Toast::new(ToastOrigin::Bottom).child(Label::new("A toast")))
3736            // })
3737            // .children(
3738            //     Some(
3739            //         div()
3740            //             .absolute()
3741            //             .top(px(50.))
3742            //             .left(px(640.))
3743            //             .z_index(8)
3744            //             .child(LanguageSelector::new("language-selector")),
3745            //     )
3746            //     .filter(|_| self.is_language_selector_open()),
3747            // )
3748            .z_index(8)
3749            // Debug
3750            .child(
3751                div()
3752                    .flex()
3753                    .flex_col()
3754                    .z_index(9)
3755                    .absolute()
3756                    .top_20()
3757                    .left_1_4()
3758                    .w_40()
3759                    .gap_2(), // .when(self.show_debug, |this| {
3760                              //     this.child(Button::<Workspace>::new("Toggle User Settings").on_click(
3761                              //         Arc::new(|workspace, cx| workspace.debug_toggle_user_settings(cx)),
3762                              //     ))
3763                              //     .child(
3764                              //         Button::<Workspace>::new("Toggle Toasts").on_click(Arc::new(
3765                              //             |workspace, cx| workspace.debug_toggle_toast(cx),
3766                              //         )),
3767                              //     )
3768                              //     .child(
3769                              //         Button::<Workspace>::new("Toggle Livestream").on_click(Arc::new(
3770                              //             |workspace, cx| workspace.debug_toggle_livestream(cx),
3771                              //         )),
3772                              //     )
3773                              // })
3774                              // .child(
3775                              //     Button::<Workspace>::new("Toggle Debug")
3776                              //         .on_click(Arc::new(|workspace, cx| workspace.toggle_debug(cx))),
3777                              // ),
3778            )
3779    }
3780}
3781// todo!()
3782// impl Entity for Workspace {
3783//     type Event = Event;
3784
3785//     fn release(&mut self, cx: &mut AppContext) {
3786//         self.app_state.workspace_store.update(cx, |store, _| {
3787//             store.workspaces.remove(&self.weak_self);
3788//         })
3789//     }
3790// }
3791
3792// impl View for Workspace {
3793//     fn ui_name() -> &'static str {
3794//         "Workspace"
3795//     }
3796
3797//     fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
3798//         let theme = theme::current(cx).clone();
3799//         Stack::new()
3800//             .with_child(
3801//                 Flex::column()
3802//                     .with_child(self.render_titlebar(&theme, cx))
3803//                     .with_child(
3804//                         Stack::new()
3805//                             .with_child({
3806//                                 let project = self.project.clone();
3807//                                 Flex::row()
3808//                                     .with_children(self.render_dock(DockPosition::Left, cx))
3809//                                     .with_child(
3810//                                         Flex::column()
3811//                                             .with_child(
3812//                                                 FlexItem::new(
3813//                                                     self.center.render(
3814//                                                         &project,
3815//                                                         &theme,
3816//                                                         &self.follower_states,
3817//                                                         self.active_call(),
3818//                                                         self.active_pane(),
3819//                                                         self.zoomed
3820//                                                             .as_ref()
3821//                                                             .and_then(|zoomed| zoomed.upgrade(cx))
3822//                                                             .as_ref(),
3823//                                                         &self.app_state,
3824//                                                         cx,
3825//                                                     ),
3826//                                                 )
3827//                                                 .flex(1., true),
3828//                                             )
3829//                                             .with_children(
3830//                                                 self.render_dock(DockPosition::Bottom, cx),
3831//                                             )
3832//                                             .flex(1., true),
3833//                                     )
3834//                                     .with_children(self.render_dock(DockPosition::Right, cx))
3835//                             })
3836//                             .with_child(Overlay::new(
3837//                                 Stack::new()
3838//                                     .with_children(self.zoomed.as_ref().and_then(|zoomed| {
3839//                                         enum ZoomBackground {}
3840//                                         let zoomed = zoomed.upgrade(cx)?;
3841
3842//                                         let mut foreground_style =
3843//                                             theme.workspace.zoomed_pane_foreground;
3844//                                         if let Some(zoomed_dock_position) = self.zoomed_position {
3845//                                             foreground_style =
3846//                                                 theme.workspace.zoomed_panel_foreground;
3847//                                             let margin = foreground_style.margin.top;
3848//                                             let border = foreground_style.border.top;
3849
3850//                                             // Only include a margin and border on the opposite side.
3851//                                             foreground_style.margin.top = 0.;
3852//                                             foreground_style.margin.left = 0.;
3853//                                             foreground_style.margin.bottom = 0.;
3854//                                             foreground_style.margin.right = 0.;
3855//                                             foreground_style.border.top = false;
3856//                                             foreground_style.border.left = false;
3857//                                             foreground_style.border.bottom = false;
3858//                                             foreground_style.border.right = false;
3859//                                             match zoomed_dock_position {
3860//                                                 DockPosition::Left => {
3861//                                                     foreground_style.margin.right = margin;
3862//                                                     foreground_style.border.right = border;
3863//                                                 }
3864//                                                 DockPosition::Right => {
3865//                                                     foreground_style.margin.left = margin;
3866//                                                     foreground_style.border.left = border;
3867//                                                 }
3868//                                                 DockPosition::Bottom => {
3869//                                                     foreground_style.margin.top = margin;
3870//                                                     foreground_style.border.top = border;
3871//                                                 }
3872//                                             }
3873//                                         }
3874
3875//                                         Some(
3876//                                             ChildView::new(&zoomed, cx)
3877//                                                 .contained()
3878//                                                 .with_style(foreground_style)
3879//                                                 .aligned()
3880//                                                 .contained()
3881//                                                 .with_style(theme.workspace.zoomed_background)
3882//                                                 .mouse::<ZoomBackground>(0)
3883//                                                 .capture_all()
3884//                                                 .on_down(
3885//                                                     MouseButton::Left,
3886//                                                     |_, this: &mut Self, cx| {
3887//                                                         this.zoom_out(cx);
3888//                                                     },
3889//                                                 ),
3890//                                         )
3891//                                     }))
3892//                                     .with_children(self.modal.as_ref().map(|modal| {
3893//                                         // Prevent clicks within the modal from falling
3894//                                         // through to the rest of the workspace.
3895//                                         enum ModalBackground {}
3896//                                         MouseEventHandler::new::<ModalBackground, _>(
3897//                                             0,
3898//                                             cx,
3899//                                             |_, cx| ChildView::new(modal.view.as_any(), cx),
3900//                                         )
3901//                                         .on_click(MouseButton::Left, |_, _, _| {})
3902//                                         .contained()
3903//                                         .with_style(theme.workspace.modal)
3904//                                         .aligned()
3905//                                         .top()
3906//                                     }))
3907//                                     .with_children(self.render_notifications(&theme.workspace, cx)),
3908//                             ))
3909//                             .provide_resize_bounds::<WorkspaceBounds>()
3910//                             .flex(1.0, true),
3911//                     )
3912//                     .with_child(ChildView::new(&self.status_bar, cx))
3913//                     .contained()
3914//                     .with_background_color(theme.workspace.background),
3915//             )
3916//             .with_children(DragAndDrop::render(cx))
3917//             .with_children(self.render_disconnected_overlay(cx))
3918//             .into_any_named("workspace")
3919//     }
3920
3921//     fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
3922//         if cx.is_self_focused() {
3923//             cx.focus(&self.active_pane);
3924//         }
3925//     }
3926
3927//     fn modifiers_changed(&mut self, e: &ModifiersChangedEvent, cx: &mut ViewContext<Self>) -> bool {
3928//         DragAndDrop::<Workspace>::update_modifiers(e.modifiers, cx)
3929//     }
3930// }
3931
3932impl WorkspaceStore {
3933    pub fn new(client: Arc<Client>, _cx: &mut ModelContext<Self>) -> Self {
3934        Self {
3935            workspaces: Default::default(),
3936            followers: Default::default(),
3937            _subscriptions: vec![],
3938            //     client.add_request_handler(cx.weak_model(), Self::handle_follow),
3939            //     client.add_message_handler(cx.weak_model(), Self::handle_unfollow),
3940            //     client.add_message_handler(cx.weak_model(), Self::handle_update_followers),
3941            // ],
3942            client,
3943        }
3944    }
3945
3946    pub fn update_followers(
3947        &self,
3948        project_id: Option<u64>,
3949        update: proto::update_followers::Variant,
3950        cx: &AppContext,
3951    ) -> Option<()> {
3952        if !cx.has_global::<Model<ActiveCall>>() {
3953            return None;
3954        }
3955
3956        let room_id = ActiveCall::global(cx).read(cx).room()?.read(cx).id();
3957        let follower_ids: Vec<_> = self
3958            .followers
3959            .iter()
3960            .filter_map(|follower| {
3961                if follower.project_id == project_id || project_id.is_none() {
3962                    Some(follower.peer_id.into())
3963                } else {
3964                    None
3965                }
3966            })
3967            .collect();
3968        if follower_ids.is_empty() {
3969            return None;
3970        }
3971        self.client
3972            .send(proto::UpdateFollowers {
3973                room_id,
3974                project_id,
3975                follower_ids,
3976                variant: Some(update),
3977            })
3978            .log_err()
3979    }
3980
3981    pub async fn handle_follow(
3982        this: Model<Self>,
3983        envelope: TypedEnvelope<proto::Follow>,
3984        _: Arc<Client>,
3985        mut cx: AsyncAppContext,
3986    ) -> Result<proto::FollowResponse> {
3987        this.update(&mut cx, |this, cx| {
3988            let follower = Follower {
3989                project_id: envelope.payload.project_id,
3990                peer_id: envelope.original_sender_id()?,
3991            };
3992            let active_project = ActiveCall::global(cx).read(cx).location().cloned();
3993
3994            let mut response = proto::FollowResponse::default();
3995            for workspace in &this.workspaces {
3996                workspace
3997                    .update(cx, |workspace, cx| {
3998                        let handler_response = workspace.handle_follow(follower.project_id, cx);
3999                        if response.views.is_empty() {
4000                            response.views = handler_response.views;
4001                        } else {
4002                            response.views.extend_from_slice(&handler_response.views);
4003                        }
4004
4005                        if let Some(active_view_id) = handler_response.active_view_id.clone() {
4006                            if response.active_view_id.is_none()
4007                                || Some(workspace.project.downgrade()) == active_project
4008                            {
4009                                response.active_view_id = Some(active_view_id);
4010                            }
4011                        }
4012                    })
4013                    .ok();
4014            }
4015
4016            if let Err(ix) = this.followers.binary_search(&follower) {
4017                this.followers.insert(ix, follower);
4018            }
4019
4020            Ok(response)
4021        })?
4022    }
4023
4024    async fn handle_unfollow(
4025        model: Model<Self>,
4026        envelope: TypedEnvelope<proto::Unfollow>,
4027        _: Arc<Client>,
4028        mut cx: AsyncAppContext,
4029    ) -> Result<()> {
4030        model.update(&mut cx, |this, _| {
4031            let follower = Follower {
4032                project_id: envelope.payload.project_id,
4033                peer_id: envelope.original_sender_id()?,
4034            };
4035            if let Ok(ix) = this.followers.binary_search(&follower) {
4036                this.followers.remove(ix);
4037            }
4038            Ok(())
4039        })?
4040    }
4041
4042    async fn handle_update_followers(
4043        this: Model<Self>,
4044        envelope: TypedEnvelope<proto::UpdateFollowers>,
4045        _: Arc<Client>,
4046        mut cx: AsyncWindowContext,
4047    ) -> Result<()> {
4048        let leader_id = envelope.original_sender_id()?;
4049        let update = envelope.payload;
4050
4051        this.update(&mut cx, |this, cx| {
4052            for workspace in &this.workspaces {
4053                workspace.update(cx, |workspace, cx| {
4054                    let project_id = workspace.project.read(cx).remote_id();
4055                    if update.project_id != project_id && update.project_id.is_some() {
4056                        return;
4057                    }
4058                    workspace.handle_update_followers(leader_id, update.clone(), cx);
4059                })?;
4060            }
4061            Ok(())
4062        })?
4063    }
4064}
4065
4066impl ViewId {
4067    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
4068        Ok(Self {
4069            creator: message
4070                .creator
4071                .ok_or_else(|| anyhow!("creator is missing"))?,
4072            id: message.id,
4073        })
4074    }
4075
4076    pub(crate) fn to_proto(&self) -> proto::ViewId {
4077        proto::ViewId {
4078            creator: Some(self.creator),
4079            id: self.id,
4080        }
4081    }
4082}
4083
4084pub trait WorkspaceHandle {
4085    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
4086}
4087
4088impl WorkspaceHandle for View<Workspace> {
4089    fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
4090        self.read(cx)
4091            .worktrees(cx)
4092            .flat_map(|worktree| {
4093                let worktree_id = worktree.read(cx).id();
4094                worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
4095                    worktree_id,
4096                    path: f.path.clone(),
4097                })
4098            })
4099            .collect::<Vec<_>>()
4100    }
4101}
4102
4103// impl std::fmt::Debug for OpenPaths {
4104//     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4105//         f.debug_struct("OpenPaths")
4106//             .field("paths", &self.paths)
4107//             .finish()
4108//     }
4109// }
4110
4111pub struct WorkspaceCreated(pub WeakView<Workspace>);
4112
4113pub fn activate_workspace_for_project(
4114    cx: &mut AppContext,
4115    predicate: impl Fn(&Project, &AppContext) -> bool + Send + 'static,
4116) -> Option<WindowHandle<Workspace>> {
4117    for window in cx.windows() {
4118        let Some(workspace) = window.downcast::<Workspace>() else {
4119            continue;
4120        };
4121
4122        let predicate = workspace
4123            .update(cx, |workspace, cx| {
4124                let project = workspace.project.read(cx);
4125                if predicate(project, cx) {
4126                    cx.activate_window();
4127                    true
4128                } else {
4129                    false
4130                }
4131            })
4132            .log_err()
4133            .unwrap_or(false);
4134
4135        if predicate {
4136            return Some(workspace);
4137        }
4138    }
4139
4140    None
4141}
4142
4143pub async fn last_opened_workspace_paths() -> Option<WorkspaceLocation> {
4144    DB.last_workspace().await.log_err().flatten()
4145}
4146
4147// async fn join_channel_internal(
4148//     channel_id: u64,
4149//     app_state: &Arc<AppState>,
4150//     requesting_window: Option<WindowHandle<Workspace>>,
4151//     active_call: &ModelHandle<ActiveCall>,
4152//     cx: &mut AsyncAppContext,
4153// ) -> Result<bool> {
4154//     let (should_prompt, open_room) = active_call.read_with(cx, |active_call, cx| {
4155//         let Some(room) = active_call.room().map(|room| room.read(cx)) else {
4156//             return (false, None);
4157//         };
4158
4159//         let already_in_channel = room.channel_id() == Some(channel_id);
4160//         let should_prompt = room.is_sharing_project()
4161//             && room.remote_participants().len() > 0
4162//             && !already_in_channel;
4163//         let open_room = if already_in_channel {
4164//             active_call.room().cloned()
4165//         } else {
4166//             None
4167//         };
4168//         (should_prompt, open_room)
4169//     });
4170
4171//     if let Some(room) = open_room {
4172//         let task = room.update(cx, |room, cx| {
4173//             if let Some((project, host)) = room.most_active_project(cx) {
4174//                 return Some(join_remote_project(project, host, app_state.clone(), cx));
4175//             }
4176
4177//             None
4178//         });
4179//         if let Some(task) = task {
4180//             task.await?;
4181//         }
4182//         return anyhow::Ok(true);
4183//     }
4184
4185//     if should_prompt {
4186//         if let Some(workspace) = requesting_window {
4187//             if let Some(window) = workspace.update(cx, |cx| cx.window()) {
4188//                 let answer = window.prompt(
4189//                     PromptLevel::Warning,
4190//                     "Leaving this call will unshare your current project.\nDo you want to switch channels?",
4191//                     &["Yes, Join Channel", "Cancel"],
4192//                     cx,
4193//                 );
4194
4195//                 if let Some(mut answer) = answer {
4196//                     if answer.next().await == Some(1) {
4197//                         return Ok(false);
4198//                     }
4199//                 }
4200//             } else {
4201//                 return Ok(false); // unreachable!() hopefully
4202//             }
4203//         } else {
4204//             return Ok(false); // unreachable!() hopefully
4205//         }
4206//     }
4207
4208//     let client = cx.read(|cx| active_call.read(cx).client());
4209
4210//     let mut client_status = client.status();
4211
4212//     // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
4213//     'outer: loop {
4214//         let Some(status) = client_status.recv().await else {
4215//             return Err(anyhow!("error connecting"));
4216//         };
4217
4218//         match status {
4219//             Status::Connecting
4220//             | Status::Authenticating
4221//             | Status::Reconnecting
4222//             | Status::Reauthenticating => continue,
4223//             Status::Connected { .. } => break 'outer,
4224//             Status::SignedOut => return Err(anyhow!("not signed in")),
4225//             Status::UpgradeRequired => return Err(anyhow!("zed is out of date")),
4226//             Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
4227//                 return Err(anyhow!("zed is offline"))
4228//             }
4229//         }
4230//     }
4231
4232//     let room = active_call
4233//         .update(cx, |active_call, cx| {
4234//             active_call.join_channel(channel_id, cx)
4235//         })
4236//         .await?;
4237
4238//     room.update(cx, |room, _| room.room_update_completed())
4239//         .await;
4240
4241//     let task = room.update(cx, |room, cx| {
4242//         if let Some((project, host)) = room.most_active_project(cx) {
4243//             return Some(join_remote_project(project, host, app_state.clone(), cx));
4244//         }
4245
4246//         None
4247//     });
4248//     if let Some(task) = task {
4249//         task.await?;
4250//         return anyhow::Ok(true);
4251//     }
4252//     anyhow::Ok(false)
4253// }
4254
4255// pub fn join_channel(
4256//     channel_id: u64,
4257//     app_state: Arc<AppState>,
4258//     requesting_window: Option<WindowHandle<Workspace>>,
4259//     cx: &mut AppContext,
4260// ) -> Task<Result<()>> {
4261//     let active_call = ActiveCall::global(cx);
4262//     cx.spawn(|mut cx| async move {
4263//         let result = join_channel_internal(
4264//             channel_id,
4265//             &app_state,
4266//             requesting_window,
4267//             &active_call,
4268//             &mut cx,
4269//         )
4270//         .await;
4271
4272//         // join channel succeeded, and opened a window
4273//         if matches!(result, Ok(true)) {
4274//             return anyhow::Ok(());
4275//         }
4276
4277//         if requesting_window.is_some() {
4278//             return anyhow::Ok(());
4279//         }
4280
4281//         // find an existing workspace to focus and show call controls
4282//         let mut active_window = activate_any_workspace_window(&mut cx);
4283//         if active_window.is_none() {
4284//             // no open workspaces, make one to show the error in (blergh)
4285//             cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), requesting_window, cx))
4286//                 .await;
4287//         }
4288
4289//         active_window = activate_any_workspace_window(&mut cx);
4290//         if active_window.is_none() {
4291//             return result.map(|_| ()); // unreachable!() assuming new_local always opens a window
4292//         }
4293
4294//         if let Err(err) = result {
4295//             let prompt = active_window.unwrap().prompt(
4296//                 PromptLevel::Critical,
4297//                 &format!("Failed to join channel: {}", err),
4298//                 &["Ok"],
4299//                 &mut cx,
4300//             );
4301//             if let Some(mut prompt) = prompt {
4302//                 prompt.next().await;
4303//             } else {
4304//                 return Err(err);
4305//             }
4306//         }
4307
4308//         // return ok, we showed the error to the user.
4309//         return anyhow::Ok(());
4310//     })
4311// }
4312
4313// pub fn activate_any_workspace_window(cx: &mut AsyncAppContext) -> Option<AnyWindowHandle> {
4314//     for window in cx.windows() {
4315//         let found = window.update(cx, |cx| {
4316//             let is_workspace = cx.root_view().clone().downcast::<Workspace>().is_some();
4317//             if is_workspace {
4318//                 cx.activate_window();
4319//             }
4320//             is_workspace
4321//         });
4322//         if found == Some(true) {
4323//             return Some(window);
4324//         }
4325//     }
4326//     None
4327// }
4328
4329#[allow(clippy::type_complexity)]
4330pub fn open_paths(
4331    abs_paths: &[PathBuf],
4332    app_state: &Arc<AppState>,
4333    requesting_window: Option<WindowHandle<Workspace>>,
4334    cx: &mut AppContext,
4335) -> Task<
4336    anyhow::Result<(
4337        WindowHandle<Workspace>,
4338        Vec<Option<Result<Box<dyn ItemHandle>, anyhow::Error>>>,
4339    )>,
4340> {
4341    let app_state = app_state.clone();
4342    let abs_paths = abs_paths.to_vec();
4343    // Open paths in existing workspace if possible
4344    let existing = activate_workspace_for_project(cx, {
4345        let abs_paths = abs_paths.clone();
4346        move |project, cx| project.contains_paths(&abs_paths, cx)
4347    });
4348    cx.spawn(move |mut cx| async move {
4349        if let Some(existing) = existing {
4350            // // Ok((
4351            //     existing.clone(),
4352            //     cx.update_window_root(&existing, |workspace, cx| {
4353            //         workspace.open_paths(abs_paths, true, cx)
4354            //     })?
4355            //     .await,
4356            // ))
4357            todo!()
4358        } else {
4359            cx.update(move |cx| {
4360                Workspace::new_local(abs_paths, app_state.clone(), requesting_window, cx)
4361            })?
4362            .await
4363        }
4364    })
4365}
4366
4367pub fn open_new(
4368    app_state: &Arc<AppState>,
4369    cx: &mut AppContext,
4370    init: impl FnOnce(&mut Workspace, &mut ViewContext<Workspace>) + 'static + Send,
4371) -> Task<()> {
4372    let task = Workspace::new_local(Vec::new(), app_state.clone(), None, cx);
4373    cx.spawn(|mut cx| async move {
4374        if let Some((workspace, opened_paths)) = task.await.log_err() {
4375            workspace
4376                .update(&mut cx, |workspace, cx| {
4377                    if opened_paths.is_empty() {
4378                        init(workspace, cx)
4379                    }
4380                })
4381                .log_err();
4382        }
4383    })
4384}
4385
4386// pub fn create_and_open_local_file(
4387//     path: &'static Path,
4388//     cx: &mut ViewContext<Workspace>,
4389//     default_content: impl 'static + Send + FnOnce() -> Rope,
4390// ) -> Task<Result<Box<dyn ItemHandle>>> {
4391//     cx.spawn(|workspace, mut cx| async move {
4392//         let fs = workspace.read_with(&cx, |workspace, _| workspace.app_state().fs.clone())?;
4393//         if !fs.is_file(path).await {
4394//             fs.create_file(path, Default::default()).await?;
4395//             fs.save(path, &default_content(), Default::default())
4396//                 .await?;
4397//         }
4398
4399//         let mut items = workspace
4400//             .update(&mut cx, |workspace, cx| {
4401//                 workspace.with_local_workspace(cx, |workspace, cx| {
4402//                     workspace.open_paths(vec![path.to_path_buf()], false, cx)
4403//                 })
4404//             })?
4405//             .await?
4406//             .await;
4407
4408//         let item = items.pop().flatten();
4409//         item.ok_or_else(|| anyhow!("path {path:?} is not a file"))?
4410//     })
4411// }
4412
4413// pub fn join_remote_project(
4414//     project_id: u64,
4415//     follow_user_id: u64,
4416//     app_state: Arc<AppState>,
4417//     cx: &mut AppContext,
4418// ) -> Task<Result<()>> {
4419//     cx.spawn(|mut cx| async move {
4420//         let windows = cx.windows();
4421//         let existing_workspace = windows.into_iter().find_map(|window| {
4422//             window.downcast::<Workspace>().and_then(|window| {
4423//                 window
4424//                     .read_root_with(&cx, |workspace, cx| {
4425//                         if workspace.project().read(cx).remote_id() == Some(project_id) {
4426//                             Some(cx.handle().downgrade())
4427//                         } else {
4428//                             None
4429//                         }
4430//                     })
4431//                     .unwrap_or(None)
4432//             })
4433//         });
4434
4435//         let workspace = if let Some(existing_workspace) = existing_workspace {
4436//             existing_workspace
4437//         } else {
4438//             let active_call = cx.read(ActiveCall::global);
4439//             let room = active_call
4440//                 .read_with(&cx, |call, _| call.room().cloned())
4441//                 .ok_or_else(|| anyhow!("not in a call"))?;
4442//             let project = room
4443//                 .update(&mut cx, |room, cx| {
4444//                     room.join_project(
4445//                         project_id,
4446//                         app_state.languages.clone(),
4447//                         app_state.fs.clone(),
4448//                         cx,
4449//                     )
4450//                 })
4451//                 .await?;
4452
4453//             let window_bounds_override = window_bounds_env_override(&cx);
4454//             let window = cx.add_window(
4455//                 (app_state.build_window_options)(
4456//                     window_bounds_override,
4457//                     None,
4458//                     cx.platform().as_ref(),
4459//                 ),
4460//                 |cx| Workspace::new(0, project, app_state.clone(), cx),
4461//             );
4462//             let workspace = window.root(&cx).unwrap();
4463//             (app_state.initialize_workspace)(
4464//                 workspace.downgrade(),
4465//                 false,
4466//                 app_state.clone(),
4467//                 cx.clone(),
4468//             )
4469//             .await
4470//             .log_err();
4471
4472//             workspace.downgrade()
4473//         };
4474
4475//         workspace.window().activate(&mut cx);
4476//         cx.platform().activate(true);
4477
4478//         workspace.update(&mut cx, |workspace, cx| {
4479//             if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
4480//                 let follow_peer_id = room
4481//                     .read(cx)
4482//                     .remote_participants()
4483//                     .iter()
4484//                     .find(|(_, participant)| participant.user.id == follow_user_id)
4485//                     .map(|(_, p)| p.peer_id)
4486//                     .or_else(|| {
4487//                         // If we couldn't follow the given user, follow the host instead.
4488//                         let collaborator = workspace
4489//                             .project()
4490//                             .read(cx)
4491//                             .collaborators()
4492//                             .values()
4493//                             .find(|collaborator| collaborator.replica_id == 0)?;
4494//                         Some(collaborator.peer_id)
4495//                     });
4496
4497//                 if let Some(follow_peer_id) = follow_peer_id {
4498//                     workspace
4499//                         .follow(follow_peer_id, cx)
4500//                         .map(|follow| follow.detach_and_log_err(cx));
4501//                 }
4502//             }
4503//         })?;
4504
4505//         anyhow::Ok(())
4506//     })
4507// }
4508
4509// pub fn restart(_: &Restart, cx: &mut AppContext) {
4510//     let should_confirm = settings::get::<WorkspaceSettings>(cx).confirm_quit;
4511//     cx.spawn(|mut cx| async move {
4512//         let mut workspace_windows = cx
4513//             .windows()
4514//             .into_iter()
4515//             .filter_map(|window| window.downcast::<Workspace>())
4516//             .collect::<Vec<_>>();
4517
4518//         // If multiple windows have unsaved changes, and need a save prompt,
4519//         // prompt in the active window before switching to a different window.
4520//         workspace_windows.sort_by_key(|window| window.is_active(&cx) == Some(false));
4521
4522//         if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
4523//             let answer = window.prompt(
4524//                 PromptLevel::Info,
4525//                 "Are you sure you want to restart?",
4526//                 &["Restart", "Cancel"],
4527//                 &mut cx,
4528//             );
4529
4530//             if let Some(mut answer) = answer {
4531//                 let answer = answer.next().await;
4532//                 if answer != Some(0) {
4533//                     return Ok(());
4534//                 }
4535//             }
4536//         }
4537
4538//         // If the user cancels any save prompt, then keep the app open.
4539//         for window in workspace_windows {
4540//             if let Some(should_close) = window.update_root(&mut cx, |workspace, cx| {
4541//                 workspace.prepare_to_close(true, cx)
4542//             }) {
4543//                 if !should_close.await? {
4544//                     return Ok(());
4545//                 }
4546//             }
4547//         }
4548//         cx.platform().restart();
4549//         anyhow::Ok(())
4550//     })
4551//     .detach_and_log_err(cx);
4552// }
4553
4554fn parse_pixel_position_env_var(value: &str) -> Option<Point<GlobalPixels>> {
4555    let mut parts = value.split(',');
4556    let x: usize = parts.next()?.parse().ok()?;
4557    let y: usize = parts.next()?.parse().ok()?;
4558    Some(point((x as f64).into(), (y as f64).into()))
4559}
4560
4561fn parse_pixel_size_env_var(value: &str) -> Option<Size<GlobalPixels>> {
4562    let mut parts = value.split(',');
4563    let width: usize = parts.next()?.parse().ok()?;
4564    let height: usize = parts.next()?.parse().ok()?;
4565    Some(size((width as f64).into(), (height as f64).into()))
4566}
4567
4568// #[cfg(test)]
4569// mod tests {
4570//     use super::*;
4571//     use crate::{
4572//         dock::test::{TestPanel, TestPanelEvent},
4573//         item::test::{TestItem, TestItemEvent, TestProjectItem},
4574//     };
4575//     use fs::FakeFs;
4576//     use gpui::{executor::Deterministic, test::EmptyView, TestAppContext};
4577//     use project::{Project, ProjectEntryId};
4578//     use serde_json::json;
4579//     use settings::SettingsStore;
4580//     use std::{cell::RefCell, rc::Rc};
4581
4582//     #[gpui::test]
4583//     async fn test_tab_disambiguation(cx: &mut TestAppContext) {
4584//         init_test(cx);
4585
4586//         let fs = FakeFs::new(cx.background());
4587//         let project = Project::test(fs, [], cx).await;
4588//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
4589//         let workspace = window.root(cx);
4590
4591//         // Adding an item with no ambiguity renders the tab without detail.
4592//         let item1 = window.build_view(cx, |_| {
4593//             let mut item = TestItem::new();
4594//             item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
4595//             item
4596//         });
4597//         workspace.update(cx, |workspace, cx| {
4598//             workspace.add_item(Box::new(item1.clone()), cx);
4599//         });
4600//         item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), None));
4601
4602//         // Adding an item that creates ambiguity increases the level of detail on
4603//         // both tabs.
4604//         let item2 = window.build_view(cx, |_| {
4605//             let mut item = TestItem::new();
4606//             item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
4607//             item
4608//         });
4609//         workspace.update(cx, |workspace, cx| {
4610//             workspace.add_item(Box::new(item2.clone()), cx);
4611//         });
4612//         item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
4613//         item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
4614
4615//         // Adding an item that creates ambiguity increases the level of detail only
4616//         // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
4617//         // we stop at the highest detail available.
4618//         let item3 = window.build_view(cx, |_| {
4619//             let mut item = TestItem::new();
4620//             item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
4621//             item
4622//         });
4623//         workspace.update(cx, |workspace, cx| {
4624//             workspace.add_item(Box::new(item3.clone()), cx);
4625//         });
4626//         item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
4627//         item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
4628//         item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
4629//     }
4630
4631//     #[gpui::test]
4632//     async fn test_tracking_active_path(cx: &mut TestAppContext) {
4633//         init_test(cx);
4634
4635//         let fs = FakeFs::new(cx.background());
4636//         fs.insert_tree(
4637//             "/root1",
4638//             json!({
4639//                 "one.txt": "",
4640//                 "two.txt": "",
4641//             }),
4642//         )
4643//         .await;
4644//         fs.insert_tree(
4645//             "/root2",
4646//             json!({
4647//                 "three.txt": "",
4648//             }),
4649//         )
4650//         .await;
4651
4652//         let project = Project::test(fs, ["root1".as_ref()], cx).await;
4653//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
4654//         let workspace = window.root(cx);
4655//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4656//         let worktree_id = project.read_with(cx, |project, cx| {
4657//             project.worktrees(cx).next().unwrap().read(cx).id()
4658//         });
4659
4660//         let item1 = window.build_view(cx, |cx| {
4661//             TestItem::new().with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
4662//         });
4663//         let item2 = window.build_view(cx, |cx| {
4664//             TestItem::new().with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
4665//         });
4666
4667//         // Add an item to an empty pane
4668//         workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item1), cx));
4669//         project.read_with(cx, |project, cx| {
4670//             assert_eq!(
4671//                 project.active_entry(),
4672//                 project
4673//                     .entry_for_path(&(worktree_id, "one.txt").into(), cx)
4674//                     .map(|e| e.id)
4675//             );
4676//         });
4677//         assert_eq!(window.current_title(cx).as_deref(), Some("one.txt β€” root1"));
4678
4679//         // Add a second item to a non-empty pane
4680//         workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item2), cx));
4681//         assert_eq!(window.current_title(cx).as_deref(), Some("two.txt β€” root1"));
4682//         project.read_with(cx, |project, cx| {
4683//             assert_eq!(
4684//                 project.active_entry(),
4685//                 project
4686//                     .entry_for_path(&(worktree_id, "two.txt").into(), cx)
4687//                     .map(|e| e.id)
4688//             );
4689//         });
4690
4691//         // Close the active item
4692//         pane.update(cx, |pane, cx| {
4693//             pane.close_active_item(&Default::default(), cx).unwrap()
4694//         })
4695//         .await
4696//         .unwrap();
4697//         assert_eq!(window.current_title(cx).as_deref(), Some("one.txt β€” root1"));
4698//         project.read_with(cx, |project, cx| {
4699//             assert_eq!(
4700//                 project.active_entry(),
4701//                 project
4702//                     .entry_for_path(&(worktree_id, "one.txt").into(), cx)
4703//                     .map(|e| e.id)
4704//             );
4705//         });
4706
4707//         // Add a project folder
4708//         project
4709//             .update(cx, |project, cx| {
4710//                 project.find_or_create_local_worktree("/root2", true, cx)
4711//             })
4712//             .await
4713//             .unwrap();
4714//         assert_eq!(
4715//             window.current_title(cx).as_deref(),
4716//             Some("one.txt β€” root1, root2")
4717//         );
4718
4719//         // Remove a project folder
4720//         project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
4721//         assert_eq!(window.current_title(cx).as_deref(), Some("one.txt β€” root2"));
4722//     }
4723
4724//     #[gpui::test]
4725//     async fn test_close_window(cx: &mut TestAppContext) {
4726//         init_test(cx);
4727
4728//         let fs = FakeFs::new(cx.background());
4729//         fs.insert_tree("/root", json!({ "one": "" })).await;
4730
4731//         let project = Project::test(fs, ["root".as_ref()], cx).await;
4732//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
4733//         let workspace = window.root(cx);
4734
4735//         // When there are no dirty items, there's nothing to do.
4736//         let item1 = window.build_view(cx, |_| TestItem::new());
4737//         workspace.update(cx, |w, cx| w.add_item(Box::new(item1.clone()), cx));
4738//         let task = workspace.update(cx, |w, cx| w.prepare_to_close(false, cx));
4739//         assert!(task.await.unwrap());
4740
4741//         // When there are dirty untitled items, prompt to save each one. If the user
4742//         // cancels any prompt, then abort.
4743//         let item2 = window.build_view(cx, |_| TestItem::new().with_dirty(true));
4744//         let item3 = window.build_view(cx, |cx| {
4745//             TestItem::new()
4746//                 .with_dirty(true)
4747//                 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
4748//         });
4749//         workspace.update(cx, |w, cx| {
4750//             w.add_item(Box::new(item2.clone()), cx);
4751//             w.add_item(Box::new(item3.clone()), cx);
4752//         });
4753//         let task = workspace.update(cx, |w, cx| w.prepare_to_close(false, cx));
4754//         cx.foreground().run_until_parked();
4755//         window.simulate_prompt_answer(2, cx); // cancel save all
4756//         cx.foreground().run_until_parked();
4757//         window.simulate_prompt_answer(2, cx); // cancel save all
4758//         cx.foreground().run_until_parked();
4759//         assert!(!window.has_pending_prompt(cx));
4760//         assert!(!task.await.unwrap());
4761//     }
4762
4763//     #[gpui::test]
4764//     async fn test_close_pane_items(cx: &mut TestAppContext) {
4765//         init_test(cx);
4766
4767//         let fs = FakeFs::new(cx.background());
4768
4769//         let project = Project::test(fs, None, cx).await;
4770//         let window = cx.add_window(|cx| Workspace::test_new(project, cx));
4771//         let workspace = window.root(cx);
4772
4773//         let item1 = window.build_view(cx, |cx| {
4774//             TestItem::new()
4775//                 .with_dirty(true)
4776//                 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
4777//         });
4778//         let item2 = window.build_view(cx, |cx| {
4779//             TestItem::new()
4780//                 .with_dirty(true)
4781//                 .with_conflict(true)
4782//                 .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)])
4783//         });
4784//         let item3 = window.build_view(cx, |cx| {
4785//             TestItem::new()
4786//                 .with_dirty(true)
4787//                 .with_conflict(true)
4788//                 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
4789//         });
4790//         let item4 = window.build_view(cx, |cx| {
4791//             TestItem::new()
4792//                 .with_dirty(true)
4793//                 .with_project_items(&[TestProjectItem::new_untitled(cx)])
4794//         });
4795//         let pane = workspace.update(cx, |workspace, cx| {
4796//             workspace.add_item(Box::new(item1.clone()), cx);
4797//             workspace.add_item(Box::new(item2.clone()), cx);
4798//             workspace.add_item(Box::new(item3.clone()), cx);
4799//             workspace.add_item(Box::new(item4.clone()), cx);
4800//             workspace.active_pane().clone()
4801//         });
4802
4803//         let close_items = pane.update(cx, |pane, cx| {
4804//             pane.activate_item(1, true, true, cx);
4805//             assert_eq!(pane.active_item().unwrap().id(), item2.id());
4806//             let item1_id = item1.id();
4807//             let item3_id = item3.id();
4808//             let item4_id = item4.id();
4809//             pane.close_items(cx, SaveIntent::Close, move |id| {
4810//                 [item1_id, item3_id, item4_id].contains(&id)
4811//             })
4812//         });
4813//         cx.foreground().run_until_parked();
4814
4815//         assert!(window.has_pending_prompt(cx));
4816//         // Ignore "Save all" prompt
4817//         window.simulate_prompt_answer(2, cx);
4818//         cx.foreground().run_until_parked();
4819//         // There's a prompt to save item 1.
4820//         pane.read_with(cx, |pane, _| {
4821//             assert_eq!(pane.items_len(), 4);
4822//             assert_eq!(pane.active_item().unwrap().id(), item1.id());
4823//         });
4824//         // Confirm saving item 1.
4825//         window.simulate_prompt_answer(0, cx);
4826//         cx.foreground().run_until_parked();
4827
4828//         // Item 1 is saved. There's a prompt to save item 3.
4829//         pane.read_with(cx, |pane, cx| {
4830//             assert_eq!(item1.read(cx).save_count, 1);
4831//             assert_eq!(item1.read(cx).save_as_count, 0);
4832//             assert_eq!(item1.read(cx).reload_count, 0);
4833//             assert_eq!(pane.items_len(), 3);
4834//             assert_eq!(pane.active_item().unwrap().id(), item3.id());
4835//         });
4836//         assert!(window.has_pending_prompt(cx));
4837
4838//         // Cancel saving item 3.
4839//         window.simulate_prompt_answer(1, cx);
4840//         cx.foreground().run_until_parked();
4841
4842//         // Item 3 is reloaded. There's a prompt to save item 4.
4843//         pane.read_with(cx, |pane, cx| {
4844//             assert_eq!(item3.read(cx).save_count, 0);
4845//             assert_eq!(item3.read(cx).save_as_count, 0);
4846//             assert_eq!(item3.read(cx).reload_count, 1);
4847//             assert_eq!(pane.items_len(), 2);
4848//             assert_eq!(pane.active_item().unwrap().id(), item4.id());
4849//         });
4850//         assert!(window.has_pending_prompt(cx));
4851
4852//         // Confirm saving item 4.
4853//         window.simulate_prompt_answer(0, cx);
4854//         cx.foreground().run_until_parked();
4855
4856//         // There's a prompt for a path for item 4.
4857//         cx.simulate_new_path_selection(|_| Some(Default::default()));
4858//         close_items.await.unwrap();
4859
4860//         // The requested items are closed.
4861//         pane.read_with(cx, |pane, cx| {
4862//             assert_eq!(item4.read(cx).save_count, 0);
4863//             assert_eq!(item4.read(cx).save_as_count, 1);
4864//             assert_eq!(item4.read(cx).reload_count, 0);
4865//             assert_eq!(pane.items_len(), 1);
4866//             assert_eq!(pane.active_item().unwrap().id(), item2.id());
4867//         });
4868//     }
4869
4870//     #[gpui::test]
4871//     async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
4872//         init_test(cx);
4873
4874//         let fs = FakeFs::new(cx.background());
4875
4876//         let project = Project::test(fs, [], cx).await;
4877//         let window = cx.add_window(|cx| Workspace::test_new(project, cx));
4878//         let workspace = window.root(cx);
4879
4880//         // Create several workspace items with single project entries, and two
4881//         // workspace items with multiple project entries.
4882//         let single_entry_items = (0..=4)
4883//             .map(|project_entry_id| {
4884//                 window.build_view(cx, |cx| {
4885//                     TestItem::new()
4886//                         .with_dirty(true)
4887//                         .with_project_items(&[TestProjectItem::new(
4888//                             project_entry_id,
4889//                             &format!("{project_entry_id}.txt"),
4890//                             cx,
4891//                         )])
4892//                 })
4893//             })
4894//             .collect::<Vec<_>>();
4895//         let item_2_3 = window.build_view(cx, |cx| {
4896//             TestItem::new()
4897//                 .with_dirty(true)
4898//                 .with_singleton(false)
4899//                 .with_project_items(&[
4900//                     single_entry_items[2].read(cx).project_items[0].clone(),
4901//                     single_entry_items[3].read(cx).project_items[0].clone(),
4902//                 ])
4903//         });
4904//         let item_3_4 = window.build_view(cx, |cx| {
4905//             TestItem::new()
4906//                 .with_dirty(true)
4907//                 .with_singleton(false)
4908//                 .with_project_items(&[
4909//                     single_entry_items[3].read(cx).project_items[0].clone(),
4910//                     single_entry_items[4].read(cx).project_items[0].clone(),
4911//                 ])
4912//         });
4913
4914//         // Create two panes that contain the following project entries:
4915//         //   left pane:
4916//         //     multi-entry items:   (2, 3)
4917//         //     single-entry items:  0, 1, 2, 3, 4
4918//         //   right pane:
4919//         //     single-entry items:  1
4920//         //     multi-entry items:   (3, 4)
4921//         let left_pane = workspace.update(cx, |workspace, cx| {
4922//             let left_pane = workspace.active_pane().clone();
4923//             workspace.add_item(Box::new(item_2_3.clone()), cx);
4924//             for item in single_entry_items {
4925//                 workspace.add_item(Box::new(item), cx);
4926//             }
4927//             left_pane.update(cx, |pane, cx| {
4928//                 pane.activate_item(2, true, true, cx);
4929//             });
4930
4931//             workspace
4932//                 .split_and_clone(left_pane.clone(), SplitDirection::Right, cx)
4933//                 .unwrap();
4934
4935//             left_pane
4936//         });
4937
4938//         //Need to cause an effect flush in order to respect new focus
4939//         workspace.update(cx, |workspace, cx| {
4940//             workspace.add_item(Box::new(item_3_4.clone()), cx);
4941//             cx.focus(&left_pane);
4942//         });
4943
4944//         // When closing all of the items in the left pane, we should be prompted twice:
4945//         // once for project entry 0, and once for project entry 2. After those two
4946//         // prompts, the task should complete.
4947
4948//         let close = left_pane.update(cx, |pane, cx| {
4949//             pane.close_items(cx, SaveIntent::Close, move |_| true)
4950//         });
4951//         cx.foreground().run_until_parked();
4952//         // Discard "Save all" prompt
4953//         window.simulate_prompt_answer(2, cx);
4954
4955//         cx.foreground().run_until_parked();
4956//         left_pane.read_with(cx, |pane, cx| {
4957//             assert_eq!(
4958//                 pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
4959//                 &[ProjectEntryId::from_proto(0)]
4960//             );
4961//         });
4962//         window.simulate_prompt_answer(0, cx);
4963
4964//         cx.foreground().run_until_parked();
4965//         left_pane.read_with(cx, |pane, cx| {
4966//             assert_eq!(
4967//                 pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
4968//                 &[ProjectEntryId::from_proto(2)]
4969//             );
4970//         });
4971//         window.simulate_prompt_answer(0, cx);
4972
4973//         cx.foreground().run_until_parked();
4974//         close.await.unwrap();
4975//         left_pane.read_with(cx, |pane, _| {
4976//             assert_eq!(pane.items_len(), 0);
4977//         });
4978//     }
4979
4980//     #[gpui::test]
4981//     async fn test_autosave(deterministic: Arc<Deterministic>, cx: &mut gpui::TestAppContext) {
4982//         init_test(cx);
4983
4984//         let fs = FakeFs::new(cx.background());
4985
4986//         let project = Project::test(fs, [], cx).await;
4987//         let window = cx.add_window(|cx| Workspace::test_new(project, cx));
4988//         let workspace = window.root(cx);
4989//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4990
4991//         let item = window.build_view(cx, |cx| {
4992//             TestItem::new().with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
4993//         });
4994//         let item_id = item.id();
4995//         workspace.update(cx, |workspace, cx| {
4996//             workspace.add_item(Box::new(item.clone()), cx);
4997//         });
4998
4999//         // Autosave on window change.
5000//         item.update(cx, |item, cx| {
5001//             cx.update_global(|settings: &mut SettingsStore, cx| {
5002//                 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
5003//                     settings.autosave = Some(AutosaveSetting::OnWindowChange);
5004//                 })
5005//             });
5006//             item.is_dirty = true;
5007//         });
5008
5009//         // Deactivating the window saves the file.
5010//         window.simulate_deactivation(cx);
5011//         deterministic.run_until_parked();
5012//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
5013
5014//         // Autosave on focus change.
5015//         item.update(cx, |item, cx| {
5016//             cx.focus_self();
5017//             cx.update_global(|settings: &mut SettingsStore, cx| {
5018//                 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
5019//                     settings.autosave = Some(AutosaveSetting::OnFocusChange);
5020//                 })
5021//             });
5022//             item.is_dirty = true;
5023//         });
5024
5025//         // Blurring the item saves the file.
5026//         item.update(cx, |_, cx| cx.blur());
5027//         deterministic.run_until_parked();
5028//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
5029
5030//         // Deactivating the window still saves the file.
5031//         window.simulate_activation(cx);
5032//         item.update(cx, |item, cx| {
5033//             cx.focus_self();
5034//             item.is_dirty = true;
5035//         });
5036//         window.simulate_deactivation(cx);
5037
5038//         deterministic.run_until_parked();
5039//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
5040
5041//         // Autosave after delay.
5042//         item.update(cx, |item, cx| {
5043//             cx.update_global(|settings: &mut SettingsStore, cx| {
5044//                 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
5045//                     settings.autosave = Some(AutosaveSetting::AfterDelay { milliseconds: 500 });
5046//                 })
5047//             });
5048//             item.is_dirty = true;
5049//             cx.emit(TestItemEvent::Edit);
5050//         });
5051
5052//         // Delay hasn't fully expired, so the file is still dirty and unsaved.
5053//         deterministic.advance_clock(Duration::from_millis(250));
5054//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
5055
5056//         // After delay expires, the file is saved.
5057//         deterministic.advance_clock(Duration::from_millis(250));
5058//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
5059
5060//         // Autosave on focus change, ensuring closing the tab counts as such.
5061//         item.update(cx, |item, cx| {
5062//             cx.update_global(|settings: &mut SettingsStore, cx| {
5063//                 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
5064//                     settings.autosave = Some(AutosaveSetting::OnFocusChange);
5065//                 })
5066//             });
5067//             item.is_dirty = true;
5068//         });
5069
5070//         pane.update(cx, |pane, cx| {
5071//             pane.close_items(cx, SaveIntent::Close, move |id| id == item_id)
5072//         })
5073//         .await
5074//         .unwrap();
5075//         assert!(!window.has_pending_prompt(cx));
5076//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
5077
5078//         // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
5079//         workspace.update(cx, |workspace, cx| {
5080//             workspace.add_item(Box::new(item.clone()), cx);
5081//         });
5082//         item.update(cx, |item, cx| {
5083//             item.project_items[0].update(cx, |item, _| {
5084//                 item.entry_id = None;
5085//             });
5086//             item.is_dirty = true;
5087//             cx.blur();
5088//         });
5089//         deterministic.run_until_parked();
5090//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
5091
5092//         // Ensure autosave is prevented for deleted files also when closing the buffer.
5093//         let _close_items = pane.update(cx, |pane, cx| {
5094//             pane.close_items(cx, SaveIntent::Close, move |id| id == item_id)
5095//         });
5096//         deterministic.run_until_parked();
5097//         assert!(window.has_pending_prompt(cx));
5098//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
5099//     }
5100
5101//     #[gpui::test]
5102//     async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
5103//         init_test(cx);
5104
5105//         let fs = FakeFs::new(cx.background());
5106
5107//         let project = Project::test(fs, [], cx).await;
5108//         let window = cx.add_window(|cx| Workspace::test_new(project, cx));
5109//         let workspace = window.root(cx);
5110
5111//         let item = window.build_view(cx, |cx| {
5112//             TestItem::new().with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5113//         });
5114//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5115//         let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
5116//         let toolbar_notify_count = Rc::new(RefCell::new(0));
5117
5118//         workspace.update(cx, |workspace, cx| {
5119//             workspace.add_item(Box::new(item.clone()), cx);
5120//             let toolbar_notification_count = toolbar_notify_count.clone();
5121//             cx.observe(&toolbar, move |_, _, _| {
5122//                 *toolbar_notification_count.borrow_mut() += 1
5123//             })
5124//             .detach();
5125//         });
5126
5127//         pane.read_with(cx, |pane, _| {
5128//             assert!(!pane.can_navigate_backward());
5129//             assert!(!pane.can_navigate_forward());
5130//         });
5131
5132//         item.update(cx, |item, cx| {
5133//             item.set_state("one".to_string(), cx);
5134//         });
5135
5136//         // Toolbar must be notified to re-render the navigation buttons
5137//         assert_eq!(*toolbar_notify_count.borrow(), 1);
5138
5139//         pane.read_with(cx, |pane, _| {
5140//             assert!(pane.can_navigate_backward());
5141//             assert!(!pane.can_navigate_forward());
5142//         });
5143
5144//         workspace
5145//             .update(cx, |workspace, cx| workspace.go_back(pane.downgrade(), cx))
5146//             .await
5147//             .unwrap();
5148
5149//         assert_eq!(*toolbar_notify_count.borrow(), 3);
5150//         pane.read_with(cx, |pane, _| {
5151//             assert!(!pane.can_navigate_backward());
5152//             assert!(pane.can_navigate_forward());
5153//         });
5154//     }
5155
5156//     #[gpui::test]
5157//     async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
5158//         init_test(cx);
5159//         let fs = FakeFs::new(cx.background());
5160
5161//         let project = Project::test(fs, [], cx).await;
5162//         let window = cx.add_window(|cx| Workspace::test_new(project, cx));
5163//         let workspace = window.root(cx);
5164
5165//         let panel = workspace.update(cx, |workspace, cx| {
5166//             let panel = cx.build_view(|_| TestPanel::new(DockPosition::Right));
5167//             workspace.add_panel(panel.clone(), cx);
5168
5169//             workspace
5170//                 .right_dock()
5171//                 .update(cx, |right_dock, cx| right_dock.set_open(true, cx));
5172
5173//             panel
5174//         });
5175
5176//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5177//         pane.update(cx, |pane, cx| {
5178//             let item = cx.build_view(|_| TestItem::new());
5179//             pane.add_item(Box::new(item), true, true, None, cx);
5180//         });
5181
5182//         // Transfer focus from center to panel
5183//         workspace.update(cx, |workspace, cx| {
5184//             workspace.toggle_panel_focus::<TestPanel>(cx);
5185//         });
5186
5187//         workspace.read_with(cx, |workspace, cx| {
5188//             assert!(workspace.right_dock().read(cx).is_open());
5189//             assert!(!panel.is_zoomed(cx));
5190//             assert!(panel.has_focus(cx));
5191//         });
5192
5193//         // Transfer focus from panel to center
5194//         workspace.update(cx, |workspace, cx| {
5195//             workspace.toggle_panel_focus::<TestPanel>(cx);
5196//         });
5197
5198//         workspace.read_with(cx, |workspace, cx| {
5199//             assert!(workspace.right_dock().read(cx).is_open());
5200//             assert!(!panel.is_zoomed(cx));
5201//             assert!(!panel.has_focus(cx));
5202//         });
5203
5204//         // Close the dock
5205//         workspace.update(cx, |workspace, cx| {
5206//             workspace.toggle_dock(DockPosition::Right, cx);
5207//         });
5208
5209//         workspace.read_with(cx, |workspace, cx| {
5210//             assert!(!workspace.right_dock().read(cx).is_open());
5211//             assert!(!panel.is_zoomed(cx));
5212//             assert!(!panel.has_focus(cx));
5213//         });
5214
5215//         // Open the dock
5216//         workspace.update(cx, |workspace, cx| {
5217//             workspace.toggle_dock(DockPosition::Right, cx);
5218//         });
5219
5220//         workspace.read_with(cx, |workspace, cx| {
5221//             assert!(workspace.right_dock().read(cx).is_open());
5222//             assert!(!panel.is_zoomed(cx));
5223//             assert!(panel.has_focus(cx));
5224//         });
5225
5226//         // Focus and zoom panel
5227//         panel.update(cx, |panel, cx| {
5228//             cx.focus_self();
5229//             panel.set_zoomed(true, cx)
5230//         });
5231
5232//         workspace.read_with(cx, |workspace, cx| {
5233//             assert!(workspace.right_dock().read(cx).is_open());
5234//             assert!(panel.is_zoomed(cx));
5235//             assert!(panel.has_focus(cx));
5236//         });
5237
5238//         // Transfer focus to the center closes the dock
5239//         workspace.update(cx, |workspace, cx| {
5240//             workspace.toggle_panel_focus::<TestPanel>(cx);
5241//         });
5242
5243//         workspace.read_with(cx, |workspace, cx| {
5244//             assert!(!workspace.right_dock().read(cx).is_open());
5245//             assert!(panel.is_zoomed(cx));
5246//             assert!(!panel.has_focus(cx));
5247//         });
5248
5249//         // Transferring focus back to the panel keeps it zoomed
5250//         workspace.update(cx, |workspace, cx| {
5251//             workspace.toggle_panel_focus::<TestPanel>(cx);
5252//         });
5253
5254//         workspace.read_with(cx, |workspace, cx| {
5255//             assert!(workspace.right_dock().read(cx).is_open());
5256//             assert!(panel.is_zoomed(cx));
5257//             assert!(panel.has_focus(cx));
5258//         });
5259
5260//         // Close the dock while it is zoomed
5261//         workspace.update(cx, |workspace, cx| {
5262//             workspace.toggle_dock(DockPosition::Right, cx)
5263//         });
5264
5265//         workspace.read_with(cx, |workspace, cx| {
5266//             assert!(!workspace.right_dock().read(cx).is_open());
5267//             assert!(panel.is_zoomed(cx));
5268//             assert!(workspace.zoomed.is_none());
5269//             assert!(!panel.has_focus(cx));
5270//         });
5271
5272//         // Opening the dock, when it's zoomed, retains focus
5273//         workspace.update(cx, |workspace, cx| {
5274//             workspace.toggle_dock(DockPosition::Right, cx)
5275//         });
5276
5277//         workspace.read_with(cx, |workspace, cx| {
5278//             assert!(workspace.right_dock().read(cx).is_open());
5279//             assert!(panel.is_zoomed(cx));
5280//             assert!(workspace.zoomed.is_some());
5281//             assert!(panel.has_focus(cx));
5282//         });
5283
5284//         // Unzoom and close the panel, zoom the active pane.
5285//         panel.update(cx, |panel, cx| panel.set_zoomed(false, cx));
5286//         workspace.update(cx, |workspace, cx| {
5287//             workspace.toggle_dock(DockPosition::Right, cx)
5288//         });
5289//         pane.update(cx, |pane, cx| pane.toggle_zoom(&Default::default(), cx));
5290
5291//         // Opening a dock unzooms the pane.
5292//         workspace.update(cx, |workspace, cx| {
5293//             workspace.toggle_dock(DockPosition::Right, cx)
5294//         });
5295//         workspace.read_with(cx, |workspace, cx| {
5296//             let pane = pane.read(cx);
5297//             assert!(!pane.is_zoomed());
5298//             assert!(!pane.has_focus());
5299//             assert!(workspace.right_dock().read(cx).is_open());
5300//             assert!(workspace.zoomed.is_none());
5301//         });
5302//     }
5303
5304//     #[gpui::test]
5305//     async fn test_panels(cx: &mut gpui::TestAppContext) {
5306//         init_test(cx);
5307//         let fs = FakeFs::new(cx.background());
5308
5309//         let project = Project::test(fs, [], cx).await;
5310//         let window = cx.add_window(|cx| Workspace::test_new(project, cx));
5311//         let workspace = window.root(cx);
5312
5313//         let (panel_1, panel_2) = workspace.update(cx, |workspace, cx| {
5314//             // Add panel_1 on the left, panel_2 on the right.
5315//             let panel_1 = cx.build_view(|_| TestPanel::new(DockPosition::Left));
5316//             workspace.add_panel(panel_1.clone(), cx);
5317//             workspace
5318//                 .left_dock()
5319//                 .update(cx, |left_dock, cx| left_dock.set_open(true, cx));
5320//             let panel_2 = cx.build_view(|_| TestPanel::new(DockPosition::Right));
5321//             workspace.add_panel(panel_2.clone(), cx);
5322//             workspace
5323//                 .right_dock()
5324//                 .update(cx, |right_dock, cx| right_dock.set_open(true, cx));
5325
5326//             let left_dock = workspace.left_dock();
5327//             assert_eq!(
5328//                 left_dock.read(cx).visible_panel().unwrap().id(),
5329//                 panel_1.id()
5330//             );
5331//             assert_eq!(
5332//                 left_dock.read(cx).active_panel_size(cx).unwrap(),
5333//                 panel_1.size(cx)
5334//             );
5335
5336//             left_dock.update(cx, |left_dock, cx| {
5337//                 left_dock.resize_active_panel(Some(1337.), cx)
5338//             });
5339//             assert_eq!(
5340//                 workspace
5341//                     .right_dock()
5342//                     .read(cx)
5343//                     .visible_panel()
5344//                     .unwrap()
5345//                     .id(),
5346//                 panel_2.id()
5347//             );
5348
5349//             (panel_1, panel_2)
5350//         });
5351
5352//         // Move panel_1 to the right
5353//         panel_1.update(cx, |panel_1, cx| {
5354//             panel_1.set_position(DockPosition::Right, cx)
5355//         });
5356
5357//         workspace.update(cx, |workspace, cx| {
5358//             // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
5359//             // Since it was the only panel on the left, the left dock should now be closed.
5360//             assert!(!workspace.left_dock().read(cx).is_open());
5361//             assert!(workspace.left_dock().read(cx).visible_panel().is_none());
5362//             let right_dock = workspace.right_dock();
5363//             assert_eq!(
5364//                 right_dock.read(cx).visible_panel().unwrap().id(),
5365//                 panel_1.id()
5366//             );
5367//             assert_eq!(right_dock.read(cx).active_panel_size(cx).unwrap(), 1337.);
5368
5369//             // Now we move panel_2Β to the left
5370//             panel_2.set_position(DockPosition::Left, cx);
5371//         });
5372
5373//         workspace.update(cx, |workspace, cx| {
5374//             // Since panel_2 was not visible on the right, we don't open the left dock.
5375//             assert!(!workspace.left_dock().read(cx).is_open());
5376//             // And the right dock is unaffected in it's displaying of panel_1
5377//             assert!(workspace.right_dock().read(cx).is_open());
5378//             assert_eq!(
5379//                 workspace
5380//                     .right_dock()
5381//                     .read(cx)
5382//                     .visible_panel()
5383//                     .unwrap()
5384//                     .id(),
5385//                 panel_1.id()
5386//             );
5387//         });
5388
5389//         // Move panel_1 back to the left
5390//         panel_1.update(cx, |panel_1, cx| {
5391//             panel_1.set_position(DockPosition::Left, cx)
5392//         });
5393
5394//         workspace.update(cx, |workspace, cx| {
5395//             // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
5396//             let left_dock = workspace.left_dock();
5397//             assert!(left_dock.read(cx).is_open());
5398//             assert_eq!(
5399//                 left_dock.read(cx).visible_panel().unwrap().id(),
5400//                 panel_1.id()
5401//             );
5402//             assert_eq!(left_dock.read(cx).active_panel_size(cx).unwrap(), 1337.);
5403//             // And right the dock should be closed as it no longer has any panels.
5404//             assert!(!workspace.right_dock().read(cx).is_open());
5405
5406//             // Now we move panel_1 to the bottom
5407//             panel_1.set_position(DockPosition::Bottom, cx);
5408//         });
5409
5410//         workspace.update(cx, |workspace, cx| {
5411//             // Since panel_1 was visible on the left, we close the left dock.
5412//             assert!(!workspace.left_dock().read(cx).is_open());
5413//             // The bottom dock is sized based on the panel's default size,
5414//             // since the panel orientation changed from vertical to horizontal.
5415//             let bottom_dock = workspace.bottom_dock();
5416//             assert_eq!(
5417//                 bottom_dock.read(cx).active_panel_size(cx).unwrap(),
5418//                 panel_1.size(cx),
5419//             );
5420//             // Close bottom dock and move panel_1 back to the left.
5421//             bottom_dock.update(cx, |bottom_dock, cx| bottom_dock.set_open(false, cx));
5422//             panel_1.set_position(DockPosition::Left, cx);
5423//         });
5424
5425//         // Emit activated event on panel 1
5426//         panel_1.update(cx, |_, cx| cx.emit(TestPanelEvent::Activated));
5427
5428//         // Now the left dock is open and panel_1 is active and focused.
5429//         workspace.read_with(cx, |workspace, cx| {
5430//             let left_dock = workspace.left_dock();
5431//             assert!(left_dock.read(cx).is_open());
5432//             assert_eq!(
5433//                 left_dock.read(cx).visible_panel().unwrap().id(),
5434//                 panel_1.id()
5435//             );
5436//             assert!(panel_1.is_focused(cx));
5437//         });
5438
5439//         // Emit closed event on panel 2, which is not active
5440//         panel_2.update(cx, |_, cx| cx.emit(TestPanelEvent::Closed));
5441
5442//         // Wo don't close the left dock, because panel_2 wasn't the active panel
5443//         workspace.read_with(cx, |workspace, cx| {
5444//             let left_dock = workspace.left_dock();
5445//             assert!(left_dock.read(cx).is_open());
5446//             assert_eq!(
5447//                 left_dock.read(cx).visible_panel().unwrap().id(),
5448//                 panel_1.id()
5449//             );
5450//         });
5451
5452//         // Emitting a ZoomIn event shows the panel as zoomed.
5453//         panel_1.update(cx, |_, cx| cx.emit(TestPanelEvent::ZoomIn));
5454//         workspace.read_with(cx, |workspace, _| {
5455//             assert_eq!(workspace.zoomed, Some(panel_1.downgrade().into_any()));
5456//             assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
5457//         });
5458
5459//         // Move panel to another dock while it is zoomed
5460//         panel_1.update(cx, |panel, cx| panel.set_position(DockPosition::Right, cx));
5461//         workspace.read_with(cx, |workspace, _| {
5462//             assert_eq!(workspace.zoomed, Some(panel_1.downgrade().into_any()));
5463//             assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
5464//         });
5465
5466//         // If focus is transferred to another view that's not a panel or another pane, we still show
5467//         // the panel as zoomed.
5468//         let focus_receiver = window.build_view(cx, |_| EmptyView);
5469//         focus_receiver.update(cx, |_, cx| cx.focus_self());
5470//         workspace.read_with(cx, |workspace, _| {
5471//             assert_eq!(workspace.zoomed, Some(panel_1.downgrade().into_any()));
5472//             assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
5473//         });
5474
5475//         // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
5476//         workspace.update(cx, |_, cx| cx.focus_self());
5477//         workspace.read_with(cx, |workspace, _| {
5478//             assert_eq!(workspace.zoomed, None);
5479//             assert_eq!(workspace.zoomed_position, None);
5480//         });
5481
5482//         // If focus is transferred again to another view that's not a panel or a pane, we won't
5483//         // show the panel as zoomed because it wasn't zoomed before.
5484//         focus_receiver.update(cx, |_, cx| cx.focus_self());
5485//         workspace.read_with(cx, |workspace, _| {
5486//             assert_eq!(workspace.zoomed, None);
5487//             assert_eq!(workspace.zoomed_position, None);
5488//         });
5489
5490//         // When focus is transferred back to the panel, it is zoomed again.
5491//         panel_1.update(cx, |_, cx| cx.focus_self());
5492//         workspace.read_with(cx, |workspace, _| {
5493//             assert_eq!(workspace.zoomed, Some(panel_1.downgrade().into_any()));
5494//             assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
5495//         });
5496
5497//         // Emitting a ZoomOut event unzooms the panel.
5498//         panel_1.update(cx, |_, cx| cx.emit(TestPanelEvent::ZoomOut));
5499//         workspace.read_with(cx, |workspace, _| {
5500//             assert_eq!(workspace.zoomed, None);
5501//             assert_eq!(workspace.zoomed_position, None);
5502//         });
5503
5504//         // Emit closed event on panel 1, which is active
5505//         panel_1.update(cx, |_, cx| cx.emit(TestPanelEvent::Closed));
5506
5507//         // Now the left dock is closed, because panel_1 was the active panel
5508//         workspace.read_with(cx, |workspace, cx| {
5509//             let right_dock = workspace.right_dock();
5510//             assert!(!right_dock.read(cx).is_open());
5511//         });
5512//     }
5513
5514//     pub fn init_test(cx: &mut TestAppContext) {
5515//         cx.foreground().forbid_parking();
5516//         cx.update(|cx| {
5517//             cx.set_global(SettingsStore::test(cx));
5518//             theme::init((), cx);
5519//             language::init(cx);
5520//             crate::init_settings(cx);
5521//             Project::init_settings(cx);
5522//         });
5523//     }
5524// }