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