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, OverflowWrap, TextLayout, TextWrapMode},
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 lapce_xi_rope::Rope;
35use parley::Affinity;
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: Brush {} = Brush::Solid(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::Upstream,
996 CursorAffinity::Forward => Affinity::Downstream,
997 };
998
999 text_layout.text.cursor_point(index, aff)
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 index = text_layout
1063 .text
1064 .hit_test(Point::new(point.x, y as f64))
1065 .map(|cursor| text_layout.text.cursor_to_byte_index(&cursor))
1066 .unwrap_or(0);
1067 (line, index)
1068 }
1069
1070 pub fn line_col_of_point(
1075 &self,
1076 mode: Mode,
1077 point: Point,
1078 ) -> ((usize, usize), bool, CursorAffinity) {
1079 let line_height = f64::from(self.style().line_height(self.id(), 0));
1081 let info = if point.y <= 0.0 {
1082 Some(self.first_rvline_info())
1083 } else {
1084 self.screen_lines
1085 .with_untracked(|sl| {
1086 sl.iter_line_info().find(|info| {
1087 info.vline_y <= point.y && info.vline_y + line_height >= point.y
1088 })
1089 })
1090 .map(|info| info.vline_info)
1091 };
1092 let info = info.unwrap_or_else(|| {
1093 for (y_idx, info) in self.iter_rvlines(false, RVLine::default()).enumerate() {
1094 let vline_y = y_idx as f64 * line_height;
1095 if vline_y <= point.y && vline_y + line_height >= point.y {
1096 return info;
1097 }
1098 }
1099
1100 self.last_rvline_info()
1101 });
1102
1103 let rvline = info.rvline;
1104 let line = rvline.line;
1105 let text_layout = self.text_layout(line);
1106
1107 let y = text_layout.get_layout_y(rvline.line_index).unwrap_or(0.0);
1108
1109 let hit_point = Point::new(point.x, y as f64);
1110 let size = text_layout.text.size();
1111 let is_inside = hit_point.x <= size.width && hit_point.y <= size.height;
1112 let (index, affinity) = text_layout
1113 .text
1114 .hit_test(hit_point)
1115 .map(|cursor| {
1116 (
1117 text_layout.text.cursor_to_byte_index(&cursor),
1118 cursor.affinity(),
1119 )
1120 })
1121 .unwrap_or((0, Affinity::default()));
1122 let mut affinity = match affinity {
1123 Affinity::Upstream => CursorAffinity::Backward,
1124 Affinity::Downstream => CursorAffinity::Forward,
1125 };
1126 let col = text_layout.phantom_text.before_col(index);
1129 let max_col = self.line_end_col(line, mode != Mode::Normal);
1132 let mut col = col.min(max_col);
1133
1134 if !is_inside {
1137 col = info.last_col(&self.text_prov(), true);
1139 }
1140
1141 let tab_width = self.style().tab_width(self.id(), line);
1142 if self.style().atomic_soft_tabs(self.id(), line) && tab_width > 1 {
1143 col = snap_to_soft_tab_line_col(
1144 &self.text(),
1145 line,
1146 col,
1147 SnapDirection::Nearest,
1148 tab_width,
1149 );
1150 affinity = CursorAffinity::Forward;
1151 }
1152
1153 ((line, col), is_inside, affinity)
1154 }
1155
1156 pub fn line_horiz_col(&self, line: usize, horiz: &ColPosition, caret: bool) -> usize {
1158 match *horiz {
1159 ColPosition::Col(x) => {
1160 let text_layout = self.text_layout(line);
1163 let n = text_layout
1164 .text
1165 .hit_test(Point::new(x, 0.0))
1166 .map(|cursor| text_layout.text.cursor_to_byte_index(&cursor))
1167 .unwrap_or(0);
1168 let col = text_layout.phantom_text.before_col(n);
1169
1170 col.min(self.line_end_col(line, caret))
1171 }
1172 ColPosition::End => self.line_end_col(line, caret),
1173 ColPosition::Start => 0,
1174 ColPosition::FirstNonBlank => self.first_non_blank_character_on_line(line),
1175 }
1176 }
1177
1178 pub fn rvline_horiz_col(&self, rvline: RVLine, horiz: &ColPosition, caret: bool) -> usize {
1181 let RVLine { line, line_index } = rvline;
1182
1183 match *horiz {
1184 ColPosition::Col(x) => {
1185 let text_layout = self.text_layout(line);
1186 let line_count = text_layout.text.visual_line_count();
1187 let y_pos = text_layout
1188 .text
1189 .visual_line_y(line_index)
1190 .or_else(|| {
1191 if line_count > 0 {
1192 text_layout.text.visual_line_y(line_count - 1)
1193 } else {
1194 None
1195 }
1196 })
1197 .unwrap_or(0.0);
1198 let n = text_layout
1199 .text
1200 .hit_test(Point::new(x, y_pos as f64))
1201 .map(|cursor| text_layout.text.cursor_to_byte_index(&cursor))
1202 .unwrap_or(0);
1203 let col = text_layout.phantom_text.before_col(n);
1204
1205 col.min(self.line_end_col(line, caret))
1206 }
1207 ColPosition::End => {
1208 let info = self.rvline_info(rvline);
1209 self.last_col(info, caret)
1210 }
1211 ColPosition::Start => {
1212 let info = self.rvline_info(rvline);
1213 self.first_col(info)
1214 }
1215 ColPosition::FirstNonBlank => {
1216 let info = self.rvline_info(rvline);
1217 let rope_text = self.text_prov().rope_text();
1218 let next_offset =
1219 WordCursor::new(rope_text.text(), info.interval.start).next_non_blank_char();
1220
1221 next_offset - info.interval.start + self.first_col(info)
1222 }
1223 }
1224 }
1225
1226 pub fn move_right(&self, offset: usize, mode: Mode, count: usize) -> usize {
1230 self.rope_text().move_right(offset, mode, count)
1231 }
1232
1233 pub fn move_left(&self, offset: usize, mode: Mode, count: usize) -> usize {
1236 self.rope_text().move_left(offset, mode, count)
1237 }
1238}
1239
1240impl std::fmt::Debug for Editor {
1241 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1242 f.debug_tuple("Editor").field(&self.id).finish()
1243 }
1244}
1245
1246impl Editor {
1248 pub fn text_layout(&self, line: usize) -> Arc<TextLayoutLine> {
1250 self.text_layout_trigger(line, true)
1251 }
1252
1253 pub fn text_layout_trigger(&self, line: usize, trigger: bool) -> Arc<TextLayoutLine> {
1254 let cache_rev = self.doc().cache_rev().get_untracked();
1255 self.lines
1256 .get_init_text_layout(cache_rev, self.config_id(), self, line, trigger)
1257 }
1258
1259 fn try_get_text_layout(&self, line: usize) -> Option<Arc<TextLayoutLine>> {
1260 let cache_rev = self.doc().cache_rev().get_untracked();
1261 self.lines
1262 .try_get_text_layout(cache_rev, self.config_id(), line)
1263 }
1264
1265 fn new_whitespace_layout(
1269 line_content: &str,
1270 text_layout: &TextLayout,
1271 phantom: &PhantomTextLine,
1272 render_whitespace: RenderWhitespace,
1273 ) -> Option<Vec<(char, (f64, f64))>> {
1274 let mut render_leading = false;
1275 let mut render_boundary = false;
1276 let mut render_between = false;
1277
1278 match render_whitespace {
1280 RenderWhitespace::All => {
1281 render_leading = true;
1282 render_boundary = true;
1283 render_between = true;
1284 }
1285 RenderWhitespace::Boundary => {
1286 render_leading = true;
1287 render_boundary = true;
1288 }
1289 RenderWhitespace::Trailing => {} RenderWhitespace::None => return None,
1291 }
1292
1293 let mut whitespace_buffer = Vec::new();
1294 let mut rendered_whitespaces: Vec<(char, (f64, f64))> = Vec::new();
1295 let mut char_found = false;
1296 let mut col = 0;
1297 for c in line_content.chars() {
1298 match c {
1299 '\t' => {
1300 let col_left = phantom.col_after(col, true);
1301 let col_right = phantom.col_after(col + 1, false);
1302 let x0 = text_layout.cursor_point(col_left, Affinity::Upstream).x;
1303 let x1 = text_layout.cursor_point(col_right, Affinity::Upstream).x;
1304 whitespace_buffer.push(('\t', (x0, x1)));
1305 }
1306 ' ' => {
1307 let col_left = phantom.col_after(col, true);
1308 let col_right = phantom.col_after(col + 1, false);
1309 let x0 = text_layout.cursor_point(col_left, Affinity::Upstream).x;
1310 let x1 = text_layout.cursor_point(col_right, Affinity::Upstream).x;
1311 whitespace_buffer.push((' ', (x0, x1)));
1312 }
1313 _ => {
1314 if (char_found && render_between)
1315 || (char_found && render_boundary && whitespace_buffer.len() > 1)
1316 || (!char_found && render_leading)
1317 {
1318 rendered_whitespaces.extend(whitespace_buffer.iter());
1319 }
1320
1321 char_found = true;
1322 whitespace_buffer.clear();
1323 }
1324 }
1325 col += c.len_utf8();
1326 }
1327 rendered_whitespaces.extend(whitespace_buffer.iter());
1328
1329 Some(rendered_whitespaces)
1330 }
1331}
1332impl TextLayoutProvider for Editor {
1333 fn text(&self) -> Rope {
1335 Editor::text(self)
1336 }
1337
1338 fn new_text_layout(
1339 &self,
1340 line: usize,
1341 _font_size: usize,
1342 _wrap: ResolvedWrap,
1343 ) -> Arc<TextLayoutLine> {
1344 let edid = self.id();
1347 let text = self.rope_text();
1348 let style = self.style();
1349 let doc = self.doc();
1350
1351 let line_content_original = text.line_content(line);
1352
1353 let font_size = style.font_size(edid, line);
1354
1355 let line_content = if let Some(s) = line_content_original.strip_suffix("\r\n") {
1360 format!("{s} ")
1361 } else if let Some(s) = line_content_original.strip_suffix('\n') {
1362 format!("{s} ",)
1363 } else {
1364 line_content_original.to_string()
1365 };
1366 let phantom_text = doc.phantom_text(edid, &self.es.get_untracked(), line);
1368 let line_content = phantom_text.combine_with_text(&line_content);
1369
1370 let family = style.font_family(edid, line);
1371 let attrs = Attrs::new()
1372 .color(self.es.with(|s| s.ed_text_color()))
1373 .family(&family)
1374 .font_size(font_size as f32)
1375 .line_height(LineHeightValue::Px(style.line_height(edid, line)));
1376 let mut attrs_list = AttrsList::new(attrs.clone());
1377
1378 self.es.with_untracked(|es| {
1379 style.apply_attr_styles(edid, es, line, attrs.clone(), &mut attrs_list);
1380 });
1381
1382 for (offset, size, col, phantom) in phantom_text.offset_size_iter() {
1384 let start = col + offset;
1385 let end = start + size;
1386
1387 let mut attrs = attrs.clone();
1388 if let Some(fg) = phantom.fg {
1389 attrs = attrs.color(fg);
1390 } else {
1391 attrs = attrs.color(self.es.with(|es| es.phantom_color()))
1392 }
1393 if let Some(phantom_font_size) = phantom.font_size {
1394 attrs = attrs.font_size(phantom_font_size.min(font_size) as f32);
1395 }
1396 attrs_list.add_span(start..end, attrs);
1397 }
1404
1405 let mut text_layout = TextLayout::new();
1406 text_layout.set_tab_width(style.tab_width(edid, line));
1408 text_layout.set_text(&line_content, attrs_list, None);
1409
1410 match self.es.with(|s| s.wrap_method()) {
1411 WrapMethod::None => {}
1412 WrapMethod::EditorWidth => {
1413 let width = self.viewport.get_untracked().width();
1414 text_layout.set_text_wrap_mode(TextWrapMode::Wrap);
1415 text_layout.set_overflow_wrap(OverflowWrap::BreakWord);
1416 text_layout.set_size(width as f32, f32::MAX);
1417 }
1418 WrapMethod::WrapWidth { width } => {
1419 text_layout.set_text_wrap_mode(TextWrapMode::Wrap);
1420 text_layout.set_overflow_wrap(OverflowWrap::BreakWord);
1421 text_layout.set_size(width, f32::MAX);
1422 }
1423 WrapMethod::WrapColumn { .. } => {}
1425 }
1426
1427 let whitespaces = Self::new_whitespace_layout(
1428 &line_content_original,
1429 &text_layout,
1430 &phantom_text,
1431 self.es.with(|s| s.render_whitespace()),
1432 );
1433
1434 let indent_line = style.indent_line(edid, line, &line_content_original);
1435
1436 let indent = if indent_line != line {
1437 let layout = self.try_get_text_layout(indent_line).unwrap_or_else(|| {
1440 self.new_text_layout(
1441 indent_line,
1442 style.font_size(edid, indent_line),
1443 self.lines.wrap(),
1444 )
1445 });
1446 layout.indent + 1.0
1447 } else {
1448 let offset = text.first_non_blank_character_on_line(indent_line);
1449 let (_, col) = text.offset_to_line_col(offset);
1450 text_layout.cursor_point(col, Affinity::Upstream).x
1451 };
1452
1453 let mut layout_line = TextLayoutLine {
1454 text: text_layout,
1455 extra_style: Vec::new(),
1456 whitespaces,
1457 indent,
1458 phantom_text,
1459 };
1460 self.es.with_untracked(|es| {
1461 style.apply_layout_styles(edid, es, line, &mut layout_line);
1462 });
1463
1464 Arc::new(layout_line)
1465 }
1466
1467 fn before_phantom_col(&self, line: usize, col: usize) -> usize {
1468 self.doc()
1469 .before_phantom_col(self.id(), &self.es.get_untracked(), line, col)
1470 }
1471
1472 fn has_multiline_phantom(&self) -> bool {
1473 self.doc()
1474 .has_multiline_phantom(self.id(), &self.es.get_untracked())
1475 }
1476}
1477
1478struct EditorFontSizes {
1479 id: EditorId,
1480 style: ReadSignal<Rc<dyn Styling>>,
1481 doc: ReadSignal<Rc<dyn Document>>,
1482}
1483impl LineFontSizeProvider for EditorFontSizes {
1484 fn font_size(&self, line: usize) -> usize {
1485 self.style
1486 .with_untracked(|style| style.font_size(self.id, line))
1487 }
1488
1489 fn cache_id(&self) -> FontSizeCacheId {
1490 let mut hasher = DefaultHasher::new();
1491
1492 self.style
1495 .with_untracked(|style| style.id().hash(&mut hasher));
1496 self.doc
1497 .with_untracked(|doc| doc.cache_rev().get_untracked().hash(&mut hasher));
1498
1499 hasher.finish()
1500 }
1501}
1502
1503const MIN_WRAPPED_WIDTH: f32 = 100.0;
1505
1506fn create_view_effects(cx: Scope, ed: &Editor) {
1510 let ed2 = ed.clone();
1512 let ed3 = ed.clone();
1513 let ed4 = ed.clone();
1514
1515 {
1517 let cursor_info = ed.cursor_info.clone();
1518 let cursor = ed.cursor;
1519 cx.create_effect(move |_| {
1520 cursor.track();
1521 cursor_info.reset();
1522 });
1523 }
1524
1525 let update_screen_lines = |ed: &Editor| {
1526 ed.screen_lines.update(|screen_lines| {
1531 let new_screen_lines = ed.compute_screen_lines(screen_lines.base);
1532
1533 *screen_lines = new_screen_lines;
1534 });
1535 };
1536
1537 ed3.lines.layout_event.listen_with(cx, move |val| {
1540 let ed = &ed2;
1541 match val {
1545 LayoutEvent::CreatedLayout { line, .. } => {
1546 let sl = ed.screen_lines.get_untracked();
1547
1548 let should_update = sl.on_created_layout(ed, line);
1550
1551 if should_update {
1552 Effect::untrack(|| {
1553 update_screen_lines(ed);
1554 });
1555
1556 ed2.text_layout_trigger(line, true);
1561 }
1562 }
1563 }
1564 });
1565
1566 let viewport_changed_trigger = cx.create_trigger();
1570
1571 cx.create_effect(move |_| {
1574 let ed = &ed3;
1575
1576 let viewport = ed.viewport.get();
1577
1578 let wrap = match ed.es.with(|s| s.wrap_method()) {
1579 WrapMethod::None => ResolvedWrap::None,
1580 WrapMethod::EditorWidth => {
1581 ResolvedWrap::Width((viewport.width() as f32).max(MIN_WRAPPED_WIDTH))
1582 }
1583 WrapMethod::WrapColumn { .. } => todo!(),
1584 WrapMethod::WrapWidth { width } => ResolvedWrap::Width(width),
1585 };
1586
1587 ed.lines.set_wrap(wrap);
1588
1589 let base = ed.screen_lines.with_untracked(|sl| sl.base);
1591
1592 if viewport != base.with_untracked(|base| base.active_viewport) {
1594 Effect::batch(|| {
1595 base.update(|base| {
1596 base.active_viewport = viewport;
1597 });
1598 viewport_changed_trigger.notify();
1601 });
1602 }
1603 });
1604 cx.create_effect(move |_| {
1607 viewport_changed_trigger.track();
1608
1609 update_screen_lines(&ed4);
1610 });
1611}
1612
1613pub fn normal_compute_screen_lines(
1614 editor: &Editor,
1615 base: RwSignal<ScreenLinesBase>,
1616) -> ScreenLines {
1617 let lines = &editor.lines;
1618 let style = editor.style.get();
1619 let line_height = style.line_height(editor.id(), 0);
1621
1622 let (y0, y1) = base.with_untracked(|base| (base.active_viewport.y0, base.active_viewport.y1));
1623 let min_vline = VLine((y0 / line_height as f64).floor() as usize);
1625 let max_vline = VLine((y1 / line_height as f64).ceil() as usize);
1626
1627 let cache_rev = editor.doc.get().cache_rev().get();
1628 editor.lines.check_cache_rev(cache_rev);
1629
1630 let min_info = editor.iter_vlines(false, min_vline).next();
1631
1632 let mut rvlines = Vec::new();
1633 let mut info = HashMap::new();
1634
1635 let Some(min_info) = min_info else {
1636 return ScreenLines {
1637 lines: Rc::new(rvlines),
1638 info: Rc::new(info),
1639 diff_sections: None,
1640 base,
1641 };
1642 };
1643
1644 let count = max_vline.get() - min_vline.get();
1647 let iter = lines
1648 .iter_rvlines_init(
1649 editor.text_prov(),
1650 cache_rev,
1651 editor.config_id(),
1652 min_info.rvline,
1653 false,
1654 )
1655 .take(count);
1656
1657 for (i, vline_info) in iter.enumerate() {
1658 rvlines.push(vline_info.rvline);
1659
1660 let line_height = f64::from(style.line_height(editor.id(), vline_info.rvline.line));
1661
1662 let y_idx = min_vline.get() + i;
1663 let vline_y = y_idx as f64 * line_height;
1664 let line_y = vline_y - vline_info.rvline.line_index as f64 * line_height;
1665
1666 info.insert(
1669 vline_info.rvline,
1670 LineInfo {
1671 y: line_y - y0,
1672 vline_y: vline_y - y0,
1673 vline_info,
1674 },
1675 );
1676 }
1677
1678 ScreenLines {
1679 lines: Rc::new(rvlines),
1680 info: Rc::new(info),
1681 diff_sections: None,
1682 base,
1683 }
1684}
1685
1686#[derive(Clone)]
1689pub struct CursorInfo {
1690 pub hidden: RwSignal<bool>,
1691
1692 pub blink_timer: RwSignal<TimerToken>,
1693 pub should_blink: Rc<dyn Fn() -> bool + 'static>,
1695 pub blink_interval: Rc<dyn Fn() -> u64 + 'static>,
1696}
1697
1698impl CursorInfo {
1699 pub fn new(cx: Scope) -> CursorInfo {
1700 CursorInfo {
1701 hidden: cx.create_rw_signal(false),
1702
1703 blink_timer: cx.create_rw_signal(TimerToken::INVALID),
1704 should_blink: Rc::new(|| true),
1705 blink_interval: Rc::new(|| 500),
1706 }
1707 }
1708
1709 pub fn blink(&self) {
1710 let info = self.clone();
1711 let blink_interval = (info.blink_interval)();
1712 if blink_interval > 0 && (info.should_blink)() {
1713 let blink_timer = info.blink_timer;
1714 let timer_token =
1715 exec_after(Duration::from_millis(blink_interval), move |timer_token| {
1716 if info.blink_timer.try_get_untracked() == Some(timer_token) {
1717 info.hidden.update(|hide| {
1718 *hide = !*hide;
1719 });
1720 info.blink();
1721 }
1722 });
1723 blink_timer.set(timer_token);
1724 }
1725 }
1726
1727 pub fn reset(&self) {
1728 if self.hidden.get_untracked() {
1729 self.hidden.set(false);
1730 }
1731
1732 self.blink_timer.set(TimerToken::INVALID);
1733
1734 self.blink();
1735 }
1736}