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,
  33    Model, ModelContext, ParentElement, Point, Render, Size, StatefulInteractive, Styled,
  34    Subscription, Task, View, ViewContext, VisualContext, WeakView, WindowBounds, WindowContext,
  35    WindowHandle, 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(|workspace, event, cx| {
2701                if event.up.click_count == 2 {
2702                    // todo!()
2703                    // cx.zoom_window();
2704                }
2705            })
2706            .child("Collab title bar Item") // self.titlebar_item
2707    }
2708
2709    // fn active_item_path_changed(&mut self, cx: &mut ViewContext<Self>) {
2710    //     let active_entry = self.active_project_path(cx);
2711    //     self.project
2712    //         .update(cx, |project, cx| project.set_active_path(active_entry, cx));
2713    //     self.update_window_title(cx);
2714    // }
2715
2716    fn update_window_title(&mut self, cx: &mut ViewContext<Self>) {
2717        let project = self.project().read(cx);
2718        let mut title = String::new();
2719
2720        if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
2721            let filename = path
2722                .path
2723                .file_name()
2724                .map(|s| s.to_string_lossy())
2725                .or_else(|| {
2726                    Some(Cow::Borrowed(
2727                        project
2728                            .worktree_for_id(path.worktree_id, cx)?
2729                            .read(cx)
2730                            .root_name(),
2731                    ))
2732                });
2733
2734            if let Some(filename) = filename {
2735                title.push_str(filename.as_ref());
2736                title.push_str(" β€” ");
2737            }
2738        }
2739
2740        for (i, name) in project.worktree_root_names(cx).enumerate() {
2741            if i > 0 {
2742                title.push_str(", ");
2743            }
2744            title.push_str(name);
2745        }
2746
2747        if title.is_empty() {
2748            title = "empty project".to_string();
2749        }
2750
2751        if project.is_remote() {
2752            title.push_str(" ↙");
2753        } else if project.is_shared() {
2754            title.push_str(" β†—");
2755        }
2756
2757        // todo!()
2758        // cx.set_window_title(&title);
2759    }
2760
2761    fn update_window_edited(&mut self, cx: &mut ViewContext<Self>) {
2762        let is_edited = !self.project.read(cx).is_read_only()
2763            && self
2764                .items(cx)
2765                .any(|item| item.has_conflict(cx) || item.is_dirty(cx));
2766        if is_edited != self.window_edited {
2767            self.window_edited = is_edited;
2768            todo!()
2769            // cx.set_window_edited(self.window_edited)
2770        }
2771    }
2772
2773    //     fn render_disconnected_overlay(
2774    //         &self,
2775    //         cx: &mut ViewContext<Workspace>,
2776    //     ) -> Option<AnyElement<Workspace>> {
2777    //         if self.project.read(cx).is_read_only() {
2778    //             enum DisconnectedOverlay {}
2779    //             Some(
2780    //                 MouseEventHandler::new::<DisconnectedOverlay, _>(0, cx, |_, cx| {
2781    //                     let theme = &theme::current(cx);
2782    //                     Label::new(
2783    //                         "Your connection to the remote project has been lost.",
2784    //                         theme.workspace.disconnected_overlay.text.clone(),
2785    //                     )
2786    //                     .aligned()
2787    //                     .contained()
2788    //                     .with_style(theme.workspace.disconnected_overlay.container)
2789    //                 })
2790    //                 .with_cursor_style(CursorStyle::Arrow)
2791    //                 .capture_all()
2792    //                 .into_any_named("disconnected overlay"),
2793    //             )
2794    //         } else {
2795    //             None
2796    //         }
2797    //     }
2798
2799    //     fn render_notifications(
2800    //         &self,
2801    //         theme: &theme::Workspace,
2802    //         cx: &AppContext,
2803    //     ) -> Option<AnyElement<Workspace>> {
2804    //         if self.notifications.is_empty() {
2805    //             None
2806    //         } else {
2807    //             Some(
2808    //                 Flex::column()
2809    //                     .with_children(self.notifications.iter().map(|(_, _, notification)| {
2810    //                         ChildView::new(notification.as_any(), cx)
2811    //                             .contained()
2812    //                             .with_style(theme.notification)
2813    //                     }))
2814    //                     .constrained()
2815    //                     .with_width(theme.notifications.width)
2816    //                     .contained()
2817    //                     .with_style(theme.notifications.container)
2818    //                     .aligned()
2819    //                     .bottom()
2820    //                     .right()
2821    //                     .into_any(),
2822    //             )
2823    //         }
2824    //     }
2825
2826    //     // RPC handlers
2827
2828    fn handle_follow(
2829        &mut self,
2830        _follower_project_id: Option<u64>,
2831        _cx: &mut ViewContext<Self>,
2832    ) -> proto::FollowResponse {
2833        todo!()
2834
2835        //     let client = &self.app_state.client;
2836        //     let project_id = self.project.read(cx).remote_id();
2837
2838        //     let active_view_id = self.active_item(cx).and_then(|i| {
2839        //         Some(
2840        //             i.to_followable_item_handle(cx)?
2841        //                 .remote_id(client, cx)?
2842        //                 .to_proto(),
2843        //         )
2844        //     });
2845
2846        //     cx.notify();
2847
2848        //     self.last_active_view_id = active_view_id.clone();
2849        //     proto::FollowResponse {
2850        //         active_view_id,
2851        //         views: self
2852        //             .panes()
2853        //             .iter()
2854        //             .flat_map(|pane| {
2855        //                 let leader_id = self.leader_for_pane(pane);
2856        //                 pane.read(cx).items().filter_map({
2857        //                     let cx = &cx;
2858        //                     move |item| {
2859        //                         let item = item.to_followable_item_handle(cx)?;
2860        //                         if (project_id.is_none() || project_id != follower_project_id)
2861        //                             && item.is_project_item(cx)
2862        //                         {
2863        //                             return None;
2864        //                         }
2865        //                         let id = item.remote_id(client, cx)?.to_proto();
2866        //                         let variant = item.to_state_proto(cx)?;
2867        //                         Some(proto::View {
2868        //                             id: Some(id),
2869        //                             leader_id,
2870        //                             variant: Some(variant),
2871        //                         })
2872        //                     }
2873        //                 })
2874        //             })
2875        //             .collect(),
2876        //     }
2877    }
2878
2879    fn handle_update_followers(
2880        &mut self,
2881        leader_id: PeerId,
2882        message: proto::UpdateFollowers,
2883        _cx: &mut ViewContext<Self>,
2884    ) {
2885        self.leader_updates_tx
2886            .unbounded_send((leader_id, message))
2887            .ok();
2888    }
2889
2890    async fn process_leader_update(
2891        this: &WeakView<Self>,
2892        leader_id: PeerId,
2893        update: proto::UpdateFollowers,
2894        cx: &mut AsyncWindowContext,
2895    ) -> Result<()> {
2896        match update.variant.ok_or_else(|| anyhow!("invalid update"))? {
2897            proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
2898                this.update(cx, |this, _| {
2899                    for (_, state) in &mut this.follower_states {
2900                        if state.leader_id == leader_id {
2901                            state.active_view_id =
2902                                if let Some(active_view_id) = update_active_view.id.clone() {
2903                                    Some(ViewId::from_proto(active_view_id)?)
2904                                } else {
2905                                    None
2906                                };
2907                        }
2908                    }
2909                    anyhow::Ok(())
2910                })??;
2911            }
2912            proto::update_followers::Variant::UpdateView(update_view) => {
2913                let variant = update_view
2914                    .variant
2915                    .ok_or_else(|| anyhow!("missing update view variant"))?;
2916                let id = update_view
2917                    .id
2918                    .ok_or_else(|| anyhow!("missing update view id"))?;
2919                let mut tasks = Vec::new();
2920                this.update(cx, |this, cx| {
2921                    let project = this.project.clone();
2922                    for (_, state) in &mut this.follower_states {
2923                        if state.leader_id == leader_id {
2924                            let view_id = ViewId::from_proto(id.clone())?;
2925                            if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
2926                                tasks.push(item.apply_update_proto(&project, variant.clone(), cx));
2927                            }
2928                        }
2929                    }
2930                    anyhow::Ok(())
2931                })??;
2932                try_join_all(tasks).await.log_err();
2933            }
2934            proto::update_followers::Variant::CreateView(view) => {
2935                let panes = this.update(cx, |this, _| {
2936                    this.follower_states
2937                        .iter()
2938                        .filter_map(|(pane, state)| (state.leader_id == leader_id).then_some(pane))
2939                        .cloned()
2940                        .collect()
2941                })?;
2942                Self::add_views_from_leader(this.clone(), leader_id, panes, vec![view], cx).await?;
2943            }
2944        }
2945        this.update(cx, |this, cx| this.leader_updated(leader_id, cx))?;
2946        Ok(())
2947    }
2948
2949    async fn add_views_from_leader(
2950        this: WeakView<Self>,
2951        leader_id: PeerId,
2952        panes: Vec<View<Pane>>,
2953        views: Vec<proto::View>,
2954        cx: &mut AsyncWindowContext,
2955    ) -> Result<()> {
2956        let this = this.upgrade().context("workspace dropped")?;
2957
2958        let item_builders = cx.update(|_, cx| {
2959            cx.default_global::<FollowableItemBuilders>()
2960                .values()
2961                .map(|b| b.0)
2962                .collect::<Vec<_>>()
2963        })?;
2964
2965        let mut item_tasks_by_pane = HashMap::default();
2966        for pane in panes {
2967            let mut item_tasks = Vec::new();
2968            let mut leader_view_ids = Vec::new();
2969            for view in &views {
2970                let Some(id) = &view.id else { continue };
2971                let id = ViewId::from_proto(id.clone())?;
2972                let mut variant = view.variant.clone();
2973                if variant.is_none() {
2974                    Err(anyhow!("missing view variant"))?;
2975                }
2976                for build_item in &item_builders {
2977                    let task = cx.update(|_, cx| {
2978                        build_item(pane.clone(), this.clone(), id, &mut variant, cx)
2979                    })?;
2980                    if let Some(task) = task {
2981                        item_tasks.push(task);
2982                        leader_view_ids.push(id);
2983                        break;
2984                    } else {
2985                        assert!(variant.is_some());
2986                    }
2987                }
2988            }
2989
2990            item_tasks_by_pane.insert(pane, (item_tasks, leader_view_ids));
2991        }
2992
2993        for (pane, (item_tasks, leader_view_ids)) in item_tasks_by_pane {
2994            let items = futures::future::try_join_all(item_tasks).await?;
2995            this.update(cx, |this, cx| {
2996                let state = this.follower_states.get_mut(&pane)?;
2997                for (id, item) in leader_view_ids.into_iter().zip(items) {
2998                    item.set_leader_peer_id(Some(leader_id), cx);
2999                    state.items_by_leader_view_id.insert(id, item);
3000                }
3001
3002                Some(())
3003            });
3004        }
3005        Ok(())
3006    }
3007
3008    fn update_active_view_for_followers(&mut self, cx: &mut ViewContext<Self>) {
3009        let mut is_project_item = true;
3010        let mut update = proto::UpdateActiveView::default();
3011        if self.active_pane.read(cx).has_focus() {
3012            let item = self
3013                .active_item(cx)
3014                .and_then(|item| item.to_followable_item_handle(cx));
3015            if let Some(item) = item {
3016                is_project_item = item.is_project_item(cx);
3017                update = proto::UpdateActiveView {
3018                    id: item
3019                        .remote_id(&self.app_state.client, cx)
3020                        .map(|id| id.to_proto()),
3021                    leader_id: self.leader_for_pane(&self.active_pane),
3022                };
3023            }
3024        }
3025
3026        if update.id != self.last_active_view_id {
3027            self.last_active_view_id = update.id.clone();
3028            self.update_followers(
3029                is_project_item,
3030                proto::update_followers::Variant::UpdateActiveView(update),
3031                cx,
3032            );
3033        }
3034    }
3035
3036    fn update_followers(
3037        &self,
3038        project_only: bool,
3039        update: proto::update_followers::Variant,
3040        cx: &mut WindowContext,
3041    ) -> Option<()> {
3042        let project_id = if project_only {
3043            self.project.read(cx).remote_id()
3044        } else {
3045            None
3046        };
3047        self.app_state().workspace_store.update(cx, |store, cx| {
3048            store.update_followers(project_id, update, cx)
3049        })
3050    }
3051
3052    pub fn leader_for_pane(&self, pane: &View<Pane>) -> Option<PeerId> {
3053        self.follower_states.get(pane).map(|state| state.leader_id)
3054    }
3055
3056    fn leader_updated(&mut self, leader_id: PeerId, cx: &mut ViewContext<Self>) -> Option<()> {
3057        cx.notify();
3058
3059        let call = self.active_call()?;
3060        let room = call.read(cx).room()?.read(cx);
3061        let participant = room.remote_participant_for_peer_id(leader_id)?;
3062        let mut items_to_activate = Vec::new();
3063
3064        let leader_in_this_app;
3065        let leader_in_this_project;
3066        match participant.location {
3067            call2::ParticipantLocation::SharedProject { project_id } => {
3068                leader_in_this_app = true;
3069                leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
3070            }
3071            call2::ParticipantLocation::UnsharedProject => {
3072                leader_in_this_app = true;
3073                leader_in_this_project = false;
3074            }
3075            call2::ParticipantLocation::External => {
3076                leader_in_this_app = false;
3077                leader_in_this_project = false;
3078            }
3079        };
3080
3081        for (pane, state) in &self.follower_states {
3082            if state.leader_id != leader_id {
3083                continue;
3084            }
3085            if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
3086                if let Some(item) = state.items_by_leader_view_id.get(&active_view_id) {
3087                    if leader_in_this_project || !item.is_project_item(cx) {
3088                        items_to_activate.push((pane.clone(), item.boxed_clone()));
3089                    }
3090                } else {
3091                    log::warn!(
3092                        "unknown view id {:?} for leader {:?}",
3093                        active_view_id,
3094                        leader_id
3095                    );
3096                }
3097                continue;
3098            }
3099            // todo!()
3100            // if let Some(shared_screen) = self.shared_screen_for_peer(leader_id, pane, cx) {
3101            //     items_to_activate.push((pane.clone(), Box::new(shared_screen)));
3102            // }
3103        }
3104
3105        for (pane, item) in items_to_activate {
3106            let pane_was_focused = pane.read(cx).has_focus();
3107            if let Some(index) = pane.update(cx, |pane, _| pane.index_for_item(item.as_ref())) {
3108                pane.update(cx, |pane, cx| pane.activate_item(index, false, false, cx));
3109            } else {
3110                pane.update(cx, |pane, cx| {
3111                    pane.add_item(item.boxed_clone(), false, false, None, cx)
3112                });
3113            }
3114
3115            if pane_was_focused {
3116                pane.update(cx, |pane, cx| pane.focus_active_item(cx));
3117            }
3118        }
3119
3120        None
3121    }
3122
3123    //     fn shared_screen_for_peer(
3124    //         &self,
3125    //         peer_id: PeerId,
3126    //         pane: &View<Pane>,
3127    //         cx: &mut ViewContext<Self>,
3128    //     ) -> Option<View<SharedScreen>> {
3129    //         let call = self.active_call()?;
3130    //         let room = call.read(cx).room()?.read(cx);
3131    //         let participant = room.remote_participant_for_peer_id(peer_id)?;
3132    //         let track = participant.video_tracks.values().next()?.clone();
3133    //         let user = participant.user.clone();
3134
3135    //         for item in pane.read(cx).items_of_type::<SharedScreen>() {
3136    //             if item.read(cx).peer_id == peer_id {
3137    //                 return Some(item);
3138    //             }
3139    //         }
3140
3141    //         Some(cx.build_view(|cx| SharedScreen::new(&track, peer_id, user.clone(), cx)))
3142    //     }
3143
3144    pub fn on_window_activation_changed(&mut self, cx: &mut ViewContext<Self>) {
3145        if cx.is_window_active() {
3146            self.update_active_view_for_followers(cx);
3147            cx.background_executor()
3148                .spawn(persistence::DB.update_timestamp(self.database_id()))
3149                .detach();
3150        } else {
3151            for pane in &self.panes {
3152                pane.update(cx, |pane, cx| {
3153                    if let Some(item) = pane.active_item() {
3154                        item.workspace_deactivated(cx);
3155                    }
3156                    if matches!(
3157                        WorkspaceSettings::get_global(cx).autosave,
3158                        AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
3159                    ) {
3160                        for item in pane.items() {
3161                            Pane::autosave_item(item.as_ref(), self.project.clone(), cx)
3162                                .detach_and_log_err(cx);
3163                        }
3164                    }
3165                });
3166            }
3167        }
3168    }
3169
3170    fn active_call(&self) -> Option<&Model<ActiveCall>> {
3171        self.active_call.as_ref().map(|(call, _)| call)
3172    }
3173
3174    fn on_active_call_event(
3175        &mut self,
3176        _: Model<ActiveCall>,
3177        event: &call2::room::Event,
3178        cx: &mut ViewContext<Self>,
3179    ) {
3180        match event {
3181            call2::room::Event::ParticipantLocationChanged { participant_id }
3182            | call2::room::Event::RemoteVideoTracksChanged { participant_id } => {
3183                self.leader_updated(*participant_id, cx);
3184            }
3185            _ => {}
3186        }
3187    }
3188
3189    pub fn database_id(&self) -> WorkspaceId {
3190        self.database_id
3191    }
3192
3193    fn location(&self, cx: &AppContext) -> Option<WorkspaceLocation> {
3194        let project = self.project().read(cx);
3195
3196        if project.is_local() {
3197            Some(
3198                project
3199                    .visible_worktrees(cx)
3200                    .map(|worktree| worktree.read(cx).abs_path())
3201                    .collect::<Vec<_>>()
3202                    .into(),
3203            )
3204        } else {
3205            None
3206        }
3207    }
3208
3209    fn remove_panes(&mut self, member: Member, cx: &mut ViewContext<Workspace>) {
3210        match member {
3211            Member::Axis(PaneAxis { members, .. }) => {
3212                for child in members.iter() {
3213                    self.remove_panes(child.clone(), cx)
3214                }
3215            }
3216            Member::Pane(pane) => {
3217                self.force_remove_pane(&pane, cx);
3218            }
3219        }
3220    }
3221
3222    fn force_remove_pane(&mut self, pane: &View<Pane>, cx: &mut ViewContext<Workspace>) {
3223        self.panes.retain(|p| p != pane);
3224        if true {
3225            todo!()
3226            // cx.focus(self.panes.last().unwrap());
3227        }
3228        if self.last_active_center_pane == Some(pane.downgrade()) {
3229            self.last_active_center_pane = None;
3230        }
3231        cx.notify();
3232    }
3233
3234    //     fn schedule_serialize(&mut self, cx: &mut ViewContext<Self>) {
3235    //         self._schedule_serialize = Some(cx.spawn(|this, cx| async move {
3236    //             cx.background().timer(Duration::from_millis(100)).await;
3237    //             this.read_with(&cx, |this, cx| this.serialize_workspace(cx))
3238    //                 .ok();
3239    //         }));
3240    //     }
3241
3242    fn serialize_workspace(&self, cx: &mut ViewContext<Self>) {
3243        fn serialize_pane_handle(pane_handle: &View<Pane>, cx: &AppContext) -> SerializedPane {
3244            let (items, active) = {
3245                let pane = pane_handle.read(cx);
3246                let active_item_id = pane.active_item().map(|item| item.id());
3247                (
3248                    pane.items()
3249                        .filter_map(|item_handle| {
3250                            Some(SerializedItem {
3251                                kind: Arc::from(item_handle.serialized_item_kind()?),
3252                                item_id: item_handle.id().as_u64() as usize,
3253                                active: Some(item_handle.id()) == active_item_id,
3254                            })
3255                        })
3256                        .collect::<Vec<_>>(),
3257                    pane.has_focus(),
3258                )
3259            };
3260
3261            SerializedPane::new(items, active)
3262        }
3263
3264        fn build_serialized_pane_group(
3265            pane_group: &Member,
3266            cx: &AppContext,
3267        ) -> SerializedPaneGroup {
3268            match pane_group {
3269                Member::Axis(PaneAxis {
3270                    axis,
3271                    members,
3272                    flexes,
3273                    bounding_boxes: _,
3274                }) => SerializedPaneGroup::Group {
3275                    axis: *axis,
3276                    children: members
3277                        .iter()
3278                        .map(|member| build_serialized_pane_group(member, cx))
3279                        .collect::<Vec<_>>(),
3280                    flexes: Some(flexes.lock().clone()),
3281                },
3282                Member::Pane(pane_handle) => {
3283                    SerializedPaneGroup::Pane(serialize_pane_handle(&pane_handle, cx))
3284                }
3285            }
3286        }
3287
3288        fn build_serialized_docks(
3289            this: &Workspace,
3290            cx: &mut ViewContext<Workspace>,
3291        ) -> DockStructure {
3292            let left_dock = this.left_dock.read(cx);
3293            let left_visible = left_dock.is_open();
3294            let left_active_panel = left_dock
3295                .visible_panel()
3296                .and_then(|panel| Some(panel.persistent_name(cx).to_string()));
3297            let left_dock_zoom = left_dock
3298                .visible_panel()
3299                .map(|panel| panel.is_zoomed(cx))
3300                .unwrap_or(false);
3301
3302            let right_dock = this.right_dock.read(cx);
3303            let right_visible = right_dock.is_open();
3304            let right_active_panel = right_dock
3305                .visible_panel()
3306                .and_then(|panel| Some(panel.persistent_name(cx).to_string()));
3307            let right_dock_zoom = right_dock
3308                .visible_panel()
3309                .map(|panel| panel.is_zoomed(cx))
3310                .unwrap_or(false);
3311
3312            let bottom_dock = this.bottom_dock.read(cx);
3313            let bottom_visible = bottom_dock.is_open();
3314            let bottom_active_panel = bottom_dock
3315                .visible_panel()
3316                .and_then(|panel| Some(panel.persistent_name(cx).to_string()));
3317            let bottom_dock_zoom = bottom_dock
3318                .visible_panel()
3319                .map(|panel| panel.is_zoomed(cx))
3320                .unwrap_or(false);
3321
3322            DockStructure {
3323                left: DockData {
3324                    visible: left_visible,
3325                    active_panel: left_active_panel,
3326                    zoom: left_dock_zoom,
3327                },
3328                right: DockData {
3329                    visible: right_visible,
3330                    active_panel: right_active_panel,
3331                    zoom: right_dock_zoom,
3332                },
3333                bottom: DockData {
3334                    visible: bottom_visible,
3335                    active_panel: bottom_active_panel,
3336                    zoom: bottom_dock_zoom,
3337                },
3338            }
3339        }
3340
3341        if let Some(location) = self.location(cx) {
3342            // Load bearing special case:
3343            //  - with_local_workspace() relies on this to not have other stuff open
3344            //    when you open your log
3345            if !location.paths().is_empty() {
3346                let center_group = build_serialized_pane_group(&self.center.root, cx);
3347                let docks = build_serialized_docks(self, cx);
3348
3349                let serialized_workspace = SerializedWorkspace {
3350                    id: self.database_id,
3351                    location,
3352                    center_group,
3353                    bounds: Default::default(),
3354                    display: Default::default(),
3355                    docks,
3356                };
3357
3358                cx.spawn(|_, _| persistence::DB.save_workspace(serialized_workspace))
3359                    .detach();
3360            }
3361        }
3362    }
3363
3364    pub(crate) fn load_workspace(
3365        serialized_workspace: SerializedWorkspace,
3366        paths_to_open: Vec<Option<ProjectPath>>,
3367        cx: &mut ViewContext<Workspace>,
3368    ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
3369        cx.spawn(|workspace, mut cx| async move {
3370            let (project, old_center_pane) = workspace.update(&mut cx, |workspace, _| {
3371                (
3372                    workspace.project().clone(),
3373                    workspace.last_active_center_pane.clone(),
3374                )
3375            })?;
3376
3377            let mut center_group = None;
3378            let mut center_items = None;
3379
3380            // Traverse the splits tree and add to things
3381            if let Some((group, active_pane, items)) = serialized_workspace
3382                .center_group
3383                .deserialize(
3384                    &project,
3385                    serialized_workspace.id,
3386                    workspace.clone(),
3387                    &mut cx,
3388                )
3389                .await
3390            {
3391                center_items = Some(items);
3392                center_group = Some((group, active_pane))
3393            }
3394
3395            let mut items_by_project_path = cx.update(|_, cx| {
3396                center_items
3397                    .unwrap_or_default()
3398                    .into_iter()
3399                    .filter_map(|item| {
3400                        let item = item?;
3401                        let project_path = item.project_path(cx)?;
3402                        Some((project_path, item))
3403                    })
3404                    .collect::<HashMap<_, _>>()
3405            })?;
3406
3407            let opened_items = paths_to_open
3408                .into_iter()
3409                .map(|path_to_open| {
3410                    path_to_open
3411                        .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
3412                })
3413                .collect::<Vec<_>>();
3414
3415            // Remove old panes from workspace panes list
3416            workspace.update(&mut cx, |workspace, cx| {
3417                if let Some((center_group, active_pane)) = center_group {
3418                    workspace.remove_panes(workspace.center.root.clone(), cx);
3419
3420                    // Swap workspace center group
3421                    workspace.center = PaneGroup::with_root(center_group);
3422
3423                    // Change the focus to the workspace first so that we retrigger focus in on the pane.
3424                    // todo!()
3425                    // cx.focus_self();
3426                    // if let Some(active_pane) = active_pane {
3427                    //     cx.focus(&active_pane);
3428                    // } else {
3429                    //     cx.focus(workspace.panes.last().unwrap());
3430                    // }
3431                } else {
3432                    // todo!()
3433                    // let old_center_handle = old_center_pane.and_then(|weak| weak.upgrade());
3434                    // if let Some(old_center_handle) = old_center_handle {
3435                    //     cx.focus(&old_center_handle)
3436                    // } else {
3437                    //     cx.focus_self()
3438                    // }
3439                }
3440
3441                let docks = serialized_workspace.docks;
3442                workspace.left_dock.update(cx, |dock, cx| {
3443                    dock.set_open(docks.left.visible, cx);
3444                    if let Some(active_panel) = docks.left.active_panel {
3445                        if let Some(ix) = dock.panel_index_for_ui_name(&active_panel, cx) {
3446                            dock.activate_panel(ix, cx);
3447                        }
3448                    }
3449                    dock.active_panel()
3450                        .map(|panel| panel.set_zoomed(docks.left.zoom, cx));
3451                    if docks.left.visible && docks.left.zoom {
3452                        // todo!()
3453                        // cx.focus_self()
3454                    }
3455                });
3456                // TODO: I think the bug is that setting zoom or active undoes the bottom zoom or something
3457                workspace.right_dock.update(cx, |dock, cx| {
3458                    dock.set_open(docks.right.visible, cx);
3459                    if let Some(active_panel) = docks.right.active_panel {
3460                        if let Some(ix) = dock.panel_index_for_ui_name(&active_panel, cx) {
3461                            dock.activate_panel(ix, cx);
3462                        }
3463                    }
3464                    dock.active_panel()
3465                        .map(|panel| panel.set_zoomed(docks.right.zoom, cx));
3466
3467                    if docks.right.visible && docks.right.zoom {
3468                        // todo!()
3469                        // cx.focus_self()
3470                    }
3471                });
3472                workspace.bottom_dock.update(cx, |dock, cx| {
3473                    dock.set_open(docks.bottom.visible, cx);
3474                    if let Some(active_panel) = docks.bottom.active_panel {
3475                        if let Some(ix) = dock.panel_index_for_ui_name(&active_panel, cx) {
3476                            dock.activate_panel(ix, cx);
3477                        }
3478                    }
3479
3480                    dock.active_panel()
3481                        .map(|panel| panel.set_zoomed(docks.bottom.zoom, cx));
3482
3483                    if docks.bottom.visible && docks.bottom.zoom {
3484                        // todo!()
3485                        // cx.focus_self()
3486                    }
3487                });
3488
3489                cx.notify();
3490            })?;
3491
3492            // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
3493            workspace.update(&mut cx, |workspace, cx| workspace.serialize_workspace(cx))?;
3494
3495            Ok(opened_items)
3496        })
3497    }
3498
3499    //     #[cfg(any(test, feature = "test-support"))]
3500    //     pub fn test_new(project: ModelHandle<Project>, cx: &mut ViewContext<Self>) -> Self {
3501    //         use node_runtime::FakeNodeRuntime;
3502
3503    //         let client = project.read(cx).client();
3504    //         let user_store = project.read(cx).user_store();
3505
3506    //         let workspace_store = cx.add_model(|cx| WorkspaceStore::new(client.clone(), cx));
3507    //         let app_state = Arc::new(AppState {
3508    //             languages: project.read(cx).languages().clone(),
3509    //             workspace_store,
3510    //             client,
3511    //             user_store,
3512    //             fs: project.read(cx).fs().clone(),
3513    //             build_window_options: |_, _, _| Default::default(),
3514    //             initialize_workspace: |_, _, _, _| Task::ready(Ok(())),
3515    //             node_runtime: FakeNodeRuntime::new(),
3516    //         });
3517    //         Self::new(0, project, app_state, cx)
3518    //     }
3519
3520    //     fn render_dock(&self, position: DockPosition, cx: &WindowContext) -> Option<AnyElement<Self>> {
3521    //         let dock = match position {
3522    //             DockPosition::Left => &self.left_dock,
3523    //             DockPosition::Right => &self.right_dock,
3524    //             DockPosition::Bottom => &self.bottom_dock,
3525    //         };
3526    //         let active_panel = dock.read(cx).visible_panel()?;
3527    //         let element = if Some(active_panel.id()) == self.zoomed.as_ref().map(|zoomed| zoomed.id()) {
3528    //             dock.read(cx).render_placeholder(cx)
3529    //         } else {
3530    //             ChildView::new(dock, cx).into_any()
3531    //         };
3532
3533    //         Some(
3534    //             element
3535    //                 .constrained()
3536    //                 .dynamically(move |constraint, _, cx| match position {
3537    //                     DockPosition::Left | DockPosition::Right => SizeConstraint::new(
3538    //                         Vector2F::new(20., constraint.min.y()),
3539    //                         Vector2F::new(cx.window_size().x() * 0.8, constraint.max.y()),
3540    //                     ),
3541    //                     DockPosition::Bottom => SizeConstraint::new(
3542    //                         Vector2F::new(constraint.min.x(), 20.),
3543    //                         Vector2F::new(constraint.max.x(), cx.window_size().y() * 0.8),
3544    //                     ),
3545    //                 })
3546    //                 .into_any(),
3547    //         )
3548    //     }
3549    // }
3550}
3551
3552fn window_bounds_env_override(cx: &AsyncAppContext) -> Option<WindowBounds> {
3553    let display_origin = cx
3554        .update(|cx| Some(cx.displays().first()?.bounds().origin))
3555        .ok()??;
3556    ZED_WINDOW_POSITION
3557        .zip(*ZED_WINDOW_SIZE)
3558        .map(|(position, size)| {
3559            WindowBounds::Fixed(Bounds {
3560                origin: display_origin + position,
3561                size,
3562            })
3563        })
3564}
3565
3566fn open_items(
3567    serialized_workspace: Option<SerializedWorkspace>,
3568    mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
3569    app_state: Arc<AppState>,
3570    cx: &mut ViewContext<Workspace>,
3571) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> {
3572    let restored_items = serialized_workspace.map(|serialized_workspace| {
3573        Workspace::load_workspace(
3574            serialized_workspace,
3575            project_paths_to_open
3576                .iter()
3577                .map(|(_, project_path)| project_path)
3578                .cloned()
3579                .collect(),
3580            cx,
3581        )
3582    });
3583
3584    cx.spawn(|workspace, mut cx| async move {
3585        let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
3586
3587        if let Some(restored_items) = restored_items {
3588            let restored_items = restored_items.await?;
3589
3590            let restored_project_paths = restored_items
3591                .iter()
3592                .filter_map(|item| {
3593                    cx.update(|_, cx| item.as_ref()?.project_path(cx))
3594                        .ok()
3595                        .flatten()
3596                })
3597                .collect::<HashSet<_>>();
3598
3599            for restored_item in restored_items {
3600                opened_items.push(restored_item.map(Ok));
3601            }
3602
3603            project_paths_to_open
3604                .iter_mut()
3605                .for_each(|(_, project_path)| {
3606                    if let Some(project_path_to_open) = project_path {
3607                        if restored_project_paths.contains(project_path_to_open) {
3608                            *project_path = None;
3609                        }
3610                    }
3611                });
3612        } else {
3613            for _ in 0..project_paths_to_open.len() {
3614                opened_items.push(None);
3615            }
3616        }
3617        assert!(opened_items.len() == project_paths_to_open.len());
3618
3619        let tasks =
3620            project_paths_to_open
3621                .into_iter()
3622                .enumerate()
3623                .map(|(i, (abs_path, project_path))| {
3624                    let workspace = workspace.clone();
3625                    cx.spawn(|mut cx| {
3626                        let fs = app_state.fs.clone();
3627                        async move {
3628                            let file_project_path = project_path?;
3629                            if fs.is_file(&abs_path).await {
3630                                Some((
3631                                    i,
3632                                    workspace
3633                                        .update(&mut cx, |workspace, cx| {
3634                                            workspace.open_path(file_project_path, None, true, cx)
3635                                        })
3636                                        .log_err()?
3637                                        .await,
3638                                ))
3639                            } else {
3640                                None
3641                            }
3642                        }
3643                    })
3644                });
3645
3646        let tasks = tasks.collect::<Vec<_>>();
3647
3648        let tasks = futures::future::join_all(tasks.into_iter());
3649        for maybe_opened_path in tasks.await.into_iter() {
3650            if let Some((i, path_open_result)) = maybe_opened_path {
3651                opened_items[i] = Some(path_open_result);
3652            }
3653        }
3654
3655        Ok(opened_items)
3656    })
3657}
3658
3659// fn notify_of_new_dock(workspace: &WeakView<Workspace>, cx: &mut AsyncAppContext) {
3660//     const NEW_PANEL_BLOG_POST: &str = "https://zed.dev/blog/new-panel-system";
3661//     const NEW_DOCK_HINT_KEY: &str = "show_new_dock_key";
3662//     const MESSAGE_ID: usize = 2;
3663
3664//     if workspace
3665//         .read_with(cx, |workspace, cx| {
3666//             workspace.has_shown_notification_once::<MessageNotification>(MESSAGE_ID, cx)
3667//         })
3668//         .unwrap_or(false)
3669//     {
3670//         return;
3671//     }
3672
3673//     if db::kvp::KEY_VALUE_STORE
3674//         .read_kvp(NEW_DOCK_HINT_KEY)
3675//         .ok()
3676//         .flatten()
3677//         .is_some()
3678//     {
3679//         if !workspace
3680//             .read_with(cx, |workspace, cx| {
3681//                 workspace.has_shown_notification_once::<MessageNotification>(MESSAGE_ID, cx)
3682//             })
3683//             .unwrap_or(false)
3684//         {
3685//             cx.update(|cx| {
3686//                 cx.update_global::<NotificationTracker, _, _>(|tracker, _| {
3687//                     let entry = tracker
3688//                         .entry(TypeId::of::<MessageNotification>())
3689//                         .or_default();
3690//                     if !entry.contains(&MESSAGE_ID) {
3691//                         entry.push(MESSAGE_ID);
3692//                     }
3693//                 });
3694//             });
3695//         }
3696
3697//         return;
3698//     }
3699
3700//     cx.spawn(|_| async move {
3701//         db::kvp::KEY_VALUE_STORE
3702//             .write_kvp(NEW_DOCK_HINT_KEY.to_string(), "seen".to_string())
3703//             .await
3704//             .ok();
3705//     })
3706//     .detach();
3707
3708//     workspace
3709//         .update(cx, |workspace, cx| {
3710//             workspace.show_notification_once(2, cx, |cx| {
3711//                 cx.build_view(|_| {
3712//                     MessageNotification::new_element(|text, _| {
3713//                         Text::new(
3714//                             "Looking for the dock? Try ctrl-`!\nshift-escape now zooms your pane.",
3715//                             text,
3716//                         )
3717//                         .with_custom_runs(vec![26..32, 34..46], |_, bounds, cx| {
3718//                             let code_span_background_color = settings::get::<ThemeSettings>(cx)
3719//                                 .theme
3720//                                 .editor
3721//                                 .document_highlight_read_background;
3722
3723//                             cx.scene().push_quad(gpui::Quad {
3724//                                 bounds,
3725//                                 background: Some(code_span_background_color),
3726//                                 border: Default::default(),
3727//                                 corner_radii: (2.0).into(),
3728//                             })
3729//                         })
3730//                         .into_any()
3731//                     })
3732//                     .with_click_message("Read more about the new panel system")
3733//                     .on_click(|cx| cx.platform().open_url(NEW_PANEL_BLOG_POST))
3734//                 })
3735//             })
3736//         })
3737//         .ok();
3738
3739fn notify_if_database_failed(_workspace: WindowHandle<Workspace>, _cx: &mut AsyncAppContext) {
3740    const REPORT_ISSUE_URL: &str ="https://github.com/zed-industries/community/issues/new?assignees=&labels=defect%2Ctriage&template=2_bug_report.yml";
3741
3742    // todo!()
3743    // workspace
3744    //     .update(cx, |workspace, cx| {
3745    //         if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
3746    //             workspace.show_notification_once(0, cx, |cx| {
3747    //                 cx.build_view(|_| {
3748    //                     MessageNotification::new("Failed to load the database file.")
3749    //                         .with_click_message("Click to let us know about this error")
3750    //                         .on_click(|cx| cx.platform().open_url(REPORT_ISSUE_URL))
3751    //                 })
3752    //             });
3753    //         }
3754    //     })
3755    //     .log_err();
3756}
3757
3758impl EventEmitter for Workspace {
3759    type Event = Event;
3760}
3761
3762impl Render for Workspace {
3763    type Element = Div<Self>;
3764
3765    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
3766        div()
3767            .relative()
3768            .size_full()
3769            .flex()
3770            .flex_col()
3771            .font("Zed Sans")
3772            .gap_0()
3773            .justify_start()
3774            .items_start()
3775            .text_color(cx.theme().colors().text)
3776            .bg(cx.theme().colors().background)
3777            .child(self.render_titlebar(cx))
3778            .child(
3779                div()
3780                    .flex_1()
3781                    .w_full()
3782                    .flex()
3783                    .flex_row()
3784                    .overflow_hidden()
3785                    .border_t()
3786                    .border_b()
3787                    .border_color(cx.theme().colors().border)
3788                    // .children(
3789                    //     Some(
3790                    //         Panel::new("project-panel-outer", cx)
3791                    //             .side(PanelSide::Left)
3792                    //             .child(ProjectPanel::new("project-panel-inner")),
3793                    //     )
3794                    //     .filter(|_| self.is_project_panel_open()),
3795                    // )
3796                    // .children(
3797                    //     Some(
3798                    //         Panel::new("collab-panel-outer", cx)
3799                    //             .child(CollabPanel::new("collab-panel-inner"))
3800                    //             .side(PanelSide::Left),
3801                    //     )
3802                    //     .filter(|_| self.is_collab_panel_open()),
3803                    // )
3804                    // .child(NotificationToast::new(
3805                    //     "maxbrunsfeld has requested to add you as a contact.".into(),
3806                    // ))
3807                    .child(
3808                        div().flex().flex_col().flex_1().h_full().child(
3809                            div().flex().flex_1().child(self.center.render(
3810                                &self.project,
3811                                &self.follower_states,
3812                                self.active_call(),
3813                                &self.active_pane,
3814                                self.zoomed.as_ref(),
3815                                &self.app_state,
3816                                cx,
3817                            )),
3818                        ), // .children(
3819                           //     Some(
3820                           //         Panel::new("terminal-panel", cx)
3821                           //             .child(Terminal::new())
3822                           //             .allowed_sides(PanelAllowedSides::BottomOnly)
3823                           //             .side(PanelSide::Bottom),
3824                           //     )
3825                           //     .filter(|_| self.is_terminal_open()),
3826                           // ),
3827                    ), // .children(
3828                       //     Some(
3829                       //         Panel::new("chat-panel-outer", cx)
3830                       //             .side(PanelSide::Right)
3831                       //             .child(ChatPanel::new("chat-panel-inner").messages(vec![
3832                       //                 ChatMessage::new(
3833                       //                     "osiewicz".to_string(),
3834                       //                     "is this thing on?".to_string(),
3835                       //                     DateTime::parse_from_rfc3339("2023-09-27T15:40:52.707Z")
3836                       //                         .unwrap()
3837                       //                         .naive_local(),
3838                       //                 ),
3839                       //                 ChatMessage::new(
3840                       //                     "maxdeviant".to_string(),
3841                       //                     "Reading you loud and clear!".to_string(),
3842                       //                     DateTime::parse_from_rfc3339("2023-09-28T15:40:52.707Z")
3843                       //                         .unwrap()
3844                       //                         .naive_local(),
3845                       //                 ),
3846                       //             ])),
3847                       //     )
3848                       //     .filter(|_| self.is_chat_panel_open()),
3849                       // )
3850                       // .children(
3851                       //     Some(
3852                       //         Panel::new("notifications-panel-outer", cx)
3853                       //             .side(PanelSide::Right)
3854                       //             .child(NotificationsPanel::new("notifications-panel-inner")),
3855                       //     )
3856                       //     .filter(|_| self.is_notifications_panel_open()),
3857                       // )
3858                       // .children(
3859                       //     Some(
3860                       //         Panel::new("assistant-panel-outer", cx)
3861                       //             .child(AssistantPanel::new("assistant-panel-inner")),
3862                       //     )
3863                       //     .filter(|_| self.is_assistant_panel_open()),
3864                       // ),
3865            )
3866            .child(self.status_bar.clone())
3867            // .when(self.debug.show_toast, |this| {
3868            //     this.child(Toast::new(ToastOrigin::Bottom).child(Label::new("A toast")))
3869            // })
3870            // .children(
3871            //     Some(
3872            //         div()
3873            //             .absolute()
3874            //             .top(px(50.))
3875            //             .left(px(640.))
3876            //             .z_index(8)
3877            //             .child(LanguageSelector::new("language-selector")),
3878            //     )
3879            //     .filter(|_| self.is_language_selector_open()),
3880            // )
3881            .z_index(8)
3882            // Debug
3883            .child(
3884                div()
3885                    .flex()
3886                    .flex_col()
3887                    .z_index(9)
3888                    .absolute()
3889                    .top_20()
3890                    .left_1_4()
3891                    .w_40()
3892                    .gap_2(), // .when(self.show_debug, |this| {
3893                              //     this.child(Button::<Workspace>::new("Toggle User Settings").on_click(
3894                              //         Arc::new(|workspace, cx| workspace.debug_toggle_user_settings(cx)),
3895                              //     ))
3896                              //     .child(
3897                              //         Button::<Workspace>::new("Toggle Toasts").on_click(Arc::new(
3898                              //             |workspace, cx| workspace.debug_toggle_toast(cx),
3899                              //         )),
3900                              //     )
3901                              //     .child(
3902                              //         Button::<Workspace>::new("Toggle Livestream").on_click(Arc::new(
3903                              //             |workspace, cx| workspace.debug_toggle_livestream(cx),
3904                              //         )),
3905                              //     )
3906                              // })
3907                              // .child(
3908                              //     Button::<Workspace>::new("Toggle Debug")
3909                              //         .on_click(Arc::new(|workspace, cx| workspace.toggle_debug(cx))),
3910                              // ),
3911            )
3912    }
3913}
3914
3915// todo!()
3916// impl Entity for Workspace {
3917//     type Event = Event;
3918
3919//     fn release(&mut self, cx: &mut AppContext) {
3920//         self.app_state.workspace_store.update(cx, |store, _| {
3921//             store.workspaces.remove(&self.weak_self);
3922//         })
3923//     }
3924// }
3925
3926// impl View for Workspace {
3927//     fn ui_name() -> &'static str {
3928//         "Workspace"
3929//     }
3930
3931//     fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
3932//         let theme = theme::current(cx).clone();
3933//         Stack::new()
3934//             .with_child(
3935//                 Flex::column()
3936//                     .with_child(self.render_titlebar(&theme, cx))
3937//                     .with_child(
3938//                         Stack::new()
3939//                             .with_child({
3940//                                 let project = self.project.clone();
3941//                                 Flex::row()
3942//                                     .with_children(self.render_dock(DockPosition::Left, cx))
3943//                                     .with_child(
3944//                                         Flex::column()
3945//                                             .with_child(
3946//                                                 FlexItem::new(
3947//                                                     self.center.render(
3948//                                                         &project,
3949//                                                         &theme,
3950//                                                         &self.follower_states,
3951//                                                         self.active_call(),
3952//                                                         self.active_pane(),
3953//                                                         self.zoomed
3954//                                                             .as_ref()
3955//                                                             .and_then(|zoomed| zoomed.upgrade(cx))
3956//                                                             .as_ref(),
3957//                                                         &self.app_state,
3958//                                                         cx,
3959//                                                     ),
3960//                                                 )
3961//                                                 .flex(1., true),
3962//                                             )
3963//                                             .with_children(
3964//                                                 self.render_dock(DockPosition::Bottom, cx),
3965//                                             )
3966//                                             .flex(1., true),
3967//                                     )
3968//                                     .with_children(self.render_dock(DockPosition::Right, cx))
3969//                             })
3970//                             .with_child(Overlay::new(
3971//                                 Stack::new()
3972//                                     .with_children(self.zoomed.as_ref().and_then(|zoomed| {
3973//                                         enum ZoomBackground {}
3974//                                         let zoomed = zoomed.upgrade(cx)?;
3975
3976//                                         let mut foreground_style =
3977//                                             theme.workspace.zoomed_pane_foreground;
3978//                                         if let Some(zoomed_dock_position) = self.zoomed_position {
3979//                                             foreground_style =
3980//                                                 theme.workspace.zoomed_panel_foreground;
3981//                                             let margin = foreground_style.margin.top;
3982//                                             let border = foreground_style.border.top;
3983
3984//                                             // Only include a margin and border on the opposite side.
3985//                                             foreground_style.margin.top = 0.;
3986//                                             foreground_style.margin.left = 0.;
3987//                                             foreground_style.margin.bottom = 0.;
3988//                                             foreground_style.margin.right = 0.;
3989//                                             foreground_style.border.top = false;
3990//                                             foreground_style.border.left = false;
3991//                                             foreground_style.border.bottom = false;
3992//                                             foreground_style.border.right = false;
3993//                                             match zoomed_dock_position {
3994//                                                 DockPosition::Left => {
3995//                                                     foreground_style.margin.right = margin;
3996//                                                     foreground_style.border.right = border;
3997//                                                 }
3998//                                                 DockPosition::Right => {
3999//                                                     foreground_style.margin.left = margin;
4000//                                                     foreground_style.border.left = border;
4001//                                                 }
4002//                                                 DockPosition::Bottom => {
4003//                                                     foreground_style.margin.top = margin;
4004//                                                     foreground_style.border.top = border;
4005//                                                 }
4006//                                             }
4007//                                         }
4008
4009//                                         Some(
4010//                                             ChildView::new(&zoomed, cx)
4011//                                                 .contained()
4012//                                                 .with_style(foreground_style)
4013//                                                 .aligned()
4014//                                                 .contained()
4015//                                                 .with_style(theme.workspace.zoomed_background)
4016//                                                 .mouse::<ZoomBackground>(0)
4017//                                                 .capture_all()
4018//                                                 .on_down(
4019//                                                     MouseButton::Left,
4020//                                                     |_, this: &mut Self, cx| {
4021//                                                         this.zoom_out(cx);
4022//                                                     },
4023//                                                 ),
4024//                                         )
4025//                                     }))
4026//                                     .with_children(self.modal.as_ref().map(|modal| {
4027//                                         // Prevent clicks within the modal from falling
4028//                                         // through to the rest of the workspace.
4029//                                         enum ModalBackground {}
4030//                                         MouseEventHandler::new::<ModalBackground, _>(
4031//                                             0,
4032//                                             cx,
4033//                                             |_, cx| ChildView::new(modal.view.as_any(), cx),
4034//                                         )
4035//                                         .on_click(MouseButton::Left, |_, _, _| {})
4036//                                         .contained()
4037//                                         .with_style(theme.workspace.modal)
4038//                                         .aligned()
4039//                                         .top()
4040//                                     }))
4041//                                     .with_children(self.render_notifications(&theme.workspace, cx)),
4042//                             ))
4043//                             .provide_resize_bounds::<WorkspaceBounds>()
4044//                             .flex(1.0, true),
4045//                     )
4046//                     .with_child(ChildView::new(&self.status_bar, cx))
4047//                     .contained()
4048//                     .with_background_color(theme.workspace.background),
4049//             )
4050//             .with_children(DragAndDrop::render(cx))
4051//             .with_children(self.render_disconnected_overlay(cx))
4052//             .into_any_named("workspace")
4053//     }
4054
4055//     fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
4056//         if cx.is_self_focused() {
4057//             cx.focus(&self.active_pane);
4058//         }
4059//     }
4060
4061//     fn modifiers_changed(&mut self, e: &ModifiersChangedEvent, cx: &mut ViewContext<Self>) -> bool {
4062//         DragAndDrop::<Workspace>::update_modifiers(e.modifiers, cx)
4063//     }
4064// }
4065
4066impl WorkspaceStore {
4067    pub fn new(client: Arc<Client>, _cx: &mut ModelContext<Self>) -> Self {
4068        Self {
4069            workspaces: Default::default(),
4070            followers: Default::default(),
4071            _subscriptions: vec![],
4072            //     client.add_request_handler(cx.weak_model(), Self::handle_follow),
4073            //     client.add_message_handler(cx.weak_model(), Self::handle_unfollow),
4074            //     client.add_message_handler(cx.weak_model(), Self::handle_update_followers),
4075            // ],
4076            client,
4077        }
4078    }
4079
4080    pub fn update_followers(
4081        &self,
4082        project_id: Option<u64>,
4083        update: proto::update_followers::Variant,
4084        cx: &AppContext,
4085    ) -> Option<()> {
4086        if !cx.has_global::<Model<ActiveCall>>() {
4087            return None;
4088        }
4089
4090        let room_id = ActiveCall::global(cx).read(cx).room()?.read(cx).id();
4091        let follower_ids: Vec<_> = self
4092            .followers
4093            .iter()
4094            .filter_map(|follower| {
4095                if follower.project_id == project_id || project_id.is_none() {
4096                    Some(follower.peer_id.into())
4097                } else {
4098                    None
4099                }
4100            })
4101            .collect();
4102        if follower_ids.is_empty() {
4103            return None;
4104        }
4105        self.client
4106            .send(proto::UpdateFollowers {
4107                room_id,
4108                project_id,
4109                follower_ids,
4110                variant: Some(update),
4111            })
4112            .log_err()
4113    }
4114
4115    pub async fn handle_follow(
4116        this: Model<Self>,
4117        envelope: TypedEnvelope<proto::Follow>,
4118        _: Arc<Client>,
4119        mut cx: AsyncAppContext,
4120    ) -> Result<proto::FollowResponse> {
4121        this.update(&mut cx, |this, cx| {
4122            let follower = Follower {
4123                project_id: envelope.payload.project_id,
4124                peer_id: envelope.original_sender_id()?,
4125            };
4126            let active_project = ActiveCall::global(cx).read(cx).location().cloned();
4127
4128            let mut response = proto::FollowResponse::default();
4129            for workspace in &this.workspaces {
4130                workspace
4131                    .update(cx, |workspace, cx| {
4132                        let handler_response = workspace.handle_follow(follower.project_id, cx);
4133                        if response.views.is_empty() {
4134                            response.views = handler_response.views;
4135                        } else {
4136                            response.views.extend_from_slice(&handler_response.views);
4137                        }
4138
4139                        if let Some(active_view_id) = handler_response.active_view_id.clone() {
4140                            if response.active_view_id.is_none()
4141                                || Some(workspace.project.downgrade()) == active_project
4142                            {
4143                                response.active_view_id = Some(active_view_id);
4144                            }
4145                        }
4146                    })
4147                    .ok();
4148            }
4149
4150            if let Err(ix) = this.followers.binary_search(&follower) {
4151                this.followers.insert(ix, follower);
4152            }
4153
4154            Ok(response)
4155        })?
4156    }
4157
4158    async fn handle_unfollow(
4159        model: Model<Self>,
4160        envelope: TypedEnvelope<proto::Unfollow>,
4161        _: Arc<Client>,
4162        mut cx: AsyncAppContext,
4163    ) -> Result<()> {
4164        model.update(&mut cx, |this, _| {
4165            let follower = Follower {
4166                project_id: envelope.payload.project_id,
4167                peer_id: envelope.original_sender_id()?,
4168            };
4169            if let Ok(ix) = this.followers.binary_search(&follower) {
4170                this.followers.remove(ix);
4171            }
4172            Ok(())
4173        })?
4174    }
4175
4176    async fn handle_update_followers(
4177        _this: Model<Self>,
4178        _envelope: TypedEnvelope<proto::UpdateFollowers>,
4179        _: Arc<Client>,
4180        mut _cx: AsyncWindowContext,
4181    ) -> Result<()> {
4182        // let leader_id = envelope.original_sender_id()?;
4183        // let update = envelope.payload;
4184
4185        // this.update(&mut cx, |this, cx| {
4186        //     for workspace in &this.workspaces {
4187        //         let Some(workspace) = workspace.upgrade() else {
4188        //             continue;
4189        //         };
4190        //         workspace.update(cx, |workspace, cx| {
4191        //             let project_id = workspace.project.read(cx).remote_id();
4192        //             if update.project_id != project_id && update.project_id.is_some() {
4193        //                 return;
4194        //             }
4195        //             workspace.handle_update_followers(leader_id, update.clone(), cx);
4196        //         });
4197        //     }
4198        //     Ok(())
4199        // })?
4200        todo!()
4201    }
4202}
4203
4204// impl Entity for WorkspaceStore {
4205//     type Event = ();
4206// }
4207
4208impl ViewId {
4209    pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
4210        Ok(Self {
4211            creator: message
4212                .creator
4213                .ok_or_else(|| anyhow!("creator is missing"))?,
4214            id: message.id,
4215        })
4216    }
4217
4218    pub(crate) fn to_proto(&self) -> proto::ViewId {
4219        proto::ViewId {
4220            creator: Some(self.creator),
4221            id: self.id,
4222        }
4223    }
4224}
4225
4226// pub trait WorkspaceHandle {
4227//     fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
4228// }
4229
4230// impl WorkspaceHandle for View<Workspace> {
4231//     fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
4232//         self.read(cx)
4233//             .worktrees(cx)
4234//             .flat_map(|worktree| {
4235//                 let worktree_id = worktree.read(cx).id();
4236//                 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
4237//                     worktree_id,
4238//                     path: f.path.clone(),
4239//                 })
4240//             })
4241//             .collect::<Vec<_>>()
4242//     }
4243// }
4244
4245// impl std::fmt::Debug for OpenPaths {
4246//     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4247//         f.debug_struct("OpenPaths")
4248//             .field("paths", &self.paths)
4249//             .finish()
4250//     }
4251// }
4252
4253// pub struct WorkspaceCreated(pub WeakView<Workspace>);
4254
4255pub fn activate_workspace_for_project(
4256    cx: &mut AppContext,
4257    predicate: impl Fn(&Project, &AppContext) -> bool + Send + 'static,
4258) -> Option<WindowHandle<Workspace>> {
4259    for window in cx.windows() {
4260        let Some(workspace) = window.downcast::<Workspace>() else {
4261            continue;
4262        };
4263
4264        let predicate = workspace
4265            .update(cx, |workspace, cx| {
4266                let project = workspace.project.read(cx);
4267                if predicate(project, cx) {
4268                    cx.activate_window();
4269                    true
4270                } else {
4271                    false
4272                }
4273            })
4274            .log_err()
4275            .unwrap_or(false);
4276
4277        if predicate {
4278            return Some(workspace);
4279        }
4280    }
4281
4282    None
4283}
4284
4285pub async fn last_opened_workspace_paths() -> Option<WorkspaceLocation> {
4286    DB.last_workspace().await.log_err().flatten()
4287}
4288
4289// async fn join_channel_internal(
4290//     channel_id: u64,
4291//     app_state: &Arc<AppState>,
4292//     requesting_window: Option<WindowHandle<Workspace>>,
4293//     active_call: &ModelHandle<ActiveCall>,
4294//     cx: &mut AsyncAppContext,
4295// ) -> Result<bool> {
4296//     let (should_prompt, open_room) = active_call.read_with(cx, |active_call, cx| {
4297//         let Some(room) = active_call.room().map(|room| room.read(cx)) else {
4298//             return (false, None);
4299//         };
4300
4301//         let already_in_channel = room.channel_id() == Some(channel_id);
4302//         let should_prompt = room.is_sharing_project()
4303//             && room.remote_participants().len() > 0
4304//             && !already_in_channel;
4305//         let open_room = if already_in_channel {
4306//             active_call.room().cloned()
4307//         } else {
4308//             None
4309//         };
4310//         (should_prompt, open_room)
4311//     });
4312
4313//     if let Some(room) = open_room {
4314//         let task = room.update(cx, |room, cx| {
4315//             if let Some((project, host)) = room.most_active_project(cx) {
4316//                 return Some(join_remote_project(project, host, app_state.clone(), cx));
4317//             }
4318
4319//             None
4320//         });
4321//         if let Some(task) = task {
4322//             task.await?;
4323//         }
4324//         return anyhow::Ok(true);
4325//     }
4326
4327//     if should_prompt {
4328//         if let Some(workspace) = requesting_window {
4329//             if let Some(window) = workspace.update(cx, |cx| cx.window()) {
4330//                 let answer = window.prompt(
4331//                     PromptLevel::Warning,
4332//                     "Leaving this call will unshare your current project.\nDo you want to switch channels?",
4333//                     &["Yes, Join Channel", "Cancel"],
4334//                     cx,
4335//                 );
4336
4337//                 if let Some(mut answer) = answer {
4338//                     if answer.next().await == Some(1) {
4339//                         return Ok(false);
4340//                     }
4341//                 }
4342//             } else {
4343//                 return Ok(false); // unreachable!() hopefully
4344//             }
4345//         } else {
4346//             return Ok(false); // unreachable!() hopefully
4347//         }
4348//     }
4349
4350//     let client = cx.read(|cx| active_call.read(cx).client());
4351
4352//     let mut client_status = client.status();
4353
4354//     // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
4355//     'outer: loop {
4356//         let Some(status) = client_status.recv().await else {
4357//             return Err(anyhow!("error connecting"));
4358//         };
4359
4360//         match status {
4361//             Status::Connecting
4362//             | Status::Authenticating
4363//             | Status::Reconnecting
4364//             | Status::Reauthenticating => continue,
4365//             Status::Connected { .. } => break 'outer,
4366//             Status::SignedOut => return Err(anyhow!("not signed in")),
4367//             Status::UpgradeRequired => return Err(anyhow!("zed is out of date")),
4368//             Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
4369//                 return Err(anyhow!("zed is offline"))
4370//             }
4371//         }
4372//     }
4373
4374//     let room = active_call
4375//         .update(cx, |active_call, cx| {
4376//             active_call.join_channel(channel_id, cx)
4377//         })
4378//         .await?;
4379
4380//     room.update(cx, |room, _| room.room_update_completed())
4381//         .await;
4382
4383//     let task = room.update(cx, |room, cx| {
4384//         if let Some((project, host)) = room.most_active_project(cx) {
4385//             return Some(join_remote_project(project, host, app_state.clone(), cx));
4386//         }
4387
4388//         None
4389//     });
4390//     if let Some(task) = task {
4391//         task.await?;
4392//         return anyhow::Ok(true);
4393//     }
4394//     anyhow::Ok(false)
4395// }
4396
4397// pub fn join_channel(
4398//     channel_id: u64,
4399//     app_state: Arc<AppState>,
4400//     requesting_window: Option<WindowHandle<Workspace>>,
4401//     cx: &mut AppContext,
4402// ) -> Task<Result<()>> {
4403//     let active_call = ActiveCall::global(cx);
4404//     cx.spawn(|mut cx| async move {
4405//         let result = join_channel_internal(
4406//             channel_id,
4407//             &app_state,
4408//             requesting_window,
4409//             &active_call,
4410//             &mut cx,
4411//         )
4412//         .await;
4413
4414//         // join channel succeeded, and opened a window
4415//         if matches!(result, Ok(true)) {
4416//             return anyhow::Ok(());
4417//         }
4418
4419//         if requesting_window.is_some() {
4420//             return anyhow::Ok(());
4421//         }
4422
4423//         // find an existing workspace to focus and show call controls
4424//         let mut active_window = activate_any_workspace_window(&mut cx);
4425//         if active_window.is_none() {
4426//             // no open workspaces, make one to show the error in (blergh)
4427//             cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), requesting_window, cx))
4428//                 .await;
4429//         }
4430
4431//         active_window = activate_any_workspace_window(&mut cx);
4432//         if active_window.is_none() {
4433//             return result.map(|_| ()); // unreachable!() assuming new_local always opens a window
4434//         }
4435
4436//         if let Err(err) = result {
4437//             let prompt = active_window.unwrap().prompt(
4438//                 PromptLevel::Critical,
4439//                 &format!("Failed to join channel: {}", err),
4440//                 &["Ok"],
4441//                 &mut cx,
4442//             );
4443//             if let Some(mut prompt) = prompt {
4444//                 prompt.next().await;
4445//             } else {
4446//                 return Err(err);
4447//             }
4448//         }
4449
4450//         // return ok, we showed the error to the user.
4451//         return anyhow::Ok(());
4452//     })
4453// }
4454
4455// pub fn activate_any_workspace_window(cx: &mut AsyncAppContext) -> Option<AnyWindowHandle> {
4456//     for window in cx.windows() {
4457//         let found = window.update(cx, |cx| {
4458//             let is_workspace = cx.root_view().clone().downcast::<Workspace>().is_some();
4459//             if is_workspace {
4460//                 cx.activate_window();
4461//             }
4462//             is_workspace
4463//         });
4464//         if found == Some(true) {
4465//             return Some(window);
4466//         }
4467//     }
4468//     None
4469// }
4470
4471#[allow(clippy::type_complexity)]
4472pub fn open_paths(
4473    abs_paths: &[PathBuf],
4474    app_state: &Arc<AppState>,
4475    requesting_window: Option<WindowHandle<Workspace>>,
4476    cx: &mut AppContext,
4477) -> Task<
4478    anyhow::Result<(
4479        WindowHandle<Workspace>,
4480        Vec<Option<Result<Box<dyn ItemHandle>, anyhow::Error>>>,
4481    )>,
4482> {
4483    let app_state = app_state.clone();
4484    let abs_paths = abs_paths.to_vec();
4485    // Open paths in existing workspace if possible
4486    let existing = activate_workspace_for_project(cx, {
4487        let abs_paths = abs_paths.clone();
4488        move |project, cx| project.contains_paths(&abs_paths, cx)
4489    });
4490    cx.spawn(move |mut cx| async move {
4491        if let Some(existing) = existing {
4492            // // Ok((
4493            //     existing.clone(),
4494            //     cx.update_window_root(&existing, |workspace, cx| {
4495            //         workspace.open_paths(abs_paths, true, cx)
4496            //     })?
4497            //     .await,
4498            // ))
4499            todo!()
4500        } else {
4501            cx.update(move |cx| {
4502                Workspace::new_local(abs_paths, app_state.clone(), requesting_window, cx)
4503            })?
4504            .await
4505        }
4506    })
4507}
4508
4509pub fn open_new(
4510    app_state: &Arc<AppState>,
4511    cx: &mut AppContext,
4512    init: impl FnOnce(&mut Workspace, &mut ViewContext<Workspace>) + 'static + Send,
4513) -> Task<()> {
4514    let task = Workspace::new_local(Vec::new(), app_state.clone(), None, cx);
4515    cx.spawn(|mut cx| async move {
4516        if let Some((workspace, opened_paths)) = task.await.log_err() {
4517            workspace
4518                .update(&mut cx, |workspace, cx| {
4519                    if opened_paths.is_empty() {
4520                        init(workspace, cx)
4521                    }
4522                })
4523                .log_err();
4524        }
4525    })
4526}
4527
4528// pub fn create_and_open_local_file(
4529//     path: &'static Path,
4530//     cx: &mut ViewContext<Workspace>,
4531//     default_content: impl 'static + Send + FnOnce() -> Rope,
4532// ) -> Task<Result<Box<dyn ItemHandle>>> {
4533//     cx.spawn(|workspace, mut cx| async move {
4534//         let fs = workspace.read_with(&cx, |workspace, _| workspace.app_state().fs.clone())?;
4535//         if !fs.is_file(path).await {
4536//             fs.create_file(path, Default::default()).await?;
4537//             fs.save(path, &default_content(), Default::default())
4538//                 .await?;
4539//         }
4540
4541//         let mut items = workspace
4542//             .update(&mut cx, |workspace, cx| {
4543//                 workspace.with_local_workspace(cx, |workspace, cx| {
4544//                     workspace.open_paths(vec![path.to_path_buf()], false, cx)
4545//                 })
4546//             })?
4547//             .await?
4548//             .await;
4549
4550//         let item = items.pop().flatten();
4551//         item.ok_or_else(|| anyhow!("path {path:?} is not a file"))?
4552//     })
4553// }
4554
4555// pub fn join_remote_project(
4556//     project_id: u64,
4557//     follow_user_id: u64,
4558//     app_state: Arc<AppState>,
4559//     cx: &mut AppContext,
4560// ) -> Task<Result<()>> {
4561//     cx.spawn(|mut cx| async move {
4562//         let windows = cx.windows();
4563//         let existing_workspace = windows.into_iter().find_map(|window| {
4564//             window.downcast::<Workspace>().and_then(|window| {
4565//                 window
4566//                     .read_root_with(&cx, |workspace, cx| {
4567//                         if workspace.project().read(cx).remote_id() == Some(project_id) {
4568//                             Some(cx.handle().downgrade())
4569//                         } else {
4570//                             None
4571//                         }
4572//                     })
4573//                     .unwrap_or(None)
4574//             })
4575//         });
4576
4577//         let workspace = if let Some(existing_workspace) = existing_workspace {
4578//             existing_workspace
4579//         } else {
4580//             let active_call = cx.read(ActiveCall::global);
4581//             let room = active_call
4582//                 .read_with(&cx, |call, _| call.room().cloned())
4583//                 .ok_or_else(|| anyhow!("not in a call"))?;
4584//             let project = room
4585//                 .update(&mut cx, |room, cx| {
4586//                     room.join_project(
4587//                         project_id,
4588//                         app_state.languages.clone(),
4589//                         app_state.fs.clone(),
4590//                         cx,
4591//                     )
4592//                 })
4593//                 .await?;
4594
4595//             let window_bounds_override = window_bounds_env_override(&cx);
4596//             let window = cx.add_window(
4597//                 (app_state.build_window_options)(
4598//                     window_bounds_override,
4599//                     None,
4600//                     cx.platform().as_ref(),
4601//                 ),
4602//                 |cx| Workspace::new(0, project, app_state.clone(), cx),
4603//             );
4604//             let workspace = window.root(&cx).unwrap();
4605//             (app_state.initialize_workspace)(
4606//                 workspace.downgrade(),
4607//                 false,
4608//                 app_state.clone(),
4609//                 cx.clone(),
4610//             )
4611//             .await
4612//             .log_err();
4613
4614//             workspace.downgrade()
4615//         };
4616
4617//         workspace.window().activate(&mut cx);
4618//         cx.platform().activate(true);
4619
4620//         workspace.update(&mut cx, |workspace, cx| {
4621//             if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
4622//                 let follow_peer_id = room
4623//                     .read(cx)
4624//                     .remote_participants()
4625//                     .iter()
4626//                     .find(|(_, participant)| participant.user.id == follow_user_id)
4627//                     .map(|(_, p)| p.peer_id)
4628//                     .or_else(|| {
4629//                         // If we couldn't follow the given user, follow the host instead.
4630//                         let collaborator = workspace
4631//                             .project()
4632//                             .read(cx)
4633//                             .collaborators()
4634//                             .values()
4635//                             .find(|collaborator| collaborator.replica_id == 0)?;
4636//                         Some(collaborator.peer_id)
4637//                     });
4638
4639//                 if let Some(follow_peer_id) = follow_peer_id {
4640//                     workspace
4641//                         .follow(follow_peer_id, cx)
4642//                         .map(|follow| follow.detach_and_log_err(cx));
4643//                 }
4644//             }
4645//         })?;
4646
4647//         anyhow::Ok(())
4648//     })
4649// }
4650
4651// pub fn restart(_: &Restart, cx: &mut AppContext) {
4652//     let should_confirm = settings::get::<WorkspaceSettings>(cx).confirm_quit;
4653//     cx.spawn(|mut cx| async move {
4654//         let mut workspace_windows = cx
4655//             .windows()
4656//             .into_iter()
4657//             .filter_map(|window| window.downcast::<Workspace>())
4658//             .collect::<Vec<_>>();
4659
4660//         // If multiple windows have unsaved changes, and need a save prompt,
4661//         // prompt in the active window before switching to a different window.
4662//         workspace_windows.sort_by_key(|window| window.is_active(&cx) == Some(false));
4663
4664//         if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
4665//             let answer = window.prompt(
4666//                 PromptLevel::Info,
4667//                 "Are you sure you want to restart?",
4668//                 &["Restart", "Cancel"],
4669//                 &mut cx,
4670//             );
4671
4672//             if let Some(mut answer) = answer {
4673//                 let answer = answer.next().await;
4674//                 if answer != Some(0) {
4675//                     return Ok(());
4676//                 }
4677//             }
4678//         }
4679
4680//         // If the user cancels any save prompt, then keep the app open.
4681//         for window in workspace_windows {
4682//             if let Some(should_close) = window.update_root(&mut cx, |workspace, cx| {
4683//                 workspace.prepare_to_close(true, cx)
4684//             }) {
4685//                 if !should_close.await? {
4686//                     return Ok(());
4687//                 }
4688//             }
4689//         }
4690//         cx.platform().restart();
4691//         anyhow::Ok(())
4692//     })
4693//     .detach_and_log_err(cx);
4694// }
4695
4696fn parse_pixel_position_env_var(value: &str) -> Option<Point<GlobalPixels>> {
4697    let mut parts = value.split(',');
4698    let x: usize = parts.next()?.parse().ok()?;
4699    let y: usize = parts.next()?.parse().ok()?;
4700    Some(point((x as f64).into(), (y as f64).into()))
4701}
4702
4703fn parse_pixel_size_env_var(value: &str) -> Option<Size<GlobalPixels>> {
4704    let mut parts = value.split(',');
4705    let width: usize = parts.next()?.parse().ok()?;
4706    let height: usize = parts.next()?.parse().ok()?;
4707    Some(size((width as f64).into(), (height as f64).into()))
4708}
4709
4710// #[cfg(test)]
4711// mod tests {
4712//     use super::*;
4713//     use crate::{
4714//         dock::test::{TestPanel, TestPanelEvent},
4715//         item::test::{TestItem, TestItemEvent, TestProjectItem},
4716//     };
4717//     use fs::FakeFs;
4718//     use gpui::{executor::Deterministic, test::EmptyView, TestAppContext};
4719//     use project::{Project, ProjectEntryId};
4720//     use serde_json::json;
4721//     use settings::SettingsStore;
4722//     use std::{cell::RefCell, rc::Rc};
4723
4724//     #[gpui::test]
4725//     async fn test_tab_disambiguation(cx: &mut TestAppContext) {
4726//         init_test(cx);
4727
4728//         let fs = FakeFs::new(cx.background());
4729//         let project = Project::test(fs, [], cx).await;
4730//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
4731//         let workspace = window.root(cx);
4732
4733//         // Adding an item with no ambiguity renders the tab without detail.
4734//         let item1 = window.build_view(cx, |_| {
4735//             let mut item = TestItem::new();
4736//             item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
4737//             item
4738//         });
4739//         workspace.update(cx, |workspace, cx| {
4740//             workspace.add_item(Box::new(item1.clone()), cx);
4741//         });
4742//         item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), None));
4743
4744//         // Adding an item that creates ambiguity increases the level of detail on
4745//         // both tabs.
4746//         let item2 = window.build_view(cx, |_| {
4747//             let mut item = TestItem::new();
4748//             item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
4749//             item
4750//         });
4751//         workspace.update(cx, |workspace, cx| {
4752//             workspace.add_item(Box::new(item2.clone()), cx);
4753//         });
4754//         item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
4755//         item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
4756
4757//         // Adding an item that creates ambiguity increases the level of detail only
4758//         // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
4759//         // we stop at the highest detail available.
4760//         let item3 = window.build_view(cx, |_| {
4761//             let mut item = TestItem::new();
4762//             item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
4763//             item
4764//         });
4765//         workspace.update(cx, |workspace, cx| {
4766//             workspace.add_item(Box::new(item3.clone()), cx);
4767//         });
4768//         item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
4769//         item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
4770//         item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
4771//     }
4772
4773//     #[gpui::test]
4774//     async fn test_tracking_active_path(cx: &mut TestAppContext) {
4775//         init_test(cx);
4776
4777//         let fs = FakeFs::new(cx.background());
4778//         fs.insert_tree(
4779//             "/root1",
4780//             json!({
4781//                 "one.txt": "",
4782//                 "two.txt": "",
4783//             }),
4784//         )
4785//         .await;
4786//         fs.insert_tree(
4787//             "/root2",
4788//             json!({
4789//                 "three.txt": "",
4790//             }),
4791//         )
4792//         .await;
4793
4794//         let project = Project::test(fs, ["root1".as_ref()], cx).await;
4795//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
4796//         let workspace = window.root(cx);
4797//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4798//         let worktree_id = project.read_with(cx, |project, cx| {
4799//             project.worktrees(cx).next().unwrap().read(cx).id()
4800//         });
4801
4802//         let item1 = window.build_view(cx, |cx| {
4803//             TestItem::new().with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
4804//         });
4805//         let item2 = window.build_view(cx, |cx| {
4806//             TestItem::new().with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
4807//         });
4808
4809//         // Add an item to an empty pane
4810//         workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item1), cx));
4811//         project.read_with(cx, |project, cx| {
4812//             assert_eq!(
4813//                 project.active_entry(),
4814//                 project
4815//                     .entry_for_path(&(worktree_id, "one.txt").into(), cx)
4816//                     .map(|e| e.id)
4817//             );
4818//         });
4819//         assert_eq!(window.current_title(cx).as_deref(), Some("one.txt β€” root1"));
4820
4821//         // Add a second item to a non-empty pane
4822//         workspace.update(cx, |workspace, cx| workspace.add_item(Box::new(item2), cx));
4823//         assert_eq!(window.current_title(cx).as_deref(), Some("two.txt β€” root1"));
4824//         project.read_with(cx, |project, cx| {
4825//             assert_eq!(
4826//                 project.active_entry(),
4827//                 project
4828//                     .entry_for_path(&(worktree_id, "two.txt").into(), cx)
4829//                     .map(|e| e.id)
4830//             );
4831//         });
4832
4833//         // Close the active item
4834//         pane.update(cx, |pane, cx| {
4835//             pane.close_active_item(&Default::default(), cx).unwrap()
4836//         })
4837//         .await
4838//         .unwrap();
4839//         assert_eq!(window.current_title(cx).as_deref(), Some("one.txt β€” root1"));
4840//         project.read_with(cx, |project, cx| {
4841//             assert_eq!(
4842//                 project.active_entry(),
4843//                 project
4844//                     .entry_for_path(&(worktree_id, "one.txt").into(), cx)
4845//                     .map(|e| e.id)
4846//             );
4847//         });
4848
4849//         // Add a project folder
4850//         project
4851//             .update(cx, |project, cx| {
4852//                 project.find_or_create_local_worktree("/root2", true, cx)
4853//             })
4854//             .await
4855//             .unwrap();
4856//         assert_eq!(
4857//             window.current_title(cx).as_deref(),
4858//             Some("one.txt β€” root1, root2")
4859//         );
4860
4861//         // Remove a project folder
4862//         project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
4863//         assert_eq!(window.current_title(cx).as_deref(), Some("one.txt β€” root2"));
4864//     }
4865
4866//     #[gpui::test]
4867//     async fn test_close_window(cx: &mut TestAppContext) {
4868//         init_test(cx);
4869
4870//         let fs = FakeFs::new(cx.background());
4871//         fs.insert_tree("/root", json!({ "one": "" })).await;
4872
4873//         let project = Project::test(fs, ["root".as_ref()], cx).await;
4874//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
4875//         let workspace = window.root(cx);
4876
4877//         // When there are no dirty items, there's nothing to do.
4878//         let item1 = window.build_view(cx, |_| TestItem::new());
4879//         workspace.update(cx, |w, cx| w.add_item(Box::new(item1.clone()), cx));
4880//         let task = workspace.update(cx, |w, cx| w.prepare_to_close(false, cx));
4881//         assert!(task.await.unwrap());
4882
4883//         // When there are dirty untitled items, prompt to save each one. If the user
4884//         // cancels any prompt, then abort.
4885//         let item2 = window.build_view(cx, |_| TestItem::new().with_dirty(true));
4886//         let item3 = window.build_view(cx, |cx| {
4887//             TestItem::new()
4888//                 .with_dirty(true)
4889//                 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
4890//         });
4891//         workspace.update(cx, |w, cx| {
4892//             w.add_item(Box::new(item2.clone()), cx);
4893//             w.add_item(Box::new(item3.clone()), cx);
4894//         });
4895//         let task = workspace.update(cx, |w, cx| w.prepare_to_close(false, cx));
4896//         cx.foreground().run_until_parked();
4897//         window.simulate_prompt_answer(2, cx); // cancel save all
4898//         cx.foreground().run_until_parked();
4899//         window.simulate_prompt_answer(2, cx); // cancel save all
4900//         cx.foreground().run_until_parked();
4901//         assert!(!window.has_pending_prompt(cx));
4902//         assert!(!task.await.unwrap());
4903//     }
4904
4905//     #[gpui::test]
4906//     async fn test_close_pane_items(cx: &mut TestAppContext) {
4907//         init_test(cx);
4908
4909//         let fs = FakeFs::new(cx.background());
4910
4911//         let project = Project::test(fs, None, cx).await;
4912//         let window = cx.add_window(|cx| Workspace::test_new(project, cx));
4913//         let workspace = window.root(cx);
4914
4915//         let item1 = window.build_view(cx, |cx| {
4916//             TestItem::new()
4917//                 .with_dirty(true)
4918//                 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
4919//         });
4920//         let item2 = window.build_view(cx, |cx| {
4921//             TestItem::new()
4922//                 .with_dirty(true)
4923//                 .with_conflict(true)
4924//                 .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)])
4925//         });
4926//         let item3 = window.build_view(cx, |cx| {
4927//             TestItem::new()
4928//                 .with_dirty(true)
4929//                 .with_conflict(true)
4930//                 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
4931//         });
4932//         let item4 = window.build_view(cx, |cx| {
4933//             TestItem::new()
4934//                 .with_dirty(true)
4935//                 .with_project_items(&[TestProjectItem::new_untitled(cx)])
4936//         });
4937//         let pane = workspace.update(cx, |workspace, cx| {
4938//             workspace.add_item(Box::new(item1.clone()), cx);
4939//             workspace.add_item(Box::new(item2.clone()), cx);
4940//             workspace.add_item(Box::new(item3.clone()), cx);
4941//             workspace.add_item(Box::new(item4.clone()), cx);
4942//             workspace.active_pane().clone()
4943//         });
4944
4945//         let close_items = pane.update(cx, |pane, cx| {
4946//             pane.activate_item(1, true, true, cx);
4947//             assert_eq!(pane.active_item().unwrap().id(), item2.id());
4948//             let item1_id = item1.id();
4949//             let item3_id = item3.id();
4950//             let item4_id = item4.id();
4951//             pane.close_items(cx, SaveIntent::Close, move |id| {
4952//                 [item1_id, item3_id, item4_id].contains(&id)
4953//             })
4954//         });
4955//         cx.foreground().run_until_parked();
4956
4957//         assert!(window.has_pending_prompt(cx));
4958//         // Ignore "Save all" prompt
4959//         window.simulate_prompt_answer(2, cx);
4960//         cx.foreground().run_until_parked();
4961//         // There's a prompt to save item 1.
4962//         pane.read_with(cx, |pane, _| {
4963//             assert_eq!(pane.items_len(), 4);
4964//             assert_eq!(pane.active_item().unwrap().id(), item1.id());
4965//         });
4966//         // Confirm saving item 1.
4967//         window.simulate_prompt_answer(0, cx);
4968//         cx.foreground().run_until_parked();
4969
4970//         // Item 1 is saved. There's a prompt to save item 3.
4971//         pane.read_with(cx, |pane, cx| {
4972//             assert_eq!(item1.read(cx).save_count, 1);
4973//             assert_eq!(item1.read(cx).save_as_count, 0);
4974//             assert_eq!(item1.read(cx).reload_count, 0);
4975//             assert_eq!(pane.items_len(), 3);
4976//             assert_eq!(pane.active_item().unwrap().id(), item3.id());
4977//         });
4978//         assert!(window.has_pending_prompt(cx));
4979
4980//         // Cancel saving item 3.
4981//         window.simulate_prompt_answer(1, cx);
4982//         cx.foreground().run_until_parked();
4983
4984//         // Item 3 is reloaded. There's a prompt to save item 4.
4985//         pane.read_with(cx, |pane, cx| {
4986//             assert_eq!(item3.read(cx).save_count, 0);
4987//             assert_eq!(item3.read(cx).save_as_count, 0);
4988//             assert_eq!(item3.read(cx).reload_count, 1);
4989//             assert_eq!(pane.items_len(), 2);
4990//             assert_eq!(pane.active_item().unwrap().id(), item4.id());
4991//         });
4992//         assert!(window.has_pending_prompt(cx));
4993
4994//         // Confirm saving item 4.
4995//         window.simulate_prompt_answer(0, cx);
4996//         cx.foreground().run_until_parked();
4997
4998//         // There's a prompt for a path for item 4.
4999//         cx.simulate_new_path_selection(|_| Some(Default::default()));
5000//         close_items.await.unwrap();
5001
5002//         // The requested items are closed.
5003//         pane.read_with(cx, |pane, cx| {
5004//             assert_eq!(item4.read(cx).save_count, 0);
5005//             assert_eq!(item4.read(cx).save_as_count, 1);
5006//             assert_eq!(item4.read(cx).reload_count, 0);
5007//             assert_eq!(pane.items_len(), 1);
5008//             assert_eq!(pane.active_item().unwrap().id(), item2.id());
5009//         });
5010//     }
5011
5012//     #[gpui::test]
5013//     async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
5014//         init_test(cx);
5015
5016//         let fs = FakeFs::new(cx.background());
5017
5018//         let project = Project::test(fs, [], cx).await;
5019//         let window = cx.add_window(|cx| Workspace::test_new(project, cx));
5020//         let workspace = window.root(cx);
5021
5022//         // Create several workspace items with single project entries, and two
5023//         // workspace items with multiple project entries.
5024//         let single_entry_items = (0..=4)
5025//             .map(|project_entry_id| {
5026//                 window.build_view(cx, |cx| {
5027//                     TestItem::new()
5028//                         .with_dirty(true)
5029//                         .with_project_items(&[TestProjectItem::new(
5030//                             project_entry_id,
5031//                             &format!("{project_entry_id}.txt"),
5032//                             cx,
5033//                         )])
5034//                 })
5035//             })
5036//             .collect::<Vec<_>>();
5037//         let item_2_3 = window.build_view(cx, |cx| {
5038//             TestItem::new()
5039//                 .with_dirty(true)
5040//                 .with_singleton(false)
5041//                 .with_project_items(&[
5042//                     single_entry_items[2].read(cx).project_items[0].clone(),
5043//                     single_entry_items[3].read(cx).project_items[0].clone(),
5044//                 ])
5045//         });
5046//         let item_3_4 = window.build_view(cx, |cx| {
5047//             TestItem::new()
5048//                 .with_dirty(true)
5049//                 .with_singleton(false)
5050//                 .with_project_items(&[
5051//                     single_entry_items[3].read(cx).project_items[0].clone(),
5052//                     single_entry_items[4].read(cx).project_items[0].clone(),
5053//                 ])
5054//         });
5055
5056//         // Create two panes that contain the following project entries:
5057//         //   left pane:
5058//         //     multi-entry items:   (2, 3)
5059//         //     single-entry items:  0, 1, 2, 3, 4
5060//         //   right pane:
5061//         //     single-entry items:  1
5062//         //     multi-entry items:   (3, 4)
5063//         let left_pane = workspace.update(cx, |workspace, cx| {
5064//             let left_pane = workspace.active_pane().clone();
5065//             workspace.add_item(Box::new(item_2_3.clone()), cx);
5066//             for item in single_entry_items {
5067//                 workspace.add_item(Box::new(item), cx);
5068//             }
5069//             left_pane.update(cx, |pane, cx| {
5070//                 pane.activate_item(2, true, true, cx);
5071//             });
5072
5073//             workspace
5074//                 .split_and_clone(left_pane.clone(), SplitDirection::Right, cx)
5075//                 .unwrap();
5076
5077//             left_pane
5078//         });
5079
5080//         //Need to cause an effect flush in order to respect new focus
5081//         workspace.update(cx, |workspace, cx| {
5082//             workspace.add_item(Box::new(item_3_4.clone()), cx);
5083//             cx.focus(&left_pane);
5084//         });
5085
5086//         // When closing all of the items in the left pane, we should be prompted twice:
5087//         // once for project entry 0, and once for project entry 2. After those two
5088//         // prompts, the task should complete.
5089
5090//         let close = left_pane.update(cx, |pane, cx| {
5091//             pane.close_items(cx, SaveIntent::Close, move |_| true)
5092//         });
5093//         cx.foreground().run_until_parked();
5094//         // Discard "Save all" prompt
5095//         window.simulate_prompt_answer(2, cx);
5096
5097//         cx.foreground().run_until_parked();
5098//         left_pane.read_with(cx, |pane, cx| {
5099//             assert_eq!(
5100//                 pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
5101//                 &[ProjectEntryId::from_proto(0)]
5102//             );
5103//         });
5104//         window.simulate_prompt_answer(0, cx);
5105
5106//         cx.foreground().run_until_parked();
5107//         left_pane.read_with(cx, |pane, cx| {
5108//             assert_eq!(
5109//                 pane.active_item().unwrap().project_entry_ids(cx).as_slice(),
5110//                 &[ProjectEntryId::from_proto(2)]
5111//             );
5112//         });
5113//         window.simulate_prompt_answer(0, cx);
5114
5115//         cx.foreground().run_until_parked();
5116//         close.await.unwrap();
5117//         left_pane.read_with(cx, |pane, _| {
5118//             assert_eq!(pane.items_len(), 0);
5119//         });
5120//     }
5121
5122//     #[gpui::test]
5123//     async fn test_autosave(deterministic: Arc<Deterministic>, cx: &mut gpui::TestAppContext) {
5124//         init_test(cx);
5125
5126//         let fs = FakeFs::new(cx.background());
5127
5128//         let project = Project::test(fs, [], cx).await;
5129//         let window = cx.add_window(|cx| Workspace::test_new(project, cx));
5130//         let workspace = window.root(cx);
5131//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5132
5133//         let item = window.build_view(cx, |cx| {
5134//             TestItem::new().with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5135//         });
5136//         let item_id = item.id();
5137//         workspace.update(cx, |workspace, cx| {
5138//             workspace.add_item(Box::new(item.clone()), cx);
5139//         });
5140
5141//         // Autosave on window change.
5142//         item.update(cx, |item, cx| {
5143//             cx.update_global(|settings: &mut SettingsStore, cx| {
5144//                 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
5145//                     settings.autosave = Some(AutosaveSetting::OnWindowChange);
5146//                 })
5147//             });
5148//             item.is_dirty = true;
5149//         });
5150
5151//         // Deactivating the window saves the file.
5152//         window.simulate_deactivation(cx);
5153//         deterministic.run_until_parked();
5154//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
5155
5156//         // Autosave on focus change.
5157//         item.update(cx, |item, cx| {
5158//             cx.focus_self();
5159//             cx.update_global(|settings: &mut SettingsStore, cx| {
5160//                 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
5161//                     settings.autosave = Some(AutosaveSetting::OnFocusChange);
5162//                 })
5163//             });
5164//             item.is_dirty = true;
5165//         });
5166
5167//         // Blurring the item saves the file.
5168//         item.update(cx, |_, cx| cx.blur());
5169//         deterministic.run_until_parked();
5170//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
5171
5172//         // Deactivating the window still saves the file.
5173//         window.simulate_activation(cx);
5174//         item.update(cx, |item, cx| {
5175//             cx.focus_self();
5176//             item.is_dirty = true;
5177//         });
5178//         window.simulate_deactivation(cx);
5179
5180//         deterministic.run_until_parked();
5181//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
5182
5183//         // Autosave after delay.
5184//         item.update(cx, |item, cx| {
5185//             cx.update_global(|settings: &mut SettingsStore, cx| {
5186//                 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
5187//                     settings.autosave = Some(AutosaveSetting::AfterDelay { milliseconds: 500 });
5188//                 })
5189//             });
5190//             item.is_dirty = true;
5191//             cx.emit(TestItemEvent::Edit);
5192//         });
5193
5194//         // Delay hasn't fully expired, so the file is still dirty and unsaved.
5195//         deterministic.advance_clock(Duration::from_millis(250));
5196//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
5197
5198//         // After delay expires, the file is saved.
5199//         deterministic.advance_clock(Duration::from_millis(250));
5200//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
5201
5202//         // Autosave on focus change, ensuring closing the tab counts as such.
5203//         item.update(cx, |item, cx| {
5204//             cx.update_global(|settings: &mut SettingsStore, cx| {
5205//                 settings.update_user_settings::<WorkspaceSettings>(cx, |settings| {
5206//                     settings.autosave = Some(AutosaveSetting::OnFocusChange);
5207//                 })
5208//             });
5209//             item.is_dirty = true;
5210//         });
5211
5212//         pane.update(cx, |pane, cx| {
5213//             pane.close_items(cx, SaveIntent::Close, move |id| id == item_id)
5214//         })
5215//         .await
5216//         .unwrap();
5217//         assert!(!window.has_pending_prompt(cx));
5218//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
5219
5220//         // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
5221//         workspace.update(cx, |workspace, cx| {
5222//             workspace.add_item(Box::new(item.clone()), cx);
5223//         });
5224//         item.update(cx, |item, cx| {
5225//             item.project_items[0].update(cx, |item, _| {
5226//                 item.entry_id = None;
5227//             });
5228//             item.is_dirty = true;
5229//             cx.blur();
5230//         });
5231//         deterministic.run_until_parked();
5232//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
5233
5234//         // Ensure autosave is prevented for deleted files also when closing the buffer.
5235//         let _close_items = pane.update(cx, |pane, cx| {
5236//             pane.close_items(cx, SaveIntent::Close, move |id| id == item_id)
5237//         });
5238//         deterministic.run_until_parked();
5239//         assert!(window.has_pending_prompt(cx));
5240//         item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
5241//     }
5242
5243//     #[gpui::test]
5244//     async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
5245//         init_test(cx);
5246
5247//         let fs = FakeFs::new(cx.background());
5248
5249//         let project = Project::test(fs, [], cx).await;
5250//         let window = cx.add_window(|cx| Workspace::test_new(project, cx));
5251//         let workspace = window.root(cx);
5252
5253//         let item = window.build_view(cx, |cx| {
5254//             TestItem::new().with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5255//         });
5256//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5257//         let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
5258//         let toolbar_notify_count = Rc::new(RefCell::new(0));
5259
5260//         workspace.update(cx, |workspace, cx| {
5261//             workspace.add_item(Box::new(item.clone()), cx);
5262//             let toolbar_notification_count = toolbar_notify_count.clone();
5263//             cx.observe(&toolbar, move |_, _, _| {
5264//                 *toolbar_notification_count.borrow_mut() += 1
5265//             })
5266//             .detach();
5267//         });
5268
5269//         pane.read_with(cx, |pane, _| {
5270//             assert!(!pane.can_navigate_backward());
5271//             assert!(!pane.can_navigate_forward());
5272//         });
5273
5274//         item.update(cx, |item, cx| {
5275//             item.set_state("one".to_string(), cx);
5276//         });
5277
5278//         // Toolbar must be notified to re-render the navigation buttons
5279//         assert_eq!(*toolbar_notify_count.borrow(), 1);
5280
5281//         pane.read_with(cx, |pane, _| {
5282//             assert!(pane.can_navigate_backward());
5283//             assert!(!pane.can_navigate_forward());
5284//         });
5285
5286//         workspace
5287//             .update(cx, |workspace, cx| workspace.go_back(pane.downgrade(), cx))
5288//             .await
5289//             .unwrap();
5290
5291//         assert_eq!(*toolbar_notify_count.borrow(), 3);
5292//         pane.read_with(cx, |pane, _| {
5293//             assert!(!pane.can_navigate_backward());
5294//             assert!(pane.can_navigate_forward());
5295//         });
5296//     }
5297
5298//     #[gpui::test]
5299//     async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
5300//         init_test(cx);
5301//         let fs = FakeFs::new(cx.background());
5302
5303//         let project = Project::test(fs, [], cx).await;
5304//         let window = cx.add_window(|cx| Workspace::test_new(project, cx));
5305//         let workspace = window.root(cx);
5306
5307//         let panel = workspace.update(cx, |workspace, cx| {
5308//             let panel = cx.build_view(|_| TestPanel::new(DockPosition::Right));
5309//             workspace.add_panel(panel.clone(), cx);
5310
5311//             workspace
5312//                 .right_dock()
5313//                 .update(cx, |right_dock, cx| right_dock.set_open(true, cx));
5314
5315//             panel
5316//         });
5317
5318//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5319//         pane.update(cx, |pane, cx| {
5320//             let item = cx.build_view(|_| TestItem::new());
5321//             pane.add_item(Box::new(item), true, true, None, cx);
5322//         });
5323
5324//         // Transfer focus from center to panel
5325//         workspace.update(cx, |workspace, cx| {
5326//             workspace.toggle_panel_focus::<TestPanel>(cx);
5327//         });
5328
5329//         workspace.read_with(cx, |workspace, cx| {
5330//             assert!(workspace.right_dock().read(cx).is_open());
5331//             assert!(!panel.is_zoomed(cx));
5332//             assert!(panel.has_focus(cx));
5333//         });
5334
5335//         // Transfer focus from panel to center
5336//         workspace.update(cx, |workspace, cx| {
5337//             workspace.toggle_panel_focus::<TestPanel>(cx);
5338//         });
5339
5340//         workspace.read_with(cx, |workspace, cx| {
5341//             assert!(workspace.right_dock().read(cx).is_open());
5342//             assert!(!panel.is_zoomed(cx));
5343//             assert!(!panel.has_focus(cx));
5344//         });
5345
5346//         // Close the dock
5347//         workspace.update(cx, |workspace, cx| {
5348//             workspace.toggle_dock(DockPosition::Right, cx);
5349//         });
5350
5351//         workspace.read_with(cx, |workspace, cx| {
5352//             assert!(!workspace.right_dock().read(cx).is_open());
5353//             assert!(!panel.is_zoomed(cx));
5354//             assert!(!panel.has_focus(cx));
5355//         });
5356
5357//         // Open the dock
5358//         workspace.update(cx, |workspace, cx| {
5359//             workspace.toggle_dock(DockPosition::Right, cx);
5360//         });
5361
5362//         workspace.read_with(cx, |workspace, cx| {
5363//             assert!(workspace.right_dock().read(cx).is_open());
5364//             assert!(!panel.is_zoomed(cx));
5365//             assert!(panel.has_focus(cx));
5366//         });
5367
5368//         // Focus and zoom panel
5369//         panel.update(cx, |panel, cx| {
5370//             cx.focus_self();
5371//             panel.set_zoomed(true, cx)
5372//         });
5373
5374//         workspace.read_with(cx, |workspace, cx| {
5375//             assert!(workspace.right_dock().read(cx).is_open());
5376//             assert!(panel.is_zoomed(cx));
5377//             assert!(panel.has_focus(cx));
5378//         });
5379
5380//         // Transfer focus to the center closes the dock
5381//         workspace.update(cx, |workspace, cx| {
5382//             workspace.toggle_panel_focus::<TestPanel>(cx);
5383//         });
5384
5385//         workspace.read_with(cx, |workspace, cx| {
5386//             assert!(!workspace.right_dock().read(cx).is_open());
5387//             assert!(panel.is_zoomed(cx));
5388//             assert!(!panel.has_focus(cx));
5389//         });
5390
5391//         // Transferring focus back to the panel keeps it zoomed
5392//         workspace.update(cx, |workspace, cx| {
5393//             workspace.toggle_panel_focus::<TestPanel>(cx);
5394//         });
5395
5396//         workspace.read_with(cx, |workspace, cx| {
5397//             assert!(workspace.right_dock().read(cx).is_open());
5398//             assert!(panel.is_zoomed(cx));
5399//             assert!(panel.has_focus(cx));
5400//         });
5401
5402//         // Close the dock while it is zoomed
5403//         workspace.update(cx, |workspace, cx| {
5404//             workspace.toggle_dock(DockPosition::Right, cx)
5405//         });
5406
5407//         workspace.read_with(cx, |workspace, cx| {
5408//             assert!(!workspace.right_dock().read(cx).is_open());
5409//             assert!(panel.is_zoomed(cx));
5410//             assert!(workspace.zoomed.is_none());
5411//             assert!(!panel.has_focus(cx));
5412//         });
5413
5414//         // Opening the dock, when it's zoomed, retains focus
5415//         workspace.update(cx, |workspace, cx| {
5416//             workspace.toggle_dock(DockPosition::Right, cx)
5417//         });
5418
5419//         workspace.read_with(cx, |workspace, cx| {
5420//             assert!(workspace.right_dock().read(cx).is_open());
5421//             assert!(panel.is_zoomed(cx));
5422//             assert!(workspace.zoomed.is_some());
5423//             assert!(panel.has_focus(cx));
5424//         });
5425
5426//         // Unzoom and close the panel, zoom the active pane.
5427//         panel.update(cx, |panel, cx| panel.set_zoomed(false, cx));
5428//         workspace.update(cx, |workspace, cx| {
5429//             workspace.toggle_dock(DockPosition::Right, cx)
5430//         });
5431//         pane.update(cx, |pane, cx| pane.toggle_zoom(&Default::default(), cx));
5432
5433//         // Opening a dock unzooms the pane.
5434//         workspace.update(cx, |workspace, cx| {
5435//             workspace.toggle_dock(DockPosition::Right, cx)
5436//         });
5437//         workspace.read_with(cx, |workspace, cx| {
5438//             let pane = pane.read(cx);
5439//             assert!(!pane.is_zoomed());
5440//             assert!(!pane.has_focus());
5441//             assert!(workspace.right_dock().read(cx).is_open());
5442//             assert!(workspace.zoomed.is_none());
5443//         });
5444//     }
5445
5446//     #[gpui::test]
5447//     async fn test_panels(cx: &mut gpui::TestAppContext) {
5448//         init_test(cx);
5449//         let fs = FakeFs::new(cx.background());
5450
5451//         let project = Project::test(fs, [], cx).await;
5452//         let window = cx.add_window(|cx| Workspace::test_new(project, cx));
5453//         let workspace = window.root(cx);
5454
5455//         let (panel_1, panel_2) = workspace.update(cx, |workspace, cx| {
5456//             // Add panel_1 on the left, panel_2 on the right.
5457//             let panel_1 = cx.build_view(|_| TestPanel::new(DockPosition::Left));
5458//             workspace.add_panel(panel_1.clone(), cx);
5459//             workspace
5460//                 .left_dock()
5461//                 .update(cx, |left_dock, cx| left_dock.set_open(true, cx));
5462//             let panel_2 = cx.build_view(|_| TestPanel::new(DockPosition::Right));
5463//             workspace.add_panel(panel_2.clone(), cx);
5464//             workspace
5465//                 .right_dock()
5466//                 .update(cx, |right_dock, cx| right_dock.set_open(true, cx));
5467
5468//             let left_dock = workspace.left_dock();
5469//             assert_eq!(
5470//                 left_dock.read(cx).visible_panel().unwrap().id(),
5471//                 panel_1.id()
5472//             );
5473//             assert_eq!(
5474//                 left_dock.read(cx).active_panel_size(cx).unwrap(),
5475//                 panel_1.size(cx)
5476//             );
5477
5478//             left_dock.update(cx, |left_dock, cx| {
5479//                 left_dock.resize_active_panel(Some(1337.), cx)
5480//             });
5481//             assert_eq!(
5482//                 workspace
5483//                     .right_dock()
5484//                     .read(cx)
5485//                     .visible_panel()
5486//                     .unwrap()
5487//                     .id(),
5488//                 panel_2.id()
5489//             );
5490
5491//             (panel_1, panel_2)
5492//         });
5493
5494//         // Move panel_1 to the right
5495//         panel_1.update(cx, |panel_1, cx| {
5496//             panel_1.set_position(DockPosition::Right, cx)
5497//         });
5498
5499//         workspace.update(cx, |workspace, cx| {
5500//             // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
5501//             // Since it was the only panel on the left, the left dock should now be closed.
5502//             assert!(!workspace.left_dock().read(cx).is_open());
5503//             assert!(workspace.left_dock().read(cx).visible_panel().is_none());
5504//             let right_dock = workspace.right_dock();
5505//             assert_eq!(
5506//                 right_dock.read(cx).visible_panel().unwrap().id(),
5507//                 panel_1.id()
5508//             );
5509//             assert_eq!(right_dock.read(cx).active_panel_size(cx).unwrap(), 1337.);
5510
5511//             // Now we move panel_2Β to the left
5512//             panel_2.set_position(DockPosition::Left, cx);
5513//         });
5514
5515//         workspace.update(cx, |workspace, cx| {
5516//             // Since panel_2 was not visible on the right, we don't open the left dock.
5517//             assert!(!workspace.left_dock().read(cx).is_open());
5518//             // And the right dock is unaffected in it's displaying of panel_1
5519//             assert!(workspace.right_dock().read(cx).is_open());
5520//             assert_eq!(
5521//                 workspace
5522//                     .right_dock()
5523//                     .read(cx)
5524//                     .visible_panel()
5525//                     .unwrap()
5526//                     .id(),
5527//                 panel_1.id()
5528//             );
5529//         });
5530
5531//         // Move panel_1 back to the left
5532//         panel_1.update(cx, |panel_1, cx| {
5533//             panel_1.set_position(DockPosition::Left, cx)
5534//         });
5535
5536//         workspace.update(cx, |workspace, cx| {
5537//             // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
5538//             let left_dock = workspace.left_dock();
5539//             assert!(left_dock.read(cx).is_open());
5540//             assert_eq!(
5541//                 left_dock.read(cx).visible_panel().unwrap().id(),
5542//                 panel_1.id()
5543//             );
5544//             assert_eq!(left_dock.read(cx).active_panel_size(cx).unwrap(), 1337.);
5545//             // And right the dock should be closed as it no longer has any panels.
5546//             assert!(!workspace.right_dock().read(cx).is_open());
5547
5548//             // Now we move panel_1 to the bottom
5549//             panel_1.set_position(DockPosition::Bottom, cx);
5550//         });
5551
5552//         workspace.update(cx, |workspace, cx| {
5553//             // Since panel_1 was visible on the left, we close the left dock.
5554//             assert!(!workspace.left_dock().read(cx).is_open());
5555//             // The bottom dock is sized based on the panel's default size,
5556//             // since the panel orientation changed from vertical to horizontal.
5557//             let bottom_dock = workspace.bottom_dock();
5558//             assert_eq!(
5559//                 bottom_dock.read(cx).active_panel_size(cx).unwrap(),
5560//                 panel_1.size(cx),
5561//             );
5562//             // Close bottom dock and move panel_1 back to the left.
5563//             bottom_dock.update(cx, |bottom_dock, cx| bottom_dock.set_open(false, cx));
5564//             panel_1.set_position(DockPosition::Left, cx);
5565//         });
5566
5567//         // Emit activated event on panel 1
5568//         panel_1.update(cx, |_, cx| cx.emit(TestPanelEvent::Activated));
5569
5570//         // Now the left dock is open and panel_1 is active and focused.
5571//         workspace.read_with(cx, |workspace, cx| {
5572//             let left_dock = workspace.left_dock();
5573//             assert!(left_dock.read(cx).is_open());
5574//             assert_eq!(
5575//                 left_dock.read(cx).visible_panel().unwrap().id(),
5576//                 panel_1.id()
5577//             );
5578//             assert!(panel_1.is_focused(cx));
5579//         });
5580
5581//         // Emit closed event on panel 2, which is not active
5582//         panel_2.update(cx, |_, cx| cx.emit(TestPanelEvent::Closed));
5583
5584//         // Wo don't close the left dock, because panel_2 wasn't the active panel
5585//         workspace.read_with(cx, |workspace, cx| {
5586//             let left_dock = workspace.left_dock();
5587//             assert!(left_dock.read(cx).is_open());
5588//             assert_eq!(
5589//                 left_dock.read(cx).visible_panel().unwrap().id(),
5590//                 panel_1.id()
5591//             );
5592//         });
5593
5594//         // Emitting a ZoomIn event shows the panel as zoomed.
5595//         panel_1.update(cx, |_, cx| cx.emit(TestPanelEvent::ZoomIn));
5596//         workspace.read_with(cx, |workspace, _| {
5597//             assert_eq!(workspace.zoomed, Some(panel_1.downgrade().into_any()));
5598//             assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
5599//         });
5600
5601//         // Move panel to another dock while it is zoomed
5602//         panel_1.update(cx, |panel, cx| panel.set_position(DockPosition::Right, cx));
5603//         workspace.read_with(cx, |workspace, _| {
5604//             assert_eq!(workspace.zoomed, Some(panel_1.downgrade().into_any()));
5605//             assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
5606//         });
5607
5608//         // If focus is transferred to another view that's not a panel or another pane, we still show
5609//         // the panel as zoomed.
5610//         let focus_receiver = window.build_view(cx, |_| EmptyView);
5611//         focus_receiver.update(cx, |_, cx| cx.focus_self());
5612//         workspace.read_with(cx, |workspace, _| {
5613//             assert_eq!(workspace.zoomed, Some(panel_1.downgrade().into_any()));
5614//             assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
5615//         });
5616
5617//         // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
5618//         workspace.update(cx, |_, cx| cx.focus_self());
5619//         workspace.read_with(cx, |workspace, _| {
5620//             assert_eq!(workspace.zoomed, None);
5621//             assert_eq!(workspace.zoomed_position, None);
5622//         });
5623
5624//         // If focus is transferred again to another view that's not a panel or a pane, we won't
5625//         // show the panel as zoomed because it wasn't zoomed before.
5626//         focus_receiver.update(cx, |_, cx| cx.focus_self());
5627//         workspace.read_with(cx, |workspace, _| {
5628//             assert_eq!(workspace.zoomed, None);
5629//             assert_eq!(workspace.zoomed_position, None);
5630//         });
5631
5632//         // When focus is transferred back to the panel, it is zoomed again.
5633//         panel_1.update(cx, |_, cx| cx.focus_self());
5634//         workspace.read_with(cx, |workspace, _| {
5635//             assert_eq!(workspace.zoomed, Some(panel_1.downgrade().into_any()));
5636//             assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
5637//         });
5638
5639//         // Emitting a ZoomOut event unzooms the panel.
5640//         panel_1.update(cx, |_, cx| cx.emit(TestPanelEvent::ZoomOut));
5641//         workspace.read_with(cx, |workspace, _| {
5642//             assert_eq!(workspace.zoomed, None);
5643//             assert_eq!(workspace.zoomed_position, None);
5644//         });
5645
5646//         // Emit closed event on panel 1, which is active
5647//         panel_1.update(cx, |_, cx| cx.emit(TestPanelEvent::Closed));
5648
5649//         // Now the left dock is closed, because panel_1 was the active panel
5650//         workspace.read_with(cx, |workspace, cx| {
5651//             let right_dock = workspace.right_dock();
5652//             assert!(!right_dock.read(cx).is_open());
5653//         });
5654//     }
5655
5656//     pub fn init_test(cx: &mut TestAppContext) {
5657//         cx.foreground().forbid_parking();
5658//         cx.update(|cx| {
5659//             cx.set_global(SettingsStore::test(cx));
5660//             theme::init((), cx);
5661//             language::init(cx);
5662//             crate::init_settings(cx);
5663//             Project::init_settings(cx);
5664//         });
5665//     }
5666// }