workspace2.rs

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