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