1use core::indent::IndentStyle;
2use std::{
3 cell::{Cell, RefCell},
4 cmp::Ordering,
5 collections::{HashMap, hash_map::DefaultHasher},
6 hash::{Hash, Hasher},
7 rc::Rc,
8 sync::Arc,
9 time::Duration,
10};
11
12use crate::{
13 action::{TimerToken, exec_after, set_ime_allowed},
14 kurbo::{Point, Rect, Size, Vec2},
15 peniko::{Brush, Color, color::palette},
16 prop, prop_extractor,
17 reactive::{Effect, ReadSignal, RwSignal, Scope},
18 style::{CursorColor, StylePropValue, TextColor},
19 text::{Attrs, AttrsList, LineHeightValue, TextLayout, Wrap},
20 view::{IntoView, View},
21};
22use floem_editor_core::{
23 buffer::rope_text::{RopeText, RopeTextVal},
24 command::MoveCommand,
25 cursor::{ColPosition, Cursor, CursorAffinity, CursorMode},
26 mode::Mode,
27 movement::Movement,
28 register::Register,
29 selection::Selection,
30 soft_tab::{SnapDirection, snap_to_soft_tab_line_col},
31 word::WordCursor,
32};
33use floem_reactive::{SignalGet, SignalTrack, SignalUpdate, SignalWith, Trigger};
34use floem_renderer::text::Affinity;
35use lapce_xi_rope::Rope;
36
37pub mod actions;
38pub mod color;
39pub mod command;
40pub mod gutter;
41pub mod id;
42pub mod keypress;
43pub mod layout;
44pub mod listener;
45pub mod movement;
46pub mod phantom_text;
47pub mod text;
48pub mod text_document;
49pub mod view;
50pub mod visual_line;
51
52pub use floem_editor_core as core;
53use ui_events::{keyboard::Modifiers, pointer::PointerState};
54
55use self::{
56 command::Command,
57 id::EditorId,
58 layout::TextLayoutLine,
59 phantom_text::PhantomTextLine,
60 text::{Document, Preedit, PreeditData, RenderWhitespace, Styling, WrapMethod},
61 view::{LineInfo, ScreenLines, ScreenLinesBase},
62 visual_line::{
63 ConfigId, FontSizeCacheId, LayoutEvent, LineFontSizeProvider, Lines, RVLine, ResolvedWrap,
64 TextLayoutProvider, VLine, VLineInfo,
65 },
66};
67
68use super::Label;
69
70prop!(pub WrapProp: WrapMethod {} = WrapMethod::EditorWidth);
71impl StylePropValue for WrapMethod {
72 fn debug_view(&self) -> Option<Box<dyn View>> {
73 Some(crate::views::Label::new(self).into_any())
74 }
75}
76prop!(pub CursorSurroundingLines: usize {} = 1);
77prop!(pub ScrollBeyondLastLine: bool {} = false);
78prop!(pub ShowIndentGuide: bool {} = false);
79prop!(pub Modal: bool {} = false);
80prop!(pub ModalRelativeLine: bool {} = false);
81prop!(pub SmartTab: bool {} = false);
82prop!(pub PhantomColor: Color {} = palette::css::DIM_GRAY);
83prop!(pub PlaceholderColor: Color {} = palette::css::DIM_GRAY);
84prop!(pub PreeditUnderlineColor: Color {} = palette::css::WHITE);
85prop!(pub RenderWhitespaceProp: RenderWhitespace {} = RenderWhitespace::None);
86impl StylePropValue for RenderWhitespace {
87 fn debug_view(&self) -> Option<Box<dyn View>> {
88 Some(crate::views::Label::new(self).into_any())
89 }
90}
91prop!(pub IndentStyleProp: IndentStyle {} = IndentStyle::Spaces(4));
92impl StylePropValue for IndentStyle {
93 fn debug_view(&self) -> Option<Box<dyn View>> {
94 Some(Label::new(self).into_any())
95 }
96}
97prop!(pub DropdownShadow: Option<Color> {} = None);
98prop!(pub Foreground: Color { inherited } = Color::from_rgb8(0x38, 0x3A, 0x42));
99prop!(pub Focus: Option<Color> {} = None);
100prop!(pub SelectionColor: Color {} = palette::css::BLACK.with_alpha(0.5));
101prop!(pub CurrentLineColor: Option<Color> { } = None);
102prop!(pub Link: Option<Color> {} = None);
103prop!(pub VisibleWhitespaceColor: Color {} = palette::css::TRANSPARENT);
104prop!(pub IndentGuideColor: Color {} = palette::css::TRANSPARENT);
105prop!(pub StickyHeaderBackground: Option<Color> {} = None);
106
107prop_extractor! {
108 pub EditorStyle {
109 pub text_color: TextColor,
110 pub phantom_color: PhantomColor,
111 pub placeholder_color: PlaceholderColor,
112 pub preedit_underline_color: PreeditUnderlineColor,
113 pub show_indent_guide: ShowIndentGuide,
114 pub modal: Modal,
115 pub modal_relative_line: ModalRelativeLine,
117 pub smart_tab: SmartTab,
120 pub wrap_method: WrapProp,
121 pub cursor_surrounding_lines: CursorSurroundingLines,
122 pub render_whitespace: RenderWhitespaceProp,
123 pub indent_style: IndentStyleProp,
124 pub caret: CursorColor,
125 pub selection: SelectionColor,
126 pub current_line: CurrentLineColor,
127 pub visible_whitespace: VisibleWhitespaceColor,
128 pub indent_guide: IndentGuideColor,
129 pub scroll_beyond_last_line: ScrollBeyondLastLine,
130 }
131}
132impl EditorStyle {
133 pub fn ed_text_color(&self) -> Color {
134 self.text_color().unwrap_or(palette::css::BLACK)
135 }
136}
137impl EditorStyle {
138 pub fn ed_caret(&self) -> Brush {
139 self.caret()
140 }
141}
142
143pub(crate) const CHAR_WIDTH: f64 = 7.5;
144
145#[derive(Clone)]
151pub struct Editor {
152 pub cx: Cell<Scope>,
153 effects_cx: Cell<Scope>,
154
155 id: EditorId,
156
157 pub active: RwSignal<bool>,
158
159 pub read_only: RwSignal<bool>,
161
162 pub(crate) doc: RwSignal<Rc<dyn Document>>,
163 pub(crate) style: RwSignal<Rc<dyn Styling>>,
164
165 pub cursor: RwSignal<Cursor>,
166
167 pub window_origin: RwSignal<Point>,
168 pub viewport: RwSignal<Rect>,
169 pub parent_size: RwSignal<Rect>,
170
171 pub(crate) editor_view_focused_value: RwSignal<bool>,
172 pub editor_view_focused: Trigger,
173 pub editor_view_focus_lost: Trigger,
174 pub editor_view_id: RwSignal<Option<crate::view::ViewId>>,
175
176 pub scroll_delta: RwSignal<Vec2>,
178 pub scroll_to: RwSignal<Option<Vec2>>,
179
180 lines: Rc<Lines>,
182 pub screen_lines: RwSignal<ScreenLines>,
183
184 pub register: RwSignal<Register>,
186 pub cursor_info: CursorInfo,
188
189 pub last_movement: RwSignal<Movement>,
190
191 pub ime_allowed: RwSignal<bool>,
195 pub(crate) ime_cursor_area: RwSignal<Option<(Point, Size)>>,
196 owns_preedit: RwSignal<bool>,
197
198 pub es: RwSignal<EditorStyle>,
200
201 pub floem_style_id: RwSignal<u64>,
202}
203impl Editor {
204 pub fn new(cx: Scope, doc: Rc<dyn Document>, style: Rc<dyn Styling>, modal: bool) -> Editor {
209 let id = EditorId::next();
210 Editor::new_id(cx, id, doc, style, modal)
211 }
212
213 pub fn new_id(
220 cx: Scope,
221 id: EditorId,
222 doc: Rc<dyn Document>,
223 style: Rc<dyn Styling>,
224 modal: bool,
225 ) -> Editor {
226 let editor = Editor::new_direct(cx, id, doc, style, modal);
227 editor.recreate_view_effects();
228
229 editor
230 }
231
232 pub fn new_direct(
249 cx: Scope,
250 id: EditorId,
251 doc: Rc<dyn Document>,
252 style: Rc<dyn Styling>,
253 modal: bool,
254 ) -> Editor {
255 let cx = cx.create_child();
256
257 let viewport = cx.create_rw_signal(Rect::ZERO);
258 let cursor_mode = if modal {
259 CursorMode::Normal {
260 offset: 0,
261 affinity: CursorAffinity::Backward,
262 }
263 } else {
264 CursorMode::Insert(Selection::caret(0, CursorAffinity::Backward))
265 };
266 let cursor = Cursor::new(cursor_mode, None, None);
267 let cursor = cx.create_rw_signal(cursor);
268
269 let doc = cx.create_rw_signal(doc);
270 let style = cx.create_rw_signal(style);
271
272 let font_sizes = RefCell::new(Rc::new(EditorFontSizes {
273 id,
274 style: style.read_only(),
275 doc: doc.read_only(),
276 }));
277 let lines = Rc::new(Lines::new(cx, font_sizes));
278 let screen_lines = cx.create_rw_signal(ScreenLines::new(cx, viewport.get_untracked()));
279
280 let editor_style = cx.create_rw_signal(EditorStyle::default());
281
282 let ed = Editor {
283 cx: Cell::new(cx),
284 effects_cx: Cell::new(cx.create_child()),
285 id,
286 active: cx.create_rw_signal(false),
287 read_only: cx.create_rw_signal(false),
288 doc,
289 style,
290 cursor,
291 window_origin: cx.create_rw_signal(Point::ZERO),
292 viewport,
293 parent_size: cx.create_rw_signal(Rect::ZERO),
294 scroll_delta: cx.create_rw_signal(Vec2::ZERO),
295 scroll_to: cx.create_rw_signal(None),
296 editor_view_focused_value: cx.create_rw_signal(false),
297 editor_view_focused: cx.create_trigger(),
298 editor_view_focus_lost: cx.create_trigger(),
299 editor_view_id: cx.create_rw_signal(None),
300 lines,
301 screen_lines,
302 register: cx.create_rw_signal(Register::default()),
303 cursor_info: CursorInfo::new(cx),
304 last_movement: cx.create_rw_signal(Movement::Left),
305 ime_allowed: cx.create_rw_signal(false),
306 ime_cursor_area: cx.create_rw_signal(None),
307 owns_preedit: cx.create_rw_signal(false),
308 es: editor_style,
309 floem_style_id: cx.create_rw_signal(0),
310 };
311
312 create_view_effects(ed.effects_cx.get(), &ed);
313
314 ed
315 }
316
317 pub fn id(&self) -> EditorId {
318 self.id
319 }
320
321 pub fn doc(&self) -> Rc<dyn Document> {
323 self.doc.get_untracked()
324 }
325
326 pub fn doc_track(&self) -> Rc<dyn Document> {
327 self.doc.get()
328 }
329
330 pub fn doc_signal(&self) -> RwSignal<Rc<dyn Document>> {
332 self.doc
333 }
334
335 pub fn config_id(&self) -> ConfigId {
336 let style_id = self.style.with(|s| s.id());
337 let floem_style_id = self.floem_style_id;
338 ConfigId::new(style_id, floem_style_id.get_untracked())
339 }
340
341 pub fn recreate_view_effects(&self) {
342 Effect::batch(|| {
343 self.effects_cx.get().dispose();
344 self.effects_cx.set(self.cx.get().create_child());
345 create_view_effects(self.effects_cx.get(), self);
346 });
347 }
348
349 pub fn update_doc(&self, doc: Rc<dyn Document>, styling: Option<Rc<dyn Styling>>) {
351 Effect::batch(|| {
352 self.effects_cx.get().dispose();
354
355 *self.lines.font_sizes.borrow_mut() = Rc::new(EditorFontSizes {
356 id: self.id(),
357 style: self.style.read_only(),
358 doc: self.doc.read_only(),
359 });
360 self.lines.clear(0, None);
361 self.doc.set(doc);
362 if let Some(styling) = styling {
363 self.style.set(styling);
364 }
365 self.screen_lines.update(|screen_lines| {
366 screen_lines.clear(self.viewport.get_untracked());
367 });
368
369 self.effects_cx.set(self.cx.get().create_child());
371 create_view_effects(self.effects_cx.get(), self);
372 });
373 }
374
375 pub fn update_styling(&self, styling: Rc<dyn Styling>) {
376 Effect::batch(|| {
377 self.effects_cx.get().dispose();
379
380 *self.lines.font_sizes.borrow_mut() = Rc::new(EditorFontSizes {
381 id: self.id(),
382 style: self.style.read_only(),
383 doc: self.doc.read_only(),
384 });
385 self.lines.clear(0, None);
386
387 self.style.set(styling);
388
389 self.screen_lines.update(|screen_lines| {
390 screen_lines.clear(self.viewport.get_untracked());
391 });
392
393 self.effects_cx.set(self.cx.get().create_child());
395 create_view_effects(self.effects_cx.get(), self);
396 });
397 }
398
399 pub fn duplicate(&self, editor_id: Option<EditorId>) -> Editor {
400 let doc = self.doc();
401 let style = self.style();
402 let mut editor = Editor::new_direct(
403 self.cx.get(),
404 editor_id.unwrap_or_else(EditorId::next),
405 doc,
406 style,
407 false,
408 );
409
410 Effect::batch(|| {
411 editor.read_only.set(self.read_only.get_untracked());
412 editor.es.set(self.es.get_untracked());
413 editor
414 .floem_style_id
415 .set(self.floem_style_id.get_untracked());
416 editor.cursor.set(self.cursor.get_untracked());
417 editor.scroll_delta.set(self.scroll_delta.get_untracked());
418 editor.scroll_to.set(self.scroll_to.get_untracked());
419 editor.window_origin.set(self.window_origin.get_untracked());
420 editor.viewport.set(self.viewport.get_untracked());
421 editor.parent_size.set(self.parent_size.get_untracked());
422 editor.register.set(self.register.get_untracked());
423 editor.cursor_info = self.cursor_info.clone();
424 editor.last_movement.set(self.last_movement.get_untracked());
425 });
428
429 editor.recreate_view_effects();
430
431 editor
432 }
433
434 pub fn style(&self) -> Rc<dyn Styling> {
436 self.style.get_untracked()
437 }
438
439 pub fn text(&self) -> Rope {
443 self.doc().text()
444 }
445
446 pub fn rope_text(&self) -> RopeTextVal {
448 self.doc().rope_text()
449 }
450
451 pub fn lines(&self) -> &Lines {
452 &self.lines
453 }
454
455 pub fn text_prov(&self) -> &Self {
456 self
457 }
458
459 fn preedit(&self) -> PreeditData {
460 self.doc.with_untracked(|doc| doc.preedit())
461 }
462
463 pub fn set_preedit(&self, text: String, cursor: Option<(usize, usize)>, offset: usize) {
464 Effect::batch(|| {
465 self.doc().cache_rev().update(|cache_rev| {
466 *cache_rev += 1;
467 });
468
469 if self.preedit().preedit.with_untracked(|p| p.is_none()) {
470 self.owns_preedit.set(true);
471 }
472
473 self.preedit().preedit.set(Some(Preedit {
476 text,
477 cursor,
478 offset,
479 }));
480 });
481 }
482
483 pub fn commit_preedit(&self) {
484 if !self.owns_preedit.get_untracked() {
485 return;
486 }
487
488 Effect::batch(|| {
489 self.owns_preedit.set(false);
490
491 let commited = self.preedit().preedit.with_untracked(|preedit| {
492 let Some(preedit) = preedit else {
493 return false;
494 };
495
496 self.receive_char(&preedit.text);
497
498 true
499 });
500
501 if !commited {
502 return;
503 }
504
505 self.preedit().preedit.set(None);
506 self.ime_cursor_area.set(None);
507
508 if self.editor_view_focused_value.get_untracked() {
509 set_ime_allowed(false);
510 set_ime_allowed(true);
511 }
512 });
513 }
514
515 pub fn clear_preedit(&self) {
516 self.owns_preedit.set(false);
517
518 let preedit = self.preedit();
519 if preedit.preedit.with_untracked(|preedit| preedit.is_none()) {
520 return;
521 }
522
523 Effect::batch(|| {
524 preedit.preedit.set(None);
525 self.doc().cache_rev().update(|cache_rev| {
526 *cache_rev += 1;
527 });
528 });
529 }
530
531 pub fn receive_char(&self, c: &str) {
532 self.doc().receive_char(self, c)
533 }
534
535 fn compute_screen_lines(&self, base: RwSignal<ScreenLinesBase>) -> ScreenLines {
536 self.doc().compute_screen_lines(self, base)
540 }
541
542 pub fn pointer_down_primary(&self, state: &PointerState) {
544 self.active.set(true);
545 self.left_click(state);
546 }
547
548 pub fn left_click(&self, state: &PointerState) {
549 match state.count {
550 1 => {
551 self.single_click(state);
552 }
553 2 => {
554 self.double_click(state);
555 }
556 3 => {
557 self.triple_click(state);
558 }
559 _ => {}
560 }
561 }
562
563 pub fn single_click(&self, pointer_event: &PointerState) {
564 self.commit_preedit();
565
566 let mode = self.cursor.with_untracked(|c| c.get_mode());
567 let (new_offset, _, mut affinity) =
568 self.offset_of_point(mode, pointer_event.logical_point());
569
570 if self.preedit().preedit.with_untracked(|p| p.is_some()) {
571 affinity = CursorAffinity::Forward;
573 }
574
575 self.cursor.update(|cursor| {
576 cursor.set_offset(
577 new_offset,
578 affinity,
579 pointer_event.modifiers.shift(),
580 pointer_event.modifiers.alt(),
581 );
582 });
583 }
584
585 pub fn double_click(&self, pointer_event: &PointerState) {
586 self.commit_preedit();
587
588 let mode = self.cursor.with_untracked(|c| c.get_mode());
589 let (mouse_offset, ..) = self.offset_of_point(mode, pointer_event.logical_point());
590 let (start, end) = self.select_word(mouse_offset);
591
592 self.cursor.update(|cursor| {
593 cursor.add_region(
594 start,
595 end,
596 CursorAffinity::Backward,
597 pointer_event.modifiers.shift(),
598 pointer_event.modifiers.alt(),
599 );
600 });
601 }
602
603 pub fn triple_click(&self, pointer_event: &PointerState) {
604 self.commit_preedit();
605
606 let mode = self.cursor.with_untracked(|c| c.get_mode());
607 let (mouse_offset, ..) = self.offset_of_point(mode, pointer_event.logical_point());
608 let line = self.line_of_offset(mouse_offset);
609 let start = self.offset_of_line(line);
610 let end = self.offset_of_line(line + 1);
611
612 self.cursor.update(|cursor| {
613 cursor.add_region(
614 start,
615 end,
616 CursorAffinity::Backward,
617 pointer_event.modifiers.shift(),
618 pointer_event.modifiers.alt(),
619 )
620 });
621 }
622
623 pub fn pointer_move(&self, pointer_event: &PointerState) {
624 let mode = self.cursor.with_untracked(|c| c.get_mode());
625 let (offset, _, affinity) = self.offset_of_point(mode, pointer_event.logical_point());
626 if self.active.get_untracked() && self.cursor.with_untracked(|c| c.offset()) != offset {
627 self.commit_preedit();
628
629 self.cursor.update(|cursor| {
630 cursor.set_offset(offset, affinity, true, pointer_event.modifiers.alt())
631 });
632 }
633 }
634
635 pub fn pointer_up(&self, _pointer_event: &PointerState) {
636 self.active.set(false);
637 }
638
639 fn right_click(&self, pointer_event: &PointerState) {
640 let mode = self.cursor.with_untracked(|c| c.get_mode());
641 let (offset, ..) = self.offset_of_point(mode, pointer_event.logical_point());
642 let doc = self.doc();
643 let pointer_inside_selection = self
644 .cursor
645 .with_untracked(|c| c.edit_selection(&doc.rope_text()).contains(offset));
646 if !pointer_inside_selection {
647 self.single_click(pointer_event);
649 }
650 }
651
652 pub fn page_move(&self, down: bool, mods: Modifiers) {
654 let viewport = self.viewport.get_untracked();
655 let line_height = f64::from(self.line_height(0));
657 let lines = (viewport.height() / line_height / 2.0).round() as usize;
658 let distance = (lines as f64) * line_height;
659 self.scroll_delta
660 .set(Vec2::new(0.0, if down { distance } else { -distance }));
661 let cmd = if down {
662 MoveCommand::Down
663 } else {
664 MoveCommand::Up
665 };
666 let cmd = Command::Move(cmd);
667 self.doc().run_command(self, &cmd, Some(lines), mods);
668 }
669
670 pub fn center_window(&self) {
671 let viewport = self.viewport.get_untracked();
672 let line_height = f64::from(self.line_height(0));
674 let offset = self.cursor.with_untracked(|cursor| cursor.offset());
675 let (line, _col) = self.offset_to_line_col(offset);
676
677 let viewport_center = viewport.height() / 2.0;
678
679 let current_line_position = line as f64 * line_height;
680
681 let desired_top = current_line_position - viewport_center + (line_height / 2.0);
682
683 let scroll_delta = desired_top - viewport.y0;
684
685 self.scroll_delta.set(Vec2::new(0.0, scroll_delta));
686 }
687
688 pub fn top_of_window(&self, scroll_off: usize) {
689 let viewport = self.viewport.get_untracked();
690 let line_height = f64::from(self.line_height(0));
692 let offset = self.cursor.with_untracked(|cursor| cursor.offset());
693 let (line, _col) = self.offset_to_line_col(offset);
694
695 let desired_top = (line.saturating_sub(scroll_off)) as f64 * line_height;
696
697 let scroll_delta = desired_top - viewport.y0;
698
699 self.scroll_delta.set(Vec2::new(0.0, scroll_delta));
700 }
701
702 pub fn bottom_of_window(&self, scroll_off: usize) {
703 let viewport = self.viewport.get_untracked();
704 let line_height = f64::from(self.line_height(0));
706 let offset = self.cursor.with_untracked(|cursor| cursor.offset());
707 let (line, _col) = self.offset_to_line_col(offset);
708
709 let desired_bottom = (line + scroll_off + 1) as f64 * line_height - viewport.height();
710
711 let scroll_delta = desired_bottom - viewport.y0;
712
713 self.scroll_delta.set(Vec2::new(0.0, scroll_delta));
714 }
715
716 pub fn scroll(&self, top_shift: f64, down: bool, count: usize, mods: Modifiers) {
717 let viewport = self.viewport.get_untracked();
718 let line_height = f64::from(self.line_height(0));
720 let diff = line_height * count as f64;
721 let diff = if down { diff } else { -diff };
722
723 let offset = self.cursor.with_untracked(|cursor| cursor.offset());
724 let (line, _col) = self.offset_to_line_col(offset);
725 let top = viewport.y0 + diff + top_shift;
726 let bottom = viewport.y0 + diff + viewport.height();
727
728 let new_line = if (line + 1) as f64 * line_height + line_height > bottom {
729 let line = (bottom / line_height).floor() as usize;
730 line.saturating_sub(2)
731 } else if line as f64 * line_height - line_height < top {
732 let line = (top / line_height).ceil() as usize;
733 line + 1
734 } else {
735 line
736 };
737
738 self.scroll_delta.set(Vec2::new(0.0, diff));
739
740 let res = match new_line.cmp(&line) {
741 Ordering::Greater => Some((MoveCommand::Down, new_line - line)),
742 Ordering::Less => Some((MoveCommand::Up, line - new_line)),
743 _ => None,
744 };
745
746 if let Some((cmd, count)) = res {
747 let cmd = Command::Move(cmd);
748 self.doc().run_command(self, &cmd, Some(count), mods);
749 }
750 }
751
752 pub fn phantom_text(&self, line: usize) -> PhantomTextLine {
755 self.doc()
756 .phantom_text(self.id(), &self.es.get_untracked(), line)
757 }
758
759 pub fn line_height(&self, line: usize) -> f32 {
760 self.style().line_height(self.id(), line)
761 }
762
763 pub fn iter_vlines(
767 &self,
768 backwards: bool,
769 start: VLine,
770 ) -> impl Iterator<Item = VLineInfo> + '_ {
771 self.lines.iter_vlines(self.text_prov(), backwards, start)
772 }
773
774 pub fn iter_vlines_over(
777 &self,
778 backwards: bool,
779 start: VLine,
780 end: VLine,
781 ) -> impl Iterator<Item = VLineInfo> + '_ {
782 self.lines
783 .iter_vlines_over(self.text_prov(), backwards, start, end)
784 }
785
786 pub fn iter_rvlines(
790 &self,
791 backwards: bool,
792 start: RVLine,
793 ) -> impl Iterator<Item = VLineInfo<()>> + '_ {
794 self.lines.iter_rvlines(self.text_prov(), backwards, start)
795 }
796
797 pub fn iter_rvlines_over(
804 &self,
805 backwards: bool,
806 start: RVLine,
807 end_line: usize,
808 ) -> impl Iterator<Item = VLineInfo<()>> + '_ {
809 self.lines
810 .iter_rvlines_over(self.text_prov(), backwards, start, end_line)
811 }
812
813 pub fn first_rvline_info(&self) -> VLineInfo<()> {
816 self.rvline_info(RVLine::default())
817 }
818
819 pub fn num_lines(&self) -> usize {
821 self.rope_text().num_lines()
822 }
823
824 pub fn last_line(&self) -> usize {
826 self.rope_text().last_line()
827 }
828
829 pub fn last_vline(&self) -> VLine {
830 self.lines.last_vline(self.text_prov())
831 }
832
833 pub fn last_rvline(&self) -> RVLine {
834 self.lines.last_rvline(self.text_prov())
835 }
836
837 pub fn last_rvline_info(&self) -> VLineInfo<()> {
838 self.rvline_info(self.last_rvline())
839 }
840
841 pub fn offset_to_line_col(&self, offset: usize) -> (usize, usize) {
845 self.rope_text().offset_to_line_col(offset)
846 }
847
848 pub fn offset_of_line(&self, offset: usize) -> usize {
849 self.rope_text().offset_of_line(offset)
850 }
851
852 pub fn offset_of_line_col(&self, line: usize, col: usize) -> usize {
853 self.rope_text().offset_of_line_col(line, col)
854 }
855
856 pub fn line_of_offset(&self, offset: usize) -> usize {
858 self.rope_text().line_of_offset(offset)
859 }
860
861 pub fn first_non_blank_character_on_line(&self, line: usize) -> usize {
863 self.rope_text().first_non_blank_character_on_line(line)
864 }
865
866 pub fn line_end_col(&self, line: usize, caret: bool) -> usize {
867 self.rope_text().line_end_col(line, caret)
868 }
869
870 pub fn select_word(&self, offset: usize) -> (usize, usize) {
871 self.rope_text().select_word(offset)
872 }
873
874 pub fn vline_of_offset(&self, offset: usize, affinity: CursorAffinity) -> VLine {
880 self.lines
881 .vline_of_offset(&self.text_prov(), offset, affinity)
882 }
883
884 pub fn vline_of_line(&self, line: usize) -> VLine {
885 self.lines.vline_of_line(&self.text_prov(), line)
886 }
887
888 pub fn rvline_of_line(&self, line: usize) -> RVLine {
889 self.lines.rvline_of_line(&self.text_prov(), line)
890 }
891
892 pub fn vline_of_rvline(&self, rvline: RVLine) -> VLine {
893 self.lines.vline_of_rvline(&self.text_prov(), rvline)
894 }
895
896 pub fn offset_of_vline(&self, vline: VLine) -> usize {
898 self.lines.offset_of_vline(&self.text_prov(), vline)
899 }
900
901 pub fn vline_col_of_offset(&self, offset: usize, affinity: CursorAffinity) -> (VLine, usize) {
905 self.lines
906 .vline_col_of_offset(&self.text_prov(), offset, affinity)
907 }
908
909 pub fn rvline_of_offset(&self, offset: usize, affinity: CursorAffinity) -> RVLine {
910 self.lines
911 .rvline_of_offset(&self.text_prov(), offset, affinity)
912 }
913
914 pub fn rvline_col_of_offset(&self, offset: usize, affinity: CursorAffinity) -> (RVLine, usize) {
915 self.lines
916 .rvline_col_of_offset(&self.text_prov(), offset, affinity)
917 }
918
919 pub fn offset_of_rvline(&self, rvline: RVLine) -> usize {
920 self.lines.offset_of_rvline(&self.text_prov(), rvline)
921 }
922
923 pub fn vline_info(&self, vline: VLine) -> VLineInfo {
924 let vline = vline.min(self.last_vline());
925 self.iter_vlines(false, vline).next().unwrap()
926 }
927
928 pub fn screen_rvline_info_of_offset(
929 &self,
930 offset: usize,
931 affinity: CursorAffinity,
932 ) -> Option<VLineInfo<()>> {
933 let rvline = self.rvline_of_offset(offset, affinity);
934 self.screen_lines.with_untracked(|screen_lines| {
935 screen_lines
936 .iter_vline_info()
937 .find(|vline_info| vline_info.rvline == rvline)
938 })
939 }
940
941 pub fn rvline_info(&self, rvline: RVLine) -> VLineInfo<()> {
942 let rvline = rvline.min(self.last_rvline());
943 self.iter_rvlines(false, rvline).next().unwrap()
944 }
945
946 pub fn rvline_info_of_offset(&self, offset: usize, affinity: CursorAffinity) -> VLineInfo<()> {
947 let rvline = self.rvline_of_offset(offset, affinity);
948 self.rvline_info(rvline)
949 }
950
951 pub fn first_col<T: std::fmt::Debug>(&self, info: VLineInfo<T>) -> usize {
953 info.first_col(&self.text_prov())
954 }
955
956 pub fn last_col<T: std::fmt::Debug>(&self, info: VLineInfo<T>, caret: bool) -> usize {
958 info.last_col(&self.text_prov(), caret)
959 }
960
961 pub fn max_line_width(&self) -> f64 {
964 self.lines.max_width()
965 }
966
967 pub fn line_point_of_offset(&self, offset: usize, affinity: CursorAffinity) -> Point {
970 let (line, col) = self.offset_to_line_col(offset);
971 self.line_point_of_line_col(line, col, affinity, false)
972 }
973
974 pub fn line_point_of_line_col(
977 &self,
978 line: usize,
979 col: usize,
980 affinity: CursorAffinity,
981 force_affinity: bool,
982 ) -> Point {
983 let text_layout = self.text_layout(line);
984 let index = if force_affinity {
985 text_layout
986 .phantom_text
987 .col_after_force(col, affinity == CursorAffinity::Forward)
988 } else {
989 text_layout
990 .phantom_text
991 .col_after(col, affinity == CursorAffinity::Forward)
992 };
993
994 let aff = match affinity {
995 CursorAffinity::Backward => Affinity::Before,
996 CursorAffinity::Forward => Affinity::After,
997 };
998
999 text_layout.text.hit_position_aff(index, aff).point
1000 }
1001
1002 pub fn points_of_offset(&self, offset: usize, affinity: CursorAffinity) -> (Point, Point) {
1004 let line = self.line_of_offset(offset);
1005 let line_height = f64::from(self.style().line_height(self.id(), line));
1006
1007 let vline = self.rvline_info_of_offset(offset, affinity);
1008 let Some(info) = self.screen_lines.with_untracked(|sl| sl.info(vline.rvline)) else {
1009 return (Point::new(0.0, 0.0), Point::new(0.0, 0.0));
1013 };
1014
1015 let y = info.vline_y;
1016
1017 let x = self.line_point_of_offset(offset, affinity).x;
1018
1019 (Point::new(x, y), Point::new(x, y + line_height))
1020 }
1021
1022 pub fn offset_of_point(&self, mode: Mode, point: Point) -> (usize, bool, CursorAffinity) {
1027 let ((line, col), is_inside, affinity) = self.line_col_of_point(mode, point);
1028 (self.offset_of_line_col(line, col), is_inside, affinity)
1029 }
1030
1031 pub fn line_col_of_point_with_phantom(&self, point: Point) -> (usize, usize) {
1033 let line_height = f64::from(self.style().line_height(self.id(), 0));
1034 let info = if point.y <= 0.0 {
1035 Some(self.first_rvline_info())
1036 } else {
1037 self.screen_lines
1038 .with_untracked(|sl| {
1039 sl.iter_line_info().find(|info| {
1040 info.vline_y <= point.y && info.vline_y + line_height >= point.y
1041 })
1042 })
1043 .map(|info| info.vline_info)
1044 };
1045 let info = info.unwrap_or_else(|| {
1046 for (y_idx, info) in self.iter_rvlines(false, RVLine::default()).enumerate() {
1047 let vline_y = y_idx as f64 * line_height;
1048 if vline_y <= point.y && vline_y + line_height >= point.y {
1049 return info;
1050 }
1051 }
1052
1053 self.last_rvline_info()
1054 });
1055
1056 let rvline = info.rvline;
1057 let line = rvline.line;
1058 let text_layout = self.text_layout(line);
1059
1060 let y = text_layout.get_layout_y(rvline.line_index).unwrap_or(0.0);
1061
1062 let hit_point = text_layout.text.hit_point(Point::new(point.x, y as f64));
1063 (line, hit_point.index)
1064 }
1065
1066 pub fn line_col_of_point(
1071 &self,
1072 mode: Mode,
1073 point: Point,
1074 ) -> ((usize, usize), bool, CursorAffinity) {
1075 let line_height = f64::from(self.style().line_height(self.id(), 0));
1077 let info = if point.y <= 0.0 {
1078 Some(self.first_rvline_info())
1079 } else {
1080 self.screen_lines
1081 .with_untracked(|sl| {
1082 sl.iter_line_info().find(|info| {
1083 info.vline_y <= point.y && info.vline_y + line_height >= point.y
1084 })
1085 })
1086 .map(|info| info.vline_info)
1087 };
1088 let info = info.unwrap_or_else(|| {
1089 for (y_idx, info) in self.iter_rvlines(false, RVLine::default()).enumerate() {
1090 let vline_y = y_idx as f64 * line_height;
1091 if vline_y <= point.y && vline_y + line_height >= point.y {
1092 return info;
1093 }
1094 }
1095
1096 self.last_rvline_info()
1097 });
1098
1099 let rvline = info.rvline;
1100 let line = rvline.line;
1101 let text_layout = self.text_layout(line);
1102
1103 let y = text_layout.get_layout_y(rvline.line_index).unwrap_or(0.0);
1104
1105 let hit_point = text_layout.text.hit_point(Point::new(point.x, y as f64));
1106 let mut affinity = match hit_point.affinity {
1107 Affinity::Before => CursorAffinity::Backward,
1108 Affinity::After => CursorAffinity::Forward,
1109 };
1110 let col = text_layout.phantom_text.before_col(hit_point.index);
1113 let max_col = self.line_end_col(line, mode != Mode::Normal);
1116 let mut col = col.min(max_col);
1117
1118 if !hit_point.is_inside {
1121 col = info.last_col(&self.text_prov(), true);
1123 }
1124
1125 let tab_width = self.style().tab_width(self.id(), line);
1126 if self.style().atomic_soft_tabs(self.id(), line) && tab_width > 1 {
1127 col = snap_to_soft_tab_line_col(
1128 &self.text(),
1129 line,
1130 col,
1131 SnapDirection::Nearest,
1132 tab_width,
1133 );
1134 affinity = CursorAffinity::Forward;
1135 }
1136
1137 ((line, col), hit_point.is_inside, affinity)
1138 }
1139
1140 pub fn line_horiz_col(&self, line: usize, horiz: &ColPosition, caret: bool) -> usize {
1142 match *horiz {
1143 ColPosition::Col(x) => {
1144 let text_layout = self.text_layout(line);
1147 let hit_point = text_layout.text.hit_point(Point::new(x, 0.0));
1148 let n = hit_point.index;
1149 let col = text_layout.phantom_text.before_col(n);
1150
1151 col.min(self.line_end_col(line, caret))
1152 }
1153 ColPosition::End => self.line_end_col(line, caret),
1154 ColPosition::Start => 0,
1155 ColPosition::FirstNonBlank => self.first_non_blank_character_on_line(line),
1156 }
1157 }
1158
1159 pub fn rvline_horiz_col(&self, rvline: RVLine, horiz: &ColPosition, caret: bool) -> usize {
1162 let RVLine { line, line_index } = rvline;
1163
1164 match *horiz {
1165 ColPosition::Col(x) => {
1166 let text_layout = self.text_layout(line);
1167 let y_pos = text_layout
1168 .text
1169 .layout_runs()
1170 .nth(line_index)
1171 .map(|run| run.line_y)
1172 .or_else(|| text_layout.text.layout_runs().last().map(|run| run.line_y))
1173 .unwrap_or(0.0);
1174 let hit_point = text_layout.text.hit_point(Point::new(x, y_pos as f64));
1175 let n = hit_point.index;
1176 let col = text_layout.phantom_text.before_col(n);
1177
1178 col.min(self.line_end_col(line, caret))
1179 }
1180 ColPosition::End => {
1181 let info = self.rvline_info(rvline);
1182 self.last_col(info, caret)
1183 }
1184 ColPosition::Start => {
1185 let info = self.rvline_info(rvline);
1186 self.first_col(info)
1187 }
1188 ColPosition::FirstNonBlank => {
1189 let info = self.rvline_info(rvline);
1190 let rope_text = self.text_prov().rope_text();
1191 let next_offset =
1192 WordCursor::new(rope_text.text(), info.interval.start).next_non_blank_char();
1193
1194 next_offset - info.interval.start + self.first_col(info)
1195 }
1196 }
1197 }
1198
1199 pub fn move_right(&self, offset: usize, mode: Mode, count: usize) -> usize {
1203 self.rope_text().move_right(offset, mode, count)
1204 }
1205
1206 pub fn move_left(&self, offset: usize, mode: Mode, count: usize) -> usize {
1209 self.rope_text().move_left(offset, mode, count)
1210 }
1211}
1212
1213impl std::fmt::Debug for Editor {
1214 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1215 f.debug_tuple("Editor").field(&self.id).finish()
1216 }
1217}
1218
1219impl Editor {
1221 pub fn text_layout(&self, line: usize) -> Arc<TextLayoutLine> {
1223 self.text_layout_trigger(line, true)
1224 }
1225
1226 pub fn text_layout_trigger(&self, line: usize, trigger: bool) -> Arc<TextLayoutLine> {
1227 let cache_rev = self.doc().cache_rev().get_untracked();
1228 self.lines
1229 .get_init_text_layout(cache_rev, self.config_id(), self, line, trigger)
1230 }
1231
1232 fn try_get_text_layout(&self, line: usize) -> Option<Arc<TextLayoutLine>> {
1233 let cache_rev = self.doc().cache_rev().get_untracked();
1234 self.lines
1235 .try_get_text_layout(cache_rev, self.config_id(), line)
1236 }
1237
1238 fn new_whitespace_layout(
1242 line_content: &str,
1243 text_layout: &TextLayout,
1244 phantom: &PhantomTextLine,
1245 render_whitespace: RenderWhitespace,
1246 ) -> Option<Vec<(char, (f64, f64))>> {
1247 let mut render_leading = false;
1248 let mut render_boundary = false;
1249 let mut render_between = false;
1250
1251 match render_whitespace {
1253 RenderWhitespace::All => {
1254 render_leading = true;
1255 render_boundary = true;
1256 render_between = true;
1257 }
1258 RenderWhitespace::Boundary => {
1259 render_leading = true;
1260 render_boundary = true;
1261 }
1262 RenderWhitespace::Trailing => {} RenderWhitespace::None => return None,
1264 }
1265
1266 let mut whitespace_buffer = Vec::new();
1267 let mut rendered_whitespaces: Vec<(char, (f64, f64))> = Vec::new();
1268 let mut char_found = false;
1269 let mut col = 0;
1270 for c in line_content.chars() {
1271 match c {
1272 '\t' => {
1273 let col_left = phantom.col_after(col, true);
1274 let col_right = phantom.col_after(col + 1, false);
1275 let x0 = text_layout.hit_position(col_left).point.x;
1276 let x1 = text_layout.hit_position(col_right).point.x;
1277 whitespace_buffer.push(('\t', (x0, x1)));
1278 }
1279 ' ' => {
1280 let col_left = phantom.col_after(col, true);
1281 let col_right = phantom.col_after(col + 1, false);
1282 let x0 = text_layout.hit_position(col_left).point.x;
1283 let x1 = text_layout.hit_position(col_right).point.x;
1284 whitespace_buffer.push((' ', (x0, x1)));
1285 }
1286 _ => {
1287 if (char_found && render_between)
1288 || (char_found && render_boundary && whitespace_buffer.len() > 1)
1289 || (!char_found && render_leading)
1290 {
1291 rendered_whitespaces.extend(whitespace_buffer.iter());
1292 }
1293
1294 char_found = true;
1295 whitespace_buffer.clear();
1296 }
1297 }
1298 col += c.len_utf8();
1299 }
1300 rendered_whitespaces.extend(whitespace_buffer.iter());
1301
1302 Some(rendered_whitespaces)
1303 }
1304}
1305impl TextLayoutProvider for Editor {
1306 fn text(&self) -> Rope {
1308 Editor::text(self)
1309 }
1310
1311 fn new_text_layout(
1312 &self,
1313 line: usize,
1314 _font_size: usize,
1315 _wrap: ResolvedWrap,
1316 ) -> Arc<TextLayoutLine> {
1317 let edid = self.id();
1320 let text = self.rope_text();
1321 let style = self.style();
1322 let doc = self.doc();
1323
1324 let line_content_original = text.line_content(line);
1325
1326 let font_size = style.font_size(edid, line);
1327
1328 let line_content = if let Some(s) = line_content_original.strip_suffix("\r\n") {
1333 format!("{s} ")
1334 } else if let Some(s) = line_content_original.strip_suffix('\n') {
1335 format!("{s} ",)
1336 } else {
1337 line_content_original.to_string()
1338 };
1339 let phantom_text = doc.phantom_text(edid, &self.es.get_untracked(), line);
1341 let line_content = phantom_text.combine_with_text(&line_content);
1342
1343 let family = style.font_family(edid, line);
1344 let attrs = Attrs::new()
1345 .color(self.es.with(|s| s.ed_text_color()))
1346 .family(&family)
1347 .font_size(font_size as f32)
1348 .line_height(LineHeightValue::Px(style.line_height(edid, line)));
1349 let mut attrs_list = AttrsList::new(attrs.clone());
1350
1351 self.es.with_untracked(|es| {
1352 style.apply_attr_styles(edid, es, line, attrs.clone(), &mut attrs_list);
1353 });
1354
1355 for (offset, size, col, phantom) in phantom_text.offset_size_iter() {
1357 let start = col + offset;
1358 let end = start + size;
1359
1360 let mut attrs = attrs.clone();
1361 if let Some(fg) = phantom.fg {
1362 attrs = attrs.color(fg);
1363 } else {
1364 attrs = attrs.color(self.es.with(|es| es.phantom_color()))
1365 }
1366 if let Some(phantom_font_size) = phantom.font_size {
1367 attrs = attrs.font_size(phantom_font_size.min(font_size) as f32);
1368 }
1369 attrs_list.add_span(start..end, attrs);
1370 }
1377
1378 let mut text_layout = TextLayout::new();
1379 text_layout.set_tab_width(style.tab_width(edid, line));
1381 text_layout.set_text(&line_content, attrs_list, None);
1382
1383 match self.es.with(|s| s.wrap_method()) {
1385 WrapMethod::None => {}
1386 WrapMethod::EditorWidth => {
1387 let width = self.viewport.get_untracked().width();
1388 text_layout.set_wrap(Wrap::WordOrGlyph);
1389 text_layout.set_size(width as f32, f32::MAX);
1390 }
1391 WrapMethod::WrapWidth { width } => {
1392 text_layout.set_wrap(Wrap::WordOrGlyph);
1393 text_layout.set_size(width, f32::MAX);
1394 }
1395 WrapMethod::WrapColumn { .. } => {}
1397 }
1398
1399 let whitespaces = Self::new_whitespace_layout(
1400 &line_content_original,
1401 &text_layout,
1402 &phantom_text,
1403 self.es.with(|s| s.render_whitespace()),
1404 );
1405
1406 let indent_line = style.indent_line(edid, line, &line_content_original);
1407
1408 let indent = if indent_line != line {
1409 let layout = self.try_get_text_layout(indent_line).unwrap_or_else(|| {
1412 self.new_text_layout(
1413 indent_line,
1414 style.font_size(edid, indent_line),
1415 self.lines.wrap(),
1416 )
1417 });
1418 layout.indent + 1.0
1419 } else {
1420 let offset = text.first_non_blank_character_on_line(indent_line);
1421 let (_, col) = text.offset_to_line_col(offset);
1422 text_layout.hit_position(col).point.x
1423 };
1424
1425 let mut layout_line = TextLayoutLine {
1426 text: text_layout,
1427 extra_style: Vec::new(),
1428 whitespaces,
1429 indent,
1430 phantom_text,
1431 };
1432 self.es.with_untracked(|es| {
1433 style.apply_layout_styles(edid, es, line, &mut layout_line);
1434 });
1435
1436 Arc::new(layout_line)
1437 }
1438
1439 fn before_phantom_col(&self, line: usize, col: usize) -> usize {
1440 self.doc()
1441 .before_phantom_col(self.id(), &self.es.get_untracked(), line, col)
1442 }
1443
1444 fn has_multiline_phantom(&self) -> bool {
1445 self.doc()
1446 .has_multiline_phantom(self.id(), &self.es.get_untracked())
1447 }
1448}
1449
1450struct EditorFontSizes {
1451 id: EditorId,
1452 style: ReadSignal<Rc<dyn Styling>>,
1453 doc: ReadSignal<Rc<dyn Document>>,
1454}
1455impl LineFontSizeProvider for EditorFontSizes {
1456 fn font_size(&self, line: usize) -> usize {
1457 self.style
1458 .with_untracked(|style| style.font_size(self.id, line))
1459 }
1460
1461 fn cache_id(&self) -> FontSizeCacheId {
1462 let mut hasher = DefaultHasher::new();
1463
1464 self.style
1467 .with_untracked(|style| style.id().hash(&mut hasher));
1468 self.doc
1469 .with_untracked(|doc| doc.cache_rev().get_untracked().hash(&mut hasher));
1470
1471 hasher.finish()
1472 }
1473}
1474
1475const MIN_WRAPPED_WIDTH: f32 = 100.0;
1477
1478fn create_view_effects(cx: Scope, ed: &Editor) {
1482 let ed2 = ed.clone();
1484 let ed3 = ed.clone();
1485 let ed4 = ed.clone();
1486
1487 {
1489 let cursor_info = ed.cursor_info.clone();
1490 let cursor = ed.cursor;
1491 cx.create_effect(move |_| {
1492 cursor.track();
1493 cursor_info.reset();
1494 });
1495 }
1496
1497 let update_screen_lines = |ed: &Editor| {
1498 ed.screen_lines.update(|screen_lines| {
1503 let new_screen_lines = ed.compute_screen_lines(screen_lines.base);
1504
1505 *screen_lines = new_screen_lines;
1506 });
1507 };
1508
1509 ed3.lines.layout_event.listen_with(cx, move |val| {
1512 let ed = &ed2;
1513 match val {
1517 LayoutEvent::CreatedLayout { line, .. } => {
1518 let sl = ed.screen_lines.get_untracked();
1519
1520 let should_update = sl.on_created_layout(ed, line);
1522
1523 if should_update {
1524 Effect::untrack(|| {
1525 update_screen_lines(ed);
1526 });
1527
1528 ed2.text_layout_trigger(line, true);
1533 }
1534 }
1535 }
1536 });
1537
1538 let viewport_changed_trigger = cx.create_trigger();
1542
1543 cx.create_effect(move |_| {
1546 let ed = &ed3;
1547
1548 let viewport = ed.viewport.get();
1549
1550 let wrap = match ed.es.with(|s| s.wrap_method()) {
1551 WrapMethod::None => ResolvedWrap::None,
1552 WrapMethod::EditorWidth => {
1553 ResolvedWrap::Width((viewport.width() as f32).max(MIN_WRAPPED_WIDTH))
1554 }
1555 WrapMethod::WrapColumn { .. } => todo!(),
1556 WrapMethod::WrapWidth { width } => ResolvedWrap::Width(width),
1557 };
1558
1559 ed.lines.set_wrap(wrap);
1560
1561 let base = ed.screen_lines.with_untracked(|sl| sl.base);
1563
1564 if viewport != base.with_untracked(|base| base.active_viewport) {
1566 Effect::batch(|| {
1567 base.update(|base| {
1568 base.active_viewport = viewport;
1569 });
1570 viewport_changed_trigger.notify();
1573 });
1574 }
1575 });
1576 cx.create_effect(move |_| {
1579 viewport_changed_trigger.track();
1580
1581 update_screen_lines(&ed4);
1582 });
1583}
1584
1585pub fn normal_compute_screen_lines(
1586 editor: &Editor,
1587 base: RwSignal<ScreenLinesBase>,
1588) -> ScreenLines {
1589 let lines = &editor.lines;
1590 let style = editor.style.get();
1591 let line_height = style.line_height(editor.id(), 0);
1593
1594 let (y0, y1) = base.with_untracked(|base| (base.active_viewport.y0, base.active_viewport.y1));
1595 let min_vline = VLine((y0 / line_height as f64).floor() as usize);
1597 let max_vline = VLine((y1 / line_height as f64).ceil() as usize);
1598
1599 let cache_rev = editor.doc.get().cache_rev().get();
1600 editor.lines.check_cache_rev(cache_rev);
1601
1602 let min_info = editor.iter_vlines(false, min_vline).next();
1603
1604 let mut rvlines = Vec::new();
1605 let mut info = HashMap::new();
1606
1607 let Some(min_info) = min_info else {
1608 return ScreenLines {
1609 lines: Rc::new(rvlines),
1610 info: Rc::new(info),
1611 diff_sections: None,
1612 base,
1613 };
1614 };
1615
1616 let count = max_vline.get() - min_vline.get();
1619 let iter = lines
1620 .iter_rvlines_init(
1621 editor.text_prov(),
1622 cache_rev,
1623 editor.config_id(),
1624 min_info.rvline,
1625 false,
1626 )
1627 .take(count);
1628
1629 for (i, vline_info) in iter.enumerate() {
1630 rvlines.push(vline_info.rvline);
1631
1632 let line_height = f64::from(style.line_height(editor.id(), vline_info.rvline.line));
1633
1634 let y_idx = min_vline.get() + i;
1635 let vline_y = y_idx as f64 * line_height;
1636 let line_y = vline_y - vline_info.rvline.line_index as f64 * line_height;
1637
1638 info.insert(
1641 vline_info.rvline,
1642 LineInfo {
1643 y: line_y - y0,
1644 vline_y: vline_y - y0,
1645 vline_info,
1646 },
1647 );
1648 }
1649
1650 ScreenLines {
1651 lines: Rc::new(rvlines),
1652 info: Rc::new(info),
1653 diff_sections: None,
1654 base,
1655 }
1656}
1657
1658#[derive(Clone)]
1661pub struct CursorInfo {
1662 pub hidden: RwSignal<bool>,
1663
1664 pub blink_timer: RwSignal<TimerToken>,
1665 pub should_blink: Rc<dyn Fn() -> bool + 'static>,
1667 pub blink_interval: Rc<dyn Fn() -> u64 + 'static>,
1668}
1669
1670impl CursorInfo {
1671 pub fn new(cx: Scope) -> CursorInfo {
1672 CursorInfo {
1673 hidden: cx.create_rw_signal(false),
1674
1675 blink_timer: cx.create_rw_signal(TimerToken::INVALID),
1676 should_blink: Rc::new(|| true),
1677 blink_interval: Rc::new(|| 500),
1678 }
1679 }
1680
1681 pub fn blink(&self) {
1682 let info = self.clone();
1683 let blink_interval = (info.blink_interval)();
1684 if blink_interval > 0 && (info.should_blink)() {
1685 let blink_timer = info.blink_timer;
1686 let timer_token =
1687 exec_after(Duration::from_millis(blink_interval), move |timer_token| {
1688 if info.blink_timer.try_get_untracked() == Some(timer_token) {
1689 info.hidden.update(|hide| {
1690 *hide = !*hide;
1691 });
1692 info.blink();
1693 }
1694 });
1695 blink_timer.set(timer_token);
1696 }
1697 }
1698
1699 pub fn reset(&self) {
1700 if self.hidden.get_untracked() {
1701 self.hidden.set(false);
1702 }
1703
1704 self.blink_timer.set(TimerToken::INVALID);
1705
1706 self.blink();
1707 }
1708}