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