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// pub mod shared_screen;
  12mod status_bar;
  13mod toolbar;
  14mod workspace_settings;
  15
  16pub use crate::persistence::{
  17    model::{
  18        DockData, DockStructure, ItemId, SerializedItem, SerializedPane, SerializedPaneGroup,
  19        SerializedWorkspace,
  20    },
  21    WorkspaceDb,
  22};
  23use anyhow::{anyhow, Context as _, Result};
  24use call2::ActiveCall;
  25use client2::{
  26    proto::{self, PeerId},
  27    Client, TypedEnvelope, UserStore,
  28};
  29use collections::{HashMap, HashSet};
  30use dock::{Dock, DockPosition, PanelButtons};
  31use futures::{
  32    channel::{mpsc, oneshot},
  33    future::try_join_all,
  34    Future, FutureExt, StreamExt,
  35};
  36use gpui2::{
  37    div, point, size, AnyModel, AnyView, AnyWeakView, AppContext, AsyncAppContext,
  38    AsyncWindowContext, Bounds, Component, Div, EntityId, EventEmitter, GlobalPixels, Model,
  39    ModelContext, ParentElement, Point, Render, Size, StatefulInteractive, Styled, Subscription,
  40    Task, View, ViewContext, VisualContext, WeakView, WindowBounds, WindowContext, WindowHandle,
  41    WindowOptions,
  42};
  43use item::{FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, ProjectItem};
  44use language2::LanguageRegistry;
  45use lazy_static::lazy_static;
  46use node_runtime::NodeRuntime;
  47use notifications::{simple_message_notification::MessageNotification, NotificationHandle};
  48pub use pane::*;
  49pub use pane_group::*;
  50use persistence::{model::WorkspaceLocation, DB};
  51use postage::stream::Stream;
  52use project2::{Project, ProjectEntryId, ProjectPath, Worktree};
  53use serde::Deserialize;
  54use settings2::Settings;
  55use status_bar::StatusBar;
  56pub use status_bar::StatusItemView;
  57use std::{
  58    any::TypeId,
  59    borrow::Cow,
  60    env,
  61    path::{Path, PathBuf},
  62    sync::{atomic::AtomicUsize, Arc},
  63    time::Duration,
  64};
  65use theme2::ActiveTheme;
  66pub use toolbar::{ToolbarItemLocation, ToolbarItemView};
  67use util::ResultExt;
  68use uuid::Uuid;
  69use workspace_settings::{AutosaveSetting, WorkspaceSettings};
  70
  71lazy_static! {
  72    static ref ZED_WINDOW_SIZE: Option<Size<GlobalPixels>> = env::var("ZED_WINDOW_SIZE")
  73        .ok()
  74        .as_deref()
  75        .and_then(parse_pixel_size_env_var);
  76    static ref ZED_WINDOW_POSITION: Option<Point<GlobalPixels>> = env::var("ZED_WINDOW_POSITION")
  77        .ok()
  78        .as_deref()
  79        .and_then(parse_pixel_position_env_var);
  80}
  81
  82// pub trait Modal: View {
  83//     fn has_focus(&self) -> bool;
  84//     fn dismiss_on_event(event: &Self::Event) -> bool;
  85// }
  86
  87// trait ModalHandle {
  88//     fn as_any(&self) -> &AnyViewHandle;
  89//     fn has_focus(&self, cx: &WindowContext) -> bool;
  90// }
  91
  92// impl<T: Modal> ModalHandle for View<T> {
  93//     fn as_any(&self) -> &AnyViewHandle {
  94//         self
  95//     }
  96
  97//     fn has_focus(&self, cx: &WindowContext) -> bool {
  98//         self.read(cx).has_focus()
  99//     }
 100// }
 101
 102// #[derive(Clone, PartialEq)]
 103// pub struct RemoveWorktreeFromProject(pub WorktreeId);
 104
 105// actions!(
 106//     workspace,
 107//     [
 108//         Open,
 109//         NewFile,
 110//         NewWindow,
 111//         CloseWindow,
 112//         CloseInactiveTabsAndPanes,
 113//         AddFolderToProject,
 114//         Unfollow,
 115//         SaveAs,
 116//         ReloadActiveItem,
 117//         ActivatePreviousPane,
 118//         ActivateNextPane,
 119//         FollowNextCollaborator,
 120//         NewTerminal,
 121//         NewCenterTerminal,
 122//         ToggleTerminalFocus,
 123//         NewSearch,
 124//         Feedback,
 125//         Restart,
 126//         Welcome,
 127//         ToggleZoom,
 128//         ToggleLeftDock,
 129//         ToggleRightDock,
 130//         ToggleBottomDock,
 131//         CloseAllDocks,
 132//     ]
 133// );
 134
 135// #[derive(Clone, PartialEq)]
 136// pub struct OpenPaths {
 137//     pub paths: Vec<PathBuf>,
 138// }
 139
 140// #[derive(Clone, Deserialize, PartialEq)]
 141// pub struct ActivatePane(pub usize);
 142
 143// #[derive(Clone, Deserialize, PartialEq)]
 144// pub struct ActivatePaneInDirection(pub SplitDirection);
 145
 146// #[derive(Clone, Deserialize, PartialEq)]
 147// pub struct SwapPaneInDirection(pub SplitDirection);
 148
 149// #[derive(Clone, Deserialize, PartialEq)]
 150// pub struct NewFileInDirection(pub SplitDirection);
 151
 152// #[derive(Clone, PartialEq, Debug, Deserialize)]
 153// #[serde(rename_all = "camelCase")]
 154// pub struct SaveAll {
 155//     pub save_intent: Option<SaveIntent>,
 156// }
 157
 158// #[derive(Clone, PartialEq, Debug, Deserialize)]
 159// #[serde(rename_all = "camelCase")]
 160// pub struct Save {
 161//     pub save_intent: Option<SaveIntent>,
 162// }
 163
 164// #[derive(Clone, PartialEq, Debug, Deserialize, Default)]
 165// #[serde(rename_all = "camelCase")]
 166// pub struct CloseAllItemsAndPanes {
 167//     pub save_intent: Option<SaveIntent>,
 168// }
 169
 170#[derive(Deserialize)]
 171pub struct Toast {
 172    id: usize,
 173    msg: Cow<'static, str>,
 174    #[serde(skip)]
 175    on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut WindowContext)>)>,
 176}
 177
 178// impl Toast {
 179//     pub fn new<I: Into<Cow<'static, str>>>(id: usize, msg: I) -> Self {
 180//         Toast {
 181//             id,
 182//             msg: msg.into(),
 183//             on_click: None,
 184//         }
 185//     }
 186
 187//     pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
 188//     where
 189//         M: Into<Cow<'static, str>>,
 190//         F: Fn(&mut WindowContext) + 'static,
 191//     {
 192//         self.on_click = Some((message.into(), Arc::new(on_click)));
 193//         self
 194//     }
 195// }
 196
 197// impl PartialEq for Toast {
 198//     fn eq(&self, other: &Self) -> bool {
 199//         self.id == other.id
 200//             && self.msg == other.msg
 201//             && self.on_click.is_some() == other.on_click.is_some()
 202//     }
 203// }
 204
 205// impl Clone for Toast {
 206//     fn clone(&self) -> Self {
 207//         Toast {
 208//             id: self.id,
 209//             msg: self.msg.to_owned(),
 210//             on_click: self.on_click.clone(),
 211//         }
 212//     }
 213// }
 214
 215// #[derive(Clone, Deserialize, PartialEq)]
 216// pub struct OpenTerminal {
 217//     pub working_directory: PathBuf,
 218// }
 219
 220// impl_actions!(
 221//     workspace,
 222//     [
 223//         ActivatePane,
 224//         ActivatePaneInDirection,
 225//         SwapPaneInDirection,
 226//         NewFileInDirection,
 227//         Toast,
 228//         OpenTerminal,
 229//         SaveAll,
 230//         Save,
 231//         CloseAllItemsAndPanes,
 232//     ]
 233// );
 234
 235pub type WorkspaceId = i64;
 236
 237pub fn init_settings(cx: &mut AppContext) {
 238    WorkspaceSettings::register(cx);
 239    ItemSettings::register(cx);
 240}
 241
 242pub fn init(app_state: Arc<AppState>, cx: &mut AppContext) {
 243    init_settings(cx);
 244    pane::init(cx);
 245    notifications::init(cx);
 246
 247    //     cx.add_global_action({
 248    //         let app_state = Arc::downgrade(&app_state);
 249    //         move |_: &Open, cx: &mut AppContext| {
 250    //             let mut paths = cx.prompt_for_paths(PathPromptOptions {
 251    //                 files: true,
 252    //                 directories: true,
 253    //                 multiple: true,
 254    //             });
 255
 256    //             if let Some(app_state) = app_state.upgrade() {
 257    //                 cx.spawn(move |mut cx| async move {
 258    //                     if let Some(paths) = paths.recv().await.flatten() {
 259    //                         cx.update(|cx| {
 260    //                             open_paths(&paths, &app_state, None, cx).detach_and_log_err(cx)
 261    //                         });
 262    //                     }
 263    //                 })
 264    //                 .detach();
 265    //             }
 266    //         }
 267    //     });
 268    //     cx.add_async_action(Workspace::open);
 269
 270    //     cx.add_async_action(Workspace::follow_next_collaborator);
 271    //     cx.add_async_action(Workspace::close);
 272    //     cx.add_async_action(Workspace::close_inactive_items_and_panes);
 273    //     cx.add_async_action(Workspace::close_all_items_and_panes);
 274    //     cx.add_global_action(Workspace::close_global);
 275    //     cx.add_global_action(restart);
 276    //     cx.add_async_action(Workspace::save_all);
 277    //     cx.add_action(Workspace::add_folder_to_project);
 278    //     cx.add_action(
 279    //         |workspace: &mut Workspace, _: &Unfollow, cx: &mut ViewContext<Workspace>| {
 280    //             let pane = workspace.active_pane().clone();
 281    //             workspace.unfollow(&pane, cx);
 282    //         },
 283    //     );
 284    //     cx.add_action(
 285    //         |workspace: &mut Workspace, action: &Save, cx: &mut ViewContext<Workspace>| {
 286    //             workspace
 287    //                 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), cx)
 288    //                 .detach_and_log_err(cx);
 289    //         },
 290    //     );
 291    //     cx.add_action(
 292    //         |workspace: &mut Workspace, _: &SaveAs, cx: &mut ViewContext<Workspace>| {
 293    //             workspace
 294    //                 .save_active_item(SaveIntent::SaveAs, cx)
 295    //                 .detach_and_log_err(cx);
 296    //         },
 297    //     );
 298    //     cx.add_action(|workspace: &mut Workspace, _: &ActivatePreviousPane, cx| {
 299    //         workspace.activate_previous_pane(cx)
 300    //     });
 301    //     cx.add_action(|workspace: &mut Workspace, _: &ActivateNextPane, cx| {
 302    //         workspace.activate_next_pane(cx)
 303    //     });
 304
 305    //     cx.add_action(
 306    //         |workspace: &mut Workspace, action: &ActivatePaneInDirection, cx| {
 307    //             workspace.activate_pane_in_direction(action.0, cx)
 308    //         },
 309    //     );
 310
 311    //     cx.add_action(
 312    //         |workspace: &mut Workspace, action: &SwapPaneInDirection, cx| {
 313    //             workspace.swap_pane_in_direction(action.0, cx)
 314    //         },
 315    //     );
 316
 317    //     cx.add_action(|workspace: &mut Workspace, _: &ToggleLeftDock, cx| {
 318    //         workspace.toggle_dock(DockPosition::Left, cx);
 319    //     });
 320    //     cx.add_action(|workspace: &mut Workspace, _: &ToggleRightDock, cx| {
 321    //         workspace.toggle_dock(DockPosition::Right, cx);
 322    //     });
 323    //     cx.add_action(|workspace: &mut Workspace, _: &ToggleBottomDock, cx| {
 324    //         workspace.toggle_dock(DockPosition::Bottom, cx);
 325    //     });
 326    //     cx.add_action(|workspace: &mut Workspace, _: &CloseAllDocks, cx| {
 327    //         workspace.close_all_docks(cx);
 328    //     });
 329    //     cx.add_action(Workspace::activate_pane_at_index);
 330    //     cx.add_action(|workspace: &mut Workspace, _: &ReopenClosedItem, cx| {
 331    //         workspace.reopen_closed_item(cx).detach();
 332    //     });
 333    //     cx.add_action(|workspace: &mut Workspace, _: &GoBack, cx| {
 334    //         workspace
 335    //             .go_back(workspace.active_pane().downgrade(), cx)
 336    //             .detach();
 337    //     });
 338    //     cx.add_action(|workspace: &mut Workspace, _: &GoForward, cx| {
 339    //         workspace
 340    //             .go_forward(workspace.active_pane().downgrade(), cx)
 341    //             .detach();
 342    //     });
 343
 344    //     cx.add_action(|_: &mut Workspace, _: &install_cli::Install, cx| {
 345    //         cx.spawn(|workspace, mut cx| async move {
 346    //             let err = install_cli::install_cli(&cx)
 347    //                 .await
 348    //                 .context("Failed to create CLI symlink");
 349
 350    //             workspace.update(&mut cx, |workspace, cx| {
 351    //                 if matches!(err, Err(_)) {
 352    //                     err.notify_err(workspace, cx);
 353    //                 } else {
 354    //                     workspace.show_notification(1, cx, |cx| {
 355    //                         cx.build_view(|_| {
 356    //                             MessageNotification::new("Successfully installed the `zed` binary")
 357    //                         })
 358    //                     });
 359    //                 }
 360    //             })
 361    //         })
 362    //         .detach();
 363    //     });
 364}
 365
 366type ProjectItemBuilders =
 367    HashMap<TypeId, fn(Model<Project>, AnyModel, &mut ViewContext<Pane>) -> Box<dyn ItemHandle>>;
 368pub fn register_project_item<I: ProjectItem>(cx: &mut AppContext) {
 369    let builders = cx.default_global::<ProjectItemBuilders>();
 370    builders.insert(TypeId::of::<I::Item>(), |project, model, cx| {
 371        let item = model.downcast::<I::Item>().unwrap();
 372        Box::new(cx.build_view(|cx| I::for_project_item(project, item, cx)))
 373    });
 374}
 375
 376type FollowableItemBuilder = fn(
 377    View<Pane>,
 378    View<Workspace>,
 379    ViewId,
 380    &mut Option<proto::view::Variant>,
 381    &mut AppContext,
 382) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>;
 383type FollowableItemBuilders = HashMap<
 384    TypeId,
 385    (
 386        FollowableItemBuilder,
 387        fn(&AnyView) -> Box<dyn FollowableItemHandle>,
 388    ),
 389>;
 390pub fn register_followable_item<I: FollowableItem>(cx: &mut AppContext) {
 391    let builders = cx.default_global::<FollowableItemBuilders>();
 392    builders.insert(
 393        TypeId::of::<I>(),
 394        (
 395            |pane, workspace, id, state, cx| {
 396                I::from_state_proto(pane, workspace, id, state, cx).map(|task| {
 397                    cx.foreground_executor()
 398                        .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
 399                })
 400            },
 401            |this| Box::new(this.clone().downcast::<I>().unwrap()),
 402        ),
 403    );
 404}
 405
 406type ItemDeserializers = HashMap<
 407    Arc<str>,
 408    fn(
 409        Model<Project>,
 410        WeakView<Workspace>,
 411        WorkspaceId,
 412        ItemId,
 413        &mut ViewContext<Pane>,
 414    ) -> Task<Result<Box<dyn ItemHandle>>>,
 415>;
 416pub fn register_deserializable_item<I: Item>(cx: &mut AppContext) {
 417    if let Some(serialized_item_kind) = I::serialized_item_kind() {
 418        let deserializers = cx.default_global::<ItemDeserializers>();
 419        deserializers.insert(
 420            Arc::from(serialized_item_kind),
 421            |project, workspace, workspace_id, item_id, cx| {
 422                let task = I::deserialize(project, workspace, workspace_id, item_id, cx);
 423                cx.foreground_executor()
 424                    .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
 425            },
 426        );
 427    }
 428}
 429
 430pub struct AppState {
 431    pub languages: Arc<LanguageRegistry>,
 432    pub client: Arc<Client>,
 433    pub user_store: Model<UserStore>,
 434    pub workspace_store: Model<WorkspaceStore>,
 435    pub fs: Arc<dyn fs2::Fs>,
 436    pub build_window_options:
 437        fn(Option<WindowBounds>, Option<Uuid>, &mut AppContext) -> WindowOptions,
 438    pub initialize_workspace: fn(
 439        WeakView<Workspace>,
 440        bool,
 441        Arc<AppState>,
 442        AsyncWindowContext,
 443    ) -> Task<anyhow::Result<()>>,
 444    pub node_runtime: Arc<dyn NodeRuntime>,
 445}
 446
 447pub struct WorkspaceStore {
 448    workspaces: HashSet<WindowHandle<Workspace>>,
 449    followers: Vec<Follower>,
 450    client: Arc<Client>,
 451    _subscriptions: Vec<client2::Subscription>,
 452}
 453
 454#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
 455struct Follower {
 456    project_id: Option<u64>,
 457    peer_id: PeerId,
 458}
 459
 460impl AppState {
 461    #[cfg(any(test, feature = "test-support"))]
 462    pub fn test(cx: &mut AppContext) -> Arc<Self> {
 463        use gpui2::Context;
 464        use node_runtime::FakeNodeRuntime;
 465        use settings2::SettingsStore;
 466
 467        if !cx.has_global::<SettingsStore>() {
 468            let settings_store = SettingsStore::test(cx);
 469            cx.set_global(settings_store);
 470        }
 471
 472        let fs = fs2::FakeFs::new(cx.background_executor().clone());
 473        let languages = Arc::new(LanguageRegistry::test());
 474        let http_client = util::http::FakeHttpClient::with_404_response();
 475        let client = Client::new(http_client.clone(), cx);
 476        let user_store = cx.build_model(|cx| UserStore::new(client.clone(), http_client, cx));
 477        let workspace_store = cx.build_model(|cx| WorkspaceStore::new(client.clone(), cx));
 478
 479        // todo!()
 480        // theme::init((), cx);
 481        client2::init(&client, cx);
 482        crate::init_settings(cx);
 483
 484        Arc::new(Self {
 485            client,
 486            fs,
 487            languages,
 488            user_store,
 489            workspace_store,
 490            node_runtime: FakeNodeRuntime::new(),
 491            initialize_workspace: |_, _, _, _| Task::ready(Ok(())),
 492            build_window_options: |_, _, _| Default::default(),
 493        })
 494    }
 495}
 496
 497struct DelayedDebouncedEditAction {
 498    task: Option<Task<()>>,
 499    cancel_channel: Option<oneshot::Sender<()>>,
 500}
 501
 502impl DelayedDebouncedEditAction {
 503    fn new() -> DelayedDebouncedEditAction {
 504        DelayedDebouncedEditAction {
 505            task: None,
 506            cancel_channel: None,
 507        }
 508    }
 509
 510    fn fire_new<F>(&mut self, delay: Duration, cx: &mut ViewContext<Workspace>, func: F)
 511    where
 512        F: 'static + Send + FnOnce(&mut Workspace, &mut ViewContext<Workspace>) -> Task<Result<()>>,
 513    {
 514        if let Some(channel) = self.cancel_channel.take() {
 515            _ = channel.send(());
 516        }
 517
 518        let (sender, mut receiver) = oneshot::channel::<()>();
 519        self.cancel_channel = Some(sender);
 520
 521        let previous_task = self.task.take();
 522        self.task = Some(cx.spawn(move |workspace, mut cx| async move {
 523            let mut timer = cx.background_executor().timer(delay).fuse();
 524            if let Some(previous_task) = previous_task {
 525                previous_task.await;
 526            }
 527
 528            futures::select_biased! {
 529                _ = receiver => return,
 530                    _ = timer => {}
 531            }
 532
 533            if let Some(result) = workspace
 534                .update(&mut cx, |workspace, cx| (func)(workspace, cx))
 535                .log_err()
 536            {
 537                result.await.log_err();
 538            }
 539        }));
 540    }
 541}
 542
 543pub enum Event {
 544    PaneAdded(View<Pane>),
 545    ContactRequestedJoin(u64),
 546}
 547
 548pub struct Workspace {
 549    weak_self: WeakView<Self>,
 550    //     modal: Option<ActiveModal>,
 551    zoomed: Option<AnyWeakView>,
 552    //     zoomed_position: Option<DockPosition>,
 553    center: PaneGroup,
 554    left_dock: View<Dock>,
 555    bottom_dock: View<Dock>,
 556    right_dock: View<Dock>,
 557    panes: Vec<View<Pane>>,
 558    panes_by_item: HashMap<EntityId, WeakView<Pane>>,
 559    active_pane: View<Pane>,
 560    last_active_center_pane: Option<WeakView<Pane>>,
 561    last_active_view_id: Option<proto::ViewId>,
 562    status_bar: View<StatusBar>,
 563    //     titlebar_item: Option<AnyViewHandle>,
 564    notifications: Vec<(TypeId, usize, Box<dyn NotificationHandle>)>,
 565    project: Model<Project>,
 566    follower_states: HashMap<View<Pane>, FollowerState>,
 567    last_leaders_by_pane: HashMap<WeakView<Pane>, PeerId>,
 568    window_edited: bool,
 569    active_call: Option<(Model<ActiveCall>, Vec<Subscription>)>,
 570    leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
 571    database_id: WorkspaceId,
 572    app_state: Arc<AppState>,
 573    subscriptions: Vec<Subscription>,
 574    _apply_leader_updates: Task<Result<()>>,
 575    _observe_current_user: Task<Result<()>>,
 576    _schedule_serialize: Option<Task<()>>,
 577    pane_history_timestamp: Arc<AtomicUsize>,
 578}
 579
 580// struct ActiveModal {
 581//     view: Box<dyn ModalHandle>,
 582//     previously_focused_view_id: Option<usize>,
 583// }
 584
 585#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 586pub struct ViewId {
 587    pub creator: PeerId,
 588    pub id: u64,
 589}
 590
 591#[derive(Default)]
 592struct FollowerState {
 593    leader_id: PeerId,
 594    active_view_id: Option<ViewId>,
 595    items_by_leader_view_id: HashMap<ViewId, Box<dyn FollowableItemHandle>>,
 596}
 597
 598enum WorkspaceBounds {}
 599
 600impl Workspace {
 601    pub fn new(
 602        workspace_id: WorkspaceId,
 603        project: Model<Project>,
 604        app_state: Arc<AppState>,
 605        cx: &mut ViewContext<Self>,
 606    ) -> Self {
 607        cx.observe(&project, |_, _, cx| cx.notify()).detach();
 608        cx.subscribe(&project, move |this, _, event, cx| {
 609            match event {
 610                project2::Event::RemoteIdChanged(_) => {
 611                    this.update_window_title(cx);
 612                }
 613
 614                project2::Event::CollaboratorLeft(peer_id) => {
 615                    this.collaborator_left(*peer_id, cx);
 616                }
 617
 618                project2::Event::WorktreeRemoved(_) | project2::Event::WorktreeAdded => {
 619                    this.update_window_title(cx);
 620                    this.serialize_workspace(cx);
 621                }
 622
 623                project2::Event::DisconnectedFromHost => {
 624                    this.update_window_edited(cx);
 625                    cx.blur();
 626                }
 627
 628                project2::Event::Closed => {
 629                    cx.remove_window();
 630                }
 631
 632                project2::Event::DeletedEntry(entry_id) => {
 633                    for pane in this.panes.iter() {
 634                        pane.update(cx, |pane, cx| {
 635                            pane.handle_deleted_project_item(*entry_id, cx)
 636                        });
 637                    }
 638                }
 639
 640                project2::Event::Notification(message) => this.show_notification(0, cx, |cx| {
 641                    cx.build_view(|_| MessageNotification::new(message.clone()))
 642                }),
 643
 644                _ => {}
 645            }
 646            cx.notify()
 647        })
 648        .detach();
 649
 650        let weak_handle = cx.view().downgrade();
 651        let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
 652
 653        let center_pane = cx.build_view(|cx| {
 654            Pane::new(
 655                weak_handle.clone(),
 656                project.clone(),
 657                pane_history_timestamp.clone(),
 658                cx,
 659            )
 660        });
 661        cx.subscribe(&center_pane, Self::handle_pane_event).detach();
 662        // todo!()
 663        // cx.focus(&center_pane);
 664        cx.emit(Event::PaneAdded(center_pane.clone()));
 665
 666        let window_handle = cx.window_handle().downcast::<Workspace>().unwrap();
 667        app_state.workspace_store.update(cx, |store, _| {
 668            store.workspaces.insert(window_handle);
 669        });
 670
 671        let mut current_user = app_state.user_store.read(cx).watch_current_user();
 672        let mut connection_status = app_state.client.status();
 673        let _observe_current_user = cx.spawn(|this, mut cx| async move {
 674            current_user.next().await;
 675            connection_status.next().await;
 676            let mut stream =
 677                Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
 678
 679            while stream.recv().await.is_some() {
 680                this.update(&mut cx, |_, cx| cx.notify())?;
 681            }
 682            anyhow::Ok(())
 683        });
 684
 685        // All leader updates are enqueued and then processed in a single task, so
 686        // that each asynchronous operation can be run in order.
 687        let (leader_updates_tx, mut leader_updates_rx) =
 688            mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
 689        let _apply_leader_updates = cx.spawn(|this, mut cx| async move {
 690            while let Some((leader_id, update)) = leader_updates_rx.next().await {
 691                Self::process_leader_update(&this, leader_id, update, &mut cx)
 692                    .await
 693                    .log_err();
 694            }
 695
 696            Ok(())
 697        });
 698
 699        // todo!("replace with a different mechanism")
 700        // cx.emit_global(WorkspaceCreated(weak_handle.clone()));
 701
 702        let left_dock = cx.build_view(|_| Dock::new(DockPosition::Left));
 703        let bottom_dock = cx.build_view(|_| Dock::new(DockPosition::Bottom));
 704        let right_dock = cx.build_view(|_| Dock::new(DockPosition::Right));
 705        let left_dock_buttons =
 706            cx.build_view(|cx| PanelButtons::new(left_dock.clone(), weak_handle.clone(), cx));
 707        let bottom_dock_buttons =
 708            cx.build_view(|cx| PanelButtons::new(bottom_dock.clone(), weak_handle.clone(), cx));
 709        let right_dock_buttons =
 710            cx.build_view(|cx| PanelButtons::new(right_dock.clone(), weak_handle.clone(), cx));
 711        let status_bar = cx.build_view(|cx| {
 712            let mut status_bar = StatusBar::new(&center_pane.clone(), cx);
 713            status_bar.add_left_item(left_dock_buttons, cx);
 714            status_bar.add_right_item(right_dock_buttons, cx);
 715            status_bar.add_right_item(bottom_dock_buttons, cx);
 716            status_bar
 717        });
 718
 719        // todo!()
 720        // cx.update_default_global::<DragAndDrop<Workspace>, _, _>(|drag_and_drop, _| {
 721        //     drag_and_drop.register_container(weak_handle.clone());
 722        // });
 723
 724        let mut active_call = None;
 725        if cx.has_global::<Model<ActiveCall>>() {
 726            let call = cx.global::<Model<ActiveCall>>().clone();
 727            let mut subscriptions = Vec::new();
 728            subscriptions.push(cx.subscribe(&call, Self::on_active_call_event));
 729            active_call = Some((call, subscriptions));
 730        }
 731
 732        let subscriptions = vec![
 733            cx.observe_window_activation(Self::on_window_activation_changed),
 734            cx.observe_window_bounds(move |_, cx| {
 735                if let Some(display) = cx.display() {
 736                    // Transform fixed bounds to be stored in terms of the containing display
 737                    let mut bounds = cx.window_bounds();
 738                    if let WindowBounds::Fixed(window_bounds) = &mut bounds {
 739                        let display_bounds = display.bounds();
 740                        window_bounds.origin.x -= display_bounds.origin.x;
 741                        window_bounds.origin.y -= display_bounds.origin.y;
 742                    }
 743
 744                    if let Some(display_uuid) = display.uuid().log_err() {
 745                        cx.background_executor()
 746                            .spawn(DB.set_window_bounds(workspace_id, bounds, display_uuid))
 747                            .detach_and_log_err(cx);
 748                    }
 749                }
 750                cx.notify();
 751            }),
 752            cx.observe(&left_dock, |this, _, cx| {
 753                this.serialize_workspace(cx);
 754                cx.notify();
 755            }),
 756            cx.observe(&bottom_dock, |this, _, cx| {
 757                this.serialize_workspace(cx);
 758                cx.notify();
 759            }),
 760            cx.observe(&right_dock, |this, _, cx| {
 761                this.serialize_workspace(cx);
 762                cx.notify();
 763            }),
 764        ];
 765
 766        cx.defer(|this, cx| this.update_window_title(cx));
 767        Workspace {
 768            weak_self: weak_handle.clone(),
 769            // modal: None,
 770            zoomed: None,
 771            // zoomed_position: None,
 772            center: PaneGroup::new(center_pane.clone()),
 773            panes: vec![center_pane.clone()],
 774            panes_by_item: Default::default(),
 775            active_pane: center_pane.clone(),
 776            last_active_center_pane: Some(center_pane.downgrade()),
 777            last_active_view_id: None,
 778            status_bar,
 779            // titlebar_item: None,
 780            notifications: Default::default(),
 781            left_dock,
 782            bottom_dock,
 783            right_dock,
 784            project: project.clone(),
 785            follower_states: Default::default(),
 786            last_leaders_by_pane: Default::default(),
 787            window_edited: false,
 788            active_call,
 789            database_id: workspace_id,
 790            app_state,
 791            _observe_current_user,
 792            _apply_leader_updates,
 793            _schedule_serialize: None,
 794            leader_updates_tx,
 795            subscriptions,
 796            pane_history_timestamp,
 797        }
 798    }
 799
 800    fn new_local(
 801        abs_paths: Vec<PathBuf>,
 802        app_state: Arc<AppState>,
 803        _requesting_window: Option<WindowHandle<Workspace>>,
 804        cx: &mut AppContext,
 805    ) -> Task<
 806        anyhow::Result<(
 807            WindowHandle<Workspace>,
 808            Vec<Option<Result<Box<dyn ItemHandle>, anyhow::Error>>>,
 809        )>,
 810    > {
 811        let project_handle = Project::local(
 812            app_state.client.clone(),
 813            app_state.node_runtime.clone(),
 814            app_state.user_store.clone(),
 815            app_state.languages.clone(),
 816            app_state.fs.clone(),
 817            cx,
 818        );
 819
 820        cx.spawn(|mut cx| async move {
 821            let serialized_workspace: Option<SerializedWorkspace> = None; //persistence::DB.workspace_for_roots(&abs_paths.as_slice());
 822
 823            let paths_to_open = Arc::new(abs_paths);
 824
 825            // Get project paths for all of the abs_paths
 826            let mut worktree_roots: HashSet<Arc<Path>> = Default::default();
 827            let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
 828                Vec::with_capacity(paths_to_open.len());
 829            for path in paths_to_open.iter().cloned() {
 830                if let Some((worktree, project_entry)) = cx
 831                    .update(|cx| {
 832                        Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
 833                    })?
 834                    .await
 835                    .log_err()
 836                {
 837                    worktree_roots.extend(worktree.update(&mut cx, |tree, _| tree.abs_path()).ok());
 838                    project_paths.push((path, Some(project_entry)));
 839                } else {
 840                    project_paths.push((path, None));
 841                }
 842            }
 843
 844            let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
 845                serialized_workspace.id
 846            } else {
 847                DB.next_id().await.unwrap_or(0)
 848            };
 849
 850            // todo!()
 851            let window = /*if let Some(window) = requesting_window {
 852                cx.update_window(window.into(), |old_workspace, cx| {
 853                    cx.replace_root_view(|cx| {
 854                        Workspace::new(workspace_id, project_handle.clone(), app_state.clone(), cx)
 855                    });
 856                });
 857                window
 858                } else */ {
 859                let window_bounds_override = window_bounds_env_override(&cx);
 860                let (bounds, display) = if let Some(bounds) = window_bounds_override {
 861                    (Some(bounds), None)
 862                } else {
 863                    serialized_workspace
 864                        .as_ref()
 865                        .and_then(|serialized_workspace| {
 866                            let serialized_display = serialized_workspace.display?;
 867                            let mut bounds = serialized_workspace.bounds?;
 868
 869                            // Stored bounds are relative to the containing display.
 870                            // So convert back to global coordinates if that screen still exists
 871                            if let WindowBounds::Fixed(mut window_bounds) = bounds {
 872                                let screen =
 873                                    cx.update(|cx|
 874                                        cx.displays()
 875                                            .into_iter()
 876                                            .find(|display| display.uuid().ok() == Some(serialized_display))
 877                                    ).ok()??;
 878                                let screen_bounds = screen.bounds();
 879                                window_bounds.origin.x += screen_bounds.origin.x;
 880                                window_bounds.origin.y += screen_bounds.origin.y;
 881                                bounds = WindowBounds::Fixed(window_bounds);
 882                            }
 883
 884                            Some((bounds, serialized_display))
 885                        })
 886                        .unzip()
 887                };
 888
 889                // Use the serialized workspace to construct the new window
 890                let options =
 891                    cx.update(|cx| (app_state.build_window_options)(bounds, display, cx))?;
 892
 893                cx.open_window(options, {
 894                    let app_state = app_state.clone();
 895                    let workspace_id = workspace_id.clone();
 896                    let project_handle = project_handle.clone();
 897                    move |cx| {
 898                        cx.build_view(|cx| {
 899                            Workspace::new(workspace_id, project_handle, app_state, cx)
 900                        })
 901                    }
 902                })?
 903            };
 904
 905            // todo!() Ask how to do this
 906            let weak_view = window.update(&mut cx, |_, cx| cx.view().downgrade())?;
 907            let async_cx = window.update(&mut cx, |_, cx| cx.to_async())?;
 908
 909            (app_state.initialize_workspace)(
 910                weak_view,
 911                serialized_workspace.is_some(),
 912                app_state.clone(),
 913                async_cx,
 914            )
 915            .await
 916            .log_err();
 917
 918            window
 919                .update(&mut cx, |_, cx| cx.activate_window())
 920                .log_err();
 921
 922            notify_if_database_failed(window, &mut cx);
 923            let opened_items = window
 924                .update(&mut cx, |_workspace, cx| {
 925                    open_items(
 926                        serialized_workspace,
 927                        project_paths,
 928                        app_state,
 929                        cx,
 930                    )
 931                })?
 932                .await
 933                .unwrap_or_default();
 934
 935            Ok((window, opened_items))
 936        })
 937    }
 938
 939    pub fn weak_handle(&self) -> WeakView<Self> {
 940        self.weak_self.clone()
 941    }
 942
 943    pub fn left_dock(&self) -> &View<Dock> {
 944        &self.left_dock
 945    }
 946
 947    pub fn bottom_dock(&self) -> &View<Dock> {
 948        &self.bottom_dock
 949    }
 950
 951    pub fn right_dock(&self) -> &View<Dock> {
 952        &self.right_dock
 953    }
 954
 955    //     pub fn add_panel<T: Panel>(&mut self, panel: View<T>, cx: &mut ViewContext<Self>)
 956    //     where
 957    //         T::Event: std::fmt::Debug,
 958    //     {
 959    //         self.add_panel_with_extra_event_handler(panel, cx, |_, _, _, _| {})
 960    //     }
 961
 962    //     pub fn add_panel_with_extra_event_handler<T: Panel, F>(
 963    //         &mut self,
 964    //         panel: View<T>,
 965    //         cx: &mut ViewContext<Self>,
 966    //         handler: F,
 967    //     ) where
 968    //         T::Event: std::fmt::Debug,
 969    //         F: Fn(&mut Self, &View<T>, &T::Event, &mut ViewContext<Self>) + 'static,
 970    //     {
 971    //         let dock = match panel.position(cx) {
 972    //             DockPosition::Left => &self.left_dock,
 973    //             DockPosition::Bottom => &self.bottom_dock,
 974    //             DockPosition::Right => &self.right_dock,
 975    //         };
 976
 977    //         self.subscriptions.push(cx.subscribe(&panel, {
 978    //             let mut dock = dock.clone();
 979    //             let mut prev_position = panel.position(cx);
 980    //             move |this, panel, event, cx| {
 981    //                 if T::should_change_position_on_event(event) {
 982    //                     let new_position = panel.read(cx).position(cx);
 983    //                     let mut was_visible = false;
 984    //                     dock.update(cx, |dock, cx| {
 985    //                         prev_position = new_position;
 986
 987    //                         was_visible = dock.is_open()
 988    //                             && dock
 989    //                                 .visible_panel()
 990    //                                 .map_or(false, |active_panel| active_panel.id() == panel.id());
 991    //                         dock.remove_panel(&panel, cx);
 992    //                     });
 993
 994    //                     if panel.is_zoomed(cx) {
 995    //                         this.zoomed_position = Some(new_position);
 996    //                     }
 997
 998    //                     dock = match panel.read(cx).position(cx) {
 999    //                         DockPosition::Left => &this.left_dock,
1000    //                         DockPosition::Bottom => &this.bottom_dock,
1001    //                         DockPosition::Right => &this.right_dock,
1002    //                     }
1003    //                     .clone();
1004    //                     dock.update(cx, |dock, cx| {
1005    //                         dock.add_panel(panel.clone(), cx);
1006    //                         if was_visible {
1007    //                             dock.set_open(true, cx);
1008    //                             dock.activate_panel(dock.panels_len() - 1, cx);
1009    //                         }
1010    //                     });
1011    //                 } else if T::should_zoom_in_on_event(event) {
1012    //                     dock.update(cx, |dock, cx| dock.set_panel_zoomed(&panel, true, cx));
1013    //                     if !panel.has_focus(cx) {
1014    //                         cx.focus(&panel);
1015    //                     }
1016    //                     this.zoomed = Some(panel.downgrade().into_any());
1017    //                     this.zoomed_position = Some(panel.read(cx).position(cx));
1018    //                 } else if T::should_zoom_out_on_event(event) {
1019    //                     dock.update(cx, |dock, cx| dock.set_panel_zoomed(&panel, false, cx));
1020    //                     if this.zoomed_position == Some(prev_position) {
1021    //                         this.zoomed = None;
1022    //                         this.zoomed_position = None;
1023    //                     }
1024    //                     cx.notify();
1025    //                 } else if T::is_focus_event(event) {
1026    //                     let position = panel.read(cx).position(cx);
1027    //                     this.dismiss_zoomed_items_to_reveal(Some(position), cx);
1028    //                     if panel.is_zoomed(cx) {
1029    //                         this.zoomed = Some(panel.downgrade().into_any());
1030    //                         this.zoomed_position = Some(position);
1031    //                     } else {
1032    //                         this.zoomed = None;
1033    //                         this.zoomed_position = None;
1034    //                     }
1035    //                     this.update_active_view_for_followers(cx);
1036    //                     cx.notify();
1037    //                 } else {
1038    //                     handler(this, &panel, event, cx)
1039    //                 }
1040    //             }
1041    //         }));
1042
1043    //         dock.update(cx, |dock, cx| dock.add_panel(panel, cx));
1044    //     }
1045
1046    pub fn status_bar(&self) -> &View<StatusBar> {
1047        &self.status_bar
1048    }
1049
1050    pub fn app_state(&self) -> &Arc<AppState> {
1051        &self.app_state
1052    }
1053
1054    pub fn user_store(&self) -> &Model<UserStore> {
1055        &self.app_state.user_store
1056    }
1057
1058    pub fn project(&self) -> &Model<Project> {
1059        &self.project
1060    }
1061
1062    //     pub fn recent_navigation_history(
1063    //         &self,
1064    //         limit: Option<usize>,
1065    //         cx: &AppContext,
1066    //     ) -> Vec<(ProjectPath, Option<PathBuf>)> {
1067    //         let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
1068    //         let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
1069    //         for pane in &self.panes {
1070    //             let pane = pane.read(cx);
1071    //             pane.nav_history()
1072    //                 .for_each_entry(cx, |entry, (project_path, fs_path)| {
1073    //                     if let Some(fs_path) = &fs_path {
1074    //                         abs_paths_opened
1075    //                             .entry(fs_path.clone())
1076    //                             .or_default()
1077    //                             .insert(project_path.clone());
1078    //                     }
1079    //                     let timestamp = entry.timestamp;
1080    //                     match history.entry(project_path) {
1081    //                         hash_map::Entry::Occupied(mut entry) => {
1082    //                             let (_, old_timestamp) = entry.get();
1083    //                             if &timestamp > old_timestamp {
1084    //                                 entry.insert((fs_path, timestamp));
1085    //                             }
1086    //                         }
1087    //                         hash_map::Entry::Vacant(entry) => {
1088    //                             entry.insert((fs_path, timestamp));
1089    //                         }
1090    //                     }
1091    //                 });
1092    //         }
1093
1094    //         history
1095    //             .into_iter()
1096    //             .sorted_by_key(|(_, (_, timestamp))| *timestamp)
1097    //             .map(|(project_path, (fs_path, _))| (project_path, fs_path))
1098    //             .rev()
1099    //             .filter(|(history_path, abs_path)| {
1100    //                 let latest_project_path_opened = abs_path
1101    //                     .as_ref()
1102    //                     .and_then(|abs_path| abs_paths_opened.get(abs_path))
1103    //                     .and_then(|project_paths| {
1104    //                         project_paths
1105    //                             .iter()
1106    //                             .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
1107    //                     });
1108
1109    //                 match latest_project_path_opened {
1110    //                     Some(latest_project_path_opened) => latest_project_path_opened == history_path,
1111    //                     None => true,
1112    //                 }
1113    //             })
1114    //             .take(limit.unwrap_or(usize::MAX))
1115    //             .collect()
1116    //     }
1117
1118    //     fn navigate_history(
1119    //         &mut self,
1120    //         pane: WeakView<Pane>,
1121    //         mode: NavigationMode,
1122    //         cx: &mut ViewContext<Workspace>,
1123    //     ) -> Task<Result<()>> {
1124    //         let to_load = if let Some(pane) = pane.upgrade(cx) {
1125    //             cx.focus(&pane);
1126
1127    //             pane.update(cx, |pane, cx| {
1128    //                 loop {
1129    //                     // Retrieve the weak item handle from the history.
1130    //                     let entry = pane.nav_history_mut().pop(mode, cx)?;
1131
1132    //                     // If the item is still present in this pane, then activate it.
1133    //                     if let Some(index) = entry
1134    //                         .item
1135    //                         .upgrade(cx)
1136    //                         .and_then(|v| pane.index_for_item(v.as_ref()))
1137    //                     {
1138    //                         let prev_active_item_index = pane.active_item_index();
1139    //                         pane.nav_history_mut().set_mode(mode);
1140    //                         pane.activate_item(index, true, true, cx);
1141    //                         pane.nav_history_mut().set_mode(NavigationMode::Normal);
1142
1143    //                         let mut navigated = prev_active_item_index != pane.active_item_index();
1144    //                         if let Some(data) = entry.data {
1145    //                             navigated |= pane.active_item()?.navigate(data, cx);
1146    //                         }
1147
1148    //                         if navigated {
1149    //                             break None;
1150    //                         }
1151    //                     }
1152    //                     // If the item is no longer present in this pane, then retrieve its
1153    //                     // project path in order to reopen it.
1154    //                     else {
1155    //                         break pane
1156    //                             .nav_history()
1157    //                             .path_for_item(entry.item.id())
1158    //                             .map(|(project_path, _)| (project_path, entry));
1159    //                     }
1160    //                 }
1161    //             })
1162    //         } else {
1163    //             None
1164    //         };
1165
1166    //         if let Some((project_path, entry)) = to_load {
1167    //             // If the item was no longer present, then load it again from its previous path.
1168    //             let task = self.load_path(project_path, cx);
1169    //             cx.spawn(|workspace, mut cx| async move {
1170    //                 let task = task.await;
1171    //                 let mut navigated = false;
1172    //                 if let Some((project_entry_id, build_item)) = task.log_err() {
1173    //                     let prev_active_item_id = pane.update(&mut cx, |pane, _| {
1174    //                         pane.nav_history_mut().set_mode(mode);
1175    //                         pane.active_item().map(|p| p.id())
1176    //                     })?;
1177
1178    //                     pane.update(&mut cx, |pane, cx| {
1179    //                         let item = pane.open_item(project_entry_id, true, cx, build_item);
1180    //                         navigated |= Some(item.id()) != prev_active_item_id;
1181    //                         pane.nav_history_mut().set_mode(NavigationMode::Normal);
1182    //                         if let Some(data) = entry.data {
1183    //                             navigated |= item.navigate(data, cx);
1184    //                         }
1185    //                     })?;
1186    //                 }
1187
1188    //                 if !navigated {
1189    //                     workspace
1190    //                         .update(&mut cx, |workspace, cx| {
1191    //                             Self::navigate_history(workspace, pane, mode, cx)
1192    //                         })?
1193    //                         .await?;
1194    //                 }
1195
1196    //                 Ok(())
1197    //             })
1198    //         } else {
1199    //             Task::ready(Ok(()))
1200    //         }
1201    //     }
1202
1203    //     pub fn go_back(
1204    //         &mut self,
1205    //         pane: WeakView<Pane>,
1206    //         cx: &mut ViewContext<Workspace>,
1207    //     ) -> Task<Result<()>> {
1208    //         self.navigate_history(pane, NavigationMode::GoingBack, cx)
1209    //     }
1210
1211    //     pub fn go_forward(
1212    //         &mut self,
1213    //         pane: WeakView<Pane>,
1214    //         cx: &mut ViewContext<Workspace>,
1215    //     ) -> Task<Result<()>> {
1216    //         self.navigate_history(pane, NavigationMode::GoingForward, cx)
1217    //     }
1218
1219    //     pub fn reopen_closed_item(&mut self, cx: &mut ViewContext<Workspace>) -> Task<Result<()>> {
1220    //         self.navigate_history(
1221    //             self.active_pane().downgrade(),
1222    //             NavigationMode::ReopeningClosedItem,
1223    //             cx,
1224    //         )
1225    //     }
1226
1227    //     pub fn client(&self) -> &Client {
1228    //         &self.app_state.client
1229    //     }
1230
1231    //     pub fn set_titlebar_item(&mut self, item: AnyViewHandle, cx: &mut ViewContext<Self>) {
1232    //         self.titlebar_item = Some(item);
1233    //         cx.notify();
1234    //     }
1235
1236    //     pub fn titlebar_item(&self) -> Option<AnyViewHandle> {
1237    //         self.titlebar_item.clone()
1238    //     }
1239
1240    //     /// Call the given callback with a workspace whose project is local.
1241    //     ///
1242    //     /// If the given workspace has a local project, then it will be passed
1243    //     /// to the callback. Otherwise, a new empty window will be created.
1244    //     pub fn with_local_workspace<T, F>(
1245    //         &mut self,
1246    //         cx: &mut ViewContext<Self>,
1247    //         callback: F,
1248    //     ) -> Task<Result<T>>
1249    //     where
1250    //         T: 'static,
1251    //         F: 'static + FnOnce(&mut Workspace, &mut ViewContext<Workspace>) -> T,
1252    //     {
1253    //         if self.project.read(cx).is_local() {
1254    //             Task::Ready(Some(Ok(callback(self, cx))))
1255    //         } else {
1256    //             let task = Self::new_local(Vec::new(), self.app_state.clone(), None, cx);
1257    //             cx.spawn(|_vh, mut cx| async move {
1258    //                 let (workspace, _) = task.await;
1259    //                 workspace.update(&mut cx, callback)
1260    //             })
1261    //         }
1262    //     }
1263
1264    //     pub fn worktrees<'a>(
1265    //         &self,
1266    //         cx: &'a AppContext,
1267    //     ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
1268    //         self.project.read(cx).worktrees(cx)
1269    //     }
1270
1271    //     pub fn visible_worktrees<'a>(
1272    //         &self,
1273    //         cx: &'a AppContext,
1274    //     ) -> impl 'a + Iterator<Item = ModelHandle<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    //         cx.focus_self();
1838    //         cx.notify();
1839    //         self.serialize_workspace(cx);
1840    //     }
1841
1842    //     /// Transfer focus to the panel of the given type.
1843    //     pub fn focus_panel<T: Panel>(&mut self, cx: &mut ViewContext<Self>) -> Option<View<T>> {
1844    //         self.focus_or_unfocus_panel::<T>(cx, |_, _| true)?
1845    //             .as_any()
1846    //             .clone()
1847    //             .downcast()
1848    //     }
1849
1850    //     /// Focus the panel of the given type if it isn't already focused. If it is
1851    //     /// already focused, then transfer focus back to the workspace center.
1852    //     pub fn toggle_panel_focus<T: Panel>(&mut self, cx: &mut ViewContext<Self>) {
1853    //         self.focus_or_unfocus_panel::<T>(cx, |panel, cx| !panel.has_focus(cx));
1854    //     }
1855
1856    //     /// Focus or unfocus the given panel type, depending on the given callback.
1857    //     fn focus_or_unfocus_panel<T: Panel>(
1858    //         &mut self,
1859    //         cx: &mut ViewContext<Self>,
1860    //         should_focus: impl Fn(&dyn PanelHandle, &mut ViewContext<Dock>) -> bool,
1861    //     ) -> Option<Rc<dyn PanelHandle>> {
1862    //         for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
1863    //             if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
1864    //                 let mut focus_center = false;
1865    //                 let mut reveal_dock = false;
1866    //                 let panel = dock.update(cx, |dock, cx| {
1867    //                     dock.activate_panel(panel_index, cx);
1868
1869    //                     let panel = dock.active_panel().cloned();
1870    //                     if let Some(panel) = panel.as_ref() {
1871    //                         if should_focus(&**panel, cx) {
1872    //                             dock.set_open(true, cx);
1873    //                             cx.focus(panel.as_any());
1874    //                             reveal_dock = true;
1875    //                         } else {
1876    //                             // if panel.is_zoomed(cx) {
1877    //                             //     dock.set_open(false, cx);
1878    //                             // }
1879    //                             focus_center = true;
1880    //                         }
1881    //                     }
1882    //                     panel
1883    //                 });
1884
1885    //                 if focus_center {
1886    //                     cx.focus_self();
1887    //                 }
1888
1889    //                 self.serialize_workspace(cx);
1890    //                 cx.notify();
1891    //                 return panel;
1892    //             }
1893    //         }
1894    //         None
1895    //     }
1896
1897    //     pub fn panel<T: Panel>(&self, cx: &WindowContext) -> Option<View<T>> {
1898    //         for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
1899    //             let dock = dock.read(cx);
1900    //             if let Some(panel) = dock.panel::<T>() {
1901    //                 return Some(panel);
1902    //             }
1903    //         }
1904    //         None
1905    //     }
1906
1907    //     fn zoom_out(&mut self, cx: &mut ViewContext<Self>) {
1908    //         for pane in &self.panes {
1909    //             pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
1910    //         }
1911
1912    //         self.left_dock.update(cx, |dock, cx| dock.zoom_out(cx));
1913    //         self.bottom_dock.update(cx, |dock, cx| dock.zoom_out(cx));
1914    //         self.right_dock.update(cx, |dock, cx| dock.zoom_out(cx));
1915    //         self.zoomed = None;
1916    //         self.zoomed_position = None;
1917
1918    //         cx.notify();
1919    //     }
1920
1921    //     #[cfg(any(test, feature = "test-support"))]
1922    //     pub fn zoomed_view(&self, cx: &AppContext) -> Option<AnyViewHandle> {
1923    //         self.zoomed.and_then(|view| view.upgrade(cx))
1924    //     }
1925
1926    //     fn dismiss_zoomed_items_to_reveal(
1927    //         &mut self,
1928    //         dock_to_reveal: Option<DockPosition>,
1929    //         cx: &mut ViewContext<Self>,
1930    //     ) {
1931    //         // If a center pane is zoomed, unzoom it.
1932    //         for pane in &self.panes {
1933    //             if pane != &self.active_pane || dock_to_reveal.is_some() {
1934    //                 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
1935    //             }
1936    //         }
1937
1938    //         // If another dock is zoomed, hide it.
1939    //         let mut focus_center = false;
1940    //         for dock in [&self.left_dock, &self.right_dock, &self.bottom_dock] {
1941    //             dock.update(cx, |dock, cx| {
1942    //                 if Some(dock.position()) != dock_to_reveal {
1943    //                     if let Some(panel) = dock.active_panel() {
1944    //                         if panel.is_zoomed(cx) {
1945    //                             focus_center |= panel.has_focus(cx);
1946    //                             dock.set_open(false, cx);
1947    //                         }
1948    //                     }
1949    //                 }
1950    //             });
1951    //         }
1952
1953    //         if focus_center {
1954    //             cx.focus_self();
1955    //         }
1956
1957    //         if self.zoomed_position != dock_to_reveal {
1958    //             self.zoomed = None;
1959    //             self.zoomed_position = None;
1960    //         }
1961
1962    //         cx.notify();
1963    //     }
1964
1965    fn add_pane(&mut self, _cx: &mut ViewContext<Self>) -> View<Pane> {
1966        todo!()
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)
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    //     fn shared_screen_for_peer(
3126    //         &self,
3127    //         peer_id: PeerId,
3128    //         pane: &View<Pane>,
3129    //         cx: &mut ViewContext<Self>,
3130    //     ) -> Option<View<SharedScreen>> {
3131    //         let call = self.active_call()?;
3132    //         let room = call.read(cx).room()?.read(cx);
3133    //         let participant = room.remote_participant_for_peer_id(peer_id)?;
3134    //         let track = participant.video_tracks.values().next()?.clone();
3135    //         let user = participant.user.clone();
3136
3137    //         for item in pane.read(cx).items_of_type::<SharedScreen>() {
3138    //             if item.read(cx).peer_id == peer_id {
3139    //                 return Some(item);
3140    //             }
3141    //         }
3142
3143    //         Some(cx.build_view(|cx| SharedScreen::new(&track, peer_id, user.clone(), cx)))
3144    //     }
3145
3146    pub fn on_window_activation_changed(&mut self, cx: &mut ViewContext<Self>) {
3147        if cx.is_window_active() {
3148            self.update_active_view_for_followers(cx);
3149            cx.background_executor()
3150                .spawn(persistence::DB.update_timestamp(self.database_id()))
3151                .detach();
3152        } else {
3153            for pane in &self.panes {
3154                pane.update(cx, |pane, cx| {
3155                    if let Some(item) = pane.active_item() {
3156                        item.workspace_deactivated(cx);
3157                    }
3158                    if matches!(
3159                        WorkspaceSettings::get_global(cx).autosave,
3160                        AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
3161                    ) {
3162                        for item in pane.items() {
3163                            Pane::autosave_item(item.as_ref(), self.project.clone(), cx)
3164                                .detach_and_log_err(cx);
3165                        }
3166                    }
3167                });
3168            }
3169        }
3170    }
3171
3172    fn active_call(&self) -> Option<&Model<ActiveCall>> {
3173        self.active_call.as_ref().map(|(call, _)| call)
3174    }
3175
3176    fn on_active_call_event(
3177        &mut self,
3178        _: Model<ActiveCall>,
3179        event: &call2::room::Event,
3180        cx: &mut ViewContext<Self>,
3181    ) {
3182        match event {
3183            call2::room::Event::ParticipantLocationChanged { participant_id }
3184            | call2::room::Event::RemoteVideoTracksChanged { participant_id } => {
3185                self.leader_updated(*participant_id, cx);
3186            }
3187            _ => {}
3188        }
3189    }
3190
3191    pub fn database_id(&self) -> WorkspaceId {
3192        self.database_id
3193    }
3194
3195    fn location(&self, cx: &AppContext) -> Option<WorkspaceLocation> {
3196        let project = self.project().read(cx);
3197
3198        if project.is_local() {
3199            Some(
3200                project
3201                    .visible_worktrees(cx)
3202                    .map(|worktree| worktree.read(cx).abs_path())
3203                    .collect::<Vec<_>>()
3204                    .into(),
3205            )
3206        } else {
3207            None
3208        }
3209    }
3210
3211    fn remove_panes(&mut self, member: Member, cx: &mut ViewContext<Workspace>) {
3212        match member {
3213            Member::Axis(PaneAxis { members, .. }) => {
3214                for child in members.iter() {
3215                    self.remove_panes(child.clone(), cx)
3216                }
3217            }
3218            Member::Pane(pane) => {
3219                self.force_remove_pane(&pane, cx);
3220            }
3221        }
3222    }
3223
3224    fn force_remove_pane(&mut self, pane: &View<Pane>, cx: &mut ViewContext<Workspace>) {
3225        self.panes.retain(|p| p != pane);
3226        if true {
3227            todo!()
3228            // cx.focus(self.panes.last().unwrap());
3229        }
3230        if self.last_active_center_pane == Some(pane.downgrade()) {
3231            self.last_active_center_pane = None;
3232        }
3233        cx.notify();
3234    }
3235
3236    //     fn schedule_serialize(&mut self, cx: &mut ViewContext<Self>) {
3237    //         self._schedule_serialize = Some(cx.spawn(|this, cx| async move {
3238    //             cx.background().timer(Duration::from_millis(100)).await;
3239    //             this.read_with(&cx, |this, cx| this.serialize_workspace(cx))
3240    //                 .ok();
3241    //         }));
3242    //     }
3243
3244    fn serialize_workspace(&self, cx: &mut ViewContext<Self>) {
3245        fn serialize_pane_handle(pane_handle: &View<Pane>, cx: &AppContext) -> SerializedPane {
3246            let (items, active) = {
3247                let pane = pane_handle.read(cx);
3248                let active_item_id = pane.active_item().map(|item| item.id());
3249                (
3250                    pane.items()
3251                        .filter_map(|item_handle| {
3252                            Some(SerializedItem {
3253                                kind: Arc::from(item_handle.serialized_item_kind()?),
3254                                item_id: item_handle.id().as_u64() as usize,
3255                                active: Some(item_handle.id()) == active_item_id,
3256                            })
3257                        })
3258                        .collect::<Vec<_>>(),
3259                    pane.has_focus(),
3260                )
3261            };
3262
3263            SerializedPane::new(items, active)
3264        }
3265
3266        fn build_serialized_pane_group(
3267            pane_group: &Member,
3268            cx: &AppContext,
3269        ) -> SerializedPaneGroup {
3270            match pane_group {
3271                Member::Axis(PaneAxis {
3272                    axis,
3273                    members,
3274                    flexes,
3275                    bounding_boxes: _,
3276                }) => SerializedPaneGroup::Group {
3277                    axis: *axis,
3278                    children: members
3279                        .iter()
3280                        .map(|member| build_serialized_pane_group(member, cx))
3281                        .collect::<Vec<_>>(),
3282                    flexes: Some(flexes.lock().clone()),
3283                },
3284                Member::Pane(pane_handle) => {
3285                    SerializedPaneGroup::Pane(serialize_pane_handle(&pane_handle, cx))
3286                }
3287            }
3288        }
3289
3290        fn build_serialized_docks(
3291            this: &Workspace,
3292            cx: &mut ViewContext<Workspace>,
3293        ) -> DockStructure {
3294            let left_dock = this.left_dock.read(cx);
3295            let left_visible = left_dock.is_open();
3296            let left_active_panel = left_dock
3297                .visible_panel()
3298                .and_then(|panel| Some(panel.persistent_name(cx).to_string()));
3299            let left_dock_zoom = left_dock
3300                .visible_panel()
3301                .map(|panel| panel.is_zoomed(cx))
3302                .unwrap_or(false);
3303
3304            let right_dock = this.right_dock.read(cx);
3305            let right_visible = right_dock.is_open();
3306            let right_active_panel = right_dock
3307                .visible_panel()
3308                .and_then(|panel| Some(panel.persistent_name(cx).to_string()));
3309            let right_dock_zoom = right_dock
3310                .visible_panel()
3311                .map(|panel| panel.is_zoomed(cx))
3312                .unwrap_or(false);
3313
3314            let bottom_dock = this.bottom_dock.read(cx);
3315            let bottom_visible = bottom_dock.is_open();
3316            let bottom_active_panel = bottom_dock
3317                .visible_panel()
3318                .and_then(|panel| Some(panel.persistent_name(cx).to_string()));
3319            let bottom_dock_zoom = bottom_dock
3320                .visible_panel()
3321                .map(|panel| panel.is_zoomed(cx))
3322                .unwrap_or(false);
3323
3324            DockStructure {
3325                left: DockData {
3326                    visible: left_visible,
3327                    active_panel: left_active_panel,
3328                    zoom: left_dock_zoom,
3329                },
3330                right: DockData {
3331                    visible: right_visible,
3332                    active_panel: right_active_panel,
3333                    zoom: right_dock_zoom,
3334                },
3335                bottom: DockData {
3336                    visible: bottom_visible,
3337                    active_panel: bottom_active_panel,
3338                    zoom: bottom_dock_zoom,
3339                },
3340            }
3341        }
3342
3343        if let Some(location) = self.location(cx) {
3344            // Load bearing special case:
3345            //  - with_local_workspace() relies on this to not have other stuff open
3346            //    when you open your log
3347            if !location.paths().is_empty() {
3348                let center_group = build_serialized_pane_group(&self.center.root, cx);
3349                let docks = build_serialized_docks(self, cx);
3350
3351                let serialized_workspace = SerializedWorkspace {
3352                    id: self.database_id,
3353                    location,
3354                    center_group,
3355                    bounds: Default::default(),
3356                    display: Default::default(),
3357                    docks,
3358                };
3359
3360                cx.spawn(|_, _| persistence::DB.save_workspace(serialized_workspace))
3361                    .detach();
3362            }
3363        }
3364    }
3365
3366    pub(crate) fn load_workspace(
3367        serialized_workspace: SerializedWorkspace,
3368        paths_to_open: Vec<Option<ProjectPath>>,
3369        cx: &mut ViewContext<Workspace>,
3370    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
3371        cx.spawn(|workspace, mut cx| async move {
3372            let (project, old_center_pane) = workspace.update(&mut cx, |workspace, _| {
3373                (
3374                    workspace.project().clone(),
3375                    workspace.last_active_center_pane.clone(),
3376                )
3377            })?;
3378
3379            let mut center_group = None;
3380            let mut center_items = None;
3381
3382            // Traverse the splits tree and add to things
3383            if let Some((group, active_pane, items)) = serialized_workspace
3384                .center_group
3385                .deserialize(
3386                    &project,
3387                    serialized_workspace.id,
3388                    workspace.clone(),
3389                    &mut cx,
3390                )
3391                .await
3392            {
3393                center_items = Some(items);
3394                center_group = Some((group, active_pane))
3395            }
3396
3397            let mut items_by_project_path = cx.update(|_, cx| {
3398                center_items
3399                    .unwrap_or_default()
3400                    .into_iter()
3401                    .filter_map(|item| {
3402                        let item = item?;
3403                        let project_path = item.project_path(cx)?;
3404                        Some((project_path, item))
3405                    })
3406                    .collect::<HashMap<_, _>>()
3407            })?;
3408
3409            let opened_items = paths_to_open
3410                .into_iter()
3411                .map(|path_to_open| {
3412                    path_to_open
3413                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
3414                })
3415                .collect::<Vec<_>>();
3416
3417            // Remove old panes from workspace panes list
3418            workspace.update(&mut cx, |workspace, cx| {
3419                if let Some((center_group, active_pane)) = center_group {
3420                    workspace.remove_panes(workspace.center.root.clone(), cx);
3421
3422                    // Swap workspace center group
3423                    workspace.center = PaneGroup::with_root(center_group);
3424
3425                    // Change the focus to the workspace first so that we retrigger focus in on the pane.
3426                    // todo!()
3427                    // cx.focus_self();
3428                    // if let Some(active_pane) = active_pane {
3429                    //     cx.focus(&active_pane);
3430                    // } else {
3431                    //     cx.focus(workspace.panes.last().unwrap());
3432                    // }
3433                } else {
3434                    // todo!()
3435                    // let old_center_handle = old_center_pane.and_then(|weak| weak.upgrade());
3436                    // if let Some(old_center_handle) = old_center_handle {
3437                    //     cx.focus(&old_center_handle)
3438                    // } else {
3439                    //     cx.focus_self()
3440                    // }
3441                }
3442
3443                let docks = serialized_workspace.docks;
3444                workspace.left_dock.update(cx, |dock, cx| {
3445                    dock.set_open(docks.left.visible, cx);
3446                    if let Some(active_panel) = docks.left.active_panel {
3447                        if let Some(ix) = dock.panel_index_for_ui_name(&active_panel, cx) {
3448                            dock.activate_panel(ix, cx);
3449                        }
3450                    }
3451                    dock.active_panel()
3452                        .map(|panel| panel.set_zoomed(docks.left.zoom, cx));
3453                    if docks.left.visible && docks.left.zoom {
3454                        // todo!()
3455                        // cx.focus_self()
3456                    }
3457                });
3458                // TODO: I think the bug is that setting zoom or active undoes the bottom zoom or something
3459                workspace.right_dock.update(cx, |dock, cx| {
3460                    dock.set_open(docks.right.visible, cx);
3461                    if let Some(active_panel) = docks.right.active_panel {
3462                        if let Some(ix) = dock.panel_index_for_ui_name(&active_panel, cx) {
3463                            dock.activate_panel(ix, cx);
3464                        }
3465                    }
3466                    dock.active_panel()
3467                        .map(|panel| panel.set_zoomed(docks.right.zoom, cx));
3468
3469                    if docks.right.visible && docks.right.zoom {
3470                        // todo!()
3471                        // cx.focus_self()
3472                    }
3473                });
3474                workspace.bottom_dock.update(cx, |dock, cx| {
3475                    dock.set_open(docks.bottom.visible, cx);
3476                    if let Some(active_panel) = docks.bottom.active_panel {
3477                        if let Some(ix) = dock.panel_index_for_ui_name(&active_panel, cx) {
3478                            dock.activate_panel(ix, cx);
3479                        }
3480                    }
3481
3482                    dock.active_panel()
3483                        .map(|panel| panel.set_zoomed(docks.bottom.zoom, cx));
3484
3485                    if docks.bottom.visible && docks.bottom.zoom {
3486                        // todo!()
3487                        // cx.focus_self()
3488                    }
3489                });
3490
3491                cx.notify();
3492            })?;
3493
3494            // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
3495            workspace.update(&mut cx, |workspace, cx| workspace.serialize_workspace(cx))?;
3496
3497            Ok(opened_items)
3498        })
3499    }
3500
3501    //     #[cfg(any(test, feature = "test-support"))]
3502    //     pub fn test_new(project: ModelHandle<Project>, cx: &mut ViewContext<Self>) -> Self {
3503    //         use node_runtime::FakeNodeRuntime;
3504
3505    //         let client = project.read(cx).client();
3506    //         let user_store = project.read(cx).user_store();
3507
3508    //         let workspace_store = cx.add_model(|cx| WorkspaceStore::new(client.clone(), cx));
3509    //         let app_state = Arc::new(AppState {
3510    //             languages: project.read(cx).languages().clone(),
3511    //             workspace_store,
3512    //             client,
3513    //             user_store,
3514    //             fs: project.read(cx).fs().clone(),
3515    //             build_window_options: |_, _, _| Default::default(),
3516    //             initialize_workspace: |_, _, _, _| Task::ready(Ok(())),
3517    //             node_runtime: FakeNodeRuntime::new(),
3518    //         });
3519    //         Self::new(0, project, app_state, cx)
3520    //     }
3521
3522    //     fn render_dock(&self, position: DockPosition, cx: &WindowContext) -> Option<AnyElement<Self>> {
3523    //         let dock = match position {
3524    //             DockPosition::Left => &self.left_dock,
3525    //             DockPosition::Right => &self.right_dock,
3526    //             DockPosition::Bottom => &self.bottom_dock,
3527    //         };
3528    //         let active_panel = dock.read(cx).visible_panel()?;
3529    //         let element = if Some(active_panel.id()) == self.zoomed.as_ref().map(|zoomed| zoomed.id()) {
3530    //             dock.read(cx).render_placeholder(cx)
3531    //         } else {
3532    //             ChildView::new(dock, cx).into_any()
3533    //         };
3534
3535    //         Some(
3536    //             element
3537    //                 .constrained()
3538    //                 .dynamically(move |constraint, _, cx| match position {
3539    //                     DockPosition::Left | DockPosition::Right => SizeConstraint::new(
3540    //                         Vector2F::new(20., constraint.min.y()),
3541    //                         Vector2F::new(cx.window_size().x() * 0.8, constraint.max.y()),
3542    //                     ),
3543    //                     DockPosition::Bottom => SizeConstraint::new(
3544    //                         Vector2F::new(constraint.min.x(), 20.),
3545    //                         Vector2F::new(constraint.max.x(), cx.window_size().y() * 0.8),
3546    //                     ),
3547    //                 })
3548    //                 .into_any(),
3549    //         )
3550    //     }
3551    // }
3552}
3553
3554fn window_bounds_env_override(cx: &AsyncAppContext) -> Option<WindowBounds> {
3555    let display_origin = cx
3556        .update(|cx| Some(cx.displays().first()?.bounds().origin))
3557        .ok()??;
3558    ZED_WINDOW_POSITION
3559        .zip(*ZED_WINDOW_SIZE)
3560        .map(|(position, size)| {
3561            WindowBounds::Fixed(Bounds {
3562                origin: display_origin + position,
3563                size,
3564            })
3565        })
3566}
3567
3568fn open_items(
3569    serialized_workspace: Option<SerializedWorkspace>,
3570    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
3571    app_state: Arc<AppState>,
3572    cx: &mut ViewContext<Workspace>,
3573) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> {
3574    let restored_items = serialized_workspace.map(|serialized_workspace| {
3575        Workspace::load_workspace(
3576            serialized_workspace,
3577            project_paths_to_open
3578                .iter()
3579                .map(|(_, project_path)| project_path)
3580                .cloned()
3581                .collect(),
3582            cx,
3583        )
3584    });
3585
3586    cx.spawn(|workspace, mut cx| async move {
3587        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
3588
3589        if let Some(restored_items) = restored_items {
3590            let restored_items = restored_items.await?;
3591
3592            let restored_project_paths = restored_items
3593                .iter()
3594                .filter_map(|item| {
3595                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
3596                        .ok()
3597                        .flatten()
3598                })
3599                .collect::<HashSet<_>>();
3600
3601            for restored_item in restored_items {
3602                opened_items.push(restored_item.map(Ok));
3603            }
3604
3605            project_paths_to_open
3606                .iter_mut()
3607                .for_each(|(_, project_path)| {
3608                    if let Some(project_path_to_open) = project_path {
3609                        if restored_project_paths.contains(project_path_to_open) {
3610                            *project_path = None;
3611                        }
3612                    }
3613                });
3614        } else {
3615            for _ in 0..project_paths_to_open.len() {
3616                opened_items.push(None);
3617            }
3618        }
3619        assert!(opened_items.len() == project_paths_to_open.len());
3620
3621        let tasks =
3622            project_paths_to_open
3623                .into_iter()
3624                .enumerate()
3625                .map(|(i, (abs_path, project_path))| {
3626                    let workspace = workspace.clone();
3627                    cx.spawn(|mut cx| {
3628                        let fs = app_state.fs.clone();
3629                        async move {
3630                            let file_project_path = project_path?;
3631                            if fs.is_file(&abs_path).await {
3632                                Some((
3633                                    i,
3634                                    workspace
3635                                        .update(&mut cx, |workspace, cx| {
3636                                            workspace.open_path(file_project_path, None, true, cx)
3637                                        })
3638                                        .log_err()?
3639                                        .await,
3640                                ))
3641                            } else {
3642                                None
3643                            }
3644                        }
3645                    })
3646                });
3647
3648        let tasks = tasks.collect::<Vec<_>>();
3649
3650        let tasks = futures::future::join_all(tasks.into_iter());
3651        for maybe_opened_path in tasks.await.into_iter() {
3652            if let Some((i, path_open_result)) = maybe_opened_path {
3653                opened_items[i] = Some(path_open_result);
3654            }
3655        }
3656
3657        Ok(opened_items)
3658    })
3659}
3660
3661// fn notify_of_new_dock(workspace: &WeakView<Workspace>, cx: &mut AsyncAppContext) {
3662//     const NEW_PANEL_BLOG_POST: &str = "https://zed.dev/blog/new-panel-system";
3663//     const NEW_DOCK_HINT_KEY: &str = "show_new_dock_key";
3664//     const MESSAGE_ID: usize = 2;
3665
3666//     if workspace
3667//         .read_with(cx, |workspace, cx| {
3668//             workspace.has_shown_notification_once::<MessageNotification>(MESSAGE_ID, cx)
3669//         })
3670//         .unwrap_or(false)
3671//     {
3672//         return;
3673//     }
3674
3675//     if db::kvp::KEY_VALUE_STORE
3676//         .read_kvp(NEW_DOCK_HINT_KEY)
3677//         .ok()
3678//         .flatten()
3679//         .is_some()
3680//     {
3681//         if !workspace
3682//             .read_with(cx, |workspace, cx| {
3683//                 workspace.has_shown_notification_once::<MessageNotification>(MESSAGE_ID, cx)
3684//             })
3685//             .unwrap_or(false)
3686//         {
3687//             cx.update(|cx| {
3688//                 cx.update_global::<NotificationTracker, _, _>(|tracker, _| {
3689//                     let entry = tracker
3690//                         .entry(TypeId::of::<MessageNotification>())
3691//                         .or_default();
3692//                     if !entry.contains(&MESSAGE_ID) {
3693//                         entry.push(MESSAGE_ID);
3694//                     }
3695//                 });
3696//             });
3697//         }
3698
3699//         return;
3700//     }
3701
3702//     cx.spawn(|_| async move {
3703//         db::kvp::KEY_VALUE_STORE
3704//             .write_kvp(NEW_DOCK_HINT_KEY.to_string(), "seen".to_string())
3705//             .await
3706//             .ok();
3707//     })
3708//     .detach();
3709
3710//     workspace
3711//         .update(cx, |workspace, cx| {
3712//             workspace.show_notification_once(2, cx, |cx| {
3713//                 cx.build_view(|_| {
3714//                     MessageNotification::new_element(|text, _| {
3715//                         Text::new(
3716//                             "Looking for the dock? Try ctrl-`!\nshift-escape now zooms your pane.",
3717//                             text,
3718//                         )
3719//                         .with_custom_runs(vec![26..32, 34..46], |_, bounds, cx| {
3720//                             let code_span_background_color = settings::get::<ThemeSettings>(cx)
3721//                                 .theme
3722//                                 .editor
3723//                                 .document_highlight_read_background;
3724
3725//                             cx.scene().push_quad(gpui::Quad {
3726//                                 bounds,
3727//                                 background: Some(code_span_background_color),
3728//                                 border: Default::default(),
3729//                                 corner_radii: (2.0).into(),
3730//                             })
3731//                         })
3732//                         .into_any()
3733//                     })
3734//                     .with_click_message("Read more about the new panel system")
3735//                     .on_click(|cx| cx.platform().open_url(NEW_PANEL_BLOG_POST))
3736//                 })
3737//             })
3738//         })
3739//         .ok();
3740
3741fn notify_if_database_failed(_workspace: WindowHandle<Workspace>, _cx: &mut AsyncAppContext) {
3742    const REPORT_ISSUE_URL: &str ="https://github.com/zed-industries/community/issues/new?assignees=&labels=defect%2Ctriage&template=2_bug_report.yml";
3743
3744    // todo!()
3745    // workspace
3746    //     .update(cx, |workspace, cx| {
3747    //         if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
3748    //             workspace.show_notification_once(0, cx, |cx| {
3749    //                 cx.build_view(|_| {
3750    //                     MessageNotification::new("Failed to load the database file.")
3751    //                         .with_click_message("Click to let us know about this error")
3752    //                         .on_click(|cx| cx.platform().open_url(REPORT_ISSUE_URL))
3753    //                 })
3754    //             });
3755    //         }
3756    //     })
3757    //     .log_err();
3758}
3759
3760impl EventEmitter for Workspace {
3761    type Event = Event;
3762}
3763
3764impl Render for Workspace {
3765    type Element = Div<Self>;
3766
3767    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
3768        div()
3769            .relative()
3770            .size_full()
3771            .flex()
3772            .flex_col()
3773            .font("Zed Sans")
3774            .gap_0()
3775            .justify_start()
3776            .items_start()
3777            .text_color(cx.theme().colors().text)
3778            .bg(cx.theme().colors().background)
3779            .child(self.render_titlebar(cx))
3780            .child(
3781                div()
3782                    .flex_1()
3783                    .w_full()
3784                    .flex()
3785                    .flex_row()
3786                    .overflow_hidden()
3787                    .border_t()
3788                    .border_b()
3789                    .border_color(cx.theme().colors().border)
3790                    // .children(
3791                    //     Some(
3792                    //         Panel::new("project-panel-outer", cx)
3793                    //             .side(PanelSide::Left)
3794                    //             .child(ProjectPanel::new("project-panel-inner")),
3795                    //     )
3796                    //     .filter(|_| self.is_project_panel_open()),
3797                    // )
3798                    // .children(
3799                    //     Some(
3800                    //         Panel::new("collab-panel-outer", cx)
3801                    //             .child(CollabPanel::new("collab-panel-inner"))
3802                    //             .side(PanelSide::Left),
3803                    //     )
3804                    //     .filter(|_| self.is_collab_panel_open()),
3805                    // )
3806                    // .child(NotificationToast::new(
3807                    //     "maxbrunsfeld has requested to add you as a contact.".into(),
3808                    // ))
3809                    .child(
3810                        div().flex().flex_col().flex_1().h_full().child(
3811                            div().flex().flex_1().child(self.center.render(
3812                                &self.project,
3813                                &self.follower_states,
3814                                self.active_call(),
3815                                &self.active_pane,
3816                                self.zoomed.as_ref(),
3817                                &self.app_state,
3818                                cx,
3819                            )),
3820                        ), // .children(
3821                           //     Some(
3822                           //         Panel::new("terminal-panel", cx)
3823                           //             .child(Terminal::new())
3824                           //             .allowed_sides(PanelAllowedSides::BottomOnly)
3825                           //             .side(PanelSide::Bottom),
3826                           //     )
3827                           //     .filter(|_| self.is_terminal_open()),
3828                           // ),
3829                    ), // .children(
3830                       //     Some(
3831                       //         Panel::new("chat-panel-outer", cx)
3832                       //             .side(PanelSide::Right)
3833                       //             .child(ChatPanel::new("chat-panel-inner").messages(vec![
3834                       //                 ChatMessage::new(
3835                       //                     "osiewicz".to_string(),
3836                       //                     "is this thing on?".to_string(),
3837                       //                     DateTime::parse_from_rfc3339("2023-09-27T15:40:52.707Z")
3838                       //                         .unwrap()
3839                       //                         .naive_local(),
3840                       //                 ),
3841                       //                 ChatMessage::new(
3842                       //                     "maxdeviant".to_string(),
3843                       //                     "Reading you loud and clear!".to_string(),
3844                       //                     DateTime::parse_from_rfc3339("2023-09-28T15:40:52.707Z")
3845                       //                         .unwrap()
3846                       //                         .naive_local(),
3847                       //                 ),
3848                       //             ])),
3849                       //     )
3850                       //     .filter(|_| self.is_chat_panel_open()),
3851                       // )
3852                       // .children(
3853                       //     Some(
3854                       //         Panel::new("notifications-panel-outer", cx)
3855                       //             .side(PanelSide::Right)
3856                       //             .child(NotificationsPanel::new("notifications-panel-inner")),
3857                       //     )
3858                       //     .filter(|_| self.is_notifications_panel_open()),
3859                       // )
3860                       // .children(
3861                       //     Some(
3862                       //         Panel::new("assistant-panel-outer", cx)
3863                       //             .child(AssistantPanel::new("assistant-panel-inner")),
3864                       //     )
3865                       //     .filter(|_| self.is_assistant_panel_open()),
3866                       // ),
3867            )
3868            .child(self.status_bar.clone())
3869            // .when(self.debug.show_toast, |this| {
3870            //     this.child(Toast::new(ToastOrigin::Bottom).child(Label::new("A toast")))
3871            // })
3872            // .children(
3873            //     Some(
3874            //         div()
3875            //             .absolute()
3876            //             .top(px(50.))
3877            //             .left(px(640.))
3878            //             .z_index(8)
3879            //             .child(LanguageSelector::new("language-selector")),
3880            //     )
3881            //     .filter(|_| self.is_language_selector_open()),
3882            // )
3883            .z_index(8)
3884            // Debug
3885            .child(
3886                div()
3887                    .flex()
3888                    .flex_col()
3889                    .z_index(9)
3890                    .absolute()
3891                    .top_20()
3892                    .left_1_4()
3893                    .w_40()
3894                    .gap_2(), // .when(self.show_debug, |this| {
3895                              //     this.child(Button::<Workspace>::new("Toggle User Settings").on_click(
3896                              //         Arc::new(|workspace, cx| workspace.debug_toggle_user_settings(cx)),
3897                              //     ))
3898                              //     .child(
3899                              //         Button::<Workspace>::new("Toggle Toasts").on_click(Arc::new(
3900                              //             |workspace, cx| workspace.debug_toggle_toast(cx),
3901                              //         )),
3902                              //     )
3903                              //     .child(
3904                              //         Button::<Workspace>::new("Toggle Livestream").on_click(Arc::new(
3905                              //             |workspace, cx| workspace.debug_toggle_livestream(cx),
3906                              //         )),
3907                              //     )
3908                              // })
3909                              // .child(
3910                              //     Button::<Workspace>::new("Toggle Debug")
3911                              //         .on_click(Arc::new(|workspace, cx| workspace.toggle_debug(cx))),
3912                              // ),
3913            )
3914    }
3915}
3916
3917// todo!()
3918// impl Entity for Workspace {
3919//     type Event = Event;
3920
3921//     fn release(&mut self, cx: &mut AppContext) {
3922//         self.app_state.workspace_store.update(cx, |store, _| {
3923//             store.workspaces.remove(&self.weak_self);
3924//         })
3925//     }
3926// }
3927
3928// impl View for Workspace {
3929//     fn ui_name() -> &'static str {
3930//         "Workspace"
3931//     }
3932
3933//     fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
3934//         let theme = theme::current(cx).clone();
3935//         Stack::new()
3936//             .with_child(
3937//                 Flex::column()
3938//                     .with_child(self.render_titlebar(&theme, cx))
3939//                     .with_child(
3940//                         Stack::new()
3941//                             .with_child({
3942//                                 let project = self.project.clone();
3943//                                 Flex::row()
3944//                                     .with_children(self.render_dock(DockPosition::Left, cx))
3945//                                     .with_child(
3946//                                         Flex::column()
3947//                                             .with_child(
3948//                                                 FlexItem::new(
3949//                                                     self.center.render(
3950//                                                         &project,
3951//                                                         &theme,
3952//                                                         &self.follower_states,
3953//                                                         self.active_call(),
3954//                                                         self.active_pane(),
3955//                                                         self.zoomed
3956//                                                             .as_ref()
3957//                                                             .and_then(|zoomed| zoomed.upgrade(cx))
3958//                                                             .as_ref(),
3959//                                                         &self.app_state,
3960//                                                         cx,
3961//                                                     ),
3962//                                                 )
3963//                                                 .flex(1., true),
3964//                                             )
3965//                                             .with_children(
3966//                                                 self.render_dock(DockPosition::Bottom, cx),
3967//                                             )
3968//                                             .flex(1., true),
3969//                                     )
3970//                                     .with_children(self.render_dock(DockPosition::Right, cx))
3971//                             })
3972//                             .with_child(Overlay::new(
3973//                                 Stack::new()
3974//                                     .with_children(self.zoomed.as_ref().and_then(|zoomed| {
3975//                                         enum ZoomBackground {}
3976//                                         let zoomed = zoomed.upgrade(cx)?;
3977
3978//                                         let mut foreground_style =
3979//                                             theme.workspace.zoomed_pane_foreground;
3980//                                         if let Some(zoomed_dock_position) = self.zoomed_position {
3981//                                             foreground_style =
3982//                                                 theme.workspace.zoomed_panel_foreground;
3983//                                             let margin = foreground_style.margin.top;
3984//                                             let border = foreground_style.border.top;
3985
3986//                                             // Only include a margin and border on the opposite side.
3987//                                             foreground_style.margin.top = 0.;
3988//                                             foreground_style.margin.left = 0.;
3989//                                             foreground_style.margin.bottom = 0.;
3990//                                             foreground_style.margin.right = 0.;
3991//                                             foreground_style.border.top = false;
3992//                                             foreground_style.border.left = false;
3993//                                             foreground_style.border.bottom = false;
3994//                                             foreground_style.border.right = false;
3995//                                             match zoomed_dock_position {
3996//                                                 DockPosition::Left => {
3997//                                                     foreground_style.margin.right = margin;
3998//                                                     foreground_style.border.right = border;
3999//                                                 }
4000//                                                 DockPosition::Right => {
4001//                                                     foreground_style.margin.left = margin;
4002//                                                     foreground_style.border.left = border;
4003//                                                 }
4004//                                                 DockPosition::Bottom => {
4005//                                                     foreground_style.margin.top = margin;
4006//                                                     foreground_style.border.top = border;
4007//                                                 }
4008//                                             }
4009//                                         }
4010
4011//                                         Some(
4012//                                             ChildView::new(&zoomed, cx)
4013//                                                 .contained()
4014//                                                 .with_style(foreground_style)
4015//                                                 .aligned()
4016//                                                 .contained()
4017//                                                 .with_style(theme.workspace.zoomed_background)
4018//                                                 .mouse::<ZoomBackground>(0)
4019//                                                 .capture_all()
4020//                                                 .on_down(
4021//                                                     MouseButton::Left,
4022//                                                     |_, this: &mut Self, cx| {
4023//                                                         this.zoom_out(cx);
4024//                                                     },
4025//                                                 ),
4026//                                         )
4027//                                     }))
4028//                                     .with_children(self.modal.as_ref().map(|modal| {
4029//                                         // Prevent clicks within the modal from falling
4030//                                         // through to the rest of the workspace.
4031//                                         enum ModalBackground {}
4032//                                         MouseEventHandler::new::<ModalBackground, _>(
4033//                                             0,
4034//                                             cx,
4035//                                             |_, cx| ChildView::new(modal.view.as_any(), cx),
4036//                                         )
4037//                                         .on_click(MouseButton::Left, |_, _, _| {})
4038//                                         .contained()
4039//                                         .with_style(theme.workspace.modal)
4040//                                         .aligned()
4041//                                         .top()
4042//                                     }))
4043//                                     .with_children(self.render_notifications(&theme.workspace, cx)),
4044//                             ))
4045//                             .provide_resize_bounds::<WorkspaceBounds>()
4046//                             .flex(1.0, true),
4047//                     )
4048//                     .with_child(ChildView::new(&self.status_bar, cx))
4049//                     .contained()
4050//                     .with_background_color(theme.workspace.background),
4051//             )
4052//             .with_children(DragAndDrop::render(cx))
4053//             .with_children(self.render_disconnected_overlay(cx))
4054//             .into_any_named("workspace")
4055//     }
4056
4057//     fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
4058//         if cx.is_self_focused() {
4059//             cx.focus(&self.active_pane);
4060//         }
4061//     }
4062
4063//     fn modifiers_changed(&mut self, e: &ModifiersChangedEvent, cx: &mut ViewContext<Self>) -> bool {
4064//         DragAndDrop::<Workspace>::update_modifiers(e.modifiers, cx)
4065//     }
4066// }
4067
4068impl WorkspaceStore {
4069    pub fn new(client: Arc<Client>, _cx: &mut ModelContext<Self>) -> Self {
4070        Self {
4071            workspaces: Default::default(),
4072            followers: Default::default(),
4073            _subscriptions: vec![],
4074            //     client.add_request_handler(cx.weak_model(), Self::handle_follow),
4075            //     client.add_message_handler(cx.weak_model(), Self::handle_unfollow),
4076            //     client.add_message_handler(cx.weak_model(), Self::handle_update_followers),
4077            // ],
4078            client,
4079        }
4080    }
4081
4082    pub fn update_followers(
4083        &self,
4084        project_id: Option<u64>,
4085        update: proto::update_followers::Variant,
4086        cx: &AppContext,
4087    ) -> Option<()> {
4088        if !cx.has_global::<Model<ActiveCall>>() {
4089            return None;
4090        }
4091
4092        let room_id = ActiveCall::global(cx).read(cx).room()?.read(cx).id();
4093        let follower_ids: Vec<_> = self
4094            .followers
4095            .iter()
4096            .filter_map(|follower| {
4097                if follower.project_id == project_id || project_id.is_none() {
4098                    Some(follower.peer_id.into())
4099                } else {
4100                    None
4101                }
4102            })
4103            .collect();
4104        if follower_ids.is_empty() {
4105            return None;
4106        }
4107        self.client
4108            .send(proto::UpdateFollowers {
4109                room_id,
4110                project_id,
4111                follower_ids,
4112                variant: Some(update),
4113            })
4114            .log_err()
4115    }
4116
4117    pub async fn handle_follow(
4118        this: Model<Self>,
4119        envelope: TypedEnvelope<proto::Follow>,
4120        _: Arc<Client>,
4121        mut cx: AsyncAppContext,
4122    ) -> Result<proto::FollowResponse> {
4123        this.update(&mut cx, |this, cx| {
4124            let follower = Follower {
4125                project_id: envelope.payload.project_id,
4126                peer_id: envelope.original_sender_id()?,
4127            };
4128            let active_project = ActiveCall::global(cx).read(cx).location().cloned();
4129
4130            let mut response = proto::FollowResponse::default();
4131            for workspace in &this.workspaces {
4132                workspace
4133                    .update(cx, |workspace, cx| {
4134                        let handler_response = workspace.handle_follow(follower.project_id, cx);
4135                        if response.views.is_empty() {
4136                            response.views = handler_response.views;
4137                        } else {
4138                            response.views.extend_from_slice(&handler_response.views);
4139                        }
4140
4141                        if let Some(active_view_id) = handler_response.active_view_id.clone() {
4142                            if response.active_view_id.is_none()
4143                                || Some(workspace.project.downgrade()) == active_project
4144                            {
4145                                response.active_view_id = Some(active_view_id);
4146                            }
4147                        }
4148                    })
4149                    .ok();
4150            }
4151
4152            if let Err(ix) = this.followers.binary_search(&follower) {
4153                this.followers.insert(ix, follower);
4154            }
4155
4156            Ok(response)
4157        })?
4158    }
4159
4160    async fn handle_unfollow(
4161        model: Model<Self>,
4162        envelope: TypedEnvelope<proto::Unfollow>,
4163        _: Arc<Client>,
4164        mut cx: AsyncAppContext,
4165    ) -> Result<()> {
4166        model.update(&mut cx, |this, _| {
4167            let follower = Follower {
4168                project_id: envelope.payload.project_id,
4169                peer_id: envelope.original_sender_id()?,
4170            };
4171            if let Ok(ix) = this.followers.binary_search(&follower) {
4172                this.followers.remove(ix);
4173            }
4174            Ok(())
4175        })?
4176    }
4177
4178    async fn handle_update_followers(
4179        _this: Model<Self>,
4180        _envelope: TypedEnvelope<proto::UpdateFollowers>,
4181        _: Arc<Client>,
4182        mut _cx: AsyncWindowContext,
4183    ) -> Result<()> {
4184        // let leader_id = envelope.original_sender_id()?;
4185        // let update = envelope.payload;
4186
4187        // this.update(&mut cx, |this, cx| {
4188        //     for workspace in &this.workspaces {
4189        //         let Some(workspace) = workspace.upgrade() else {
4190        //             continue;
4191        //         };
4192        //         workspace.update(cx, |workspace, cx| {
4193        //             let project_id = workspace.project.read(cx).remote_id();
4194        //             if update.project_id != project_id && update.project_id.is_some() {
4195        //                 return;
4196        //             }
4197        //             workspace.handle_update_followers(leader_id, update.clone(), cx);
4198        //         });
4199        //     }
4200        //     Ok(())
4201        // })?
4202        todo!()
4203    }
4204}
4205
4206// impl Entity for WorkspaceStore {
4207//     type Event = ();
4208// }
4209
4210impl ViewId {
4211    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
4212        Ok(Self {
4213            creator: message
4214                .creator
4215                .ok_or_else(|| anyhow!("creator is missing"))?,
4216            id: message.id,
4217        })
4218    }
4219
4220    pub(crate) fn to_proto(&self) -> proto::ViewId {
4221        proto::ViewId {
4222            creator: Some(self.creator),
4223            id: self.id,
4224        }
4225    }
4226}
4227
4228// pub trait WorkspaceHandle {
4229//     fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
4230// }
4231
4232// impl WorkspaceHandle for View<Workspace> {
4233//     fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
4234//         self.read(cx)
4235//             .worktrees(cx)
4236//             .flat_map(|worktree| {
4237//                 let worktree_id = worktree.read(cx).id();
4238//                 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
4239//                     worktree_id,
4240//                     path: f.path.clone(),
4241//                 })
4242//             })
4243//             .collect::<Vec<_>>()
4244//     }
4245// }
4246
4247// impl std::fmt::Debug for OpenPaths {
4248//     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4249//         f.debug_struct("OpenPaths")
4250//             .field("paths", &self.paths)
4251//             .finish()
4252//     }
4253// }
4254
4255// pub struct WorkspaceCreated(pub WeakView<Workspace>);
4256
4257pub fn activate_workspace_for_project(
4258    cx: &mut AppContext,
4259    predicate: impl Fn(&Project, &AppContext) -> bool + Send + 'static,
4260) -> Option<WindowHandle<Workspace>> {
4261    for window in cx.windows() {
4262        let Some(workspace) = window.downcast::<Workspace>() else {
4263            continue;
4264        };
4265
4266        let predicate = workspace
4267            .update(cx, |workspace, cx| {
4268                let project = workspace.project.read(cx);
4269                if predicate(project, cx) {
4270                    cx.activate_window();
4271                    true
4272                } else {
4273                    false
4274                }
4275            })
4276            .log_err()
4277            .unwrap_or(false);
4278
4279        if predicate {
4280            return Some(workspace);
4281        }
4282    }
4283
4284    None
4285}
4286
4287pub async fn last_opened_workspace_paths() -> Option<WorkspaceLocation> {
4288    DB.last_workspace().await.log_err().flatten()
4289}
4290
4291// async fn join_channel_internal(
4292//     channel_id: u64,
4293//     app_state: &Arc<AppState>,
4294//     requesting_window: Option<WindowHandle<Workspace>>,
4295//     active_call: &ModelHandle<ActiveCall>,
4296//     cx: &mut AsyncAppContext,
4297// ) -> Result<bool> {
4298//     let (should_prompt, open_room) = active_call.read_with(cx, |active_call, cx| {
4299//         let Some(room) = active_call.room().map(|room| room.read(cx)) else {
4300//             return (false, None);
4301//         };
4302
4303//         let already_in_channel = room.channel_id() == Some(channel_id);
4304//         let should_prompt = room.is_sharing_project()
4305//             && room.remote_participants().len() > 0
4306//             && !already_in_channel;
4307//         let open_room = if already_in_channel {
4308//             active_call.room().cloned()
4309//         } else {
4310//             None
4311//         };
4312//         (should_prompt, open_room)
4313//     });
4314
4315//     if let Some(room) = open_room {
4316//         let task = room.update(cx, |room, cx| {
4317//             if let Some((project, host)) = room.most_active_project(cx) {
4318//                 return Some(join_remote_project(project, host, app_state.clone(), cx));
4319//             }
4320
4321//             None
4322//         });
4323//         if let Some(task) = task {
4324//             task.await?;
4325//         }
4326//         return anyhow::Ok(true);
4327//     }
4328
4329//     if should_prompt {
4330//         if let Some(workspace) = requesting_window {
4331//             if let Some(window) = workspace.update(cx, |cx| cx.window()) {
4332//                 let answer = window.prompt(
4333//                     PromptLevel::Warning,
4334//                     "Leaving this call will unshare your current project.\nDo you want to switch channels?",
4335//                     &["Yes, Join Channel", "Cancel"],
4336//                     cx,
4337//                 );
4338
4339//                 if let Some(mut answer) = answer {
4340//                     if answer.next().await == Some(1) {
4341//                         return Ok(false);
4342//                     }
4343//                 }
4344//             } else {
4345//                 return Ok(false); // unreachable!() hopefully
4346//             }
4347//         } else {
4348//             return Ok(false); // unreachable!() hopefully
4349//         }
4350//     }
4351
4352//     let client = cx.read(|cx| active_call.read(cx).client());
4353
4354//     let mut client_status = client.status();
4355
4356//     // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
4357//     'outer: loop {
4358//         let Some(status) = client_status.recv().await else {
4359//             return Err(anyhow!("error connecting"));
4360//         };
4361
4362//         match status {
4363//             Status::Connecting
4364//             | Status::Authenticating
4365//             | Status::Reconnecting
4366//             | Status::Reauthenticating => continue,
4367//             Status::Connected { .. } => break 'outer,
4368//             Status::SignedOut => return Err(anyhow!("not signed in")),
4369//             Status::UpgradeRequired => return Err(anyhow!("zed is out of date")),
4370//             Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
4371//                 return Err(anyhow!("zed is offline"))
4372//             }
4373//         }
4374//     }
4375
4376//     let room = active_call
4377//         .update(cx, |active_call, cx| {
4378//             active_call.join_channel(channel_id, cx)
4379//         })
4380//         .await?;
4381
4382//     room.update(cx, |room, _| room.room_update_completed())
4383//         .await;
4384
4385//     let task = room.update(cx, |room, cx| {
4386//         if let Some((project, host)) = room.most_active_project(cx) {
4387//             return Some(join_remote_project(project, host, app_state.clone(), cx));
4388//         }
4389
4390//         None
4391//     });
4392//     if let Some(task) = task {
4393//         task.await?;
4394//         return anyhow::Ok(true);
4395//     }
4396//     anyhow::Ok(false)
4397// }
4398
4399// pub fn join_channel(
4400//     channel_id: u64,
4401//     app_state: Arc<AppState>,
4402//     requesting_window: Option<WindowHandle<Workspace>>,
4403//     cx: &mut AppContext,
4404// ) -> Task<Result<()>> {
4405//     let active_call = ActiveCall::global(cx);
4406//     cx.spawn(|mut cx| async move {
4407//         let result = join_channel_internal(
4408//             channel_id,
4409//             &app_state,
4410//             requesting_window,
4411//             &active_call,
4412//             &mut cx,
4413//         )
4414//         .await;
4415
4416//         // join channel succeeded, and opened a window
4417//         if matches!(result, Ok(true)) {
4418//             return anyhow::Ok(());
4419//         }
4420
4421//         if requesting_window.is_some() {
4422//             return anyhow::Ok(());
4423//         }
4424
4425//         // find an existing workspace to focus and show call controls
4426//         let mut active_window = activate_any_workspace_window(&mut cx);
4427//         if active_window.is_none() {
4428//             // no open workspaces, make one to show the error in (blergh)
4429//             cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), requesting_window, cx))
4430//                 .await;
4431//         }
4432
4433//         active_window = activate_any_workspace_window(&mut cx);
4434//         if active_window.is_none() {
4435//             return result.map(|_| ()); // unreachable!() assuming new_local always opens a window
4436//         }
4437
4438//         if let Err(err) = result {
4439//             let prompt = active_window.unwrap().prompt(
4440//                 PromptLevel::Critical,
4441//                 &format!("Failed to join channel: {}", err),
4442//                 &["Ok"],
4443//                 &mut cx,
4444//             );
4445//             if let Some(mut prompt) = prompt {
4446//                 prompt.next().await;
4447//             } else {
4448//                 return Err(err);
4449//             }
4450//         }
4451
4452//         // return ok, we showed the error to the user.
4453//         return anyhow::Ok(());
4454//     })
4455// }
4456
4457// pub fn activate_any_workspace_window(cx: &mut AsyncAppContext) -> Option<AnyWindowHandle> {
4458//     for window in cx.windows() {
4459//         let found = window.update(cx, |cx| {
4460//             let is_workspace = cx.root_view().clone().downcast::<Workspace>().is_some();
4461//             if is_workspace {
4462//                 cx.activate_window();
4463//             }
4464//             is_workspace
4465//         });
4466//         if found == Some(true) {
4467//             return Some(window);
4468//         }
4469//     }
4470//     None
4471// }
4472
4473#[allow(clippy::type_complexity)]
4474pub fn open_paths(
4475    abs_paths: &[PathBuf],
4476    app_state: &Arc<AppState>,
4477    requesting_window: Option<WindowHandle<Workspace>>,
4478    cx: &mut AppContext,
4479) -> Task<
4480    anyhow::Result<(
4481        WindowHandle<Workspace>,
4482        Vec<Option<Result<Box<dyn ItemHandle>, anyhow::Error>>>,
4483    )>,
4484> {
4485    let app_state = app_state.clone();
4486    let abs_paths = abs_paths.to_vec();
4487    // Open paths in existing workspace if possible
4488    let existing = activate_workspace_for_project(cx, {
4489        let abs_paths = abs_paths.clone();
4490        move |project, cx| project.contains_paths(&abs_paths, cx)
4491    });
4492    cx.spawn(move |mut cx| async move {
4493        if let Some(existing) = existing {
4494            // // Ok((
4495            //     existing.clone(),
4496            //     cx.update_window_root(&existing, |workspace, cx| {
4497            //         workspace.open_paths(abs_paths, true, cx)
4498            //     })?
4499            //     .await,
4500            // ))
4501            todo!()
4502        } else {
4503            cx.update(move |cx| {
4504                Workspace::new_local(abs_paths, app_state.clone(), requesting_window, cx)
4505            })?
4506            .await
4507        }
4508    })
4509}
4510
4511pub fn open_new(
4512    app_state: &Arc<AppState>,
4513    cx: &mut AppContext,
4514    init: impl FnOnce(&mut Workspace, &mut ViewContext<Workspace>) + 'static + Send,
4515) -> Task<()> {
4516    let task = Workspace::new_local(Vec::new(), app_state.clone(), None, cx);
4517    cx.spawn(|mut cx| async move {
4518        if let Some((workspace, opened_paths)) = task.await.log_err() {
4519            workspace
4520                .update(&mut cx, |workspace, cx| {
4521                    if opened_paths.is_empty() {
4522                        init(workspace, cx)
4523                    }
4524                })
4525                .log_err();
4526        }
4527    })
4528}
4529
4530// pub fn create_and_open_local_file(
4531//     path: &'static Path,
4532//     cx: &mut ViewContext<Workspace>,
4533//     default_content: impl 'static + Send + FnOnce() -> Rope,
4534// ) -> Task<Result<Box<dyn ItemHandle>>> {
4535//     cx.spawn(|workspace, mut cx| async move {
4536//         let fs = workspace.read_with(&cx, |workspace, _| workspace.app_state().fs.clone())?;
4537//         if !fs.is_file(path).await {
4538//             fs.create_file(path, Default::default()).await?;
4539//             fs.save(path, &default_content(), Default::default())
4540//                 .await?;
4541//         }
4542
4543//         let mut items = workspace
4544//             .update(&mut cx, |workspace, cx| {
4545//                 workspace.with_local_workspace(cx, |workspace, cx| {
4546//                     workspace.open_paths(vec![path.to_path_buf()], false, cx)
4547//                 })
4548//             })?
4549//             .await?
4550//             .await;
4551
4552//         let item = items.pop().flatten();
4553//         item.ok_or_else(|| anyhow!("path {path:?} is not a file"))?
4554//     })
4555// }
4556
4557// pub fn join_remote_project(
4558//     project_id: u64,
4559//     follow_user_id: u64,
4560//     app_state: Arc<AppState>,
4561//     cx: &mut AppContext,
4562// ) -> Task<Result<()>> {
4563//     cx.spawn(|mut cx| async move {
4564//         let windows = cx.windows();
4565//         let existing_workspace = windows.into_iter().find_map(|window| {
4566//             window.downcast::<Workspace>().and_then(|window| {
4567//                 window
4568//                     .read_root_with(&cx, |workspace, cx| {
4569//                         if workspace.project().read(cx).remote_id() == Some(project_id) {
4570//                             Some(cx.handle().downgrade())
4571//                         } else {
4572//                             None
4573//                         }
4574//                     })
4575//                     .unwrap_or(None)
4576//             })
4577//         });
4578
4579//         let workspace = if let Some(existing_workspace) = existing_workspace {
4580//             existing_workspace
4581//         } else {
4582//             let active_call = cx.read(ActiveCall::global);
4583//             let room = active_call
4584//                 .read_with(&cx, |call, _| call.room().cloned())
4585//                 .ok_or_else(|| anyhow!("not in a call"))?;
4586//             let project = room
4587//                 .update(&mut cx, |room, cx| {
4588//                     room.join_project(
4589//                         project_id,
4590//                         app_state.languages.clone(),
4591//                         app_state.fs.clone(),
4592//                         cx,
4593//                     )
4594//                 })
4595//                 .await?;
4596
4597//             let window_bounds_override = window_bounds_env_override(&cx);
4598//             let window = cx.add_window(
4599//                 (app_state.build_window_options)(
4600//                     window_bounds_override,
4601//                     None,
4602//                     cx.platform().as_ref(),
4603//                 ),
4604//                 |cx| Workspace::new(0, project, app_state.clone(), cx),
4605//             );
4606//             let workspace = window.root(&cx).unwrap();
4607//             (app_state.initialize_workspace)(
4608//                 workspace.downgrade(),
4609//                 false,
4610//                 app_state.clone(),
4611//                 cx.clone(),
4612//             )
4613//             .await
4614//             .log_err();
4615
4616//             workspace.downgrade()
4617//         };
4618
4619//         workspace.window().activate(&mut cx);
4620//         cx.platform().activate(true);
4621
4622//         workspace.update(&mut cx, |workspace, cx| {
4623//             if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
4624//                 let follow_peer_id = room
4625//                     .read(cx)
4626//                     .remote_participants()
4627//                     .iter()
4628//                     .find(|(_, participant)| participant.user.id == follow_user_id)
4629//                     .map(|(_, p)| p.peer_id)
4630//                     .or_else(|| {
4631//                         // If we couldn't follow the given user, follow the host instead.
4632//                         let collaborator = workspace
4633//                             .project()
4634//                             .read(cx)
4635//                             .collaborators()
4636//                             .values()
4637//                             .find(|collaborator| collaborator.replica_id == 0)?;
4638//                         Some(collaborator.peer_id)
4639//                     });
4640
4641//                 if let Some(follow_peer_id) = follow_peer_id {
4642//                     workspace
4643//                         .follow(follow_peer_id, cx)
4644//                         .map(|follow| follow.detach_and_log_err(cx));
4645//                 }
4646//             }
4647//         })?;
4648
4649//         anyhow::Ok(())
4650//     })
4651// }
4652
4653// pub fn restart(_: &Restart, cx: &mut AppContext) {
4654//     let should_confirm = settings::get::<WorkspaceSettings>(cx).confirm_quit;
4655//     cx.spawn(|mut cx| async move {
4656//         let mut workspace_windows = cx
4657//             .windows()
4658//             .into_iter()
4659//             .filter_map(|window| window.downcast::<Workspace>())
4660//             .collect::<Vec<_>>();
4661
4662//         // If multiple windows have unsaved changes, and need a save prompt,
4663//         // prompt in the active window before switching to a different window.
4664//         workspace_windows.sort_by_key(|window| window.is_active(&cx) == Some(false));
4665
4666//         if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
4667//             let answer = window.prompt(
4668//                 PromptLevel::Info,
4669//                 "Are you sure you want to restart?",
4670//                 &["Restart", "Cancel"],
4671//                 &mut cx,
4672//             );
4673
4674//             if let Some(mut answer) = answer {
4675//                 let answer = answer.next().await;
4676//                 if answer != Some(0) {
4677//                     return Ok(());
4678//                 }
4679//             }
4680//         }
4681
4682//         // If the user cancels any save prompt, then keep the app open.
4683//         for window in workspace_windows {
4684//             if let Some(should_close) = window.update_root(&mut cx, |workspace, cx| {
4685//                 workspace.prepare_to_close(true, cx)
4686//             }) {
4687//                 if !should_close.await? {
4688//                     return Ok(());
4689//                 }
4690//             }
4691//         }
4692//         cx.platform().restart();
4693//         anyhow::Ok(())
4694//     })
4695//     .detach_and_log_err(cx);
4696// }
4697
4698fn parse_pixel_position_env_var(value: &str) -> Option<Point<GlobalPixels>> {
4699    let mut parts = value.split(',');
4700    let x: usize = parts.next()?.parse().ok()?;
4701    let y: usize = parts.next()?.parse().ok()?;
4702    Some(point((x as f64).into(), (y as f64).into()))
4703}
4704
4705fn parse_pixel_size_env_var(value: &str) -> Option<Size<GlobalPixels>> {
4706    let mut parts = value.split(',');
4707    let width: usize = parts.next()?.parse().ok()?;
4708    let height: usize = parts.next()?.parse().ok()?;
4709    Some(size((width as f64).into(), (height as f64).into()))
4710}
4711
4712// #[cfg(test)]
4713// mod tests {
4714//     use super::*;
4715//     use crate::{
4716//         dock::test::{TestPanel, TestPanelEvent},
4717//         item::test::{TestItem, TestItemEvent, TestProjectItem},
4718//     };
4719//     use fs::FakeFs;
4720//     use gpui::{executor::Deterministic, test::EmptyView, TestAppContext};
4721//     use project::{Project, ProjectEntryId};
4722//     use serde_json::json;
4723//     use settings::SettingsStore;
4724//     use std::{cell::RefCell, rc::Rc};
4725
4726//     #[gpui::test]
4727//     async fn test_tab_disambiguation(cx: &mut TestAppContext) {
4728//         init_test(cx);
4729
4730//         let fs = FakeFs::new(cx.background());
4731//         let project = Project::test(fs, [], cx).await;
4732//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
4733//         let workspace = window.root(cx);
4734
4735//         // Adding an item with no ambiguity renders the tab without detail.
4736//         let item1 = window.build_view(cx, |_| {
4737//             let mut item = TestItem::new();
4738//             item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
4739//             item
4740//         });
4741//         workspace.update(cx, |workspace, cx| {
4742//             workspace.add_item(Box::new(item1.clone()), cx);
4743//         });
4744//         item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), None));
4745
4746//         // Adding an item that creates ambiguity increases the level of detail on
4747//         // both tabs.
4748//         let item2 = window.build_view(cx, |_| {
4749//             let mut item = TestItem::new();
4750//             item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
4751//             item
4752//         });
4753//         workspace.update(cx, |workspace, cx| {
4754//             workspace.add_item(Box::new(item2.clone()), cx);
4755//         });
4756//         item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
4757//         item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
4758
4759//         // Adding an item that creates ambiguity increases the level of detail only
4760//         // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
4761//         // we stop at the highest detail available.
4762//         let item3 = window.build_view(cx, |_| {
4763//             let mut item = TestItem::new();
4764//             item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
4765//             item
4766//         });
4767//         workspace.update(cx, |workspace, cx| {
4768//             workspace.add_item(Box::new(item3.clone()), cx);
4769//         });
4770//         item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
4771//         item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
4772//         item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
4773//     }
4774
4775//     #[gpui::test]
4776//     async fn test_tracking_active_path(cx: &mut TestAppContext) {
4777//         init_test(cx);
4778
4779//         let fs = FakeFs::new(cx.background());
4780//         fs.insert_tree(
4781//             "/root1",
4782//             json!({
4783//                 "one.txt": "",
4784//                 "two.txt": "",
4785//             }),
4786//         )
4787//         .await;
4788//         fs.insert_tree(
4789//             "/root2",
4790//             json!({
4791//                 "three.txt": "",
4792//             }),
4793//         )
4794//         .await;
4795
4796//         let project = Project::test(fs, ["root1".as_ref()], cx).await;
4797//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
4798//         let workspace = window.root(cx);
4799//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4800//         let worktree_id = project.read_with(cx, |project, cx| {
4801//             project.worktrees(cx).next().unwrap().read(cx).id()
4802//         });
4803
4804//         let item1 = window.build_view(cx, |cx| {
4805//             TestItem::new().with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
4806//         });
4807//         let item2 = window.build_view(cx, |cx| {
4808//             TestItem::new().with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
4809//         });
4810
4811//         // Add an item to an empty pane
4812//         workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item1), cx));
4813//         project.read_with(cx, |project, cx| {
4814//             assert_eq!(
4815//                 project.active_entry(),
4816//                 project
4817//                     .entry_for_path(&(worktree_id, "one.txt").into(), cx)
4818//                     .map(|e| e.id)
4819//             );
4820//         });
4821//         assert_eq!(window.current_title(cx).as_deref(), Some("one.txt β€” root1"));
4822
4823//         // Add a second item to a non-empty pane
4824//         workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item2), cx));
4825//         assert_eq!(window.current_title(cx).as_deref(), Some("two.txt β€” root1"));
4826//         project.read_with(cx, |project, cx| {
4827//             assert_eq!(
4828//                 project.active_entry(),
4829//                 project
4830//                     .entry_for_path(&(worktree_id, "two.txt").into(), cx)
4831//                     .map(|e| e.id)
4832//             );
4833//         });
4834
4835//         // Close the active item
4836//         pane.update(cx, |pane, cx| {
4837//             pane.close_active_item(&Default::default(), cx).unwrap()
4838//         })
4839//         .await
4840//         .unwrap();
4841//         assert_eq!(window.current_title(cx).as_deref(), Some("one.txt β€” root1"));
4842//         project.read_with(cx, |project, cx| {
4843//             assert_eq!(
4844//                 project.active_entry(),
4845//                 project
4846//                     .entry_for_path(&(worktree_id, "one.txt").into(), cx)
4847//                     .map(|e| e.id)
4848//             );
4849//         });
4850
4851//         // Add a project folder
4852//         project
4853//             .update(cx, |project, cx| {
4854//                 project.find_or_create_local_worktree("/root2", true, cx)
4855//             })
4856//             .await
4857//             .unwrap();
4858//         assert_eq!(
4859//             window.current_title(cx).as_deref(),
4860//             Some("one.txt β€” root1, root2")
4861//         );
4862
4863//         // Remove a project folder
4864//         project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
4865//         assert_eq!(window.current_title(cx).as_deref(), Some("one.txt β€” root2"));
4866//     }
4867
4868//     #[gpui::test]
4869//     async fn test_close_window(cx: &mut TestAppContext) {
4870//         init_test(cx);
4871
4872//         let fs = FakeFs::new(cx.background());
4873//         fs.insert_tree("/root", json!({ "one": "" })).await;
4874
4875//         let project = Project::test(fs, ["root".as_ref()], cx).await;
4876//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
4877//         let workspace = window.root(cx);
4878
4879//         // When there are no dirty items, there's nothing to do.
4880//         let item1 = window.build_view(cx, |_| TestItem::new());
4881//         workspace.update(cx, |w, cx| w.add_item(Box::new(item1.clone()), cx));
4882//         let task = workspace.update(cx, |w, cx| w.prepare_to_close(false, cx));
4883//         assert!(task.await.unwrap());
4884
4885//         // When there are dirty untitled items, prompt to save each one. If the user
4886//         // cancels any prompt, then abort.
4887//         let item2 = window.build_view(cx, |_| TestItem::new().with_dirty(true));
4888//         let item3 = window.build_view(cx, |cx| {
4889//             TestItem::new()
4890//                 .with_dirty(true)
4891//                 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
4892//         });
4893//         workspace.update(cx, |w, cx| {
4894//             w.add_item(Box::new(item2.clone()), cx);
4895//             w.add_item(Box::new(item3.clone()), cx);
4896//         });
4897//         let task = workspace.update(cx, |w, cx| w.prepare_to_close(false, cx));
4898//         cx.foreground().run_until_parked();
4899//         window.simulate_prompt_answer(2, cx); // cancel save all
4900//         cx.foreground().run_until_parked();
4901//         window.simulate_prompt_answer(2, cx); // cancel save all
4902//         cx.foreground().run_until_parked();
4903//         assert!(!window.has_pending_prompt(cx));
4904//         assert!(!task.await.unwrap());
4905//     }
4906
4907//     #[gpui::test]
4908//     async fn test_close_pane_items(cx: &mut TestAppContext) {
4909//         init_test(cx);
4910
4911//         let fs = FakeFs::new(cx.background());
4912
4913//         let project = Project::test(fs, None, cx).await;
4914//         let window = cx.add_window(|cx| Workspace::test_new(project, cx));
4915//         let workspace = window.root(cx);
4916
4917//         let item1 = window.build_view(cx, |cx| {
4918//             TestItem::new()
4919//                 .with_dirty(true)
4920//                 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
4921//         });
4922//         let item2 = window.build_view(cx, |cx| {
4923//             TestItem::new()
4924//                 .with_dirty(true)
4925//                 .with_conflict(true)
4926//                 .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)])
4927//         });
4928//         let item3 = window.build_view(cx, |cx| {
4929//             TestItem::new()
4930//                 .with_dirty(true)
4931//                 .with_conflict(true)
4932//                 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
4933//         });
4934//         let item4 = window.build_view(cx, |cx| {
4935//             TestItem::new()
4936//                 .with_dirty(true)
4937//                 .with_project_items(&[TestProjectItem::new_untitled(cx)])
4938//         });
4939//         let pane = workspace.update(cx, |workspace, cx| {
4940//             workspace.add_item(Box::new(item1.clone()), cx);
4941//             workspace.add_item(Box::new(item2.clone()), cx);
4942//             workspace.add_item(Box::new(item3.clone()), cx);
4943//             workspace.add_item(Box::new(item4.clone()), cx);
4944//             workspace.active_pane().clone()
4945//         });
4946
4947//         let close_items = pane.update(cx, |pane, cx| {
4948//             pane.activate_item(1, true, true, cx);
4949//             assert_eq!(pane.active_item().unwrap().id(), item2.id());
4950//             let item1_id = item1.id();
4951//             let item3_id = item3.id();
4952//             let item4_id = item4.id();
4953//             pane.close_items(cx, SaveIntent::Close, move |id| {
4954//                 [item1_id, item3_id, item4_id].contains(&id)
4955//             })
4956//         });
4957//         cx.foreground().run_until_parked();
4958
4959//         assert!(window.has_pending_prompt(cx));
4960//         // Ignore "Save all" prompt
4961//         window.simulate_prompt_answer(2, cx);
4962//         cx.foreground().run_until_parked();
4963//         // There's a prompt to save item 1.
4964//         pane.read_with(cx, |pane, _| {
4965//             assert_eq!(pane.items_len(), 4);
4966//             assert_eq!(pane.active_item().unwrap().id(), item1.id());
4967//         });
4968//         // Confirm saving item 1.
4969//         window.simulate_prompt_answer(0, cx);
4970//         cx.foreground().run_until_parked();
4971
4972//         // Item 1 is saved. There's a prompt to save item 3.
4973//         pane.read_with(cx, |pane, cx| {
4974//             assert_eq!(item1.read(cx).save_count, 1);
4975//             assert_eq!(item1.read(cx).save_as_count, 0);
4976//             assert_eq!(item1.read(cx).reload_count, 0);
4977//             assert_eq!(pane.items_len(), 3);
4978//             assert_eq!(pane.active_item().unwrap().id(), item3.id());
4979//         });
4980//         assert!(window.has_pending_prompt(cx));
4981
4982//         // Cancel saving item 3.
4983//         window.simulate_prompt_answer(1, cx);
4984//         cx.foreground().run_until_parked();
4985
4986//         // Item 3 is reloaded. There's a prompt to save item 4.
4987//         pane.read_with(cx, |pane, cx| {
4988//             assert_eq!(item3.read(cx).save_count, 0);
4989//             assert_eq!(item3.read(cx).save_as_count, 0);
4990//             assert_eq!(item3.read(cx).reload_count, 1);
4991//             assert_eq!(pane.items_len(), 2);
4992//             assert_eq!(pane.active_item().unwrap().id(), item4.id());
4993//         });
4994//         assert!(window.has_pending_prompt(cx));
4995
4996//         // Confirm saving item 4.
4997//         window.simulate_prompt_answer(0, cx);
4998//         cx.foreground().run_until_parked();
4999
5000//         // There's a prompt for a path for item 4.
5001//         cx.simulate_new_path_selection(|_| Some(Default::default()));
5002//         close_items.await.unwrap();
5003
5004//         // The requested items are closed.
5005//         pane.read_with(cx, |pane, cx| {
5006//             assert_eq!(item4.read(cx).save_count, 0);
5007//             assert_eq!(item4.read(cx).save_as_count, 1);
5008//             assert_eq!(item4.read(cx).reload_count, 0);
5009//             assert_eq!(pane.items_len(), 1);
5010//             assert_eq!(pane.active_item().unwrap().id(), item2.id());
5011//         });
5012//     }
5013
5014//     #[gpui::test]
5015//     async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
5016//         init_test(cx);
5017
5018//         let fs = FakeFs::new(cx.background());
5019
5020//         let project = Project::test(fs, [], cx).await;
5021//         let window = cx.add_window(|cx| Workspace::test_new(project, cx));
5022//         let workspace = window.root(cx);
5023
5024//         // Create several workspace items with single project entries, and two
5025//         // workspace items with multiple project entries.
5026//         let single_entry_items = (0..=4)
5027//             .map(|project_entry_id| {
5028//                 window.build_view(cx, |cx| {
5029//                     TestItem::new()
5030//                         .with_dirty(true)
5031//                         .with_project_items(&[TestProjectItem::new(
5032//                             project_entry_id,
5033//                             &format!("{project_entry_id}.txt"),
5034//                             cx,
5035//                         )])
5036//                 })
5037//             })
5038//             .collect::<Vec<_>>();
5039//         let item_2_3 = window.build_view(cx, |cx| {
5040//             TestItem::new()
5041//                 .with_dirty(true)
5042//                 .with_singleton(false)
5043//                 .with_project_items(&[
5044//                     single_entry_items[2].read(cx).project_items[0].clone(),
5045//                     single_entry_items[3].read(cx).project_items[0].clone(),
5046//                 ])
5047//         });
5048//         let item_3_4 = window.build_view(cx, |cx| {
5049//             TestItem::new()
5050//                 .with_dirty(true)
5051//                 .with_singleton(false)
5052//                 .with_project_items(&[
5053//                     single_entry_items[3].read(cx).project_items[0].clone(),
5054//                     single_entry_items[4].read(cx).project_items[0].clone(),
5055//                 ])
5056//         });
5057
5058//         // Create two panes that contain the following project entries:
5059//         //   left pane:
5060//         //     multi-entry items:   (2, 3)
5061//         //     single-entry items:  0, 1, 2, 3, 4
5062//         //   right pane:
5063//         //     single-entry items:  1
5064//         //     multi-entry items:   (3, 4)
5065//         let left_pane = workspace.update(cx, |workspace, cx| {
5066//             let left_pane = workspace.active_pane().clone();
5067//             workspace.add_item(Box::new(item_2_3.clone()), cx);
5068//             for item in single_entry_items {
5069//                 workspace.add_item(Box::new(item), cx);
5070//             }
5071//             left_pane.update(cx, |pane, cx| {
5072//                 pane.activate_item(2, true, true, cx);
5073//             });
5074
5075//             workspace
5076//                 .split_and_clone(left_pane.clone(), SplitDirection::Right, cx)
5077//                 .unwrap();
5078
5079//             left_pane
5080//         });
5081
5082//         //Need to cause an effect flush in order to respect new focus
5083//         workspace.update(cx, |workspace, cx| {
5084//             workspace.add_item(Box::new(item_3_4.clone()), cx);
5085//             cx.focus(&left_pane);
5086//         });
5087
5088//         // When closing all of the items in the left pane, we should be prompted twice:
5089//         // once for project entry 0, and once for project entry 2. After those two
5090//         // prompts, the task should complete.
5091
5092//         let close = left_pane.update(cx, |pane, cx| {
5093//             pane.close_items(cx, SaveIntent::Close, move |_| true)
5094//         });
5095//         cx.foreground().run_until_parked();
5096//         // Discard "Save all" prompt
5097//         window.simulate_prompt_answer(2, cx);
5098
5099//         cx.foreground().run_until_parked();
5100//         left_pane.read_with(cx, |pane, cx| {
5101//             assert_eq!(
5102//                 pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
5103//                 &[ProjectEntryId::from_proto(0)]
5104//             );
5105//         });
5106//         window.simulate_prompt_answer(0, cx);
5107
5108//         cx.foreground().run_until_parked();
5109//         left_pane.read_with(cx, |pane, cx| {
5110//             assert_eq!(
5111//                 pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
5112//                 &[ProjectEntryId::from_proto(2)]
5113//             );
5114//         });
5115//         window.simulate_prompt_answer(0, cx);
5116
5117//         cx.foreground().run_until_parked();
5118//         close.await.unwrap();
5119//         left_pane.read_with(cx, |pane, _| {
5120//             assert_eq!(pane.items_len(), 0);
5121//         });
5122//     }
5123
5124//     #[gpui::test]
5125//     async fn test_autosave(deterministic: Arc<Deterministic>, cx: &mut gpui::TestAppContext) {
5126//         init_test(cx);
5127
5128//         let fs = FakeFs::new(cx.background());
5129
5130//         let project = Project::test(fs, [], cx).await;
5131//         let window = cx.add_window(|cx| Workspace::test_new(project, cx));
5132//         let workspace = window.root(cx);
5133//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5134
5135//         let item = window.build_view(cx, |cx| {
5136//             TestItem::new().with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5137//         });
5138//         let item_id = item.id();
5139//         workspace.update(cx, |workspace, cx| {
5140//             workspace.add_item(Box::new(item.clone()), cx);
5141//         });
5142
5143//         // Autosave on window change.
5144//         item.update(cx, |item, cx| {
5145//             cx.update_global(|settings: &mut SettingsStore, cx| {
5146//                 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
5147//                     settings.autosave = Some(AutosaveSetting::OnWindowChange);
5148//                 })
5149//             });
5150//             item.is_dirty = true;
5151//         });
5152
5153//         // Deactivating the window saves the file.
5154//         window.simulate_deactivation(cx);
5155//         deterministic.run_until_parked();
5156//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
5157
5158//         // Autosave on focus change.
5159//         item.update(cx, |item, cx| {
5160//             cx.focus_self();
5161//             cx.update_global(|settings: &mut SettingsStore, cx| {
5162//                 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
5163//                     settings.autosave = Some(AutosaveSetting::OnFocusChange);
5164//                 })
5165//             });
5166//             item.is_dirty = true;
5167//         });
5168
5169//         // Blurring the item saves the file.
5170//         item.update(cx, |_, cx| cx.blur());
5171//         deterministic.run_until_parked();
5172//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
5173
5174//         // Deactivating the window still saves the file.
5175//         window.simulate_activation(cx);
5176//         item.update(cx, |item, cx| {
5177//             cx.focus_self();
5178//             item.is_dirty = true;
5179//         });
5180//         window.simulate_deactivation(cx);
5181
5182//         deterministic.run_until_parked();
5183//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
5184
5185//         // Autosave after delay.
5186//         item.update(cx, |item, cx| {
5187//             cx.update_global(|settings: &mut SettingsStore, cx| {
5188//                 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
5189//                     settings.autosave = Some(AutosaveSetting::AfterDelay { milliseconds: 500 });
5190//                 })
5191//             });
5192//             item.is_dirty = true;
5193//             cx.emit(TestItemEvent::Edit);
5194//         });
5195
5196//         // Delay hasn't fully expired, so the file is still dirty and unsaved.
5197//         deterministic.advance_clock(Duration::from_millis(250));
5198//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
5199
5200//         // After delay expires, the file is saved.
5201//         deterministic.advance_clock(Duration::from_millis(250));
5202//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
5203
5204//         // Autosave on focus change, ensuring closing the tab counts as such.
5205//         item.update(cx, |item, cx| {
5206//             cx.update_global(|settings: &mut SettingsStore, cx| {
5207//                 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
5208//                     settings.autosave = Some(AutosaveSetting::OnFocusChange);
5209//                 })
5210//             });
5211//             item.is_dirty = true;
5212//         });
5213
5214//         pane.update(cx, |pane, cx| {
5215//             pane.close_items(cx, SaveIntent::Close, move |id| id == item_id)
5216//         })
5217//         .await
5218//         .unwrap();
5219//         assert!(!window.has_pending_prompt(cx));
5220//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
5221
5222//         // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
5223//         workspace.update(cx, |workspace, cx| {
5224//             workspace.add_item(Box::new(item.clone()), cx);
5225//         });
5226//         item.update(cx, |item, cx| {
5227//             item.project_items[0].update(cx, |item, _| {
5228//                 item.entry_id = None;
5229//             });
5230//             item.is_dirty = true;
5231//             cx.blur();
5232//         });
5233//         deterministic.run_until_parked();
5234//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
5235
5236//         // Ensure autosave is prevented for deleted files also when closing the buffer.
5237//         let _close_items = pane.update(cx, |pane, cx| {
5238//             pane.close_items(cx, SaveIntent::Close, move |id| id == item_id)
5239//         });
5240//         deterministic.run_until_parked();
5241//         assert!(window.has_pending_prompt(cx));
5242//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
5243//     }
5244
5245//     #[gpui::test]
5246//     async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
5247//         init_test(cx);
5248
5249//         let fs = FakeFs::new(cx.background());
5250
5251//         let project = Project::test(fs, [], cx).await;
5252//         let window = cx.add_window(|cx| Workspace::test_new(project, cx));
5253//         let workspace = window.root(cx);
5254
5255//         let item = window.build_view(cx, |cx| {
5256//             TestItem::new().with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5257//         });
5258//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5259//         let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
5260//         let toolbar_notify_count = Rc::new(RefCell::new(0));
5261
5262//         workspace.update(cx, |workspace, cx| {
5263//             workspace.add_item(Box::new(item.clone()), cx);
5264//             let toolbar_notification_count = toolbar_notify_count.clone();
5265//             cx.observe(&toolbar, move |_, _, _| {
5266//                 *toolbar_notification_count.borrow_mut() += 1
5267//             })
5268//             .detach();
5269//         });
5270
5271//         pane.read_with(cx, |pane, _| {
5272//             assert!(!pane.can_navigate_backward());
5273//             assert!(!pane.can_navigate_forward());
5274//         });
5275
5276//         item.update(cx, |item, cx| {
5277//             item.set_state("one".to_string(), cx);
5278//         });
5279
5280//         // Toolbar must be notified to re-render the navigation buttons
5281//         assert_eq!(*toolbar_notify_count.borrow(), 1);
5282
5283//         pane.read_with(cx, |pane, _| {
5284//             assert!(pane.can_navigate_backward());
5285//             assert!(!pane.can_navigate_forward());
5286//         });
5287
5288//         workspace
5289//             .update(cx, |workspace, cx| workspace.go_back(pane.downgrade(), cx))
5290//             .await
5291//             .unwrap();
5292
5293//         assert_eq!(*toolbar_notify_count.borrow(), 3);
5294//         pane.read_with(cx, |pane, _| {
5295//             assert!(!pane.can_navigate_backward());
5296//             assert!(pane.can_navigate_forward());
5297//         });
5298//     }
5299
5300//     #[gpui::test]
5301//     async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
5302//         init_test(cx);
5303//         let fs = FakeFs::new(cx.background());
5304
5305//         let project = Project::test(fs, [], cx).await;
5306//         let window = cx.add_window(|cx| Workspace::test_new(project, cx));
5307//         let workspace = window.root(cx);
5308
5309//         let panel = workspace.update(cx, |workspace, cx| {
5310//             let panel = cx.build_view(|_| TestPanel::new(DockPosition::Right));
5311//             workspace.add_panel(panel.clone(), cx);
5312
5313//             workspace
5314//                 .right_dock()
5315//                 .update(cx, |right_dock, cx| right_dock.set_open(true, cx));
5316
5317//             panel
5318//         });
5319
5320//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5321//         pane.update(cx, |pane, cx| {
5322//             let item = cx.build_view(|_| TestItem::new());
5323//             pane.add_item(Box::new(item), true, true, None, cx);
5324//         });
5325
5326//         // Transfer focus from center to panel
5327//         workspace.update(cx, |workspace, cx| {
5328//             workspace.toggle_panel_focus::<TestPanel>(cx);
5329//         });
5330
5331//         workspace.read_with(cx, |workspace, cx| {
5332//             assert!(workspace.right_dock().read(cx).is_open());
5333//             assert!(!panel.is_zoomed(cx));
5334//             assert!(panel.has_focus(cx));
5335//         });
5336
5337//         // Transfer focus from panel to center
5338//         workspace.update(cx, |workspace, cx| {
5339//             workspace.toggle_panel_focus::<TestPanel>(cx);
5340//         });
5341
5342//         workspace.read_with(cx, |workspace, cx| {
5343//             assert!(workspace.right_dock().read(cx).is_open());
5344//             assert!(!panel.is_zoomed(cx));
5345//             assert!(!panel.has_focus(cx));
5346//         });
5347
5348//         // Close the dock
5349//         workspace.update(cx, |workspace, cx| {
5350//             workspace.toggle_dock(DockPosition::Right, cx);
5351//         });
5352
5353//         workspace.read_with(cx, |workspace, cx| {
5354//             assert!(!workspace.right_dock().read(cx).is_open());
5355//             assert!(!panel.is_zoomed(cx));
5356//             assert!(!panel.has_focus(cx));
5357//         });
5358
5359//         // Open the dock
5360//         workspace.update(cx, |workspace, cx| {
5361//             workspace.toggle_dock(DockPosition::Right, cx);
5362//         });
5363
5364//         workspace.read_with(cx, |workspace, cx| {
5365//             assert!(workspace.right_dock().read(cx).is_open());
5366//             assert!(!panel.is_zoomed(cx));
5367//             assert!(panel.has_focus(cx));
5368//         });
5369
5370//         // Focus and zoom panel
5371//         panel.update(cx, |panel, cx| {
5372//             cx.focus_self();
5373//             panel.set_zoomed(true, cx)
5374//         });
5375
5376//         workspace.read_with(cx, |workspace, cx| {
5377//             assert!(workspace.right_dock().read(cx).is_open());
5378//             assert!(panel.is_zoomed(cx));
5379//             assert!(panel.has_focus(cx));
5380//         });
5381
5382//         // Transfer focus to the center closes the dock
5383//         workspace.update(cx, |workspace, cx| {
5384//             workspace.toggle_panel_focus::<TestPanel>(cx);
5385//         });
5386
5387//         workspace.read_with(cx, |workspace, cx| {
5388//             assert!(!workspace.right_dock().read(cx).is_open());
5389//             assert!(panel.is_zoomed(cx));
5390//             assert!(!panel.has_focus(cx));
5391//         });
5392
5393//         // Transferring focus back to the panel keeps it zoomed
5394//         workspace.update(cx, |workspace, cx| {
5395//             workspace.toggle_panel_focus::<TestPanel>(cx);
5396//         });
5397
5398//         workspace.read_with(cx, |workspace, cx| {
5399//             assert!(workspace.right_dock().read(cx).is_open());
5400//             assert!(panel.is_zoomed(cx));
5401//             assert!(panel.has_focus(cx));
5402//         });
5403
5404//         // Close the dock while it is zoomed
5405//         workspace.update(cx, |workspace, cx| {
5406//             workspace.toggle_dock(DockPosition::Right, cx)
5407//         });
5408
5409//         workspace.read_with(cx, |workspace, cx| {
5410//             assert!(!workspace.right_dock().read(cx).is_open());
5411//             assert!(panel.is_zoomed(cx));
5412//             assert!(workspace.zoomed.is_none());
5413//             assert!(!panel.has_focus(cx));
5414//         });
5415
5416//         // Opening the dock, when it's zoomed, retains focus
5417//         workspace.update(cx, |workspace, cx| {
5418//             workspace.toggle_dock(DockPosition::Right, cx)
5419//         });
5420
5421//         workspace.read_with(cx, |workspace, cx| {
5422//             assert!(workspace.right_dock().read(cx).is_open());
5423//             assert!(panel.is_zoomed(cx));
5424//             assert!(workspace.zoomed.is_some());
5425//             assert!(panel.has_focus(cx));
5426//         });
5427
5428//         // Unzoom and close the panel, zoom the active pane.
5429//         panel.update(cx, |panel, cx| panel.set_zoomed(false, cx));
5430//         workspace.update(cx, |workspace, cx| {
5431//             workspace.toggle_dock(DockPosition::Right, cx)
5432//         });
5433//         pane.update(cx, |pane, cx| pane.toggle_zoom(&Default::default(), cx));
5434
5435//         // Opening a dock unzooms the pane.
5436//         workspace.update(cx, |workspace, cx| {
5437//             workspace.toggle_dock(DockPosition::Right, cx)
5438//         });
5439//         workspace.read_with(cx, |workspace, cx| {
5440//             let pane = pane.read(cx);
5441//             assert!(!pane.is_zoomed());
5442//             assert!(!pane.has_focus());
5443//             assert!(workspace.right_dock().read(cx).is_open());
5444//             assert!(workspace.zoomed.is_none());
5445//         });
5446//     }
5447
5448//     #[gpui::test]
5449//     async fn test_panels(cx: &mut gpui::TestAppContext) {
5450//         init_test(cx);
5451//         let fs = FakeFs::new(cx.background());
5452
5453//         let project = Project::test(fs, [], cx).await;
5454//         let window = cx.add_window(|cx| Workspace::test_new(project, cx));
5455//         let workspace = window.root(cx);
5456
5457//         let (panel_1, panel_2) = workspace.update(cx, |workspace, cx| {
5458//             // Add panel_1 on the left, panel_2 on the right.
5459//             let panel_1 = cx.build_view(|_| TestPanel::new(DockPosition::Left));
5460//             workspace.add_panel(panel_1.clone(), cx);
5461//             workspace
5462//                 .left_dock()
5463//                 .update(cx, |left_dock, cx| left_dock.set_open(true, cx));
5464//             let panel_2 = cx.build_view(|_| TestPanel::new(DockPosition::Right));
5465//             workspace.add_panel(panel_2.clone(), cx);
5466//             workspace
5467//                 .right_dock()
5468//                 .update(cx, |right_dock, cx| right_dock.set_open(true, cx));
5469
5470//             let left_dock = workspace.left_dock();
5471//             assert_eq!(
5472//                 left_dock.read(cx).visible_panel().unwrap().id(),
5473//                 panel_1.id()
5474//             );
5475//             assert_eq!(
5476//                 left_dock.read(cx).active_panel_size(cx).unwrap(),
5477//                 panel_1.size(cx)
5478//             );
5479
5480//             left_dock.update(cx, |left_dock, cx| {
5481//                 left_dock.resize_active_panel(Some(1337.), cx)
5482//             });
5483//             assert_eq!(
5484//                 workspace
5485//                     .right_dock()
5486//                     .read(cx)
5487//                     .visible_panel()
5488//                     .unwrap()
5489//                     .id(),
5490//                 panel_2.id()
5491//             );
5492
5493//             (panel_1, panel_2)
5494//         });
5495
5496//         // Move panel_1 to the right
5497//         panel_1.update(cx, |panel_1, cx| {
5498//             panel_1.set_position(DockPosition::Right, cx)
5499//         });
5500
5501//         workspace.update(cx, |workspace, cx| {
5502//             // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
5503//             // Since it was the only panel on the left, the left dock should now be closed.
5504//             assert!(!workspace.left_dock().read(cx).is_open());
5505//             assert!(workspace.left_dock().read(cx).visible_panel().is_none());
5506//             let right_dock = workspace.right_dock();
5507//             assert_eq!(
5508//                 right_dock.read(cx).visible_panel().unwrap().id(),
5509//                 panel_1.id()
5510//             );
5511//             assert_eq!(right_dock.read(cx).active_panel_size(cx).unwrap(), 1337.);
5512
5513//             // Now we move panel_2Β to the left
5514//             panel_2.set_position(DockPosition::Left, cx);
5515//         });
5516
5517//         workspace.update(cx, |workspace, cx| {
5518//             // Since panel_2 was not visible on the right, we don't open the left dock.
5519//             assert!(!workspace.left_dock().read(cx).is_open());
5520//             // And the right dock is unaffected in it's displaying of panel_1
5521//             assert!(workspace.right_dock().read(cx).is_open());
5522//             assert_eq!(
5523//                 workspace
5524//                     .right_dock()
5525//                     .read(cx)
5526//                     .visible_panel()
5527//                     .unwrap()
5528//                     .id(),
5529//                 panel_1.id()
5530//             );
5531//         });
5532
5533//         // Move panel_1 back to the left
5534//         panel_1.update(cx, |panel_1, cx| {
5535//             panel_1.set_position(DockPosition::Left, cx)
5536//         });
5537
5538//         workspace.update(cx, |workspace, cx| {
5539//             // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
5540//             let left_dock = workspace.left_dock();
5541//             assert!(left_dock.read(cx).is_open());
5542//             assert_eq!(
5543//                 left_dock.read(cx).visible_panel().unwrap().id(),
5544//                 panel_1.id()
5545//             );
5546//             assert_eq!(left_dock.read(cx).active_panel_size(cx).unwrap(), 1337.);
5547//             // And right the dock should be closed as it no longer has any panels.
5548//             assert!(!workspace.right_dock().read(cx).is_open());
5549
5550//             // Now we move panel_1 to the bottom
5551//             panel_1.set_position(DockPosition::Bottom, cx);
5552//         });
5553
5554//         workspace.update(cx, |workspace, cx| {
5555//             // Since panel_1 was visible on the left, we close the left dock.
5556//             assert!(!workspace.left_dock().read(cx).is_open());
5557//             // The bottom dock is sized based on the panel's default size,
5558//             // since the panel orientation changed from vertical to horizontal.
5559//             let bottom_dock = workspace.bottom_dock();
5560//             assert_eq!(
5561//                 bottom_dock.read(cx).active_panel_size(cx).unwrap(),
5562//                 panel_1.size(cx),
5563//             );
5564//             // Close bottom dock and move panel_1 back to the left.
5565//             bottom_dock.update(cx, |bottom_dock, cx| bottom_dock.set_open(false, cx));
5566//             panel_1.set_position(DockPosition::Left, cx);
5567//         });
5568
5569//         // Emit activated event on panel 1
5570//         panel_1.update(cx, |_, cx| cx.emit(TestPanelEvent::Activated));
5571
5572//         // Now the left dock is open and panel_1 is active and focused.
5573//         workspace.read_with(cx, |workspace, cx| {
5574//             let left_dock = workspace.left_dock();
5575//             assert!(left_dock.read(cx).is_open());
5576//             assert_eq!(
5577//                 left_dock.read(cx).visible_panel().unwrap().id(),
5578//                 panel_1.id()
5579//             );
5580//             assert!(panel_1.is_focused(cx));
5581//         });
5582
5583//         // Emit closed event on panel 2, which is not active
5584//         panel_2.update(cx, |_, cx| cx.emit(TestPanelEvent::Closed));
5585
5586//         // Wo don't close the left dock, because panel_2 wasn't the active panel
5587//         workspace.read_with(cx, |workspace, cx| {
5588//             let left_dock = workspace.left_dock();
5589//             assert!(left_dock.read(cx).is_open());
5590//             assert_eq!(
5591//                 left_dock.read(cx).visible_panel().unwrap().id(),
5592//                 panel_1.id()
5593//             );
5594//         });
5595
5596//         // Emitting a ZoomIn event shows the panel as zoomed.
5597//         panel_1.update(cx, |_, cx| cx.emit(TestPanelEvent::ZoomIn));
5598//         workspace.read_with(cx, |workspace, _| {
5599//             assert_eq!(workspace.zoomed, Some(panel_1.downgrade().into_any()));
5600//             assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
5601//         });
5602
5603//         // Move panel to another dock while it is zoomed
5604//         panel_1.update(cx, |panel, cx| panel.set_position(DockPosition::Right, cx));
5605//         workspace.read_with(cx, |workspace, _| {
5606//             assert_eq!(workspace.zoomed, Some(panel_1.downgrade().into_any()));
5607//             assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
5608//         });
5609
5610//         // If focus is transferred to another view that's not a panel or another pane, we still show
5611//         // the panel as zoomed.
5612//         let focus_receiver = window.build_view(cx, |_| EmptyView);
5613//         focus_receiver.update(cx, |_, cx| cx.focus_self());
5614//         workspace.read_with(cx, |workspace, _| {
5615//             assert_eq!(workspace.zoomed, Some(panel_1.downgrade().into_any()));
5616//             assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
5617//         });
5618
5619//         // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
5620//         workspace.update(cx, |_, cx| cx.focus_self());
5621//         workspace.read_with(cx, |workspace, _| {
5622//             assert_eq!(workspace.zoomed, None);
5623//             assert_eq!(workspace.zoomed_position, None);
5624//         });
5625
5626//         // If focus is transferred again to another view that's not a panel or a pane, we won't
5627//         // show the panel as zoomed because it wasn't zoomed before.
5628//         focus_receiver.update(cx, |_, cx| cx.focus_self());
5629//         workspace.read_with(cx, |workspace, _| {
5630//             assert_eq!(workspace.zoomed, None);
5631//             assert_eq!(workspace.zoomed_position, None);
5632//         });
5633
5634//         // When focus is transferred back to the panel, it is zoomed again.
5635//         panel_1.update(cx, |_, cx| cx.focus_self());
5636//         workspace.read_with(cx, |workspace, _| {
5637//             assert_eq!(workspace.zoomed, Some(panel_1.downgrade().into_any()));
5638//             assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
5639//         });
5640
5641//         // Emitting a ZoomOut event unzooms the panel.
5642//         panel_1.update(cx, |_, cx| cx.emit(TestPanelEvent::ZoomOut));
5643//         workspace.read_with(cx, |workspace, _| {
5644//             assert_eq!(workspace.zoomed, None);
5645//             assert_eq!(workspace.zoomed_position, None);
5646//         });
5647
5648//         // Emit closed event on panel 1, which is active
5649//         panel_1.update(cx, |_, cx| cx.emit(TestPanelEvent::Closed));
5650
5651//         // Now the left dock is closed, because panel_1 was the active panel
5652//         workspace.read_with(cx, |workspace, cx| {
5653//             let right_dock = workspace.right_dock();
5654//             assert!(!right_dock.read(cx).is_open());
5655//         });
5656//     }
5657
5658//     pub fn init_test(cx: &mut TestAppContext) {
5659//         cx.foreground().forbid_parking();
5660//         cx.update(|cx| {
5661//             cx.set_global(SettingsStore::test(cx));
5662//             theme::init((), cx);
5663//             language::init(cx);
5664//             crate::init_settings(cx);
5665//             Project::init_settings(cx);
5666//         });
5667//     }
5668// }