From 40c3e925ad5bc8b23a3c320cdc8312f5e2b989d1 Mon Sep 17 00:00:00 2001 From: K Simmons Date: Sat, 15 Oct 2022 15:08:21 -0700 Subject: [PATCH 1/4] Add cursor blink setting and replicate cursor shape to remote collaborators --- Cargo.lock | 1 + assets/settings/default.json | 2 + crates/editor/src/editor.rs | 24 +++++++--- crates/editor/src/element.rs | 60 ++++++++++--------------- crates/editor/src/items.rs | 1 + crates/editor/src/multi_buffer.rs | 10 +++-- crates/language/src/buffer.rs | 21 ++++++++- crates/language/src/buffer_tests.rs | 4 +- crates/language/src/proto.rs | 27 ++++++++++- crates/rpc/proto/zed.proto | 9 ++++ crates/settings/src/settings.rs | 7 +++ crates/terminal/Cargo.toml | 17 +++---- crates/terminal/src/terminal_element.rs | 3 +- crates/vim/src/state.rs | 2 +- crates/vim/src/vim.rs | 3 +- 15 files changed, 128 insertions(+), 63 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1a399ad4ad..188113a66d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5828,6 +5828,7 @@ dependencies = [ "futures 0.3.24", "gpui", "itertools", + "language", "lazy_static", "libc", "mio-extras", diff --git a/assets/settings/default.json b/assets/settings/default.json index 2ccd2c5f97..57f76f5f21 100644 --- a/assets/settings/default.json +++ b/assets/settings/default.json @@ -69,6 +69,8 @@ // The column at which to soft-wrap lines, for buffers where soft-wrap // is enabled. "preferred_line_length": 80, + // Whether the cursor blinks in the editor. + "cursor_blink": true, // Whether to indent lines using tab characters, as opposed to multiple // spaces. "hard_tabs": false, diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs index 070fc69f7e..901547db2e 100644 --- a/crates/editor/src/editor.rs +++ b/crates/editor/src/editor.rs @@ -42,9 +42,9 @@ use hover_popover::{hide_hover, HoverState}; pub use items::MAX_TAB_TITLE_LEN; pub use language::{char_kind, CharKind}; use language::{ - AutoindentMode, BracketPair, Buffer, CodeAction, CodeLabel, Completion, Diagnostic, - DiagnosticSeverity, IndentKind, IndentSize, Language, OffsetRangeExt, OffsetUtf16, Point, - Selection, SelectionGoal, TransactionId, + AutoindentMode, BracketPair, Buffer, CodeAction, CodeLabel, Completion, CursorShape, + Diagnostic, DiagnosticSeverity, IndentKind, IndentSize, Language, OffsetRangeExt, OffsetUtf16, + Point, Selection, SelectionGoal, TransactionId, }; use link_go_to_definition::{hide_link_definition, LinkGoToDefinitionState}; pub use multi_buffer::{ @@ -1478,6 +1478,7 @@ impl Editor { buffer.set_active_selections( &self.selections.disjoint_anchors(), self.selections.line_mode, + self.cursor_shape, cx, ) }); @@ -6145,7 +6146,17 @@ impl Editor { fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext) { if epoch == self.blink_epoch && self.focused && !self.blinking_paused { - self.show_local_cursors = !self.show_local_cursors; + let newest_head = self.selections.newest::(cx).head(); + let language_name = self + .buffer + .read(cx) + .language_at(newest_head, cx) + .map(|l| l.name()); + + self.show_local_cursors = !self.show_local_cursors + || !cx + .global::() + .cursor_blink(language_name.as_deref()); cx.notify(); let epoch = self.next_blink_epoch(); @@ -6466,9 +6477,7 @@ impl View for Editor { } Stack::new() - .with_child( - EditorElement::new(self.handle.clone(), style.clone(), self.cursor_shape).boxed(), - ) + .with_child(EditorElement::new(self.handle.clone(), style.clone()).boxed()) .with_child(ChildView::new(&self.mouse_context_menu, cx).boxed()) .boxed() } @@ -6491,6 +6500,7 @@ impl View for Editor { buffer.set_active_selections( &self.selections.disjoint_anchors(), self.selections.line_mode, + self.cursor_shape, cx, ); } diff --git a/crates/editor/src/element.rs b/crates/editor/src/element.rs index 3e68c6766f..d2090741d8 100644 --- a/crates/editor/src/element.rs +++ b/crates/editor/src/element.rs @@ -35,7 +35,7 @@ use gpui::{ WeakViewHandle, }; use json::json; -use language::{Bias, DiagnosticSeverity, OffsetUtf16, Point, Selection}; +use language::{Bias, CursorShape, DiagnosticSeverity, OffsetUtf16, Point, Selection}; use project::ProjectPath; use settings::{GitGutter, Settings}; use smallvec::SmallVec; @@ -56,6 +56,7 @@ struct DiffHunkLayout { struct SelectionLayout { head: DisplayPoint, + cursor_shape: CursorShape, range: Range, } @@ -63,6 +64,7 @@ impl SelectionLayout { fn new( selection: Selection, line_mode: bool, + cursor_shape: CursorShape, map: &DisplaySnapshot, ) -> Self { if line_mode { @@ -70,6 +72,7 @@ impl SelectionLayout { let point_range = map.expand_to_line(selection.range()); Self { head: selection.head().to_display_point(map), + cursor_shape, range: point_range.start.to_display_point(map) ..point_range.end.to_display_point(map), } @@ -77,6 +80,7 @@ impl SelectionLayout { let selection = selection.map(|p| p.to_display_point(map)); Self { head: selection.head(), + cursor_shape, range: selection.range(), } } @@ -87,19 +91,13 @@ impl SelectionLayout { pub struct EditorElement { view: WeakViewHandle, style: Arc, - cursor_shape: CursorShape, } impl EditorElement { - pub fn new( - view: WeakViewHandle, - style: EditorStyle, - cursor_shape: CursorShape, - ) -> Self { + pub fn new(view: WeakViewHandle, style: EditorStyle) -> Self { Self { view, style: Arc::new(style), - cursor_shape, } } @@ -723,7 +721,7 @@ impl EditorElement { if block_width == 0.0 { block_width = layout.position_map.em_width; } - let block_text = if let CursorShape::Block = self.cursor_shape { + let block_text = if let CursorShape::Block = selection.cursor_shape { layout .position_map .snapshot @@ -759,7 +757,7 @@ impl EditorElement { block_width, origin: vec2f(x, y), line_height: layout.position_map.line_height, - shape: self.cursor_shape, + shape: selection.cursor_shape, block_text, }); } @@ -1648,7 +1646,7 @@ impl Element for EditorElement { ); let mut remote_selections = HashMap::default(); - for (replica_id, line_mode, selection) in display_map + for (replica_id, line_mode, cursor_shape, selection) in display_map .buffer_snapshot .remote_selections_in_range(&(start_anchor.clone()..end_anchor.clone())) { @@ -1659,7 +1657,12 @@ impl Element for EditorElement { remote_selections .entry(replica_id) .or_insert(Vec::new()) - .push(SelectionLayout::new(selection, line_mode, &display_map)); + .push(SelectionLayout::new( + selection, + line_mode, + cursor_shape, + &display_map, + )); } selections.extend(remote_selections); @@ -1691,7 +1694,12 @@ impl Element for EditorElement { local_selections .into_iter() .map(|selection| { - SelectionLayout::new(selection, view.selections.line_mode, &display_map) + SelectionLayout::new( + selection, + view.selections.line_mode, + view.cursor_shape, + &display_map, + ) }) .collect(), )); @@ -2094,20 +2102,6 @@ fn layout_line( ) } -#[derive(Copy, Clone, PartialEq, Eq, Debug)] -pub enum CursorShape { - Bar, - Block, - Underscore, - Hollow, -} - -impl Default for CursorShape { - fn default() -> Self { - CursorShape::Bar - } -} - #[derive(Debug)] pub struct Cursor { origin: Vector2F, @@ -2348,11 +2342,7 @@ mod tests { let (window_id, editor) = cx.add_window(Default::default(), |cx| { Editor::new(EditorMode::Full, buffer, None, None, cx) }); - let element = EditorElement::new( - editor.downgrade(), - editor.read(cx).style(cx), - CursorShape::Bar, - ); + let element = EditorElement::new(editor.downgrade(), editor.read(cx).style(cx)); let layouts = editor.update(cx, |editor, cx| { let snapshot = editor.snapshot(cx); @@ -2388,11 +2378,7 @@ mod tests { cx.blur(); }); - let mut element = EditorElement::new( - editor.downgrade(), - editor.read(cx).style(cx), - CursorShape::Bar, - ); + let mut element = EditorElement::new(editor.downgrade(), editor.read(cx).style(cx)); let mut scene = Scene::new(1.0); let mut presenter = cx.build_presenter(window_id, 30., Default::default()); diff --git a/crates/editor/src/items.rs b/crates/editor/src/items.rs index e6a4eebffb..cf69d2a922 100644 --- a/crates/editor/src/items.rs +++ b/crates/editor/src/items.rs @@ -120,6 +120,7 @@ impl FollowableItem for Editor { buffer.set_active_selections( &self.selections.disjoint_anchors(), self.selections.line_mode, + self.cursor_shape, cx, ); } diff --git a/crates/editor/src/multi_buffer.rs b/crates/editor/src/multi_buffer.rs index 448564ed98..1cff003868 100644 --- a/crates/editor/src/multi_buffer.rs +++ b/crates/editor/src/multi_buffer.rs @@ -8,7 +8,7 @@ use git::diff::DiffHunk; use gpui::{AppContext, Entity, ModelContext, ModelHandle, Task}; pub use language::Completion; use language::{ - char_kind, AutoindentMode, Buffer, BufferChunks, BufferSnapshot, CharKind, Chunk, + char_kind, AutoindentMode, Buffer, BufferChunks, BufferSnapshot, CharKind, Chunk, CursorShape, DiagnosticEntry, Event, File, IndentSize, Language, OffsetRangeExt, OffsetUtf16, Outline, OutlineItem, Point, PointUtf16, Selection, TextDimension, ToOffset as _, ToOffsetUtf16 as _, ToPoint as _, ToPointUtf16 as _, TransactionId, @@ -604,6 +604,7 @@ impl MultiBuffer { &mut self, selections: &[Selection], line_mode: bool, + cursor_shape: CursorShape, cx: &mut ModelContext, ) { let mut selections_by_buffer: HashMap>> = @@ -668,7 +669,7 @@ impl MultiBuffer { } Some(selection) })); - buffer.set_active_selections(merged_selections, line_mode, cx); + buffer.set_active_selections(merged_selections, line_mode, cursor_shape, cx); }); } } @@ -2698,7 +2699,7 @@ impl MultiBufferSnapshot { pub fn remote_selections_in_range<'a>( &'a self, range: &'a Range, - ) -> impl 'a + Iterator)> { + ) -> impl 'a + Iterator)> { let mut cursor = self.excerpts.cursor::>(); cursor.seek(&Some(&range.start.excerpt_id), Bias::Left, &()); cursor @@ -2715,7 +2716,7 @@ impl MultiBufferSnapshot { excerpt .buffer .remote_selections_in_range(query_range) - .flat_map(move |(replica_id, line_mode, selections)| { + .flat_map(move |(replica_id, line_mode, cursor_shape, selections)| { selections.map(move |selection| { let mut start = Anchor { buffer_id: Some(excerpt.buffer_id), @@ -2737,6 +2738,7 @@ impl MultiBufferSnapshot { ( replica_id, line_mode, + cursor_shape, Selection { id: selection.id, start, diff --git a/crates/language/src/buffer.rs b/crates/language/src/buffer.rs index 274777b81c..da7bd53324 100644 --- a/crates/language/src/buffer.rs +++ b/crates/language/src/buffer.rs @@ -111,9 +111,19 @@ pub enum IndentKind { Tab, } +#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] +pub enum CursorShape { + #[default] + Bar, + Block, + Underscore, + Hollow, +} + #[derive(Clone, Debug)] struct SelectionSet { line_mode: bool, + cursor_shape: CursorShape, selections: Arc<[Selection]>, lamport_timestamp: clock::Lamport, } @@ -161,6 +171,7 @@ pub enum Operation { selections: Arc<[Selection]>, lamport_timestamp: clock::Lamport, line_mode: bool, + cursor_shape: CursorShape, }, UpdateCompletionTriggers { triggers: Vec, @@ -395,6 +406,7 @@ impl Buffer { selections: set.selections.clone(), lamport_timestamp: set.lamport_timestamp, line_mode: set.line_mode, + cursor_shape: set.cursor_shape, }) })); operations.push(proto::serialize_operation(&Operation::UpdateDiagnostics { @@ -1227,6 +1239,7 @@ impl Buffer { &mut self, selections: Arc<[Selection]>, line_mode: bool, + cursor_shape: CursorShape, cx: &mut ModelContext, ) { let lamport_timestamp = self.text.lamport_clock.tick(); @@ -1236,6 +1249,7 @@ impl Buffer { selections: selections.clone(), lamport_timestamp, line_mode, + cursor_shape, }, ); self.send_operation( @@ -1243,13 +1257,14 @@ impl Buffer { selections, line_mode, lamport_timestamp, + cursor_shape, }, cx, ); } pub fn remove_active_selections(&mut self, cx: &mut ModelContext) { - self.set_active_selections(Arc::from([]), false, cx); + self.set_active_selections(Arc::from([]), false, Default::default(), cx); } pub fn set_text(&mut self, text: T, cx: &mut ModelContext) -> Option @@ -1474,6 +1489,7 @@ impl Buffer { selections, lamport_timestamp, line_mode, + cursor_shape, } => { if let Some(set) = self.remote_selections.get(&lamport_timestamp.replica_id) { if set.lamport_timestamp > lamport_timestamp { @@ -1487,6 +1503,7 @@ impl Buffer { selections, lamport_timestamp, line_mode, + cursor_shape, }, ); self.text.lamport_clock.observe(lamport_timestamp); @@ -2236,6 +2253,7 @@ impl BufferSnapshot { Item = ( ReplicaId, bool, + CursorShape, impl Iterator> + '_, ), > + '_ { @@ -2259,6 +2277,7 @@ impl BufferSnapshot { ( *replica_id, set.line_mode, + set.cursor_shape, set.selections[start_ix..end_ix].iter(), ) }) diff --git a/crates/language/src/buffer_tests.rs b/crates/language/src/buffer_tests.rs index 0f3ab50f4a..f1b51f7e02 100644 --- a/crates/language/src/buffer_tests.rs +++ b/crates/language/src/buffer_tests.rs @@ -1283,7 +1283,7 @@ fn test_random_collaboration(cx: &mut MutableAppContext, mut rng: StdRng) { selections ); active_selections.insert(replica_id, selections.clone()); - buffer.set_active_selections(selections, false, cx); + buffer.set_active_selections(selections, false, Default::default(), cx); }); mutation_count -= 1; } @@ -1448,7 +1448,7 @@ fn test_random_collaboration(cx: &mut MutableAppContext, mut rng: StdRng) { let buffer = buffer.read(cx).snapshot(); let actual_remote_selections = buffer .remote_selections_in_range(Anchor::MIN..Anchor::MAX) - .map(|(replica_id, _, selections)| (replica_id, selections.collect::>())) + .map(|(replica_id, _, _, selections)| (replica_id, selections.collect::>())) .collect::>(); let expected_remote_selections = active_selections .iter() diff --git a/crates/language/src/proto.rs b/crates/language/src/proto.rs index 9e3ee7d46b..f93d99f76b 100644 --- a/crates/language/src/proto.rs +++ b/crates/language/src/proto.rs @@ -1,5 +1,6 @@ use crate::{ - diagnostic_set::DiagnosticEntry, CodeAction, CodeLabel, Completion, Diagnostic, Language, + diagnostic_set::DiagnosticEntry, CodeAction, CodeLabel, Completion, CursorShape, Diagnostic, + Language, }; use anyhow::{anyhow, Result}; use clock::ReplicaId; @@ -52,11 +53,13 @@ pub fn serialize_operation(operation: &crate::Operation) -> proto::Operation { selections, line_mode, lamport_timestamp, + cursor_shape, } => proto::operation::Variant::UpdateSelections(proto::operation::UpdateSelections { replica_id: lamport_timestamp.replica_id as u32, lamport_timestamp: lamport_timestamp.value, selections: serialize_selections(selections), line_mode: *line_mode, + cursor_shape: serialize_cursor_shape(cursor_shape) as i32, }), crate::Operation::UpdateDiagnostics { diagnostics, @@ -125,6 +128,24 @@ pub fn serialize_selection(selection: &Selection) -> proto::Selection { } } +pub fn serialize_cursor_shape(cursor_shape: &CursorShape) -> proto::CursorShape { + match cursor_shape { + CursorShape::Bar => proto::CursorShape::CursorBar, + CursorShape::Block => proto::CursorShape::CursorBlock, + CursorShape::Underscore => proto::CursorShape::CursorUnderscore, + CursorShape::Hollow => proto::CursorShape::CursorHollow, + } +} + +pub fn deserialize_cursor_shape(cursor_shape: proto::CursorShape) -> CursorShape { + match cursor_shape { + proto::CursorShape::CursorBar => CursorShape::Bar, + proto::CursorShape::CursorBlock => CursorShape::Block, + proto::CursorShape::CursorUnderscore => CursorShape::Underscore, + proto::CursorShape::CursorHollow => CursorShape::Hollow, + } +} + pub fn serialize_diagnostics<'a>( diagnostics: impl IntoIterator>, ) -> Vec { @@ -223,6 +244,10 @@ pub fn deserialize_operation(message: proto::Operation) -> Result { diff --git a/crates/rpc/proto/zed.proto b/crates/rpc/proto/zed.proto index 1248bb0551..380b83ae8d 100644 --- a/crates/rpc/proto/zed.proto +++ b/crates/rpc/proto/zed.proto @@ -908,6 +908,7 @@ message SelectionSet { repeated Selection selections = 2; uint32 lamport_timestamp = 3; bool line_mode = 4; + CursorShape cursor_shape = 5; } message Selection { @@ -917,6 +918,13 @@ message Selection { bool reversed = 4; } +enum CursorShape { + CursorBar = 0; + CursorBlock = 1; + CursorUnderscore = 2; + CursorHollow = 3; +} + message Anchor { uint32 replica_id = 1; uint32 local_timestamp = 2; @@ -982,6 +990,7 @@ message Operation { uint32 lamport_timestamp = 2; repeated Selection selections = 3; bool line_mode = 4; + CursorShape cursor_shape = 5; } message UpdateCompletionTriggers { diff --git a/crates/settings/src/settings.rs b/crates/settings/src/settings.rs index 63bc5962fa..f079ae8670 100644 --- a/crates/settings/src/settings.rs +++ b/crates/settings/src/settings.rs @@ -79,6 +79,7 @@ pub struct GitGutterConfig {} pub struct EditorSettings { pub tab_size: Option, pub hard_tabs: Option, + pub cursor_blink: Option, pub soft_wrap: Option, pub preferred_line_length: Option, pub format_on_save: Option, @@ -301,6 +302,7 @@ impl Settings { editor_defaults: EditorSettings { tab_size: required(defaults.editor.tab_size), hard_tabs: required(defaults.editor.hard_tabs), + cursor_blink: required(defaults.editor.cursor_blink), soft_wrap: required(defaults.editor.soft_wrap), preferred_line_length: required(defaults.editor.preferred_line_length), format_on_save: required(defaults.editor.format_on_save), @@ -390,6 +392,10 @@ impl Settings { self.language_setting(language, |settings| settings.hard_tabs) } + pub fn cursor_blink(&self, language: Option<&str>) -> bool { + self.language_setting(language, |settings| settings.cursor_blink) + } + pub fn soft_wrap(&self, language: Option<&str>) -> SoftWrap { self.language_setting(language, |settings| settings.soft_wrap) } @@ -444,6 +450,7 @@ impl Settings { editor_defaults: EditorSettings { tab_size: Some(4.try_into().unwrap()), hard_tabs: Some(false), + cursor_blink: Some(true), soft_wrap: Some(SoftWrap::None), preferred_line_length: Some(80), format_on_save: Some(FormatOnSave::On), diff --git a/crates/terminal/Cargo.toml b/crates/terminal/Cargo.toml index a0b5231501..efd6a73967 100644 --- a/crates/terminal/Cargo.toml +++ b/crates/terminal/Cargo.toml @@ -8,16 +8,17 @@ path = "src/terminal.rs" doctest = false [dependencies] +context_menu = { path = "../context_menu" } +editor = { path = "../editor" } +language = { path = "../language" } +gpui = { path = "../gpui" } +project = { path = "../project" } +settings = { path = "../settings" } +theme = { path = "../theme" } +util = { path = "../util" } +workspace = { path = "../workspace" } alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "a51dbe25d67e84d6ed4261e640d3954fbdd9be45" } procinfo = { git = "https://github.com/zed-industries/wezterm", rev = "5cd757e5f2eb039ed0c6bb6512223e69d5efc64d", default-features = false } -editor = { path = "../editor" } -util = { path = "../util" } -gpui = { path = "../gpui" } -theme = { path = "../theme" } -settings = { path = "../settings" } -workspace = { path = "../workspace" } -project = { path = "../project" } -context_menu = { path = "../context_menu" } smallvec = { version = "1.6", features = ["union"] } smol = "1.2.5" mio-extras = "2.0.6" diff --git a/crates/terminal/src/terminal_element.rs b/crates/terminal/src/terminal_element.rs index df745dae46..823d99c801 100644 --- a/crates/terminal/src/terminal_element.rs +++ b/crates/terminal/src/terminal_element.rs @@ -4,7 +4,7 @@ use alacritty_terminal::{ index::Point, term::{cell::Flags, TermMode}, }; -use editor::{Cursor, CursorShape, HighlightedRange, HighlightedRangeLine}; +use editor::{Cursor, HighlightedRange, HighlightedRangeLine}; use gpui::{ color::Color, elements::{Empty, Overlay}, @@ -20,6 +20,7 @@ use gpui::{ WeakViewHandle, }; use itertools::Itertools; +use language::CursorShape; use ordered_float::OrderedFloat; use settings::Settings; use theme::TerminalStyle; diff --git a/crates/vim/src/state.rs b/crates/vim/src/state.rs index fef0da2099..b5acb50e7c 100644 --- a/crates/vim/src/state.rs +++ b/crates/vim/src/state.rs @@ -1,5 +1,5 @@ -use editor::CursorShape; use gpui::keymap::Context; +use language::CursorShape; use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)] diff --git a/crates/vim/src/vim.rs b/crates/vim/src/vim.rs index 81bafcf3e2..ce3a7e2366 100644 --- a/crates/vim/src/vim.rs +++ b/crates/vim/src/vim.rs @@ -12,8 +12,9 @@ mod visual; use collections::HashMap; use command_palette::CommandPaletteFilter; -use editor::{Bias, Cancel, CursorShape, Editor}; +use editor::{Bias, Cancel, Editor}; use gpui::{impl_actions, MutableAppContext, Subscription, ViewContext, WeakViewHandle}; +use language::CursorShape; use serde::Deserialize; use settings::Settings; From 09a0b3eb55521403c9f4428a77577cbfcab78884 Mon Sep 17 00:00:00 2001 From: K Simmons Date: Sat, 15 Oct 2022 15:10:43 -0700 Subject: [PATCH 2/4] increment protocol version --- crates/rpc/src/rpc.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/rpc/src/rpc.rs b/crates/rpc/src/rpc.rs index 5fb9ca79a2..89963eb062 100644 --- a/crates/rpc/src/rpc.rs +++ b/crates/rpc/src/rpc.rs @@ -6,4 +6,4 @@ pub use conn::Connection; pub use peer::*; mod macros; -pub const PROTOCOL_VERSION: u32 = 35; +pub const PROTOCOL_VERSION: u32 = 36; From 54cf6fa838b74c94fb9e547b6c3aab2e02448580 Mon Sep 17 00:00:00 2001 From: K Simmons Date: Mon, 17 Oct 2022 16:19:03 -0700 Subject: [PATCH 3/4] Pull blink functionality out of editor and into blink manager. Make blink manager subscribe to settings changes in order to start blinking properly when it is re-enabled. Co-Authored-By: Mikayla Maki --- assets/settings/default.json | 4 +- crates/editor/src/blink_manager.rs | 110 +++++++++++++++++++++++++++++ crates/editor/src/editor.rs | 84 ++++------------------ crates/editor/src/element.rs | 2 +- crates/settings/src/settings.rs | 13 ++-- 5 files changed, 131 insertions(+), 82 deletions(-) create mode 100644 crates/editor/src/blink_manager.rs diff --git a/assets/settings/default.json b/assets/settings/default.json index 57f76f5f21..51aa108cd9 100644 --- a/assets/settings/default.json +++ b/assets/settings/default.json @@ -10,6 +10,8 @@ // Whether to show the informational hover box when moving the mouse // over symbols in the editor. "hover_popover_enabled": true, + // Whether the cursor blinks in the editor. + "cursor_blink": true, // Whether to pop the completions menu while typing in an editor without // explicitly requesting it. "show_completions_on_input": true, @@ -69,8 +71,6 @@ // The column at which to soft-wrap lines, for buffers where soft-wrap // is enabled. "preferred_line_length": 80, - // Whether the cursor blinks in the editor. - "cursor_blink": true, // Whether to indent lines using tab characters, as opposed to multiple // spaces. "hard_tabs": false, diff --git a/crates/editor/src/blink_manager.rs b/crates/editor/src/blink_manager.rs new file mode 100644 index 0000000000..77d10534d2 --- /dev/null +++ b/crates/editor/src/blink_manager.rs @@ -0,0 +1,110 @@ +use std::time::Duration; + +use gpui::{Entity, ModelContext}; +use settings::Settings; +use smol::Timer; + +pub struct BlinkManager { + blink_interval: Duration, + + blink_epoch: usize, + blinking_paused: bool, + visible: bool, + enabled: bool, +} + +impl BlinkManager { + pub fn new(blink_interval: Duration, cx: &mut ModelContext) -> Self { + let weak_handle = cx.weak_handle(); + cx.observe_global::(move |_, cx| { + if let Some(this) = weak_handle.upgrade(cx) { + // Make sure we blink the cursors if the setting is re-enabled + this.update(cx, |this, cx| this.blink_cursors(this.blink_epoch, cx)); + } + }) + .detach(); + + Self { + blink_interval, + + blink_epoch: 0, + blinking_paused: false, + visible: true, + enabled: true, + } + } + + fn next_blink_epoch(&mut self) -> usize { + self.blink_epoch += 1; + self.blink_epoch + } + + pub fn pause_blinking(&mut self, cx: &mut ModelContext) { + if !self.visible { + self.visible = true; + cx.notify(); + } + + let epoch = self.next_blink_epoch(); + let interval = self.blink_interval; + cx.spawn(|this, mut cx| { + let this = this.downgrade(); + async move { + Timer::after(interval).await; + if let Some(this) = this.upgrade(&cx) { + this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx)) + } + } + }) + .detach(); + } + + fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ModelContext) { + if epoch == self.blink_epoch { + self.blinking_paused = false; + self.blink_cursors(epoch, cx); + } + } + + fn blink_cursors(&mut self, epoch: usize, cx: &mut ModelContext) { + if cx.global::().cursor_blink { + if epoch == self.blink_epoch && self.enabled && !self.blinking_paused { + self.visible = !self.visible; + cx.notify(); + + let epoch = self.next_blink_epoch(); + let interval = self.blink_interval; + cx.spawn(|this, mut cx| { + let this = this.downgrade(); + async move { + Timer::after(interval).await; + if let Some(this) = this.upgrade(&cx) { + this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx)); + } + } + }) + .detach(); + } + } else if !self.visible { + self.visible = true; + cx.notify(); + } + } + + pub fn enable(&mut self, cx: &mut ModelContext) { + self.enabled = true; + self.blink_cursors(self.blink_epoch, cx); + } + + pub fn disable(&mut self, _: &mut ModelContext) { + self.enabled = true; + } + + pub fn visible(&self) -> bool { + self.visible + } +} + +impl Entity for BlinkManager { + type Event = (); +} diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs index 901547db2e..f3edee1a9e 100644 --- a/crates/editor/src/editor.rs +++ b/crates/editor/src/editor.rs @@ -1,3 +1,4 @@ +mod blink_manager; pub mod display_map; mod element; mod highlight_matching_bracket; @@ -16,6 +17,7 @@ pub mod test; use aho_corasick::AhoCorasick; use anyhow::Result; +use blink_manager::BlinkManager; use clock::ReplicaId; use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque}; pub use display_map::DisplayPoint; @@ -447,12 +449,10 @@ pub struct Editor { override_text_style: Option>, project: Option>, focused: bool, - show_local_cursors: bool, + blink_manager: ModelHandle, show_local_selections: bool, show_scrollbars: bool, hide_scrollbar_task: Option>, - blink_epoch: usize, - blinking_paused: bool, mode: EditorMode, vertical_scroll_margin: f32, placeholder_text: Option>, @@ -1076,6 +1076,8 @@ impl Editor { let selections = SelectionsCollection::new(display_map.clone(), buffer.clone()); + let blink_manager = cx.add_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx)); + let mut this = Self { handle: cx.weak_handle(), buffer: buffer.clone(), @@ -1097,12 +1099,10 @@ impl Editor { scroll_top_anchor: Anchor::min(), autoscroll_request: None, focused: false, - show_local_cursors: false, + blink_manager: blink_manager.clone(), show_local_selections: true, show_scrollbars: true, hide_scrollbar_task: None, - blink_epoch: 0, - blinking_paused: false, mode, vertical_scroll_margin: 3.0, placeholder_text: None, @@ -1130,6 +1130,7 @@ impl Editor { cx.observe(&buffer, Self::on_buffer_changed), cx.subscribe(&buffer, Self::on_buffer_event), cx.observe(&display_map, Self::on_display_map_changed), + cx.observe(&blink_manager, |_, _, cx| cx.notify()), ], }; this.end_selection(cx); @@ -1542,7 +1543,7 @@ impl Editor { refresh_matching_bracket_highlights(self, cx); } - self.pause_cursor_blinking(cx); + self.blink_manager.update(cx, BlinkManager::pause_blinking); cx.emit(Event::SelectionsChanged { local }); cx.notify(); } @@ -6111,70 +6112,8 @@ impl Editor { highlights } - fn next_blink_epoch(&mut self) -> usize { - self.blink_epoch += 1; - self.blink_epoch - } - - fn pause_cursor_blinking(&mut self, cx: &mut ViewContext) { - if !self.focused { - return; - } - - self.show_local_cursors = true; - cx.notify(); - - let epoch = self.next_blink_epoch(); - cx.spawn(|this, mut cx| { - let this = this.downgrade(); - async move { - Timer::after(CURSOR_BLINK_INTERVAL).await; - if let Some(this) = this.upgrade(&cx) { - this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx)) - } - } - }) - .detach(); - } - - fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext) { - if epoch == self.blink_epoch { - self.blinking_paused = false; - self.blink_cursors(epoch, cx); - } - } - - fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext) { - if epoch == self.blink_epoch && self.focused && !self.blinking_paused { - let newest_head = self.selections.newest::(cx).head(); - let language_name = self - .buffer - .read(cx) - .language_at(newest_head, cx) - .map(|l| l.name()); - - self.show_local_cursors = !self.show_local_cursors - || !cx - .global::() - .cursor_blink(language_name.as_deref()); - cx.notify(); - - let epoch = self.next_blink_epoch(); - cx.spawn(|this, mut cx| { - let this = this.downgrade(); - async move { - Timer::after(CURSOR_BLINK_INTERVAL).await; - if let Some(this) = this.upgrade(&cx) { - this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx)); - } - } - }) - .detach(); - } - } - - pub fn show_local_cursors(&self) -> bool { - self.show_local_cursors && self.focused + pub fn show_local_cursors(&self, cx: &AppContext) -> bool { + self.blink_manager.read(cx).visible() && self.focused } pub fn show_scrollbars(&self) -> bool { @@ -6493,7 +6432,7 @@ impl View for Editor { cx.focus(&rename.editor); } else { self.focused = true; - self.blink_cursors(self.blink_epoch, cx); + self.blink_manager.update(cx, BlinkManager::enable); self.buffer.update(cx, |buffer, cx| { buffer.finalize_last_transaction(cx); if self.leader_replica_id.is_none() { @@ -6512,6 +6451,7 @@ impl View for Editor { let blurred_event = EditorBlurred(cx.handle()); cx.emit_global(blurred_event); self.focused = false; + self.blink_manager.update(cx, BlinkManager::disable); self.buffer .update(cx, |buffer, cx| buffer.remove_active_selections(cx)); self.hide_context_menu(cx); diff --git a/crates/editor/src/element.rs b/crates/editor/src/element.rs index d2090741d8..57eee99405 100644 --- a/crates/editor/src/element.rs +++ b/crates/editor/src/element.rs @@ -705,7 +705,7 @@ impl EditorElement { cx, ); - if view.show_local_cursors() || *replica_id != local_replica_id { + if view.show_local_cursors(cx) || *replica_id != local_replica_id { let cursor_position = selection.head; if layout .visible_display_row_range diff --git a/crates/settings/src/settings.rs b/crates/settings/src/settings.rs index f079ae8670..ee389c7a0e 100644 --- a/crates/settings/src/settings.rs +++ b/crates/settings/src/settings.rs @@ -28,6 +28,7 @@ pub struct Settings { pub buffer_font_family: FamilyId, pub default_buffer_font_size: f32, pub buffer_font_size: f32, + pub cursor_blink: bool, pub hover_popover_enabled: bool, pub show_completions_on_input: bool, pub vim_mode: bool, @@ -79,7 +80,6 @@ pub struct GitGutterConfig {} pub struct EditorSettings { pub tab_size: Option, pub hard_tabs: Option, - pub cursor_blink: Option, pub soft_wrap: Option, pub preferred_line_length: Option, pub format_on_save: Option, @@ -235,6 +235,8 @@ pub struct SettingsFileContent { #[serde(default)] pub buffer_font_size: Option, #[serde(default)] + pub cursor_blink: Option, + #[serde(default)] pub hover_popover_enabled: Option, #[serde(default)] pub show_completions_on_input: Option, @@ -293,6 +295,7 @@ impl Settings { .unwrap(), buffer_font_size: defaults.buffer_font_size.unwrap(), default_buffer_font_size: defaults.buffer_font_size.unwrap(), + cursor_blink: defaults.cursor_blink.unwrap(), hover_popover_enabled: defaults.hover_popover_enabled.unwrap(), show_completions_on_input: defaults.show_completions_on_input.unwrap(), projects_online_by_default: defaults.projects_online_by_default.unwrap(), @@ -302,7 +305,6 @@ impl Settings { editor_defaults: EditorSettings { tab_size: required(defaults.editor.tab_size), hard_tabs: required(defaults.editor.hard_tabs), - cursor_blink: required(defaults.editor.cursor_blink), soft_wrap: required(defaults.editor.soft_wrap), preferred_line_length: required(defaults.editor.preferred_line_length), format_on_save: required(defaults.editor.format_on_save), @@ -348,6 +350,7 @@ impl Settings { ); merge(&mut self.buffer_font_size, data.buffer_font_size); merge(&mut self.default_buffer_font_size, data.buffer_font_size); + merge(&mut self.cursor_blink, data.cursor_blink); merge(&mut self.hover_popover_enabled, data.hover_popover_enabled); merge( &mut self.show_completions_on_input, @@ -392,10 +395,6 @@ impl Settings { self.language_setting(language, |settings| settings.hard_tabs) } - pub fn cursor_blink(&self, language: Option<&str>) -> bool { - self.language_setting(language, |settings| settings.cursor_blink) - } - pub fn soft_wrap(&self, language: Option<&str>) -> SoftWrap { self.language_setting(language, |settings| settings.soft_wrap) } @@ -442,6 +441,7 @@ impl Settings { buffer_font_family: cx.font_cache().load_family(&["Monaco"]).unwrap(), buffer_font_size: 14., default_buffer_font_size: 14., + cursor_blink: true, hover_popover_enabled: true, show_completions_on_input: true, vim_mode: false, @@ -450,7 +450,6 @@ impl Settings { editor_defaults: EditorSettings { tab_size: Some(4.try_into().unwrap()), hard_tabs: Some(false), - cursor_blink: Some(true), soft_wrap: Some(SoftWrap::None), preferred_line_length: Some(80), format_on_save: Some(FormatOnSave::On), From 54428ca6f6d5c63e82de6a360cb49d199f4b0d1d Mon Sep 17 00:00:00 2001 From: K Simmons Date: Mon, 17 Oct 2022 16:49:34 -0700 Subject: [PATCH 4/4] swap to using vercel to run the local zed.dev server --- Procfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Procfile b/Procfile index a64b411ef3..e1b87dd48b 100644 --- a/Procfile +++ b/Procfile @@ -1,2 +1,2 @@ -web: cd ../zed.dev && PORT=3000 npx next dev +web: cd ../zed.dev && PORT=3000 npx vercel dev collab: cd crates/collab && cargo run