editor singleline (#3257)

Mikayla Maki created

- Implement Editor::single_line
- Fix confusing error message
- Fix loading keyfiles
- Wire up GoToLine modal

Change summary

crates/editor2/src/editor.rs         | 25 ++++++++++---------------
crates/editor2/src/element.rs        | 17 +++++++++++------
crates/go_to_line2/src/go_to_line.rs |  8 +++-----
crates/gpui2/src/element.rs          |  5 ++++-
crates/gpui2/src/interactive.rs      |  7 ++++---
crates/gpui2/src/style.rs            |  4 ++++
crates/settings2/src/keymap_file.rs  |  6 ++++--
crates/workspace2/src/modal_layer.rs | 14 +++-----------
crates/workspace2/src/workspace2.rs  |  6 +++---
9 files changed, 46 insertions(+), 46 deletions(-)

Detailed changes

crates/editor2/src/editor.rs 🔗

@@ -36,10 +36,10 @@ pub use element::{
 use futures::FutureExt;
 use fuzzy::{StringMatch, StringMatchCandidate};
 use gpui::{
-    actions, div, px, AnyElement, AppContext, BackgroundExecutor, Context, DispatchContext, Div,
-    Element, Entity, EventEmitter, FocusHandle, FontStyle, FontWeight, Hsla, Model, Pixels, Render,
-    Styled, Subscription, Task, TextStyle, View, ViewContext, VisualContext, WeakView,
-    WindowContext,
+    actions, div, px, relative, AnyElement, AppContext, BackgroundExecutor, Context,
+    DispatchContext, Div, Element, Entity, EventEmitter, FocusHandle, FontStyle, FontWeight, Hsla,
+    Model, Pixels, Render, Styled, Subscription, Task, TextStyle, View, ViewContext, VisualContext,
+    WeakView, WindowContext,
 };
 use highlight_matching_bracket::refresh_matching_bracket_highlights;
 use hover_popover::{hide_hover, HoverState};
@@ -593,7 +593,6 @@ pub struct EditorStyle {
     pub background: Hsla,
     pub local_player: PlayerColor,
     pub text: TextStyle,
-    pub line_height_scalar: f32,
     pub scrollbar_width: Pixels,
     pub syntax: Arc<SyntaxTheme>,
     pub diagnostic_style: DiagnosticStyle,
@@ -1795,14 +1794,11 @@ impl InlayHintRefreshReason {
 }
 
 impl Editor {
-    //     pub fn single_line(
-    //         field_editor_style: Option<Arc<GetFieldEditorTheme>>,
-    //         cx: &mut ViewContext<Self>,
-    //     ) -> Self {
-    //         let buffer = cx.build_model(|cx| Buffer::new(0, cx.model_id() as u64, String::new()));
-    //         let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
-    //         Self::new(EditorMode::SingleLine, buffer, None, field_editor_style, cx)
-    //     }
+    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
+        let buffer = cx.build_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), String::new()));
+        let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
+        Self::new(EditorMode::SingleLine, buffer, None, cx)
+    }
 
     //     pub fn multi_line(
     //         field_editor_style: Option<Arc<GetFieldEditorTheme>>,
@@ -9372,14 +9368,13 @@ impl Render for Editor {
             font_size: settings.buffer_font_size.into(),
             font_weight: FontWeight::NORMAL,
             font_style: FontStyle::Normal,
-            line_height: Default::default(),
+            line_height: relative(settings.buffer_line_height.value()),
             underline: None,
         };
         EditorElement::new(EditorStyle {
             background: cx.theme().colors().editor_background,
             local_player: cx.theme().players().local(),
             text: text_style,
-            line_height_scalar: settings.buffer_line_height.value(),
             scrollbar_width: px(12.),
             syntax: cx.theme().syntax().clone(),
             diagnostic_style: cx.theme().diagnostic_style(),

crates/editor2/src/element.rs 🔗

@@ -8,10 +8,11 @@ use crate::{
 use anyhow::Result;
 use collections::{BTreeMap, HashMap};
 use gpui::{
-    black, hsla, point, px, relative, size, transparent_black, Action, AnyElement, BorrowWindow,
-    Bounds, ContentMask, Corners, DispatchContext, DispatchPhase, Edges, Element, ElementId,
-    Entity, Hsla, KeyDownEvent, KeyListener, KeyMatch, Line, Pixels, ScrollWheelEvent, ShapedGlyph,
-    Size, StatefulInteraction, Style, TextRun, TextStyle, TextSystem, ViewContext, WindowContext,
+    black, hsla, point, px, relative, size, transparent_black, Action, AnyElement,
+    BorrowAppContext, BorrowWindow, Bounds, ContentMask, Corners, DispatchContext, DispatchPhase,
+    Edges, Element, ElementId, Entity, Hsla, KeyDownEvent, KeyListener, KeyMatch, Line, Pixels,
+    ScrollWheelEvent, ShapedGlyph, Size, StatefulInteraction, Style, TextRun, TextStyle,
+    TextSystem, ViewContext, WindowContext,
 };
 use itertools::Itertools;
 use language::language_settings::ShowWhitespaceSetting;
@@ -1605,7 +1606,7 @@ impl EditorElement {
         let style = self.style.clone();
         let font_id = cx.text_system().font_id(&style.text.font()).unwrap();
         let font_size = style.text.font_size.to_pixels(cx.rem_size());
-        let line_height = (font_size * style.line_height_scalar).round();
+        let line_height = style.text.line_height_in_pixels(cx.rem_size());
         let em_width = cx
             .text_system()
             .typographic_bounds(font_id, font_size, 'm')
@@ -2593,7 +2594,11 @@ impl Element<Editor> for EditorElement {
         let rem_size = cx.rem_size();
         let mut style = Style::default();
         style.size.width = relative(1.).into();
-        style.size.height = relative(1.).into();
+        style.size.height = match editor.mode {
+            EditorMode::SingleLine => self.style.text.line_height_in_pixels(cx.rem_size()).into(),
+            EditorMode::AutoHeight { .. } => todo!(),
+            EditorMode::Full => relative(1.).into(),
+        };
         cx.request_layout(&style, None)
     }
 

crates/go_to_line2/src/go_to_line.rs 🔗

@@ -1,12 +1,10 @@
-use gpui::{div, px, red, AppContext, Div, Render, Styled, ViewContext, VisualContext};
-use serde::Deserialize;
+use gpui::{actions, div, px, red, AppContext, Div, Render, Styled, ViewContext, VisualContext};
 use workspace::ModalRegistry;
 
-// actions!(go_to_line, [Toggle]);
-#[derive(Clone, Default, PartialEq, Deserialize)]
-struct Toggle;
+actions!(Toggle);
 
 pub fn init(cx: &mut AppContext) {
+    cx.register_action_type::<Toggle>();
     cx.global_mut::<ModalRegistry>()
         .register_modal(Toggle, |_, cx| {
             // if let Some(editor) = workspace

crates/gpui2/src/element.rs 🔗

@@ -134,7 +134,10 @@ where
                         .layout(state, frame_state.as_mut().unwrap(), cx);
                 }
             }
-            _ => panic!("must call initialize before layout"),
+            ElementRenderPhase::Start => panic!("must call initialize before layout"),
+            ElementRenderPhase::LayoutRequested { .. } | ElementRenderPhase::Painted => {
+                panic!("element rendered twice")
+            }
         };
 
         self.phase = ElementRenderPhase::LayoutRequested {

crates/gpui2/src/interactive.rs 🔗

@@ -397,9 +397,10 @@ pub trait ElementInteraction<V: 'static>: 'static {
                         None
                     }),
                 ));
-                let result = stateful.stateless.initialize(cx, f);
-                stateful.key_listeners.pop();
-                result
+
+                cx.with_key_dispatch_context(stateful.dispatch_context.clone(), |cx| {
+                    cx.with_key_listeners(mem::take(&mut stateful.key_listeners), f)
+                })
             })
         } else {
             let stateless = self.as_stateless_mut();

crates/gpui2/src/style.rs 🔗

@@ -189,6 +189,10 @@ impl TextStyle {
         }
     }
 
+    pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
+        self.line_height.to_pixels(self.font_size, rem_size)
+    }
+
     pub fn to_run(&self, len: usize) -> TextRun {
         TextRun {
             len,

crates/settings2/src/keymap_file.rs 🔗

@@ -1,7 +1,7 @@
 use crate::{settings_store::parse_json_with_comments, SettingsAssets};
 use anyhow::{anyhow, Context, Result};
 use collections::BTreeMap;
-use gpui::{AppContext, KeyBinding, SharedString};
+use gpui::{actions, Action, AppContext, KeyBinding, SharedString};
 use schemars::{
     gen::{SchemaGenerator, SchemaSettings},
     schema::{InstanceType, Schema, SchemaObject, SingleOrVec, SubschemaValidation},
@@ -137,8 +137,10 @@ impl KeymapFile {
     }
 }
 
+actions!(NoAction);
+
 fn no_action() -> Box<dyn gpui::Action> {
-    todo!()
+    NoAction.boxed_clone()
 }
 
 #[cfg(test)]

crates/workspace2/src/modal_layer.rs 🔗

@@ -1,8 +1,8 @@
 use std::{any::TypeId, sync::Arc};
 
 use gpui::{
-    div, AnyView, AppContext, Component, DispatchPhase, Div, ParentElement, Render,
-    StatelessInteractive, View, ViewContext,
+    div, AnyView, AppContext, DispatchPhase, Div, ParentElement, Render, StatelessInteractive,
+    View, ViewContext,
 };
 
 use crate::Workspace;
@@ -28,10 +28,6 @@ struct ToggleModal {
     name: String,
 }
 
-// complete change of plan?
-// on_action(ToggleModal{ name})
-// register_modal(name, |workspace, cx| { ... })
-
 impl ModalRegistry {
     pub fn register_modal<A: 'static, V, B>(&mut self, action: A, build_view: B)
     where
@@ -40,12 +36,10 @@ impl ModalRegistry {
     {
         let build_view = Arc::new(build_view);
 
-        dbg!("yonder");
         self.registered_modals.push((
             TypeId::of::<A>(),
             Box::new(move |mut div| {
                 let build_view = build_view.clone();
-                dbg!("this point");
 
                 div.on_action(
                     move |workspace: &mut Workspace,
@@ -75,9 +69,7 @@ impl ModalLayer {
         Self { open_modal: None }
     }
 
-    pub fn render(&self, cx: &ViewContext<Workspace>) -> impl Component<Workspace> {
-        dbg!("rendering ModalLayer");
-
+    pub fn render(&self, workspace: &Workspace, cx: &ViewContext<Workspace>) -> Div<Workspace> {
         let mut div = div();
 
         // div, c workspace.toggle_modal()div.on_action()) {

crates/workspace2/src/workspace2.rs 🔗

@@ -3707,7 +3707,9 @@ impl Render for Workspace {
             .bg(cx.theme().colors().background)
             .child(self.render_titlebar(cx))
             .child(
-                div()
+                self.modal_layer
+                    .read(cx)
+                    .render(self, cx)
                     .flex_1()
                     .w_full()
                     .flex()
@@ -3840,8 +3842,6 @@ impl Render for Workspace {
                               //         .on_click(Arc::new(|workspace, cx| workspace.toggle_debug(cx))),
                               // ),
             )
-            //     .child(self.modal_layer.clone())
-            .child(self.modal_layer.read(cx).render(cx))
     }
 }