Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Merge branch 'main' into event-emitter
Mikayla2c67cc80ba8f
diff --cc crates/go_to_line2/src/go_to_line.rsindex 3c9cd5e31eb,af69d42d41d..c65373e6acc--- a/crates/go_to_line2/src/go_to_line.rs+++ b/crates/go_to_line2/src/go_to_line.rs@@@ -1,220 -1,195 +1,187 @@@- use gpui::{actions, div, px, red, AppContext, Div, Render, Styled, ViewContext, VisualContext};- use workspace::ModalRegistry;+ use editor::{display_map::ToDisplayPoint, scroll::autoscroll::Autoscroll, Editor};+ use gpui::{+ actions, div, AppContext, Div, EventEmitter, ParentElement, Render, SharedString,+ StatefulInteractivity, StatelessInteractive, Styled, Subscription, View, ViewContext,+ VisualContext, WindowContext,+ };+ use text::{Bias, Point};+ use theme::ActiveTheme;+ use ui::{h_stack, modal, v_stack, Label, LabelColor};+ use util::paths::FILE_ROW_COLUMN_DELIMITER;-use workspace::{Modal, ModalEvent, Workspace};++use workspace::{ModalEvent, Workspace};actions!(Toggle);pub fn init(cx: &mut AppContext) {- cx.global_mut::<ModalRegistry>()- .register_modal(Toggle, |_, cx| {- // if let Some(editor) = workspace- // .active_item(cx)- // .and_then(|active_item| active_item.downcast::<Editor>())- // {- // cx.build_view(|cx| GoToLine::new(editor, cx))- // }- let view = cx.build_view(|_| GoToLine);- view- });+ cx.observe_new_views(+ |workspace: &mut Workspace, _: &mut ViewContext<Workspace>| {+ workspace+ .modal_layer()+ .register_modal(Toggle, |workspace, cx| {+ let editor = workspace+ .active_item(cx)+ .and_then(|active_item| active_item.downcast::<Editor>())?;++ Some(cx.build_view(|cx| GoToLine::new(editor, cx)))+ });+ },+ )+ .detach();+ }++ pub struct GoToLine {+ line_editor: View<Editor>,+ active_editor: View<Editor>,+ current_text: SharedString,+ prev_scroll_position: Option<gpui::Point<f32>>,+ _subscriptions: Vec<Subscription>,+ }- // cx.add_action(GoToLine::toggle);- // cx.add_action(GoToLine::confirm);- // cx.add_action(GoToLine::cancel);+ pub enum Event {+ Dismissed,}- pub struct GoToLine;-impl EventEmitter for GoToLine {- type Event = Event;-}++impl EventEmitter<Event> for GoToLine {}+- impl Render for GoToLine {- type Element = Div<Self>;++impl EventEmitter<ModalEvent> for GoToLine {}- fn render(&mut self, _cx: &mut ViewContext<Self>) -> Self::Element {- div().bg(red()).w(px(100.0)).h(px(100.0))+ impl GoToLine {+ pub fn new(active_editor: View<Editor>, cx: &mut ViewContext<Self>) -> Self {+ let line_editor = cx.build_view(|cx| {+ let editor = Editor::single_line(cx);+ editor.focus(cx);+ editor+ });+ let line_editor_change = cx.subscribe(&line_editor, Self::on_line_editor_event);++ let editor = active_editor.read(cx);+ let cursor = editor.selections.last::<Point>(cx).head();+ let last_line = editor.buffer().read(cx).snapshot(cx).max_point().row;+ let scroll_position = active_editor.update(cx, |editor, cx| editor.scroll_position(cx));++ let current_text = format!(+ "line {} of {} (column {})",+ cursor.row + 1,+ last_line + 1,+ cursor.column + 1,+ );++ Self {+ line_editor,+ active_editor,+ current_text: current_text.into(),+ prev_scroll_position: Some(scroll_position),+ _subscriptions: vec![line_editor_change, cx.on_release(Self::release)],+ }+ }++ fn release(&mut self, cx: &mut WindowContext) {+ let scroll_position = self.prev_scroll_position.take();+ self.active_editor.update(cx, |editor, cx| {+ editor.focus(cx);+ editor.highlight_rows(None);+ if let Some(scroll_position) = scroll_position {+ editor.set_scroll_position(scroll_position, cx);+ }+ cx.notify();+ })+ }++ fn on_line_editor_event(+ &mut self,+ _: View<Editor>,+ event: &editor::Event,+ cx: &mut ViewContext<Self>,+ ) {+ match event {+ // todo!() this isn't working...+ editor::Event::Blurred => cx.emit(Event::Dismissed),+ editor::Event::BufferEdited { .. } => self.highlight_current_line(cx),+ _ => {}+ }+ }++ fn highlight_current_line(&mut self, cx: &mut ViewContext<Self>) {+ if let Some(point) = self.point_from_query(cx) {+ self.active_editor.update(cx, |active_editor, cx| {+ let snapshot = active_editor.snapshot(cx).display_snapshot;+ let point = snapshot.buffer_snapshot.clip_point(point, Bias::Left);+ let display_point = point.to_display_point(&snapshot);+ let row = display_point.row();+ active_editor.highlight_rows(Some(row..row + 1));+ active_editor.request_autoscroll(Autoscroll::center(), cx);+ });+ cx.notify();+ }+ }++ fn point_from_query(&self, cx: &ViewContext<Self>) -> Option<Point> {+ let line_editor = self.line_editor.read(cx).text(cx);+ let mut components = line_editor+ .splitn(2, FILE_ROW_COLUMN_DELIMITER)+ .map(str::trim)+ .fuse();+ let row = components.next().and_then(|row| row.parse::<u32>().ok())?;+ let column = components.next().and_then(|col| col.parse::<u32>().ok());+ Some(Point::new(+ row.saturating_sub(1),+ column.unwrap_or(0).saturating_sub(1),+ ))+ }++ fn cancel(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {+ cx.emit(Event::Dismissed);+ }++ fn confirm(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {+ if let Some(point) = self.point_from_query(cx) {+ self.active_editor.update(cx, |active_editor, cx| {+ let snapshot = active_editor.snapshot(cx).display_snapshot;+ let point = snapshot.buffer_snapshot.clip_point(point, Bias::Left);+ active_editor.change_selections(Some(Autoscroll::center()), cx, |s| {+ s.select_ranges([point..point])+ });+ });+ self.prev_scroll_position.take();+ }++ cx.emit(Event::Dismissed);}}- // pub struct GoToLine {- // //line_editor: View<Editor>,- // active_editor: View<Editor>,- // prev_scroll_position: Option<gpui::Point<Pixels>>,- // cursor_point: Point,- // max_point: Point,- // has_focus: bool,- // }-- // pub enum Event {- // Dismissed,- // }-- // impl GoToLine {- // pub fn new(active_editor: View<Editor>, cx: &mut ViewContext<Self>) -> Self {- // // let line_editor = cx.build_view(|cx| {- // // Editor::single_line(- // // Some(Arc::new(|theme| theme.picker.input_editor.clone())),- // // cx,- // // )- // // });- // // cx.subscribe(&line_editor, Self::on_line_editor_event)- // // .detach();-- // let (scroll_position, cursor_point, max_point) = active_editor.update(cx, |editor, cx| {- // let scroll_position = editor.scroll_position(cx);- // let buffer = editor.buffer().read(cx).snapshot(cx);- // (- // Some(scroll_position),- // editor.selections.newest(cx).head(),- // buffer.max_point(),- // )- // });-- // cx.on_release(|_, on_release| {}).detach();-- // Self {- // //line_editor,- // active_editor,- // prev_scroll_position: scroll_position,- // cursor_point,- // max_point,- // has_focus: false,- // }- // }-- // fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {- // cx.emit(Event::Dismissed);- // }-- // fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {- // self.prev_scroll_position.take();- // if let Some(point) = self.point_from_query(cx) {- // self.active_editor.update(cx, |active_editor, cx| {- // let snapshot = active_editor.snapshot(cx).display_snapshot;- // let point = snapshot.buffer_snapshot.clip_point(point, Bias::Left);- // active_editor.change_selections(Some(Autoscroll::center()), cx, |s| {- // s.select_ranges([point..point])- // });- // });- // }-- // cx.emit(Event::Dismissed);- // }-- // fn on_line_editor_event(- // &mut self,- // _: View<Editor>,- // event: &editor::Event,- // cx: &mut ViewContext<Self>,- // ) {- // match event {- // editor::Event::Blurred => cx.emit(Event::Dismissed),- // editor::Event::BufferEdited { .. } => {- // if let Some(point) = self.point_from_query(cx) {- // // todo!()- // // self.active_editor.update(cx, |active_editor, cx| {- // // let snapshot = active_editor.snapshot(cx).display_snapshot;- // // let point = snapshot.buffer_snapshot.clip_point(point, Bias::Left);- // // let display_point = point.to_display_point(&snapshot);- // // let row = display_point.row();- // // active_editor.highlight_rows(Some(row..row + 1));- // // active_editor.request_autoscroll(Autoscroll::center(), cx);- // // });- // cx.notify();- // }- // }- // _ => {}- // }- // }-- // fn point_from_query(&self, cx: &ViewContext<Self>) -> Option<Point> {- // return None;- // // todo!()- // // let line_editor = self.line_editor.read(cx).text(cx);- // // let mut components = line_editor- // // .splitn(2, FILE_ROW_COLUMN_DELIMITER)- // // .map(str::trim)- // // .fuse();- // // let row = components.next().and_then(|row| row.parse::<u32>().ok())?;- // // let column = components.next().and_then(|col| col.parse::<u32>().ok());- // // Some(Point::new(- // // row.saturating_sub(1),- // // column.unwrap_or(0).saturating_sub(1),- // // ))- // }- // }-- // impl EventEmitter for GoToLine {- // type Event = Event;- // }-- // impl Entity for GoToLine {- // fn release(&mut self, cx: &mut AppContext) {- // let scroll_position = self.prev_scroll_position.take();- // self.active_editor.window().update(cx, |cx| {- // self.active_editor.update(cx, |editor, cx| {- // editor.highlight_rows(None);- // if let Some(scroll_position) = scroll_position {- // editor.set_scroll_position(scroll_position, cx);- // }- // })- // });- // }- // }-- // impl Render for GoToLine {- // type Element = Div<Self>;-- // fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {- // // todo!()- // div()- // }- // }-- // impl View for GoToLine {- // fn ui_name() -> &'static str {- // "GoToLine"- // }-- // fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {- // let theme = &theme::current(cx).picker;-- // let label = format!(- // "{}{FILE_ROW_COLUMN_DELIMITER}{} of {} lines",- // self.cursor_point.row + 1,- // self.cursor_point.column + 1,- // self.max_point.row + 1- // );-- // Flex::new(Axis::Vertical)- // .with_child(- // ChildView::new(&self.line_editor, cx)- // .contained()- // .with_style(theme.input_editor.container),- // )- // .with_child(- // Label::new(label, theme.no_matches.label.clone())- // .contained()- // .with_style(theme.no_matches.container),- // )- // .contained()- // .with_style(theme.container)- // .constrained()- // .with_max_width(500.0)- // .into_any_named("go to line")- // }-- // fn focus_in(&mut self, _: AnyView, cx: &mut ViewContext<Self>) {- // self.has_focus = true;- // cx.focus(&self.line_editor);- // }-- // fn focus_out(&mut self, _: AnyView, _: &mut ViewContext<Self>) {- // self.has_focus = false;- // }- // }-- // impl Modal for GoToLine {- // fn has_focus(&self) -> bool {- // self.has_focus- // }-impl Modal for GoToLine {- fn to_modal_event(&self, e: &Self::Event) -> Option<ModalEvent> {- match e {- Event::Dismissed => Some(ModalEvent::Dismissed),- }- }-}--- // fn dismiss_on_event(event: &Self::Event) -> bool {- // matches!(event, Event::Dismissed)- // }- // }+ impl Render for GoToLine {+ type Element = Div<Self, StatefulInteractivity<Self>>;++ fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {+ modal(cx)+ .id("go to line")+ .on_action(Self::cancel)+ .on_action(Self::confirm)+ .w_96()+ .child(+ v_stack()+ .px_1()+ .pt_0p5()+ .gap_px()+ .child(+ v_stack()+ .py_0p5()+ .px_1()+ .child(div().px_1().py_0p5().child(self.line_editor.clone())),+ )+ .child(+ div()+ .h_px()+ .w_full()+ .bg(cx.theme().colors().element_background),+ )+ .child(+ h_stack()+ .justify_between()+ .px_2()+ .py_1()+ .child(Label::new(self.current_text.clone()).color(LabelColor::Muted)),+ ),+ )+ }+ }diff --cc crates/gpui2/src/window.rsindex 405d7c5bd11,1daebf184c1..ce50b8e7f11--- a/crates/gpui2/src/window.rs+++ b/crates/gpui2/src/window.rs@@@ -2176,25 -2176,12 +2184,12 @@@ impl<'a, V: 'static> ViewContext<'a, V}}--impl<V> ViewContext<'_, V>--where- V: InputHandler + 'static,- V: EventEmitter,- V::Event: 'static,--{- pub fn handle_text_input(&mut self) {- self.window.requested_input_handler = Some(Box::new(WindowInputHandler {- cx: self.app.this.clone(),- window: self.window_handle(),- handler: self.view().downgrade(),- }));- }- }-- pub fn emit(&mut self, event: V::Event) {+impl<V> ViewContext<'_, V> {+ pub fn emit<Evt>(&mut self, event: Evt)+ where+ Evt: 'static,+ V: EventEmitter<Evt>,+ {let emitter = self.view.model.entity_id;self.app.push_effect(Effect::Emit {emitter,diff --cc crates/workspace2/src/modal_layer.rsindex 4121574b6a4,564db0f9829..a5760380f5e--- a/crates/workspace2/src/modal_layer.rs+++ b/crates/workspace2/src/modal_layer.rs@@@ -1,35 -1,38 +1,34 @@@use crate::Workspace;use gpui::{- div, AnyView, AppContext, Div, ParentElement, Render, StatelessInteractive, View, ViewContext,+ div, px, AnyView, Component, Div, EventEmitter, ParentElement, Render, StatelessInteractive,+ Styled, Subscription, View, ViewContext,};use std::{any::TypeId, sync::Arc};+ use ui::v_stack;- pub struct ModalRegistry {- registered_modals: Vec<(TypeId, Box<dyn Fn(Div<Workspace>) -> Div<Workspace>>)>,- }-- pub trait Modal {}-- #[derive(Clone)]pub struct ModalLayer {open_modal: Option<AnyView>,+ subscription: Option<Subscription>,+ registered_modals: Vec<(TypeId, Box<dyn Fn(Div<Workspace>) -> Div<Workspace>>)>,}- pub fn init_modal_registry(cx: &mut AppContext) {- cx.set_global(ModalRegistry {- registered_modals: Vec::new(),- });+ pub enum ModalEvent {+ Dismissed,}- struct ToggleModal {- name: String,-pub trait Modal: EventEmitter + Render {- fn to_modal_event(&self, _: &Self::Event) -> Option<ModalEvent>;--}-+ impl ModalLayer {+ pub fn new() -> Self {+ Self {+ open_modal: None,+ subscription: None,+ registered_modals: Vec::new(),+ }+ }- impl ModalRegistry {pub fn register_modal<A: 'static, V, B>(&mut self, action: A, build_view: B)where- V: Render,- B: Fn(&Workspace, &mut ViewContext<Workspace>) -> View<V> + 'static,- V: Modal,++ V: EventEmitter<ModalEvent> + Render,+ B: Fn(&mut Workspace, &mut ViewContext<Workspace>) -> Option<View<V>> + 'static,{let build_view = Arc::new(build_view);@@@ -51,29 -50,47 +46,47 @@@}),));}- }- impl ModalLayer {- pub fn new() -> Self {- Self { open_modal: None }- pub fn show_modal<V: Modal>(&mut self, new_modal: View<V>, cx: &mut ViewContext<Workspace>) {- self.subscription = Some(cx.subscribe(&new_modal, |this, modal, e, cx| {- match modal.read(cx).to_modal_event(e) {- Some(ModalEvent::Dismissed) => this.modal_layer().hide_modal(cx),- None => {}- }++ pub fn show_modal<V>(&mut self, new_modal: View<V>, cx: &mut ViewContext<Workspace>)++ where++ V: EventEmitter<ModalEvent> + Render,++ {++ self.subscription = Some(cx.subscribe(&new_modal, |this, modal, e, cx| match e {++ ModalEvent::Dismissed => this.modal_layer().hide_modal(cx),+ }));+ self.open_modal = Some(new_modal.into());+ cx.notify();}- pub fn render(&self, workspace: &Workspace, cx: &ViewContext<Workspace>) -> Div<Workspace> {- let mut div = div();-- // div, c workspace.toggle_modal()div.on_action()) {- //- // }+ pub fn hide_modal(&mut self, cx: &mut ViewContext<Workspace>) {+ self.open_modal.take();+ self.subscription.take();+ cx.notify();+ }- // for (type_id, action) in cx.global::<ModalRegistry>().registered_modals.iter() {- // div = div.useful_on_action(*type_id, action)- // }+ pub fn wrapper_element(&self, cx: &ViewContext<Workspace>) -> Div<Workspace> {+ let mut parent = div().relative().size_full();- for (_, action) in cx.global::<ModalRegistry>().registered_modals.iter() {- div = (action)(div);+ for (_, action) in self.registered_modals.iter() {+ parent = (action)(parent);}- div.children(self.open_modal.clone())+ parent.when_some(self.open_modal.as_ref(), |parent, open_modal| {+ let container1 = div()+ .absolute()+ .flex()+ .flex_col()+ .items_center()+ .size_full()+ .top_0()+ .left_0()+ .z_index(400);++ // transparent layer+ let container2 = v_stack().h(px(0.0)).relative().top_20();++ parent.child(container1.child(container2.child(open_modal.clone())))+ })}}diff --cc crates/workspace2/src/toolbar.rsindex 1e45a178970,25054571da9..1d67da06b22--- a/crates/workspace2/src/toolbar.rs+++ b/crates/workspace2/src/toolbar.rs@@@ -1,11 -1,10 +1,13 @@@use crate::ItemHandle;- use gpui::{AnyView, Entity, EntityId, EventEmitter, Render, View, ViewContext, WindowContext};+ use gpui::{- AnyView, AppContext, Div, Entity, EntityId, EventEmitter, Render, View, ViewContext,- WindowContext,++ AnyView, Div, Entity, EntityId, EventEmitter, Render, View, ViewContext, WindowContext,+ };-pub trait ToolbarItemView: Render + EventEmitter {+pub enum ToolbarItemEvent {+ ChangeLocation(ToolbarItemLocation),+}++pub trait ToolbarItemView: Render + EventEmitter<ToolbarItemEvent> {fn set_active_pane_item(&mut self,active_pane_item: Option<&dyn crate::ItemHandle>,@@@ -125,61 -141,61 +135,6 @@@ impl Render for Toolbar// }// }--// <<<<<<< HEAD--// =======--// #[allow(clippy::too_many_arguments)]--// fn nav_button<A: Action, F: 'static + Fn(&mut Toolbar, &mut ViewContext<Toolbar>)>(--// svg_path: &'static str,--// style: theme::Interactive<theme::IconButton>,--// nav_button_height: f32,--// tooltip_style: TooltipStyle,--// enabled: bool,--// spacing: f32,--// on_click: F,--// tooltip_action: A,--// action_name: &'static str,--// cx: &mut ViewContext<Toolbar>,--// ) -> AnyElement<Toolbar> {--// MouseEventHandler::new::<A, _>(0, cx, |state, _| {--// let style = if enabled {--// style.style_for(state)--// } else {--// style.disabled_style()--// };--// Svg::new(svg_path)--// .with_color(style.color)--// .constrained()--// .with_width(style.icon_width)--// .aligned()--// .contained()--// .with_style(style.container)--// .constrained()--// .with_width(style.button_width)--// .with_height(nav_button_height)--// .aligned()--// .top()--// })--// .with_cursor_style(if enabled {--// CursorStyle::PointingHand--// } else {--// CursorStyle::default()--// })--// .on_click(MouseButton::Left, move |_, toolbar, cx| {--// on_click(toolbar, cx)--// })--// .with_tooltip::<A>(--// 0,--// action_name,--// Some(Box::new(tooltip_action)),--// tooltip_style,--// cx,--// )--// .contained()--// .with_margin_right(spacing)--// .into_any_named("nav button")--// }----// >>>>>>> 139cbbfd3aebd0863a7d51b0c12d748764cf0b2eimpl Toolbar {pub fn new() -> Self {Self {