Merge branch 'main' into completions-styles

Nate Butler created

Change summary

Cargo.lock                                                        |   6 
Cargo.toml                                                        |   3 
crates/call2/Cargo.toml                                           |   3 
crates/call2/src/call2.rs                                         | 169 
crates/call2/src/participant.rs                                   |   2 
crates/call2/src/room.rs                                          |  12 
crates/call2/src/shared_screen.rs                                 | 157 
crates/client2/src/client2.rs                                     |   1 
crates/collab_ui2/src/collab_panel.rs                             |  48 
crates/collab_ui2/src/collab_titlebar_item.rs                     | 153 
crates/collab_ui2/src/collab_ui.rs                                |  64 
crates/collab_ui2/src/face_pile.rs                                | 105 
crates/collab_ui2/src/notifications.rs                            |  16 
crates/collab_ui2/src/notifications/incoming_call_notification.rs | 348 
crates/editor2/src/editor.rs                                      |  41 
crates/editor2/src/element.rs                                     |   7 
crates/go_to_line2/src/go_to_line.rs                              |  21 
crates/gpui2/src/app.rs                                           |   6 
crates/gpui2/src/elements/img.rs                                  |  86 
crates/gpui2/src/elements/uniform_list.rs                         |   2 
crates/gpui2/src/platform/mac/window.rs                           |   3 
crates/gpui2/src/window.rs                                        |   7 
crates/language/src/highlight_map.rs                              |   8 
crates/language/src/language.rs                                   |   4 
crates/language/src/syntax_map/syntax_map_tests.rs                |   2 
crates/language2/src/highlight_map.rs                             |   8 
crates/language2/src/language2.rs                                 |   4 
crates/language2/src/syntax_map/syntax_map_tests.rs               |   2 
crates/picker2/src/picker2.rs                                     |   1 
crates/project_panel2/src/project_panel.rs                        |   1 
crates/search2/src/buffer_search.rs                               | 119 
crates/semantic_index/src/semantic_index_tests.rs                 |   4 
crates/storybook2/src/story_selector.rs                           |  13 
crates/ui2/src/components/avatar.rs                               |  16 
crates/ui2/src/components/list.rs                                 |   4 
crates/ui2/src/components/stories.rs                              |   2 
crates/ui2/src/components/stories/avatar.rs                       |   4 
crates/ui2/src/components/stories/list_item.rs                    |  26 
crates/util/src/channel.rs                                        |   2 
crates/workspace/src/workspace.rs                                 |  20 
crates/workspace2/src/modal_layer.rs                              |   1 
crates/workspace2/src/shared_screen.rs                            | 151 
crates/workspace2/src/workspace2.rs                               | 122 
crates/zed/src/languages/elixir/embedding.scm                     |   4 
crates/zed2/Cargo.toml                                            |   2 
crates/zed2/src/main.rs                                           |  34 
crates/zed2/src/zed2.rs                                           |  17 
47 files changed, 1,166 insertions(+), 665 deletions(-)

Detailed changes

Cargo.lock 🔗

@@ -1193,6 +1193,7 @@ dependencies = [
  "fs2",
  "futures 0.3.28",
  "gpui2",
+ "image",
  "language2",
  "live_kit_client2",
  "log",
@@ -1204,6 +1205,8 @@ dependencies = [
  "serde_derive",
  "serde_json",
  "settings2",
+ "smallvec",
+ "ui2",
  "util",
  "workspace2",
 ]
@@ -9927,7 +9930,7 @@ dependencies = [
 [[package]]
 name = "tree-sitter"
 version = "0.20.10"
-source = "git+https://github.com/tree-sitter/tree-sitter?rev=35a6052fbcafc5e5fc0f9415b8652be7dcaf7222#35a6052fbcafc5e5fc0f9415b8652be7dcaf7222"
+source = "git+https://github.com/tree-sitter/tree-sitter?rev=3b0159d25559b603af566ade3c83d930bf466db1#3b0159d25559b603af566ade3c83d930bf466db1"
 dependencies = [
  "cc",
  "regex",
@@ -11644,6 +11647,7 @@ dependencies = [
  "async-recursion 0.3.2",
  "async-tar",
  "async-trait",
+ "audio2",
  "auto_update2",
  "backtrace",
  "call2",

Cargo.toml 🔗

@@ -195,8 +195,9 @@ tree-sitter-lua = "0.0.14"
 tree-sitter-nix = { git = "https://github.com/nix-community/tree-sitter-nix", rev = "66e3e9ce9180ae08fc57372061006ef83f0abde7" }
 tree-sitter-nu = { git = "https://github.com/nushell/tree-sitter-nu", rev = "786689b0562b9799ce53e824cb45a1a2a04dc673"}
 tree-sitter-vue = {git = "https://github.com/zed-industries/tree-sitter-vue", rev = "9b6cb221ccb8d0b956fcb17e9a1efac2feefeb58"}
+
 [patch.crates-io]
-tree-sitter = { git = "https://github.com/tree-sitter/tree-sitter", rev = "35a6052fbcafc5e5fc0f9415b8652be7dcaf7222" }
+tree-sitter = { git = "https://github.com/tree-sitter/tree-sitter", rev = "3b0159d25559b603af566ade3c83d930bf466db1" }
 async-task = { git = "https://github.com/zed-industries/async-task", rev = "341b57d6de98cdfd7b418567b8de2022ca993a6e" }
 
 # TODO - Remove when a version is released with this PR: https://github.com/servo/core-foundation-rs/pull/457

crates/call2/Cargo.toml 🔗

@@ -31,16 +31,19 @@ media = { path = "../media" }
 project = { package = "project2", path = "../project2" }
 settings = { package = "settings2", path = "../settings2" }
 util = { path = "../util" }
+ui = {package = "ui2", path = "../ui2"}
 workspace = {package = "workspace2", path = "../workspace2"}
 async-trait.workspace = true
 anyhow.workspace = true
 async-broadcast = "0.4"
 futures.workspace = true
+image = "0.23"
 postage.workspace = true
 schemars.workspace = true
 serde.workspace = true
 serde_json.workspace = true
 serde_derive.workspace = true
+smallvec.workspace = true
 
 [dev-dependencies]
 client = { package = "client2", path = "../client2", features = ["test-support"] }

crates/call2/src/call2.rs 🔗

@@ -1,8 +1,9 @@
 pub mod call_settings;
 pub mod participant;
 pub mod room;
+mod shared_screen;
 
-use anyhow::{anyhow, bail, Result};
+use anyhow::{anyhow, Result};
 use async_trait::async_trait;
 use audio::Audio;
 use call_settings::CallSettings;
@@ -13,8 +14,8 @@ use client::{
 use collections::HashSet;
 use futures::{channel::oneshot, future::Shared, Future, FutureExt};
 use gpui::{
-    AppContext, AsyncAppContext, AsyncWindowContext, Context, EventEmitter, Model, ModelContext,
-    Subscription, Task, View, ViewContext, WeakModel, WeakView,
+    AppContext, AsyncAppContext, Context, EventEmitter, Model, ModelContext, Subscription, Task,
+    View, ViewContext, VisualContext, WeakModel, WeakView,
 };
 pub use participant::ParticipantLocation;
 use postage::watch;
@@ -22,6 +23,7 @@ use project::Project;
 use room::Event;
 pub use room::Room;
 use settings::Settings;
+use shared_screen::SharedScreen;
 use std::sync::Arc;
 use util::ResultExt;
 use workspace::{item::ItemHandle, CallHandler, Pane, Workspace};
@@ -549,42 +551,6 @@ impl Call {
 
 #[async_trait(?Send)]
 impl CallHandler for Call {
-    fn shared_screen_for_peer(
-        &self,
-        peer_id: PeerId,
-        _pane: &View<Pane>,
-        cx: &mut ViewContext<Workspace>,
-    ) -> Option<Box<dyn ItemHandle>> {
-        let (call, _) = self.active_call.as_ref()?;
-        let room = call.read(cx).room()?.read(cx);
-        let participant = room.remote_participant_for_peer_id(peer_id)?;
-        let _track = participant.video_tracks.values().next()?.clone();
-        let _user = participant.user.clone();
-        todo!();
-        // for item in pane.read(cx).items_of_type::<SharedScreen>() {
-        //     if item.read(cx).peer_id == peer_id {
-        //         return Box::new(Some(item));
-        //     }
-        // }
-
-        // Some(Box::new(cx.build_view(|cx| {
-        //     SharedScreen::new(&track, peer_id, user.clone(), cx)
-        // })))
-    }
-
-    fn room_id(&self, cx: &AppContext) -> Option<u64> {
-        Some(self.active_call.as_ref()?.0.read(cx).room()?.read(cx).id())
-    }
-    fn hang_up(&self, mut cx: AsyncWindowContext) -> Result<Task<Result<()>>> {
-        let Some((call, _)) = self.active_call.as_ref() else {
-            bail!("Cannot exit a call; not in a call");
-        };
-
-        call.update(&mut cx, |this, cx| this.hang_up(cx))
-    }
-    fn active_project(&self, cx: &AppContext) -> Option<WeakModel<Project>> {
-        ActiveCall::global(cx).read(cx).location().cloned()
-    }
     fn peer_state(
         &mut self,
         leader_id: PeerId,
@@ -618,6 +584,131 @@ impl CallHandler for Call {
 
         Some((leader_in_this_project, leader_in_this_app))
     }
+
+    fn shared_screen_for_peer(
+        &self,
+        peer_id: PeerId,
+        pane: &View<Pane>,
+        cx: &mut ViewContext<Workspace>,
+    ) -> Option<Box<dyn ItemHandle>> {
+        let (call, _) = self.active_call.as_ref()?;
+        let room = call.read(cx).room()?.read(cx);
+        let participant = room.remote_participant_for_peer_id(peer_id)?;
+        let track = participant.video_tracks.values().next()?.clone();
+        let user = participant.user.clone();
+        for item in pane.read(cx).items_of_type::<SharedScreen>() {
+            if item.read(cx).peer_id == peer_id {
+                return Some(Box::new(item));
+            }
+        }
+
+        Some(Box::new(cx.build_view(|cx| {
+            SharedScreen::new(&track, peer_id, user.clone(), cx)
+        })))
+    }
+    fn room_id(&self, cx: &AppContext) -> Option<u64> {
+        Some(self.active_call.as_ref()?.0.read(cx).room()?.read(cx).id())
+    }
+    fn hang_up(&self, cx: &mut AppContext) -> Task<Result<()>> {
+        let Some((call, _)) = self.active_call.as_ref() else {
+            return Task::ready(Err(anyhow!("Cannot exit a call; not in a call")));
+        };
+
+        call.update(cx, |this, cx| this.hang_up(cx))
+    }
+    fn active_project(&self, cx: &AppContext) -> Option<WeakModel<Project>> {
+        ActiveCall::global(cx).read(cx).location().cloned()
+    }
+    fn invite(
+        &mut self,
+        called_user_id: u64,
+        initial_project: Option<Model<Project>>,
+        cx: &mut AppContext,
+    ) -> Task<Result<()>> {
+        ActiveCall::global(cx).update(cx, |this, cx| {
+            this.invite(called_user_id, initial_project, cx)
+        })
+    }
+    fn remote_participants(&self, cx: &AppContext) -> Option<Vec<(Arc<User>, PeerId)>> {
+        self.active_call
+            .as_ref()
+            .map(|call| {
+                call.0.read(cx).room().map(|room| {
+                    room.read(cx)
+                        .remote_participants()
+                        .iter()
+                        .map(|participant| {
+                            (participant.1.user.clone(), participant.1.peer_id.clone())
+                        })
+                        .collect()
+                })
+            })
+            .flatten()
+    }
+    fn is_muted(&self, cx: &AppContext) -> Option<bool> {
+        self.active_call
+            .as_ref()
+            .map(|call| {
+                call.0
+                    .read(cx)
+                    .room()
+                    .map(|room| room.read(cx).is_muted(cx))
+            })
+            .flatten()
+    }
+    fn toggle_mute(&self, cx: &mut AppContext) {
+        self.active_call.as_ref().map(|call| {
+            call.0.update(cx, |this, cx| {
+                this.room().map(|room| {
+                    room.update(cx, |this, cx| {
+                        this.toggle_mute(cx).log_err();
+                    })
+                })
+            })
+        });
+    }
+    fn toggle_screen_share(&self, cx: &mut AppContext) {
+        self.active_call.as_ref().map(|call| {
+            call.0.update(cx, |this, cx| {
+                this.room().map(|room| {
+                    room.update(cx, |this, cx| {
+                        if this.is_screen_sharing() {
+                            this.unshare_screen(cx).log_err();
+                        } else {
+                            let t = this.share_screen(cx);
+                            cx.spawn(move |_, _| async move {
+                                t.await.log_err();
+                            })
+                            .detach();
+                        }
+                    })
+                })
+            })
+        });
+    }
+    fn toggle_deafen(&self, cx: &mut AppContext) {
+        self.active_call.as_ref().map(|call| {
+            call.0.update(cx, |this, cx| {
+                this.room().map(|room| {
+                    room.update(cx, |this, cx| {
+                        this.toggle_deafen(cx).log_err();
+                    })
+                })
+            })
+        });
+    }
+    fn is_deafened(&self, cx: &AppContext) -> Option<bool> {
+        self.active_call
+            .as_ref()
+            .map(|call| {
+                call.0
+                    .read(cx)
+                    .room()
+                    .map(|room| room.read(cx).is_deafened())
+            })
+            .flatten()
+            .flatten()
+    }
 }
 
 #[cfg(test)]

crates/call2/src/participant.rs 🔗

@@ -4,7 +4,7 @@ use client::{proto, User};
 use collections::HashMap;
 use gpui::WeakModel;
 pub use live_kit_client::Frame;
-use live_kit_client::{RemoteAudioTrack, RemoteVideoTrack};
+pub(crate) use live_kit_client::{RemoteAudioTrack, RemoteVideoTrack};
 use project::Project;
 use std::sync::Arc;
 

crates/call2/src/room.rs 🔗

@@ -1,7 +1,4 @@
-use crate::{
-    call_settings::CallSettings,
-    participant::{LocalParticipant, ParticipantLocation, RemoteParticipant},
-};
+use crate::participant::{LocalParticipant, ParticipantLocation, RemoteParticipant};
 use anyhow::{anyhow, Result};
 use audio::{Audio, Sound};
 use client::{
@@ -21,7 +18,6 @@ use live_kit_client::{
 };
 use postage::{sink::Sink, stream::Stream, watch};
 use project::Project;
-use settings::Settings;
 use std::{future::Future, mem, sync::Arc, time::Duration};
 use util::{post_inc, ResultExt, TryFutureExt};
 
@@ -332,8 +328,10 @@ impl Room {
         }
     }
 
-    pub fn mute_on_join(cx: &AppContext) -> bool {
-        CallSettings::get_global(cx).mute_on_join || client::IMPERSONATE_LOGIN.is_some()
+    pub fn mute_on_join(_cx: &AppContext) -> bool {
+        // todo!() po: This should be uncommented, though then unmuting does not work
+        false
+        //CallSettings::get_global(cx).mute_on_join || client::IMPERSONATE_LOGIN.is_some()
     }
 
     fn from_join_response(

crates/call2/src/shared_screen.rs 🔗

@@ -0,0 +1,157 @@
+use crate::participant::{Frame, RemoteVideoTrack};
+use anyhow::Result;
+use client::{proto::PeerId, User};
+use futures::StreamExt;
+use gpui::{
+    div, AppContext, Div, Element, EventEmitter, FocusHandle, FocusableView, ParentElement, Render,
+    SharedString, Task, View, ViewContext, VisualContext, WindowContext,
+};
+use std::sync::{Arc, Weak};
+use workspace::{item::Item, ItemNavHistory, WorkspaceId};
+
+pub enum Event {
+    Close,
+}
+
+pub struct SharedScreen {
+    track: Weak<RemoteVideoTrack>,
+    frame: Option<Frame>,
+    // temporary addition just to render something interactive.
+    current_frame_id: usize,
+    pub peer_id: PeerId,
+    user: Arc<User>,
+    nav_history: Option<ItemNavHistory>,
+    _maintain_frame: Task<Result<()>>,
+    focus: FocusHandle,
+}
+
+impl SharedScreen {
+    pub fn new(
+        track: &Arc<RemoteVideoTrack>,
+        peer_id: PeerId,
+        user: Arc<User>,
+        cx: &mut ViewContext<Self>,
+    ) -> Self {
+        cx.focus_handle();
+        let mut frames = track.frames();
+        Self {
+            track: Arc::downgrade(track),
+            frame: None,
+            peer_id,
+            user,
+            nav_history: Default::default(),
+            _maintain_frame: cx.spawn(|this, mut cx| async move {
+                while let Some(frame) = frames.next().await {
+                    this.update(&mut cx, |this, cx| {
+                        this.frame = Some(frame);
+                        cx.notify();
+                    })?;
+                }
+                this.update(&mut cx, |_, cx| cx.emit(Event::Close))?;
+                Ok(())
+            }),
+            focus: cx.focus_handle(),
+            current_frame_id: 0,
+        }
+    }
+}
+
+impl EventEmitter<Event> for SharedScreen {}
+impl EventEmitter<workspace::item::ItemEvent> for SharedScreen {}
+
+impl FocusableView for SharedScreen {
+    fn focus_handle(&self, _: &AppContext) -> FocusHandle {
+        self.focus.clone()
+    }
+}
+impl Render for SharedScreen {
+    type Element = Div;
+    fn render(&mut self, _: &mut ViewContext<Self>) -> Self::Element {
+        let frame = self.frame.clone();
+        let frame_id = self.current_frame_id;
+        self.current_frame_id = self.current_frame_id.wrapping_add(1);
+        div().children(frame.map(|_| {
+            ui::Label::new(frame_id.to_string()).color(ui::Color::Error)
+            // img().data(Arc::new(ImageData::new(image::ImageBuffer::new(
+            //     frame.width() as u32,
+            //     frame.height() as u32,
+            // ))))
+        }))
+    }
+}
+// impl View for SharedScreen {
+//     fn ui_name() -> &'static str {
+//         "SharedScreen"
+//     }
+
+//     fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
+//         enum Focus {}
+
+//         let frame = self.frame.clone();
+//         MouseEventHandler::new::<Focus, _>(0, cx, |_, cx| {
+//             Canvas::new(move |bounds, _, _, cx| {
+//                 if let Some(frame) = frame.clone() {
+//                     let size = constrain_size_preserving_aspect_ratio(
+//                         bounds.size(),
+//                         vec2f(frame.width() as f32, frame.height() as f32),
+//                     );
+//                     let origin = bounds.origin() + (bounds.size() / 2.) - size / 2.;
+//                     cx.scene().push_surface(gpui::platform::mac::Surface {
+//                         bounds: RectF::new(origin, size),
+//                         image_buffer: frame.image(),
+//                     });
+//                 }
+//             })
+//             .contained()
+//             .with_style(theme::current(cx).shared_screen)
+//         })
+//         .on_down(MouseButton::Left, |_, _, cx| cx.focus_parent())
+//         .into_any()
+//     }
+// }
+
+impl Item for SharedScreen {
+    fn tab_tooltip_text(&self, _: &AppContext) -> Option<SharedString> {
+        Some(format!("{}'s screen", self.user.github_login).into())
+    }
+    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
+        if let Some(nav_history) = self.nav_history.as_mut() {
+            nav_history.push::<()>(None, cx);
+        }
+    }
+
+    fn tab_content(&self, _: Option<usize>, _: &WindowContext<'_>) -> gpui::AnyElement {
+        div().child("Shared screen").into_any()
+        // Flex::row()
+        //     .with_child(
+        //         Svg::new("icons/desktop.svg")
+        //             .with_color(style.label.text.color)
+        //             .constrained()
+        //             .with_width(style.type_icon_width)
+        //             .aligned()
+        //             .contained()
+        //             .with_margin_right(style.spacing),
+        //     )
+        //     .with_child(
+        //         Label::new(
+        //             format!("{}'s screen", self.user.github_login),
+        //             style.label.clone(),
+        //         )
+        //         .aligned(),
+        //     )
+        //     .into_any()
+    }
+
+    fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
+        self.nav_history = Some(history);
+    }
+
+    fn clone_on_split(
+        &self,
+        _workspace_id: WorkspaceId,
+        cx: &mut ViewContext<Self>,
+    ) -> Option<View<Self>> {
+        let track = self.track.upgrade()?;
+        Some(cx.build_view(|cx| Self::new(&track, self.peer_id, self.user.clone(), cx)))
+    }
+}

crates/client2/src/client2.rs 🔗

@@ -551,7 +551,6 @@ impl Client {
         F: 'static + Future<Output = Result<()>>,
     {
         let message_type_id = TypeId::of::<M>();
-
         let mut state = self.state.write();
         state
             .models_by_message_type

crates/collab_ui2/src/collab_panel.rs 🔗

@@ -157,15 +157,17 @@ const COLLABORATION_PANEL_KEY: &'static str = "CollaborationPanel";
 
 use std::sync::Arc;
 
+use client::{Client, Contact, UserStore};
 use db::kvp::KEY_VALUE_STORE;
 use gpui::{
     actions, div, serde_json, AppContext, AsyncWindowContext, Div, EventEmitter, FocusHandle,
-    Focusable, FocusableView, InteractiveElement, ParentElement, Render, View, ViewContext,
-    VisualContext, WeakView,
+    Focusable, FocusableView, InteractiveElement, Model, ParentElement, Render, Styled, View,
+    ViewContext, VisualContext, WeakView,
 };
 use project::Fs;
 use serde_derive::{Deserialize, Serialize};
 use settings::Settings;
+use ui::{h_stack, Avatar, Label};
 use util::ResultExt;
 use workspace::{
     dock::{DockPosition, Panel, PanelEvent},
@@ -299,8 +301,8 @@ pub struct CollabPanel {
     // channel_editing_state: Option<ChannelEditingState>,
     // entries: Vec<ListEntry>,
     // selection: Option<usize>,
-    // user_store: ModelHandle<UserStore>,
-    // client: Arc<Client>,
+    user_store: Model<UserStore>,
+    _client: Arc<Client>,
     // channel_store: ModelHandle<ChannelStore>,
     // project: ModelHandle<Project>,
     // match_candidates: Vec<StringMatchCandidate>,
@@ -595,7 +597,7 @@ impl CollabPanel {
                 //                 entries: Vec::default(),
                 //                 channel_editing_state: None,
                 //                 selection: None,
-                //                 user_store: workspace.user_store().clone(),
+                user_store: workspace.user_store().clone(),
                 //                 channel_store: ChannelStore::global(cx),
                 //                 project: workspace.project().clone(),
                 //                 subscriptions: Vec::default(),
@@ -603,7 +605,7 @@ impl CollabPanel {
                 //                 collapsed_sections: vec![Section::Offline],
                 //                 collapsed_channels: Vec::default(),
                 _workspace: workspace.weak_handle(),
-                //                 client: workspace.app_state().client.clone(),
+                _client: workspace.app_state().client.clone(),
                 //                 context_menu_on_selected: true,
                 //                 drag_target_channel: ChannelDragTarget::None,
                 //                 list_state,
@@ -663,6 +665,9 @@ impl CollabPanel {
         })
     }
 
+    fn contacts(&self, cx: &AppContext) -> Option<Vec<Arc<Contact>>> {
+        Some(self.user_store.read(cx).contacts().to_owned())
+    }
     pub async fn load(
         workspace: WeakView<Workspace>,
         mut cx: AsyncWindowContext,
@@ -3297,11 +3302,38 @@ impl CollabPanel {
 impl Render for CollabPanel {
     type Element = Focusable<Div>;
 
-    fn render(&mut self, _cx: &mut ViewContext<Self>) -> Self::Element {
+    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
+        let contacts = self.contacts(cx).unwrap_or_default();
+        let workspace = self._workspace.clone();
         div()
             .key_context("CollabPanel")
             .track_focus(&self.focus_handle)
-            .child("COLLAB PANEL")
+            .children(contacts.into_iter().map(|contact| {
+                let id = contact.user.id;
+                h_stack()
+                    .p_2()
+                    .gap_2()
+                    .children(
+                        contact
+                            .user
+                            .avatar
+                            .as_ref()
+                            .map(|avatar| Avatar::data(avatar.clone())),
+                    )
+                    .child(Label::new(contact.user.github_login.clone()))
+                    .on_mouse_down(gpui::MouseButton::Left, {
+                        let workspace = workspace.clone();
+                        move |_, cx| {
+                            workspace
+                                .update(cx, |this, cx| {
+                                    this.call_state()
+                                        .invite(id, None, cx)
+                                        .detach_and_log_err(cx)
+                                })
+                                .log_err();
+                        }
+                    })
+            }))
     }
 }
 

crates/collab_ui2/src/collab_titlebar_item.rs 🔗

@@ -31,15 +31,18 @@ use std::sync::Arc;
 use call::ActiveCall;
 use client::{Client, UserStore};
 use gpui::{
-    div, px, rems, AppContext, Div, InteractiveElement, IntoElement, Model, ParentElement, Render,
-    Stateful, StatefulInteractiveElement, Styled, Subscription, ViewContext, VisualContext,
-    WeakView, WindowBounds,
+    div, px, rems, AppContext, Div, Element, InteractiveElement, IntoElement, Model, MouseButton,
+    ParentElement, Render, RenderOnce, Stateful, StatefulInteractiveElement, Styled, Subscription,
+    ViewContext, VisualContext, WeakView, WindowBounds,
 };
 use project::Project;
 use theme::ActiveTheme;
-use ui::{h_stack, Button, ButtonVariant, Color, KeyBinding, Label, Tooltip};
+use ui::{h_stack, Avatar, Button, ButtonVariant, Color, IconButton, KeyBinding, Tooltip};
+use util::ResultExt;
 use workspace::Workspace;
 
+use crate::face_pile::FacePile;
+
 // const MAX_PROJECT_NAME_LENGTH: usize = 40;
 // const MAX_BRANCH_NAME_LENGTH: usize = 40;
 
@@ -85,6 +88,41 @@ impl Render for CollabTitlebarItem {
     type Element = Stateful<Div>;
 
     fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
+        let is_in_room = self
+            .workspace
+            .update(cx, |this, cx| this.call_state().is_in_room(cx))
+            .unwrap_or_default();
+        let is_shared = is_in_room && self.project.read(cx).is_shared();
+        let current_user = self.user_store.read(cx).current_user();
+        let client = self.client.clone();
+        let users = self
+            .workspace
+            .update(cx, |this, cx| this.call_state().remote_participants(cx))
+            .log_err()
+            .flatten();
+        let mic_icon = if self
+            .workspace
+            .update(cx, |this, cx| this.call_state().is_muted(cx))
+            .log_err()
+            .flatten()
+            .unwrap_or_default()
+        {
+            ui::Icon::MicMute
+        } else {
+            ui::Icon::Mic
+        };
+        let speakers_icon = if self
+            .workspace
+            .update(cx, |this, cx| this.call_state().is_deafened(cx))
+            .log_err()
+            .flatten()
+            .unwrap_or_default()
+        {
+            ui::Icon::AudioOff
+        } else {
+            ui::Icon::AudioOn
+        };
+        let workspace = self.workspace.clone();
         h_stack()
             .id("titlebar")
             .justify_between()
@@ -155,8 +193,111 @@ impl Render for CollabTitlebarItem {
                                 .into()
                             }),
                     ),
-            ) // self.titlebar_item
-            .child(h_stack().child(Label::new("Right side titlebar item")))
+            )
+            .when_some(
+                users.zip(current_user.clone()),
+                |this, (remote_participants, current_user)| {
+                    let mut pile = FacePile::default();
+                    pile.extend(
+                        current_user
+                            .avatar
+                            .clone()
+                            .map(|avatar| {
+                                div().child(Avatar::data(avatar.clone())).into_any_element()
+                            })
+                            .into_iter()
+                            .chain(remote_participants.into_iter().flat_map(|(user, peer_id)| {
+                                user.avatar.as_ref().map(|avatar| {
+                                    div()
+                                        .child(
+                                            Avatar::data(avatar.clone()).into_element().into_any(),
+                                        )
+                                        .on_mouse_down(MouseButton::Left, {
+                                            let workspace = workspace.clone();
+                                            move |_, cx| {
+                                                workspace
+                                                    .update(cx, |this, cx| {
+                                                        this.open_shared_screen(peer_id, cx);
+                                                    })
+                                                    .log_err();
+                                            }
+                                        })
+                                        .into_any_element()
+                                })
+                            })),
+                    );
+                    this.child(pile.render(cx))
+                },
+            )
+            .child(div().flex_1())
+            .when(is_in_room, |this| {
+                this.child(
+                    h_stack()
+                        .child(
+                            h_stack()
+                                .child(Button::new(if is_shared { "Unshare" } else { "Share" }))
+                                .child(IconButton::new("leave-call", ui::Icon::Exit).on_click({
+                                    let workspace = workspace.clone();
+                                    move |_, cx| {
+                                        workspace
+                                            .update(cx, |this, cx| {
+                                                this.call_state().hang_up(cx).detach();
+                                            })
+                                            .log_err();
+                                    }
+                                })),
+                        )
+                        .child(
+                            h_stack()
+                                .child(IconButton::new("mute-microphone", mic_icon).on_click({
+                                    let workspace = workspace.clone();
+                                    move |_, cx| {
+                                        workspace
+                                            .update(cx, |this, cx| {
+                                                this.call_state().toggle_mute(cx);
+                                            })
+                                            .log_err();
+                                    }
+                                }))
+                                .child(IconButton::new("mute-sound", speakers_icon).on_click({
+                                    let workspace = workspace.clone();
+                                    move |_, cx| {
+                                        workspace
+                                            .update(cx, |this, cx| {
+                                                this.call_state().toggle_deafen(cx);
+                                            })
+                                            .log_err();
+                                    }
+                                }))
+                                .child(IconButton::new("screen-share", ui::Icon::Screen).on_click(
+                                    move |_, cx| {
+                                        workspace
+                                            .update(cx, |this, cx| {
+                                                this.call_state().toggle_screen_share(cx);
+                                            })
+                                            .log_err();
+                                    },
+                                ))
+                                .pl_2(),
+                        ),
+                )
+            })
+            .map(|this| {
+                if let Some(user) = current_user {
+                    this.when_some(user.avatar.clone(), |this, avatar| {
+                        this.child(ui::Avatar::data(avatar))
+                    })
+                } else {
+                    this.child(Button::new("Sign in").on_click(move |_, cx| {
+                        let client = client.clone();
+                        cx.spawn(move |cx| async move {
+                            client.authenticate_and_connect(true, &cx).await?;
+                            Ok::<(), anyhow::Error>(())
+                        })
+                        .detach_and_log_err(cx);
+                    }))
+                }
+            })
     }
 }
 

crates/collab_ui2/src/collab_ui.rs 🔗

@@ -7,11 +7,14 @@ pub mod notification_panel;
 pub mod notifications;
 mod panel_settings;
 
-use std::sync::Arc;
+use std::{rc::Rc, sync::Arc};
 
 pub use collab_panel::CollabPanel;
 pub use collab_titlebar_item::CollabTitlebarItem;
-use gpui::AppContext;
+use gpui::{
+    point, AppContext, GlobalPixels, Pixels, PlatformDisplay, Size, WindowBounds, WindowKind,
+    WindowOptions,
+};
 pub use panel_settings::{
     ChatPanelSettings, CollaborationPanelSettings, NotificationPanelSettings,
 };
@@ -23,7 +26,7 @@ use workspace::AppState;
 //     [ToggleScreenSharing, ToggleMute, ToggleDeafen, LeaveCall]
 // );
 
-pub fn init(_app_state: &Arc<AppState>, cx: &mut AppContext) {
+pub fn init(app_state: &Arc<AppState>, cx: &mut AppContext) {
     CollaborationPanelSettings::register(cx);
     ChatPanelSettings::register(cx);
     NotificationPanelSettings::register(cx);
@@ -32,7 +35,7 @@ pub fn init(_app_state: &Arc<AppState>, cx: &mut AppContext) {
     collab_titlebar_item::init(cx);
     collab_panel::init(cx);
     // chat_panel::init(cx);
-    // notifications::init(&app_state, cx);
+    notifications::init(&app_state, cx);
 
     // cx.add_global_action(toggle_screen_sharing);
     // cx.add_global_action(toggle_mute);
@@ -95,31 +98,36 @@ pub fn init(_app_state: &Arc<AppState>, cx: &mut AppContext) {
 //     }
 // }
 
-// fn notification_window_options(
-//     screen: Rc<dyn Screen>,
-//     window_size: Vector2F,
-// ) -> WindowOptions<'static> {
-//     const NOTIFICATION_PADDING: f32 = 16.;
+fn notification_window_options(
+    screen: Rc<dyn PlatformDisplay>,
+    window_size: Size<Pixels>,
+) -> WindowOptions {
+    let notification_margin_width = GlobalPixels::from(16.);
+    let notification_margin_height = GlobalPixels::from(-0.) - GlobalPixels::from(48.);
 
-//     let screen_bounds = screen.content_bounds();
-//     WindowOptions {
-//         bounds: WindowBounds::Fixed(RectF::new(
-//             screen_bounds.upper_right()
-//                 + vec2f(
-//                     -NOTIFICATION_PADDING - window_size.x(),
-//                     NOTIFICATION_PADDING,
-//                 ),
-//             window_size,
-//         )),
-//         titlebar: None,
-//         center: false,
-//         focus: false,
-//         show: true,
-//         kind: WindowKind::PopUp,
-//         is_movable: false,
-//         screen: Some(screen),
-//     }
-// }
+    let screen_bounds = screen.bounds();
+    let size: Size<GlobalPixels> = window_size.into();
+
+    // todo!() use content bounds instead of screen.bounds and get rid of magics in point's 2nd argument.
+    let bounds = gpui::Bounds::<GlobalPixels> {
+        origin: screen_bounds.upper_right()
+            - point(
+                size.width + notification_margin_width,
+                notification_margin_height,
+            ),
+        size: window_size.into(),
+    };
+    WindowOptions {
+        bounds: WindowBounds::Fixed(bounds),
+        titlebar: None,
+        center: false,
+        focus: false,
+        show: true,
+        kind: WindowKind::PopUp,
+        is_movable: false,
+        display_id: Some(screen.id()),
+    }
+}
 
 // fn render_avatar<T: 'static>(
 //     avatar: Option<Arc<ImageData>>,

crates/collab_ui2/src/face_pile.rs 🔗

@@ -1,54 +1,48 @@
-// use std::ops::Range;
+use gpui::{
+    div, AnyElement, Div, IntoElement as _, ParentElement as _, RenderOnce, Styled, WindowContext,
+};
 
-// use gpui::{
-//     geometry::{
-//         rect::RectF,
-//         vector::{vec2f, Vector2F},
-//     },
-//     json::ToJson,
-//     serde_json::{self, json},
-//     AnyElement, Axis, Element, View, ViewContext,
-// };
+#[derive(Default)]
+pub(crate) struct FacePile {
+    faces: Vec<AnyElement>,
+}
 
-// pub(crate) struct FacePile<V: View> {
-//     overlap: f32,
-//     faces: Vec<AnyElement<V>>,
-// }
+impl RenderOnce for FacePile {
+    type Rendered = Div;
 
-// impl<V: View> FacePile<V> {
-//     pub fn new(overlap: f32) -> Self {
-//         Self {
-//             overlap,
-//             faces: Vec::new(),
-//         }
-//     }
-// }
+    fn render(self, _: &mut WindowContext) -> Self::Rendered {
+        let player_count = self.faces.len();
+        let player_list = self.faces.into_iter().enumerate().map(|(ix, player)| {
+            let isnt_last = ix < player_count - 1;
 
-// impl<V: View> Element<V> for FacePile<V> {
-//     type LayoutState = ();
-//     type PaintState = ();
+            div().when(isnt_last, |div| div.neg_mr_1()).child(player)
+        });
+        div().p_1().flex().items_center().children(player_list)
+    }
+}
 
+// impl Element for FacePile {
+//     type State = ();
 //     fn layout(
 //         &mut self,
-//         constraint: gpui::SizeConstraint,
-//         view: &mut V,
-//         cx: &mut ViewContext<V>,
-//     ) -> (Vector2F, Self::LayoutState) {
-//         debug_assert!(constraint.max_along(Axis::Horizontal) == f32::INFINITY);
-
+//         state: Option<Self::State>,
+//         cx: &mut WindowContext,
+//     ) -> (LayoutId, Self::State) {
 //         let mut width = 0.;
 //         let mut max_height = 0.;
+//         let mut faces = Vec::with_capacity(self.faces.len());
 //         for face in &mut self.faces {
-//             let layout = face.layout(constraint, view, cx);
+//             let layout = face.layout(cx);
 //             width += layout.x();
 //             max_height = f32::max(max_height, layout.y());
+//             faces.push(layout);
 //         }
 //         width -= self.overlap * self.faces.len().saturating_sub(1) as f32;
-
-//         (
-//             Vector2F::new(width, max_height.clamp(1., constraint.max.y())),
-//             (),
-//         )
+//         (cx.request_layout(&Style::default(), faces), ())
+//         // (
+//         //     Vector2F::new(width, max_height.clamp(1., constraint.max.y())),
+//         //     (),
+//         // ))
 //     }
 
 //     fn paint(
@@ -77,37 +71,10 @@
 
 //         ()
 //     }
-
-//     fn rect_for_text_range(
-//         &self,
-//         _: Range<usize>,
-//         _: RectF,
-//         _: RectF,
-//         _: &Self::LayoutState,
-//         _: &Self::PaintState,
-//         _: &V,
-//         _: &ViewContext<V>,
-//     ) -> Option<RectF> {
-//         None
-//     }
-
-//     fn debug(
-//         &self,
-//         bounds: RectF,
-//         _: &Self::LayoutState,
-//         _: &Self::PaintState,
-//         _: &V,
-//         _: &ViewContext<V>,
-//     ) -> serde_json::Value {
-//         json!({
-//             "type": "FacePile",
-//             "bounds": bounds.to_json()
-//         })
-//     }
 // }
 
-// impl<V: View> Extend<AnyElement<V>> for FacePile<V> {
-//     fn extend<T: IntoIterator<Item = AnyElement<V>>>(&mut self, children: T) {
-//         self.faces.extend(children);
-//     }
-// }
+impl Extend<AnyElement> for FacePile {
+    fn extend<T: IntoIterator<Item = AnyElement>>(&mut self, children: T) {
+        self.faces.extend(children);
+    }
+}

crates/collab_ui2/src/notifications.rs 🔗

@@ -1,11 +1,11 @@
-// use gpui::AppContext;
-// use std::sync::Arc;
-// use workspace::AppState;
+use gpui::AppContext;
+use std::sync::Arc;
+use workspace::AppState;
 
-// pub mod incoming_call_notification;
+pub mod incoming_call_notification;
 // pub mod project_shared_notification;
 
-// pub fn init(app_state: &Arc<AppState>, cx: &mut AppContext) {
-//     incoming_call_notification::init(app_state, cx);
-//     project_shared_notification::init(app_state, cx);
-// }
+pub fn init(app_state: &Arc<AppState>, cx: &mut AppContext) {
+    incoming_call_notification::init(app_state, cx);
+    //project_shared_notification::init(app_state, cx);
+}

crates/collab_ui2/src/notifications/incoming_call_notification.rs 🔗

@@ -1,14 +1,12 @@
 use crate::notification_window_options;
 use call::{ActiveCall, IncomingCall};
-use client::proto;
 use futures::StreamExt;
 use gpui::{
-    elements::*,
-    geometry::vector::vec2f,
-    platform::{CursorStyle, MouseButton},
-    AnyElement, AppContext, Entity, View, ViewContext, WindowHandle,
+    div, green, px, red, AppContext, Div, Element, ParentElement, Render, RenderOnce,
+    StatefulInteractiveElement, Styled, ViewContext, VisualContext as _, WindowHandle,
 };
 use std::sync::{Arc, Weak};
+use ui::{h_stack, v_stack, Avatar, Button, Label};
 use util::ResultExt;
 use workspace::AppState;
 
@@ -19,23 +17,44 @@ pub fn init(app_state: &Arc<AppState>, cx: &mut AppContext) {
         let mut notification_windows: Vec<WindowHandle<IncomingCallNotification>> = Vec::new();
         while let Some(incoming_call) = incoming_call.next().await {
             for window in notification_windows.drain(..) {
-                window.remove(&mut cx);
+                window
+                    .update(&mut cx, |_, cx| {
+                        // todo!()
+                        cx.remove_window();
+                    })
+                    .log_err();
             }
 
             if let Some(incoming_call) = incoming_call {
-                let window_size = cx.read(|cx| {
-                    let theme = &theme::current(cx).incoming_call_notification;
-                    vec2f(theme.window_width, theme.window_height)
-                });
+                let unique_screens = cx.update(|cx| cx.displays()).unwrap();
+                let window_size = gpui::Size {
+                    width: px(380.),
+                    height: px(64.),
+                };
 
-                for screen in cx.platform().screens() {
+                for window in unique_screens {
+                    let options = notification_window_options(window, window_size);
                     let window = cx
-                        .add_window(notification_window_options(screen, window_size), |_| {
-                            IncomingCallNotification::new(incoming_call.clone(), app_state.clone())
-                        });
-
+                        .open_window(options, |cx| {
+                            cx.build_view(|_| {
+                                IncomingCallNotification::new(
+                                    incoming_call.clone(),
+                                    app_state.clone(),
+                                )
+                            })
+                        })
+                        .unwrap();
                     notification_windows.push(window);
                 }
+
+                // for screen in cx.platform().screens() {
+                //     let window = cx
+                //         .add_window(notification_window_options(screen, window_size), |_| {
+                //             IncomingCallNotification::new(incoming_call.clone(), app_state.clone())
+                //         });
+
+                //     notification_windows.push(window);
+                // }
             }
         }
     })
@@ -47,167 +66,196 @@ struct RespondToCall {
     accept: bool,
 }
 
-pub struct IncomingCallNotification {
+struct IncomingCallNotificationState {
     call: IncomingCall,
     app_state: Weak<AppState>,
 }
 
-impl IncomingCallNotification {
+pub struct IncomingCallNotification {
+    state: Arc<IncomingCallNotificationState>,
+}
+impl IncomingCallNotificationState {
     pub fn new(call: IncomingCall, app_state: Weak<AppState>) -> Self {
         Self { call, app_state }
     }
 
-    fn respond(&mut self, accept: bool, cx: &mut ViewContext<Self>) {
+    fn respond(&self, accept: bool, cx: &mut AppContext) {
         let active_call = ActiveCall::global(cx);
         if accept {
             let join = active_call.update(cx, |active_call, cx| active_call.accept_incoming(cx));
-            let caller_user_id = self.call.calling_user.id;
             let initial_project_id = self.call.initial_project.as_ref().map(|project| project.id);
             let app_state = self.app_state.clone();
-            cx.app_context()
-                .spawn(|mut cx| async move {
-                    join.await?;
-                    if let Some(project_id) = initial_project_id {
-                        cx.update(|cx| {
-                            if let Some(app_state) = app_state.upgrade() {
-                                workspace::join_remote_project(
-                                    project_id,
-                                    caller_user_id,
-                                    app_state,
-                                    cx,
-                                )
-                                .detach_and_log_err(cx);
-                            }
-                        });
-                    }
-                    anyhow::Ok(())
-                })
-                .detach_and_log_err(cx);
+            let cx: &mut AppContext = cx;
+            cx.spawn(|cx| async move {
+                join.await?;
+                if let Some(_project_id) = initial_project_id {
+                    cx.update(|_cx| {
+                        if let Some(_app_state) = app_state.upgrade() {
+                            // workspace::join_remote_project(
+                            //     project_id,
+                            //     caller_user_id,
+                            //     app_state,
+                            //     cx,
+                            // )
+                            // .detach_and_log_err(cx);
+                        }
+                    })
+                    .log_err();
+                }
+                anyhow::Ok(())
+            })
+            .detach_and_log_err(cx);
         } else {
             active_call.update(cx, |active_call, cx| {
                 active_call.decline_incoming(cx).log_err();
             });
         }
     }
+}
 
-    fn render_caller(&self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
-        let theme = &theme::current(cx).incoming_call_notification;
-        let default_project = proto::ParticipantProject::default();
-        let initial_project = self
-            .call
-            .initial_project
-            .as_ref()
-            .unwrap_or(&default_project);
-        Flex::row()
-            .with_children(self.call.calling_user.avatar.clone().map(|avatar| {
-                Image::from_data(avatar)
-                    .with_style(theme.caller_avatar)
-                    .aligned()
-            }))
-            .with_child(
-                Flex::column()
-                    .with_child(
-                        Label::new(
-                            self.call.calling_user.github_login.clone(),
-                            theme.caller_username.text.clone(),
-                        )
-                        .contained()
-                        .with_style(theme.caller_username.container),
-                    )
-                    .with_child(
-                        Label::new(
-                            format!(
-                                "is sharing a project in Zed{}",
-                                if initial_project.worktree_root_names.is_empty() {
-                                    ""
-                                } else {
-                                    ":"
-                                }
-                            ),
-                            theme.caller_message.text.clone(),
-                        )
-                        .contained()
-                        .with_style(theme.caller_message.container),
-                    )
-                    .with_children(if initial_project.worktree_root_names.is_empty() {
-                        None
-                    } else {
-                        Some(
-                            Label::new(
-                                initial_project.worktree_root_names.join(", "),
-                                theme.worktree_roots.text.clone(),
-                            )
-                            .contained()
-                            .with_style(theme.worktree_roots.container),
-                        )
-                    })
-                    .contained()
-                    .with_style(theme.caller_metadata)
-                    .aligned(),
-            )
-            .contained()
-            .with_style(theme.caller_container)
-            .flex(1., true)
-            .into_any()
+impl IncomingCallNotification {
+    pub fn new(call: IncomingCall, app_state: Weak<AppState>) -> Self {
+        Self {
+            state: Arc::new(IncomingCallNotificationState::new(call, app_state)),
+        }
     }
-
-    fn render_buttons(&self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
-        enum Accept {}
-        enum Decline {}
-
-        let theme = theme::current(cx);
-        Flex::column()
-            .with_child(
-                MouseEventHandler::new::<Accept, _>(0, cx, |_, _| {
-                    let theme = &theme.incoming_call_notification;
-                    Label::new("Accept", theme.accept_button.text.clone())
-                        .aligned()
-                        .contained()
-                        .with_style(theme.accept_button.container)
-                })
-                .with_cursor_style(CursorStyle::PointingHand)
-                .on_click(MouseButton::Left, |_, this, cx| {
-                    this.respond(true, cx);
-                })
-                .flex(1., true),
+    fn render_caller(&self, cx: &mut ViewContext<Self>) -> impl Element {
+        h_stack()
+            .children(
+                self.state
+                    .call
+                    .calling_user
+                    .avatar
+                    .as_ref()
+                    .map(|avatar| Avatar::data(avatar.clone())),
             )
-            .with_child(
-                MouseEventHandler::new::<Decline, _>(0, cx, |_, _| {
-                    let theme = &theme.incoming_call_notification;
-                    Label::new("Decline", theme.decline_button.text.clone())
-                        .aligned()
-                        .contained()
-                        .with_style(theme.decline_button.container)
-                })
-                .with_cursor_style(CursorStyle::PointingHand)
-                .on_click(MouseButton::Left, |_, this, cx| {
-                    this.respond(false, cx);
-                })
-                .flex(1., true),
+            .child(
+                v_stack()
+                    .child(Label::new(format!(
+                        "{} is sharing a project in Zed",
+                        self.state.call.calling_user.github_login
+                    )))
+                    .child(self.render_buttons(cx)),
             )
-            .constrained()
-            .with_width(theme.incoming_call_notification.button_width)
-            .into_any()
+        // let theme = &theme::current(cx).incoming_call_notification;
+        // let default_project = proto::ParticipantProject::default();
+        // let initial_project = self
+        //     .call
+        //     .initial_project
+        //     .as_ref()
+        //     .unwrap_or(&default_project);
+        // Flex::row()
+        //     .with_children(self.call.calling_user.avatar.clone().map(|avatar| {
+        //         Image::from_data(avatar)
+        //             .with_style(theme.caller_avatar)
+        //             .aligned()
+        //     }))
+        //     .with_child(
+        //         Flex::column()
+        //             .with_child(
+        //                 Label::new(
+        //                     self.call.calling_user.github_login.clone(),
+        //                     theme.caller_username.text.clone(),
+        //                 )
+        //                 .contained()
+        //                 .with_style(theme.caller_username.container),
+        //             )
+        //             .with_child(
+        //                 Label::new(
+        //                     format!(
+        //                         "is sharing a project in Zed{}",
+        //                         if initial_project.worktree_root_names.is_empty() {
+        //                             ""
+        //                         } else {
+        //                             ":"
+        //                         }
+        //                     ),
+        //                     theme.caller_message.text.clone(),
+        //                 )
+        //                 .contained()
+        //                 .with_style(theme.caller_message.container),
+        //             )
+        //             .with_children(if initial_project.worktree_root_names.is_empty() {
+        //                 None
+        //             } else {
+        //                 Some(
+        //                     Label::new(
+        //                         initial_project.worktree_root_names.join(", "),
+        //                         theme.worktree_roots.text.clone(),
+        //                     )
+        //                     .contained()
+        //                     .with_style(theme.worktree_roots.container),
+        //                 )
+        //             })
+        //             .contained()
+        //             .with_style(theme.caller_metadata)
+        //             .aligned(),
+        //     )
+        //     .contained()
+        //     .with_style(theme.caller_container)
+        //     .flex(1., true)
+        //     .into_any()
     }
-}
 
-impl Entity for IncomingCallNotification {
-    type Event = ();
-}
+    fn render_buttons(&self, cx: &mut ViewContext<Self>) -> impl Element {
+        h_stack()
+            .child(Button::new("Accept").render(cx).bg(green()).on_click({
+                let state = self.state.clone();
+                move |_, cx| state.respond(true, cx)
+            }))
+            .child(Button::new("Decline").render(cx).bg(red()).on_click({
+                let state = self.state.clone();
+                move |_, cx| state.respond(false, cx)
+            }))
 
-impl View for IncomingCallNotification {
-    fn ui_name() -> &'static str {
-        "IncomingCallNotification"
-    }
+        // enum Accept {}
+        // enum Decline {}
 
-    fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
-        let background = theme::current(cx).incoming_call_notification.background;
-        Flex::row()
-            .with_child(self.render_caller(cx))
-            .with_child(self.render_buttons(cx))
-            .contained()
-            .with_background_color(background)
-            .expanded()
-            .into_any()
+        // let theme = theme::current(cx);
+        // Flex::column()
+        //     .with_child(
+        //         MouseEventHandler::new::<Accept, _>(0, cx, |_, _| {
+        //             let theme = &theme.incoming_call_notification;
+        //             Label::new("Accept", theme.accept_button.text.clone())
+        //                 .aligned()
+        //                 .contained()
+        //                 .with_style(theme.accept_button.container)
+        //         })
+        //         .with_cursor_style(CursorStyle::PointingHand)
+        //         .on_click(MouseButton::Left, |_, this, cx| {
+        //             this.respond(true, cx);
+        //         })
+        //         .flex(1., true),
+        //     )
+        //     .with_child(
+        //         MouseEventHandler::new::<Decline, _>(0, cx, |_, _| {
+        //             let theme = &theme.incoming_call_notification;
+        //             Label::new("Decline", theme.decline_button.text.clone())
+        //                 .aligned()
+        //                 .contained()
+        //                 .with_style(theme.decline_button.container)
+        //         })
+        //         .with_cursor_style(CursorStyle::PointingHand)
+        //         .on_click(MouseButton::Left, |_, this, cx| {
+        //             this.respond(false, cx);
+        //         })
+        //         .flex(1., true),
+        //     )
+        //     .constrained()
+        //     .with_width(theme.incoming_call_notification.button_width)
+        //     .into_any()
+    }
+}
+impl Render for IncomingCallNotification {
+    type Element = Div;
+    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
+        div().bg(red()).flex_none().child(self.render_caller(cx))
+        // Flex::row()
+        //     .with_child()
+        //     .with_child(self.render_buttons(cx))
+        //     .contained()
+        //     .with_background_color(background)
+        //     .expanded()
+        //     .into_any()
     }
 }

crates/editor2/src/editor.rs 🔗

@@ -40,11 +40,12 @@ use fuzzy::{StringMatch, StringMatchCandidate};
 use git::diff_hunk_to_display;
 use gpui::{
     actions, div, point, prelude::*, px, relative, rems, size, uniform_list, Action, AnyElement,
-    AppContext, AsyncWindowContext, BackgroundExecutor, Bounds, ClipboardItem, Context, ElementId,
-    EventEmitter, FocusHandle, FocusableView, FontFeatures, FontStyle, FontWeight, HighlightStyle,
-    Hsla, InputHandler, InteractiveText, KeyContext, Model, MouseButton, ParentElement, Pixels,
-    Render, RenderOnce, SharedString, Styled, StyledText, Subscription, Task, TextRun, TextStyle,
-    UniformListScrollHandle, View, ViewContext, VisualContext, WeakView, WhiteSpace, WindowContext,
+    AppContext, AsyncWindowContext, BackgroundExecutor, Bounds, ClipboardItem, Context,
+    DispatchPhase, Div, ElementId, EventEmitter, FocusHandle, FocusableView, FontFeatures,
+    FontStyle, FontWeight, HighlightStyle, Hsla, InputHandler, InteractiveText, KeyContext, Model,
+    MouseButton, ParentElement, Pixels, Render, RenderOnce, SharedString, Styled, StyledText,
+    Subscription, Task, TextRun, TextStyle, UniformListScrollHandle, View, ViewContext,
+    VisualContext, WeakView, WhiteSpace, WindowContext,
 };
 use highlight_matching_bracket::refresh_matching_bracket_highlights;
 use hover_popover::{hide_hover, HoverState};
@@ -103,7 +104,7 @@ use util::{post_inc, RangeExt, ResultExt, TryFutureExt};
 use workspace::{
     item::{ItemEvent, ItemHandle},
     searchable::SearchEvent,
-    ItemNavHistory, SplitDirection, ViewId, Workspace,
+    ItemNavHistory, Pane, SplitDirection, ViewId, Workspace,
 };
 
 const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
@@ -662,6 +663,7 @@ pub struct Editor {
     pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
     gutter_width: Pixels,
     style: Option<EditorStyle>,
+    editor_actions: Vec<Box<dyn Fn(&mut ViewContext<Self>)>>,
 }
 
 pub struct EditorSnapshot {
@@ -1902,6 +1904,7 @@ impl Editor {
             pixel_position_of_newest_cursor: None,
             gutter_width: Default::default(),
             style: None,
+            editor_actions: Default::default(),
             _subscriptions: vec![
                 cx.observe(&buffer, Self::on_buffer_changed),
                 cx.subscribe(&buffer, Self::on_buffer_event),
@@ -2033,10 +2036,14 @@ impl Editor {
         &self.buffer
     }
 
-    fn workspace(&self) -> Option<View<Workspace>> {
+    pub fn workspace(&self) -> Option<View<Workspace>> {
         self.workspace.as_ref()?.0.upgrade()
     }
 
+    pub fn pane(&self, cx: &AppContext) -> Option<View<Pane>> {
+        self.workspace()?.read(cx).pane_for(&self.handle.upgrade()?)
+    }
+
     pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
         self.buffer().read(cx).title(cx)
     }
@@ -9193,6 +9200,26 @@ impl Editor {
         cx.emit(EditorEvent::Blurred);
         cx.notify();
     }
+
+    pub fn register_action<A: Action>(
+        &mut self,
+        listener: impl Fn(&A, &mut WindowContext) + 'static,
+    ) -> &mut Self {
+        let listener = Arc::new(listener);
+
+        self.editor_actions.push(Box::new(move |cx| {
+            let view = cx.view().clone();
+            let cx = cx.window_context();
+            let listener = listener.clone();
+            cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
+                let action = action.downcast_ref().unwrap();
+                if phase == DispatchPhase::Bubble {
+                    listener(action, cx)
+                }
+            })
+        }));
+        self
+    }
 }
 
 pub trait CollaborationHub {

crates/editor2/src/element.rs 🔗

@@ -128,6 +128,11 @@ impl EditorElement {
 
     fn register_actions(&self, cx: &mut WindowContext) {
         let view = &self.editor;
+        self.editor.update(cx, |editor, cx| {
+            for action in editor.editor_actions.iter() {
+                (action)(cx)
+            }
+        });
         register_action(view, cx, Editor::move_left);
         register_action(view, cx, Editor::move_right);
         register_action(view, cx, Editor::move_down);
@@ -4068,7 +4073,7 @@ fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
 //     }
 // }
 
-fn register_action<T: Action>(
+pub fn register_action<T: Action>(
     view: &View<Editor>,
     cx: &mut WindowContext,
     listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,

crates/go_to_line2/src/go_to_line.rs 🔗

@@ -8,7 +8,6 @@ use text::{Bias, Point};
 use theme::ActiveTheme;
 use ui::{h_stack, v_stack, Color, Label, StyledExt};
 use util::paths::FILE_ROW_COLUMN_DELIMITER;
-use workspace::Workspace;
 
 actions!(Toggle);
 
@@ -26,22 +25,24 @@ pub struct GoToLine {
 
 impl FocusableView for GoToLine {
     fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
-        self.active_editor.focus_handle(cx)
+        self.line_editor.focus_handle(cx)
     }
 }
 impl EventEmitter<DismissEvent> for GoToLine {}
 
 impl GoToLine {
-    fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
-        workspace.register_action(|workspace, _: &Toggle, cx| {
-            let Some(editor) = workspace
-                .active_item(cx)
-                .and_then(|active_item| active_item.downcast::<Editor>())
-            else {
+    fn register(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
+        let handle = cx.view().downgrade();
+        editor.register_action(move |_: &Toggle, cx| {
+            let Some(editor) = handle.upgrade() else {
                 return;
             };
-
-            workspace.toggle_modal(cx, move |cx| GoToLine::new(editor, cx));
+            let Some(workspace) = editor.read(cx).workspace() else {
+                return;
+            };
+            workspace.update(cx, |workspace, cx| {
+                workspace.toggle_modal(cx, move |cx| GoToLine::new(editor, cx));
+            })
         });
     }
 

crates/gpui2/src/app.rs 🔗

@@ -580,7 +580,7 @@ impl AppContext {
             .windows
             .iter()
             .filter_map(|(_, window)| {
-                let window = window.as_ref().unwrap();
+                let window = window.as_ref()?;
                 if window.dirty {
                     Some(window.handle.clone())
                 } else {
@@ -1049,7 +1049,9 @@ impl Context for AppContext {
             let root_view = window.root_view.clone().unwrap();
             let result = update(root_view, &mut WindowContext::new(cx, &mut window));
 
-            if !window.removed {
+            if window.removed {
+                cx.windows.remove(handle.id);
+            } else {
                 cx.windows
                     .get_mut(handle.id)
                     .ok_or_else(|| anyhow!("window not found"))?

crates/gpui2/src/elements/img.rs 🔗

@@ -1,30 +1,59 @@
+use std::sync::Arc;
+
 use crate::{
-    Bounds, Element, InteractiveElement, InteractiveElementState, Interactivity, IntoElement,
-    LayoutId, Pixels, SharedString, StyleRefinement, Styled, WindowContext,
+    Bounds, Element, ImageData, InteractiveElement, InteractiveElementState, Interactivity,
+    IntoElement, LayoutId, Pixels, SharedString, StyleRefinement, Styled, WindowContext,
 };
 use futures::FutureExt;
 use util::ResultExt;
 
+#[derive(Clone, Debug)]
+pub enum ImageSource {
+    /// Image content will be loaded from provided URI at render time.
+    Uri(SharedString),
+    Data(Arc<ImageData>),
+}
+
+impl From<SharedString> for ImageSource {
+    fn from(value: SharedString) -> Self {
+        Self::Uri(value)
+    }
+}
+
+impl From<Arc<ImageData>> for ImageSource {
+    fn from(value: Arc<ImageData>) -> Self {
+        Self::Data(value)
+    }
+}
+
 pub struct Img {
     interactivity: Interactivity,
-    uri: Option<SharedString>,
+    source: Option<ImageSource>,
     grayscale: bool,
 }
 
 pub fn img() -> Img {
     Img {
         interactivity: Interactivity::default(),
-        uri: None,
+        source: None,
         grayscale: false,
     }
 }
 
 impl Img {
     pub fn uri(mut self, uri: impl Into<SharedString>) -> Self {
-        self.uri = Some(uri.into());
+        self.source = Some(ImageSource::from(uri.into()));
+        self
+    }
+    pub fn data(mut self, data: Arc<ImageData>) -> Self {
+        self.source = Some(ImageSource::from(data));
         self
     }
 
+    pub fn source(mut self, source: impl Into<ImageSource>) -> Self {
+        self.source = Some(source.into());
+        self
+    }
     pub fn grayscale(mut self, grayscale: bool) -> Self {
         self.grayscale = grayscale;
         self
@@ -58,28 +87,33 @@ impl Element for Img {
             |style, _scroll_offset, cx| {
                 let corner_radii = style.corner_radii;
 
-                if let Some(uri) = self.uri.clone() {
-                    // eprintln!(">>> image_cache.get({uri}");
-                    let image_future = cx.image_cache.get(uri.clone());
-                    // eprintln!("<<< image_cache.get({uri}");
-                    if let Some(data) = image_future
-                        .clone()
-                        .now_or_never()
-                        .and_then(|result| result.ok())
-                    {
-                        let corner_radii = corner_radii.to_pixels(bounds.size, cx.rem_size());
-                        cx.with_z_index(1, |cx| {
-                            cx.paint_image(bounds, corner_radii, data, self.grayscale)
-                                .log_err()
-                        });
-                    } else {
-                        cx.spawn(|mut cx| async move {
-                            if image_future.await.ok().is_some() {
-                                cx.on_next_frame(|cx| cx.notify());
+                if let Some(source) = self.source {
+                    let image = match source {
+                        ImageSource::Uri(uri) => {
+                            let image_future = cx.image_cache.get(uri.clone());
+                            if let Some(data) = image_future
+                                .clone()
+                                .now_or_never()
+                                .and_then(|result| result.ok())
+                            {
+                                data
+                            } else {
+                                cx.spawn(|mut cx| async move {
+                                    if image_future.await.ok().is_some() {
+                                        cx.on_next_frame(|cx| cx.notify());
+                                    }
+                                })
+                                .detach();
+                                return;
                             }
-                        })
-                        .detach()
-                    }
+                        }
+                        ImageSource::Data(image) => image,
+                    };
+                    let corner_radii = corner_radii.to_pixels(bounds.size, cx.rem_size());
+                    cx.with_z_index(1, |cx| {
+                        cx.paint_image(bounds, corner_radii, image, self.grayscale)
+                            .log_err()
+                    });
                 }
             },
         )

crates/gpui2/src/elements/uniform_list.rs 🔗

@@ -9,7 +9,7 @@ use taffy::style::Overflow;
 
 /// uniform_list provides lazy rendering for a set of items that are of uniform height.
 /// When rendered into a container with overflow-y: hidden and a fixed (or max) height,
-/// uniform_list will only render the visibile subset of items.
+/// uniform_list will only render the visible subset of items.
 pub fn uniform_list<I, R, V>(
     view: View<V>,
     id: I,

crates/gpui2/src/platform/mac/window.rs 🔗

@@ -683,6 +683,9 @@ impl Drop for MacWindow {
         this.executor
             .spawn(async move {
                 unsafe {
+                    // todo!() this panic()s when you click the red close button
+                    // unless should_close returns false.
+                    // (luckliy in zed it always returns false)
                     window.close();
                 }
             })

crates/gpui2/src/window.rs 🔗

@@ -1517,6 +1517,13 @@ impl<'a> WindowContext<'a> {
                 .set_input_handler(Box::new(input_handler));
         }
     }
+
+    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
+        let mut this = self.to_async();
+        self.window
+            .platform_window
+            .on_should_close(Box::new(move || this.update(|_, cx| f(cx)).unwrap_or(true)))
+    }
 }
 
 impl Context for WindowContext<'_> {

crates/language/src/highlight_map.rs 🔗

@@ -11,7 +11,7 @@ pub struct HighlightId(pub u32);
 const DEFAULT_SYNTAX_HIGHLIGHT_ID: HighlightId = HighlightId(u32::MAX);
 
 impl HighlightMap {
-    pub fn new(capture_names: &[String], theme: &SyntaxTheme) -> Self {
+    pub fn new(capture_names: &[&str], theme: &SyntaxTheme) -> Self {
         // For each capture name in the highlight query, find the longest
         // key in the theme's syntax styles that matches all of the
         // dot-separated components of the capture name.
@@ -98,9 +98,9 @@ mod tests {
         );
 
         let capture_names = &[
-            "function.special".to_string(),
-            "function.async.rust".to_string(),
-            "variable.builtin.self".to_string(),
+            "function.special",
+            "function.async.rust",
+            "variable.builtin.self",
         ];
 
         let map = HighlightMap::new(capture_names, &theme);

crates/language/src/language.rs 🔗

@@ -1383,7 +1383,7 @@ impl Language {
         let query = Query::new(self.grammar_mut().ts_language, source)?;
 
         let mut override_configs_by_id = HashMap::default();
-        for (ix, name) in query.capture_names().iter().enumerate() {
+        for (ix, name) in query.capture_names().iter().copied().enumerate() {
             if !name.starts_with('_') {
                 let value = self.config.overrides.remove(name).unwrap_or_default();
                 for server_name in &value.opt_into_language_servers {
@@ -1396,7 +1396,7 @@ impl Language {
                     }
                 }
 
-                override_configs_by_id.insert(ix as u32, (name.clone(), value));
+                override_configs_by_id.insert(ix as u32, (name.into(), value));
             }
         }
 

crates/language/src/syntax_map/syntax_map_tests.rs 🔗

@@ -1300,7 +1300,7 @@ fn assert_capture_ranges(
         .collect::<Vec<_>>();
     for capture in captures {
         let name = &queries[capture.grammar_index].capture_names()[capture.index as usize];
-        if highlight_query_capture_names.contains(&name.as_str()) {
+        if highlight_query_capture_names.contains(&name) {
             actual_ranges.push(capture.node.byte_range());
         }
     }

crates/language2/src/highlight_map.rs 🔗

@@ -11,7 +11,7 @@ pub struct HighlightId(pub u32);
 const DEFAULT_SYNTAX_HIGHLIGHT_ID: HighlightId = HighlightId(u32::MAX);
 
 impl HighlightMap {
-    pub fn new(capture_names: &[String], theme: &SyntaxTheme) -> Self {
+    pub fn new(capture_names: &[&str], theme: &SyntaxTheme) -> Self {
         // For each capture name in the highlight query, find the longest
         // key in the theme's syntax styles that matches all of the
         // dot-separated components of the capture name.
@@ -100,9 +100,9 @@ mod tests {
         };
 
         let capture_names = &[
-            "function.special".to_string(),
-            "function.async.rust".to_string(),
-            "variable.builtin.self".to_string(),
+            "function.special",
+            "function.async.rust",
+            "variable.builtin.self",
         ];
 
         let map = HighlightMap::new(capture_names, &theme);

crates/language2/src/language2.rs 🔗

@@ -1391,7 +1391,7 @@ impl Language {
         let mut override_configs_by_id = HashMap::default();
         for (ix, name) in query.capture_names().iter().enumerate() {
             if !name.starts_with('_') {
-                let value = self.config.overrides.remove(name).unwrap_or_default();
+                let value = self.config.overrides.remove(*name).unwrap_or_default();
                 for server_name in &value.opt_into_language_servers {
                     if !self
                         .config
@@ -1402,7 +1402,7 @@ impl Language {
                     }
                 }
 
-                override_configs_by_id.insert(ix as u32, (name.clone(), value));
+                override_configs_by_id.insert(ix as u32, (name.to_string(), value));
             }
         }
 

crates/language2/src/syntax_map/syntax_map_tests.rs 🔗

@@ -1300,7 +1300,7 @@ fn assert_capture_ranges(
         .collect::<Vec<_>>();
     for capture in captures {
         let name = &queries[capture.grammar_index].capture_names()[capture.index as usize];
-        if highlight_query_capture_names.contains(&name.as_str()) {
+        if highlight_query_capture_names.contains(&name) {
             actual_ranges.push(capture.node.byte_range());
         }
     }

crates/picker2/src/picker2.rs 🔗

@@ -114,6 +114,7 @@ impl<D: PickerDelegate> Picker<D> {
     }
 
     fn cancel(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
+        dbg!("canceling!");
         self.delegate.dismissed(cx);
     }
 

crates/project_panel2/src/project_panel.rs 🔗

@@ -644,6 +644,7 @@ impl ProjectPanel {
     }
 
     fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
+        dbg!("odd");
         self.edit_state = None;
         self.update_visible_entries(None, cx);
         cx.focus(&self.focus_handle);

crates/search2/src/buffer_search.rs 🔗

@@ -7,12 +7,12 @@ use crate::{
     ToggleCaseSensitive, ToggleReplace, ToggleWholeWord,
 };
 use collections::HashMap;
-use editor::Editor;
+use editor::{Editor, EditorMode};
 use futures::channel::oneshot;
 use gpui::{
     actions, div, red, Action, AppContext, Div, EventEmitter, InteractiveElement as _, IntoElement,
     ParentElement as _, Render, Styled, Subscription, Task, View, ViewContext, VisualContext as _,
-    WindowContext,
+    WeakView, WindowContext,
 };
 use project::search::SearchQuery;
 use serde::Deserialize;
@@ -23,7 +23,7 @@ use util::ResultExt;
 use workspace::{
     item::ItemHandle,
     searchable::{Direction, SearchEvent, SearchableItemHandle, WeakSearchableItemHandle},
-    ToolbarItemLocation, ToolbarItemView, Workspace,
+    ToolbarItemLocation, ToolbarItemView,
 };
 
 #[derive(PartialEq, Clone, Deserialize, Default, Action)]
@@ -38,7 +38,7 @@ pub enum Event {
 }
 
 pub fn init(cx: &mut AppContext) {
-    cx.observe_new_views(|workspace: &mut Workspace, _| BufferSearchBar::register(workspace))
+    cx.observe_new_views(|editor: &mut Editor, cx| BufferSearchBar::register(editor, cx))
         .detach();
 }
 
@@ -187,6 +187,7 @@ impl Render for BufferSearchBar {
             })
             .on_action(cx.listener(Self::previous_history_query))
             .on_action(cx.listener(Self::next_history_query))
+            .on_action(cx.listener(Self::dismiss))
             .w_full()
             .p_1()
             .child(
@@ -294,9 +295,19 @@ impl ToolbarItemView for BufferSearchBar {
 }
 
 impl BufferSearchBar {
-    pub fn register(workspace: &mut Workspace) {
-        workspace.register_action(|workspace, a: &Deploy, cx| {
-            workspace.active_pane().update(cx, |this, cx| {
+    pub fn register(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
+        if editor.mode() != EditorMode::Full {
+            return;
+        };
+
+        let handle = cx.view().downgrade();
+
+        editor.register_action(move |a: &Deploy, cx| {
+            let Some(pane) = handle.upgrade().and_then(|editor| editor.read(cx).pane(cx)) else {
+                return;
+            };
+
+            pane.update(cx, |this, cx| {
                 this.toolbar().update(cx, |this, cx| {
                     if let Some(search_bar) = this.item_of_type::<BufferSearchBar>() {
                         search_bar.update(cx, |this, cx| {
@@ -316,11 +327,16 @@ impl BufferSearchBar {
             });
         });
         fn register_action<A: Action>(
-            workspace: &mut Workspace,
+            editor: &mut Editor,
+            handle: WeakView<Editor>,
             update: fn(&mut BufferSearchBar, &A, &mut ViewContext<BufferSearchBar>),
         ) {
-            workspace.register_action(move |workspace, action: &A, cx| {
-                workspace.active_pane().update(cx, move |this, cx| {
+            editor.register_action(move |action: &A, cx| {
+                let Some(pane) = handle.upgrade().and_then(|editor| editor.read(cx).pane(cx))
+                else {
+                    return;
+                };
+                pane.update(cx, move |this, cx| {
                     this.toolbar().update(cx, move |this, cx| {
                         if let Some(search_bar) = this.item_of_type::<BufferSearchBar>() {
                             search_bar.update(cx, move |this, cx| update(this, action, cx));
@@ -331,49 +347,76 @@ impl BufferSearchBar {
             });
         }
 
-        register_action(workspace, |this, action: &ToggleCaseSensitive, cx| {
-            if this.supported_options().case {
-                this.toggle_case_sensitive(action, cx);
-            }
-        });
-        register_action(workspace, |this, action: &ToggleWholeWord, cx| {
-            if this.supported_options().word {
-                this.toggle_whole_word(action, cx);
-            }
-        });
-        register_action(workspace, |this, action: &ToggleReplace, cx| {
-            if this.supported_options().replacement {
-                this.toggle_replace(action, cx);
-            }
-        });
-        register_action(workspace, |this, _: &ActivateRegexMode, cx| {
+        let handle = cx.view().downgrade();
+        register_action(
+            editor,
+            handle.clone(),
+            |this, action: &ToggleCaseSensitive, cx| {
+                if this.supported_options().case {
+                    this.toggle_case_sensitive(action, cx);
+                }
+            },
+        );
+        register_action(
+            editor,
+            handle.clone(),
+            |this, action: &ToggleWholeWord, cx| {
+                if this.supported_options().word {
+                    this.toggle_whole_word(action, cx);
+                }
+            },
+        );
+        register_action(
+            editor,
+            handle.clone(),
+            |this, action: &ToggleReplace, cx| {
+                if this.supported_options().replacement {
+                    this.toggle_replace(action, cx);
+                }
+            },
+        );
+        register_action(editor, handle.clone(), |this, _: &ActivateRegexMode, cx| {
             if this.supported_options().regex {
                 this.activate_search_mode(SearchMode::Regex, cx);
             }
         });
-        register_action(workspace, |this, _: &ActivateTextMode, cx| {
+        register_action(editor, handle.clone(), |this, _: &ActivateTextMode, cx| {
             this.activate_search_mode(SearchMode::Text, cx);
         });
-        register_action(workspace, |this, action: &CycleMode, cx| {
+        register_action(editor, handle.clone(), |this, action: &CycleMode, cx| {
             if this.supported_options().regex {
                 // If regex is not supported then search has just one mode (text) - in that case there's no point in supporting
                 // cycling.
                 this.cycle_mode(action, cx)
             }
         });
-        register_action(workspace, |this, action: &SelectNextMatch, cx| {
-            this.select_next_match(action, cx);
-        });
-        register_action(workspace, |this, action: &SelectPrevMatch, cx| {
-            this.select_prev_match(action, cx);
-        });
-        register_action(workspace, |this, action: &SelectAllMatches, cx| {
-            this.select_all_matches(action, cx);
-        });
-        register_action(workspace, |this, _: &editor::Cancel, cx| {
+        register_action(
+            editor,
+            handle.clone(),
+            |this, action: &SelectNextMatch, cx| {
+                this.select_next_match(action, cx);
+            },
+        );
+        register_action(
+            editor,
+            handle.clone(),
+            |this, action: &SelectPrevMatch, cx| {
+                this.select_prev_match(action, cx);
+            },
+        );
+        register_action(
+            editor,
+            handle.clone(),
+            |this, action: &SelectAllMatches, cx| {
+                this.select_all_matches(action, cx);
+            },
+        );
+        register_action(editor, handle.clone(), |this, _: &editor::Cancel, cx| {
             if !this.dismissed {
                 this.dismiss(&Dismiss, cx);
+                return;
             }
+            cx.propagate();
         });
     }
     pub fn new(cx: &mut ViewContext<Self>) -> Self {

crates/semantic_index/src/semantic_index_tests.rs 🔗

@@ -1659,13 +1659,13 @@ fn elixir_lang() -> Arc<Language> {
                 target: (identifier) @name)
                 operator: "when")
                 ])
-                (#match? @name "^(def|defp|defdelegate|defguard|defguardp|defmacro|defmacrop|defn|defnp)$")) @item
+                (#any-match? @name "^(def|defp|defdelegate|defguard|defguardp|defmacro|defmacrop|defn|defnp)$")) @item
                 )
 
             (call
                 target: (identifier) @name
                 (arguments (alias) @name)
-                (#match? @name "^(defmodule|defprotocol)$")) @item
+                (#any-match? @name "^(defmodule|defprotocol)$")) @item
             "#,
         )
         .unwrap(),

crates/storybook2/src/story_selector.rs 🔗

@@ -8,7 +8,6 @@ use clap::ValueEnum;
 use gpui::{AnyView, VisualContext};
 use strum::{EnumIter, EnumString, IntoEnumIterator};
 use ui::prelude::*;
-use ui::{AvatarStory, ButtonStory, IconStory, InputStory, LabelStory};
 
 #[derive(Debug, PartialEq, Eq, Clone, Copy, strum::Display, EnumString, EnumIter)]
 #[strum(serialize_all = "snake_case")]
@@ -22,6 +21,7 @@ pub enum ComponentStory {
     Input,
     Keybinding,
     Label,
+    ListItem,
     Scroll,
     Text,
     ZIndex,
@@ -31,15 +31,16 @@ pub enum ComponentStory {
 impl ComponentStory {
     pub fn story(&self, cx: &mut WindowContext) -> AnyView {
         match self {
-            Self::Avatar => cx.build_view(|_| AvatarStory).into(),
-            Self::Button => cx.build_view(|_| ButtonStory).into(),
+            Self::Avatar => cx.build_view(|_| ui::AvatarStory).into(),
+            Self::Button => cx.build_view(|_| ui::ButtonStory).into(),
             Self::Checkbox => cx.build_view(|_| ui::CheckboxStory).into(),
             Self::ContextMenu => cx.build_view(|_| ui::ContextMenuStory).into(),
             Self::Focus => FocusStory::view(cx).into(),
-            Self::Icon => cx.build_view(|_| IconStory).into(),
-            Self::Input => cx.build_view(|_| InputStory).into(),
+            Self::Icon => cx.build_view(|_| ui::IconStory).into(),
+            Self::Input => cx.build_view(|_| ui::InputStory).into(),
             Self::Keybinding => cx.build_view(|_| ui::KeybindingStory).into(),
-            Self::Label => cx.build_view(|_| LabelStory).into(),
+            Self::Label => cx.build_view(|_| ui::LabelStory).into(),
+            Self::ListItem => cx.build_view(|_| ui::ListItemStory).into(),
             Self::Scroll => ScrollStory::view(cx).into(),
             Self::Text => TextStory::view(cx).into(),
             Self::ZIndex => cx.build_view(|_| ZIndexStory).into(),

crates/ui2/src/components/avatar.rs 🔗

@@ -1,5 +1,7 @@
+use std::sync::Arc;
+
 use crate::prelude::*;
-use gpui::{img, Img, IntoElement};
+use gpui::{img, ImageData, ImageSource, Img, IntoElement};
 
 #[derive(Debug, Default, PartialEq, Clone)]
 pub enum Shape {
@@ -10,7 +12,7 @@ pub enum Shape {
 
 #[derive(IntoElement)]
 pub struct Avatar {
-    src: SharedString,
+    src: ImageSource,
     shape: Shape,
 }
 
@@ -26,7 +28,7 @@ impl RenderOnce for Avatar {
             img = img.rounded_md();
         }
 
-        img.uri(self.src.clone())
+        img.source(self.src.clone())
             .size_4()
             // todo!(Pull the avatar fallback background from the theme.)
             .bg(gpui::red())
@@ -34,7 +36,13 @@ impl RenderOnce for Avatar {
 }
 
 impl Avatar {
-    pub fn new(src: impl Into<SharedString>) -> Self {
+    pub fn uri(src: impl Into<SharedString>) -> Self {
+        Self {
+            src: src.into().into(),
+            shape: Shape::Circle,
+        }
+    }
+    pub fn data(src: Arc<ImageData>) -> Self {
         Self {
             src: src.into(),
             shape: Shape::Circle,

crates/ui2/src/components/list.rs 🔗

@@ -323,8 +323,8 @@ impl RenderOnce for ListItem {
                         .color(Color::Muted),
                 ),
             ),
-            Some(GraphicSlot::Avatar(src)) => Some(h_stack().child(Avatar::new(src))),
-            Some(GraphicSlot::PublicActor(src)) => Some(h_stack().child(Avatar::new(src))),
+            Some(GraphicSlot::Avatar(src)) => Some(h_stack().child(Avatar::uri(src))),
+            Some(GraphicSlot::PublicActor(src)) => Some(h_stack().child(Avatar::uri(src))),
             None => None,
         };
 

crates/ui2/src/components/stories.rs 🔗

@@ -6,6 +6,7 @@ mod icon;
 mod input;
 mod keybinding;
 mod label;
+mod list_item;
 
 pub use avatar::*;
 pub use button::*;
@@ -15,3 +16,4 @@ pub use icon::*;
 pub use input::*;
 pub use keybinding::*;
 pub use label::*;
+pub use list_item::*;

crates/ui2/src/components/stories/avatar.rs 🔗

@@ -13,10 +13,10 @@ impl Render for AvatarStory {
         Story::container()
             .child(Story::title_for::<Avatar>())
             .child(Story::label("Default"))
-            .child(Avatar::new(
+            .child(Avatar::uri(
                 "https://avatars.githubusercontent.com/u/1714999?v=4",
             ))
-            .child(Avatar::new(
+            .child(Avatar::uri(
                 "https://avatars.githubusercontent.com/u/326587?v=4",
             ))
     }

crates/ui2/src/components/stories/list_item.rs 🔗

@@ -0,0 +1,26 @@
+use gpui::{Div, Render};
+use story::Story;
+
+use crate::prelude::*;
+use crate::ListItem;
+
+pub struct ListItemStory;
+
+impl Render for ListItemStory {
+    type Element = Div;
+
+    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
+        Story::container()
+            .child(Story::title_for::<ListItem>())
+            .child(Story::label("Default"))
+            .child(ListItem::new("hello_world").child("Hello, world!"))
+            .child(Story::label("With `on_click`"))
+            .child(
+                ListItem::new("with_on_click")
+                    .child("Click me")
+                    .on_click(|_event, _cx| {
+                        println!("Clicked!");
+                    }),
+            )
+    }
+}

crates/util/src/channel.rs 🔗

@@ -19,7 +19,7 @@ lazy_static! {
 
 pub struct AppCommitSha(pub String);
 
-#[derive(Copy, Clone, PartialEq, Eq, Default)]
+#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
 pub enum ReleaseChannel {
     #[default]
     Dev,

crates/workspace/src/workspace.rs 🔗

@@ -56,14 +56,16 @@ use std::{
 };
 
 use crate::{
-    notifications::{simple_message_notification::MessageNotification, NotificationTracker},
+    notifications::NotificationTracker,
     persistence::model::{
         DockData, DockStructure, SerializedPane, SerializedPaneGroup, SerializedWorkspace,
     },
 };
 use dock::{Dock, DockPosition, Panel, PanelButtons, PanelHandle};
 use lazy_static::lazy_static;
-use notifications::{simple_message_notification, NotificationHandle, NotifyResultExt};
+use notifications::{
+    simple_message_notification::MessageNotification, NotificationHandle, NotifyResultExt,
+};
 pub use pane::*;
 pub use pane_group::*;
 use persistence::{model::SerializedItem, DB};
@@ -778,20 +780,6 @@ impl Workspace {
 
         cx.defer(|this, cx| {
             this.update_window_title(cx);
-
-            this.show_notification(0, cx, |cx| {
-                cx.add_view(|_cx| {
-                    simple_message_notification::MessageNotification::new(format!(
-                        "Error: what happens if this message is very very very very very long "
-                    ))
-                    .with_click_message("Click here because!")
-                })
-            });
-            this.show_notification(1, cx, |cx| {
-                cx.add_view(|_cx| {
-                    simple_message_notification::MessageNotification::new(format!("Nope"))
-                })
-            });
         });
         Workspace {
             weak_self: weak_handle.clone(),

crates/workspace2/src/modal_layer.rs 🔗

@@ -46,6 +46,7 @@ impl ModalLayer {
             previous_focus_handle: cx.focused(),
             focus_handle: cx.focus_handle(),
         });
+        dbg!("focusing");
         cx.focus_view(&new_modal);
         cx.notify();
     }

crates/workspace2/src/shared_screen.rs 🔗

@@ -1,151 +0,0 @@
-use crate::{
-    item::{Item, ItemEvent},
-    ItemNavHistory, WorkspaceId,
-};
-use anyhow::Result;
-use call::participant::{Frame, RemoteVideoTrack};
-use client::{proto::PeerId, User};
-use futures::StreamExt;
-use gpui::{
-    elements::*,
-    geometry::{rect::RectF, vector::vec2f},
-    platform::MouseButton,
-    AppContext, Entity, Task, View, ViewContext,
-};
-use smallvec::SmallVec;
-use std::{
-    borrow::Cow,
-    sync::{Arc, Weak},
-};
-
-pub enum Event {
-    Close,
-}
-
-pub struct SharedScreen {
-    track: Weak<RemoteVideoTrack>,
-    frame: Option<Frame>,
-    pub peer_id: PeerId,
-    user: Arc<User>,
-    nav_history: Option<ItemNavHistory>,
-    _maintain_frame: Task<Result<()>>,
-}
-
-impl SharedScreen {
-    pub fn new(
-        track: &Arc<RemoteVideoTrack>,
-        peer_id: PeerId,
-        user: Arc<User>,
-        cx: &mut ViewContext<Self>,
-    ) -> Self {
-        let mut frames = track.frames();
-        Self {
-            track: Arc::downgrade(track),
-            frame: None,
-            peer_id,
-            user,
-            nav_history: Default::default(),
-            _maintain_frame: cx.spawn(|this, mut cx| async move {
-                while let Some(frame) = frames.next().await {
-                    this.update(&mut cx, |this, cx| {
-                        this.frame = Some(frame);
-                        cx.notify();
-                    })?;
-                }
-                this.update(&mut cx, |_, cx| cx.emit(Event::Close))?;
-                Ok(())
-            }),
-        }
-    }
-}
-
-impl Entity for SharedScreen {
-    type Event = Event;
-}
-
-impl View for SharedScreen {
-    fn ui_name() -> &'static str {
-        "SharedScreen"
-    }
-
-    fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
-        enum Focus {}
-
-        let frame = self.frame.clone();
-        MouseEventHandler::new::<Focus, _>(0, cx, |_, cx| {
-            Canvas::new(move |bounds, _, _, cx| {
-                if let Some(frame) = frame.clone() {
-                    let size = constrain_size_preserving_aspect_ratio(
-                        bounds.size(),
-                        vec2f(frame.width() as f32, frame.height() as f32),
-                    );
-                    let origin = bounds.origin() + (bounds.size() / 2.) - size / 2.;
-                    cx.scene().push_surface(gpui::platform::mac::Surface {
-                        bounds: RectF::new(origin, size),
-                        image_buffer: frame.image(),
-                    });
-                }
-            })
-            .contained()
-            .with_style(theme::current(cx).shared_screen)
-        })
-        .on_down(MouseButton::Left, |_, _, cx| cx.focus_parent())
-        .into_any()
-    }
-}
-
-impl Item for SharedScreen {
-    fn tab_tooltip_text(&self, _: &AppContext) -> Option<Cow<str>> {
-        Some(format!("{}'s screen", self.user.github_login).into())
-    }
-    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
-        if let Some(nav_history) = self.nav_history.as_mut() {
-            nav_history.push::<()>(None, cx);
-        }
-    }
-
-    fn tab_content<V: 'static>(
-        &self,
-        _: Option<usize>,
-        style: &theme::Tab,
-        _: &AppContext,
-    ) -> gpui::AnyElement<V> {
-        Flex::row()
-            .with_child(
-                Svg::new("icons/desktop.svg")
-                    .with_color(style.label.text.color)
-                    .constrained()
-                    .with_width(style.type_icon_width)
-                    .aligned()
-                    .contained()
-                    .with_margin_right(style.spacing),
-            )
-            .with_child(
-                Label::new(
-                    format!("{}'s screen", self.user.github_login),
-                    style.label.clone(),
-                )
-                .aligned(),
-            )
-            .into_any()
-    }
-
-    fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
-        self.nav_history = Some(history);
-    }
-
-    fn clone_on_split(
-        &self,
-        _workspace_id: WorkspaceId,
-        cx: &mut ViewContext<Self>,
-    ) -> Option<Self> {
-        let track = self.track.upgrade()?;
-        Some(Self::new(&track, self.peer_id, self.user.clone(), cx))
-    }
-
-    fn to_item_events(event: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
-        match event {
-            Event::Close => smallvec::smallvec!(ItemEvent::CloseItem),
-        }
-    }
-}

crates/workspace2/src/workspace2.rs 🔗

@@ -9,7 +9,6 @@ pub mod pane_group;
 mod persistence;
 pub mod searchable;
 // todo!()
-// pub mod shared_screen;
 mod modal_layer;
 mod status_bar;
 mod toolbar;
@@ -19,7 +18,7 @@ use anyhow::{anyhow, Context as _, Result};
 use async_trait::async_trait;
 use client2::{
     proto::{self, PeerId},
-    Client, TypedEnvelope, UserStore,
+    Client, TypedEnvelope, User, UserStore,
 };
 use collections::{hash_map, HashMap, HashSet};
 use dock::{Dock, DockPosition, Panel, PanelButtons, PanelHandle};
@@ -344,14 +343,42 @@ impl CallHandler for TestCallHandler {
         None
     }
 
-    fn hang_up(&self, cx: AsyncWindowContext) -> Result<Task<Result<()>>> {
-        anyhow::bail!("TestCallHandler should not be hanging up")
+    fn hang_up(&self, cx: &mut AppContext) -> Task<Result<()>> {
+        Task::ready(Err(anyhow!("TestCallHandler should not be hanging up")))
     }
 
     fn active_project(&self, cx: &AppContext) -> Option<WeakModel<Project>> {
         None
     }
+
+    fn invite(
+        &mut self,
+        called_user_id: u64,
+        initial_project: Option<Model<Project>>,
+        cx: &mut AppContext,
+    ) -> Task<Result<()>> {
+        unimplemented!()
+    }
+
+    fn remote_participants(&self, cx: &AppContext) -> Option<Vec<(Arc<User>, PeerId)>> {
+        None
+    }
+
+    fn is_muted(&self, cx: &AppContext) -> Option<bool> {
+        None
+    }
+
+    fn toggle_mute(&self, cx: &mut AppContext) {}
+
+    fn toggle_screen_share(&self, cx: &mut AppContext) {}
+
+    fn toggle_deafen(&self, cx: &mut AppContext) {}
+
+    fn is_deafened(&self, cx: &AppContext) -> Option<bool> {
+        None
+    }
 }
+
 impl AppState {
     #[cfg(any(test, feature = "test-support"))]
     pub fn test(cx: &mut AppContext) -> Arc<Self> {
@@ -452,8 +479,20 @@ pub trait CallHandler {
     fn is_in_room(&self, cx: &mut ViewContext<Workspace>) -> bool {
         self.room_id(cx).is_some()
     }
-    fn hang_up(&self, cx: AsyncWindowContext) -> Result<Task<Result<()>>>;
+    fn hang_up(&self, cx: &mut AppContext) -> Task<Result<()>>;
     fn active_project(&self, cx: &AppContext) -> Option<WeakModel<Project>>;
+    fn invite(
+        &mut self,
+        called_user_id: u64,
+        initial_project: Option<Model<Project>>,
+        cx: &mut AppContext,
+    ) -> Task<Result<()>>;
+    fn remote_participants(&self, cx: &AppContext) -> Option<Vec<(Arc<User>, PeerId)>>;
+    fn is_muted(&self, cx: &AppContext) -> Option<bool>;
+    fn is_deafened(&self, cx: &AppContext) -> Option<bool>;
+    fn toggle_mute(&self, cx: &mut AppContext);
+    fn toggle_deafen(&self, cx: &mut AppContext);
+    fn toggle_screen_share(&self, cx: &mut AppContext);
 }
 
 pub struct Workspace {
@@ -1197,7 +1236,7 @@ impl Workspace {
                 if answer.await.log_err() == Some(1) {
                     return anyhow::Ok(false);
                 } else {
-                    this.update(&mut cx, |this, cx| this.call_handler.hang_up(cx.to_async()))??
+                    this.update(&mut cx, |this, cx| this.call_handler.hang_up(cx))?
                         .await
                         .log_err();
                 }
@@ -1981,13 +2020,13 @@ impl Workspace {
         item
     }
 
-    //     pub fn open_shared_screen(&mut self, peer_id: PeerId, cx: &mut ViewContext<Self>) {
-    //         if let Some(shared_screen) = self.shared_screen_for_peer(peer_id, &self.active_pane, cx) {
-    //             self.active_pane.update(cx, |pane, cx| {
-    //                 pane.add_item(Box::new(shared_screen), false, true, None, cx)
-    //             });
-    //         }
-    //     }
+    pub fn open_shared_screen(&mut self, peer_id: PeerId, cx: &mut ViewContext<Self>) {
+        if let Some(shared_screen) = self.shared_screen_for_peer(peer_id, &self.active_pane, cx) {
+            self.active_pane.update(cx, |pane, cx| {
+                pane.add_item(shared_screen, false, true, None, cx)
+            });
+        }
+    }
 
     pub fn activate_item(&mut self, item: &dyn ItemHandle, cx: &mut ViewContext<Self>) -> bool {
         let result = self.panes.iter().find_map(|pane| {
@@ -2303,6 +2342,11 @@ impl Workspace {
         &self.active_pane
     }
 
+    pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<View<Pane>> {
+        let weak_pane = self.panes_by_item.get(&handle.item_id())?;
+        weak_pane.upgrade()
+    }
+
     fn collaborator_left(&mut self, peer_id: PeerId, cx: &mut ViewContext<Self>) {
         self.follower_states.retain(|_, state| {
             if state.leader_id == peer_id {
@@ -2861,10 +2905,10 @@ impl Workspace {
                 }
                 continue;
             }
-            // todo!()
-            // if let Some(shared_screen) = self.shared_screen_for_peer(leader_id, pane, cx) {
-            //     items_to_activate.push((pane.clone(), Box::new(shared_screen)));
-            // }
+
+            if let Some(shared_screen) = self.shared_screen_for_peer(leader_id, pane, cx) {
+                items_to_activate.push((pane.clone(), shared_screen));
+            }
         }
 
         for (pane, item) in items_to_activate {
@@ -2885,27 +2929,27 @@ impl Workspace {
         None
     }
 
-    // todo!()
-    //     fn shared_screen_for_peer(
-    //         &self,
-    //         peer_id: PeerId,
-    //         pane: &View<Pane>,
-    //         cx: &mut ViewContext<Self>,
-    //     ) -> Option<View<SharedScreen>> {
-    //         let call = self.active_call()?;
-    //         let room = call.read(cx).room()?.read(cx);
-    //         let participant = room.remote_participant_for_peer_id(peer_id)?;
-    //         let track = participant.video_tracks.values().next()?.clone();
-    //         let user = participant.user.clone();
-
-    //         for item in pane.read(cx).items_of_type::<SharedScreen>() {
-    //             if item.read(cx).peer_id == peer_id {
-    //                 return Some(item);
-    //             }
-    //         }
+    fn shared_screen_for_peer(
+        &self,
+        peer_id: PeerId,
+        pane: &View<Pane>,
+        cx: &mut ViewContext<Self>,
+    ) -> Option<Box<dyn ItemHandle>> {
+        self.call_handler.shared_screen_for_peer(peer_id, pane, cx)
+        // let call = self.active_call()?;
+        // let room = call.read(cx).room()?.read(cx);
+        // let participant = room.remote_participant_for_peer_id(peer_id)?;
+        // let track = participant.video_tracks.values().next()?.clone();
+        // let user = participant.user.clone();
+
+        // for item in pane.read(cx).items_of_type::<SharedScreen>() {
+        //     if item.read(cx).peer_id == peer_id {
+        //         return Some(item);
+        //     }
+        // }
 
-    //         Some(cx.build_view(|cx| SharedScreen::new(&track, peer_id, user.clone(), cx)))
-    //     }
+        // Some(cx.build_view(|cx| SharedScreen::new(&track, peer_id, user.clone(), cx)))
+    }
 
     pub fn on_window_activation_changed(&mut self, cx: &mut ViewContext<Self>) {
         if cx.is_window_active() {
@@ -3421,6 +3465,10 @@ impl Workspace {
         self.modal_layer
             .update(cx, |modal_layer, cx| modal_layer.toggle_modal(cx, build))
     }
+
+    pub fn call_state(&mut self) -> &mut dyn CallHandler {
+        &mut *self.call_handler
+    }
 }
 
 fn window_bounds_env_override(cx: &AsyncAppContext) -> Option<WindowBounds> {

crates/zed/src/languages/elixir/embedding.scm 🔗

@@ -18,10 +18,10 @@
                     target: (identifier) @name)
                     operator: "when")
             ])
-        (#match? @name "^(def|defp|defdelegate|defguard|defguardp|defmacro|defmacrop|defn|defnp)$")) @item
+        (#any-match? @name "^(def|defp|defdelegate|defguard|defguardp|defmacro|defmacrop|defn|defnp)$")) @item
         )
 
     (call
         target: (identifier) @name
         (arguments (alias) @name)
-        (#match? @name "^(defmodule|defprotocol)$")) @item
+        (#any-match? @name "^(defmodule|defprotocol)$")) @item

crates/zed2/Cargo.toml 🔗

@@ -16,7 +16,7 @@ path = "src/main.rs"
 
 [dependencies]
 ai = { package = "ai2", path = "../ai2"}
-# audio = { path = "../audio" }
+audio = { package = "audio2", path = "../audio2" }
 # activity_indicator = { path = "../activity_indicator" }
 auto_update = { package = "auto_update2", path = "../auto_update2" }
 # breadcrumbs = { path = "../breadcrumbs" }

crates/zed2/src/main.rs 🔗

@@ -8,7 +8,7 @@ use anyhow::{anyhow, Context as _, Result};
 use backtrace::Backtrace;
 use chrono::Utc;
 use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
-use client::UserStore;
+use client::{Client, UserStore};
 use db::kvp::KEY_VALUE_STORE;
 use editor::Editor;
 use fs::RealFs;
@@ -199,7 +199,7 @@ fn main() {
         });
         cx.set_global(Arc::downgrade(&app_state));
 
-        // audio::init(Assets, cx);
+        audio::init(Assets, cx);
         auto_update::init(http.clone(), client::ZED_SERVER_URL.clone(), cx);
 
         workspace::init(app_state.clone(), cx);
@@ -249,7 +249,7 @@ fn main() {
             }
         }
 
-        let mut _triggered_authentication = false;
+        let mut triggered_authentication = false;
 
         fn open_paths_and_log_errs(
             paths: &[PathBuf],
@@ -328,23 +328,23 @@ fn main() {
         })
         .detach();
 
-        // if !triggered_authentication {
-        //     cx.spawn(|cx| async move { authenticate(client, &cx).await })
-        //         .detach_and_log_err(cx);
-        // }
+        if !triggered_authentication {
+            cx.spawn(|cx| async move { authenticate(client, &cx).await })
+                .detach_and_log_err(cx);
+        }
     });
 }
 
-// async fn authenticate(client: Arc<Client>, cx: &AsyncAppContext) -> Result<()> {
-//     if stdout_is_a_pty() {
-//         if client::IMPERSONATE_LOGIN.is_some() {
-//             client.authenticate_and_connect(false, &cx).await?;
-//         }
-//     } else if client.has_keychain_credentials(&cx) {
-//         client.authenticate_and_connect(true, &cx).await?;
-//     }
-//     Ok::<_, anyhow::Error>(())
-// }
+async fn authenticate(client: Arc<Client>, cx: &AsyncAppContext) -> Result<()> {
+    if stdout_is_a_pty() {
+        if client::IMPERSONATE_LOGIN.is_some() {
+            client.authenticate_and_connect(false, &cx).await?;
+        }
+    } else if client.has_keychain_credentials(&cx).await {
+        client.authenticate_and_connect(true, &cx).await?;
+    }
+    Ok::<_, anyhow::Error>(())
+}
 
 async fn installation_id() -> Result<(String, bool)> {
     let legacy_key_name = "device_id";

crates/zed2/src/zed2.rs 🔗

@@ -166,12 +166,17 @@ pub fn initialize_workspace(app_state: Arc<AppState>, cx: &mut AppContext) {
 
         //     vim::observe_keystrokes(cx);
 
-        //     cx.on_window_should_close(|workspace, cx| {
-        //         if let Some(task) = workspace.close(&Default::default(), cx) {
-        //             task.detach_and_log_err(cx);
-        //         }
-        //         false
-        //     });
+        let handle = cx.view().downgrade();
+        cx.on_window_should_close(move |cx| {
+            handle
+                .update(cx, |workspace, cx| {
+                    if let Some(task) = workspace.close(&Default::default(), cx) {
+                        task.detach_and_log_err(cx);
+                    }
+                    false
+                })
+                .unwrap_or(true)
+        });
 
         cx.spawn(|workspace_handle, mut cx| async move {
             let project_panel = ProjectPanel::load(workspace_handle.clone(), cx.clone());