workspace2.rs

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