iced_selection/text/
rich.rs

1use iced_widget::graphics::text::Paragraph;
2use iced_widget::graphics::text::cosmic_text;
3
4use crate::click;
5use crate::core::alignment;
6use crate::core::keyboard;
7use crate::core::keyboard::key;
8use crate::core::layout;
9use crate::core::mouse;
10use crate::core::renderer;
11use crate::core::text::{Ellipsis, Paragraph as _, Span};
12use crate::core::time::Duration;
13use crate::core::touch;
14use crate::core::widget::text::{Alignment, LineHeight, Shaping, Wrapping};
15use crate::core::widget::tree::{self, Tree};
16use crate::core::{
17    self, Element, Event, Font, Layout, Length, Pixels, Point, Rectangle,
18    Shell, Size, Vector, Widget,
19};
20use crate::selection::{Selection, SelectionEnd};
21use crate::text::{Catalog, Dragging, Style, StyleFn};
22
23/// A bunch of [`Rich`] text.
24#[must_use]
25pub struct Rich<
26    'a,
27    Link,
28    Message,
29    Theme = iced_widget::Theme,
30    Renderer = iced_widget::Renderer,
31> where
32    Link: Clone + 'static,
33    Theme: Catalog,
34    Renderer: core::text::Renderer,
35{
36    spans: Box<dyn AsRef<[Span<'a, Link, Renderer::Font>]> + 'a>,
37    size: Option<Pixels>,
38    line_height: LineHeight,
39    width: Length,
40    height: Length,
41    font: Option<Renderer::Font>,
42    align_x: Alignment,
43    align_y: alignment::Vertical,
44    wrapping: Wrapping,
45    ellipsis: Ellipsis,
46    click_interval: Option<Duration>,
47    class: Theme::Class<'a>,
48    on_link_click: Option<Box<dyn Fn(Link) -> Message + 'a>>,
49    on_link_hover: Option<Box<dyn Fn(Link) -> Message + 'a>>,
50    on_hover_lost: Option<Box<dyn Fn() -> Message + 'a>>,
51}
52
53impl<'a, Link, Message, Theme, Renderer>
54    Rich<'a, Link, Message, Theme, Renderer>
55where
56    Link: Clone + 'static,
57    Theme: Catalog,
58    Renderer: core::text::Renderer,
59    Renderer::Font: 'a,
60{
61    /// Creates a new empty [`Rich`] text.
62    pub fn new() -> Self {
63        Self {
64            spans: Box::new([]),
65            size: None,
66            line_height: LineHeight::default(),
67            width: Length::Shrink,
68            height: Length::Shrink,
69            font: None,
70            align_x: Alignment::Default,
71            align_y: alignment::Vertical::Top,
72            wrapping: Wrapping::default(),
73            ellipsis: Ellipsis::None,
74            click_interval: None,
75            class: Theme::default(),
76            on_link_click: None,
77            on_link_hover: None,
78            on_hover_lost: None,
79        }
80    }
81
82    /// Creates a new [`Rich`] text with the given text spans.
83    pub fn with_spans(
84        spans: impl AsRef<[Span<'a, Link, Renderer::Font>]> + 'a,
85    ) -> Self {
86        Self {
87            spans: Box::new(spans),
88            ..Self::new()
89        }
90    }
91
92    /// Sets the default size of the [`Rich`] text.
93    pub fn size(mut self, size: impl Into<Pixels>) -> Self {
94        self.size = Some(size.into());
95        self
96    }
97
98    /// Sets the default [`LineHeight`] of the [`Rich`] text.
99    pub fn line_height(mut self, line_height: impl Into<LineHeight>) -> Self {
100        self.line_height = line_height.into();
101        self
102    }
103
104    /// Sets the default font of the [`Rich`] text.
105    pub fn font(mut self, font: impl Into<Renderer::Font>) -> Self {
106        self.font = Some(font.into());
107        self
108    }
109
110    /// Sets the width of the [`Rich`] text boundaries.
111    pub fn width(mut self, width: impl Into<Length>) -> Self {
112        self.width = width.into();
113        self
114    }
115
116    /// Sets the height of the [`Rich`] text boundaries.
117    pub fn height(mut self, height: impl Into<Length>) -> Self {
118        self.height = height.into();
119        self
120    }
121
122    /// Centers the [`Rich`] text, both horizontally and vertically.
123    pub fn center(self) -> Self {
124        self.align_x(alignment::Horizontal::Center)
125            .align_y(alignment::Vertical::Center)
126    }
127
128    /// Sets the [`alignment::Horizontal`] of the [`Rich`] text.
129    pub fn align_x(mut self, alignment: impl Into<Alignment>) -> Self {
130        self.align_x = alignment.into();
131        self
132    }
133
134    /// Sets the [`alignment::Vertical`] of the [`Rich`] text.
135    pub fn align_y(
136        mut self,
137        alignment: impl Into<alignment::Vertical>,
138    ) -> Self {
139        self.align_y = alignment.into();
140        self
141    }
142
143    /// Sets the [`Wrapping`] strategy of the [`Rich`] text.
144    pub fn wrapping(mut self, wrapping: Wrapping) -> Self {
145        self.wrapping = wrapping;
146        self
147    }
148
149    /// Sets the [`Ellipsis`] strategy of the [`Rich`] text.
150    pub fn ellipsis(mut self, ellipsis: Ellipsis) -> Self {
151        self.ellipsis = ellipsis;
152        self
153    }
154
155    /// The maximum delay required for two consecutive clicks to be interpreted as a double click
156    /// (also applies to triple clicks).
157    ///
158    /// Defaults to 300ms.
159    pub fn click_interval(mut self, click_interval: Duration) -> Self {
160        self.click_interval = Some(click_interval);
161        self
162    }
163
164    /// Sets the message that will be produced when a link of the [`Rich`] text
165    /// is clicked.
166    ///
167    /// If the spans of the [`Rich`] text contain no links, you may need to call
168    /// this method with `on_link_click(never)` in order for the compiler to infer
169    /// the proper `Link` generic type.
170    pub fn on_link_click(
171        mut self,
172        on_link_click: impl Fn(Link) -> Message + 'a,
173    ) -> Self {
174        self.on_link_click = Some(Box::new(on_link_click));
175        self
176    }
177
178    /// Sets the message that will be produced when a link of the [`Rich`] text
179    /// is hovered.
180    pub fn on_link_hover(
181        mut self,
182        on_link_hovered: impl Fn(Link) -> Message + 'a,
183    ) -> Self {
184        self.on_link_hover = Some(Box::new(on_link_hovered));
185        self
186    }
187
188    /// Sets the message that will be produced when a link of the [`Rich`] text
189    /// is no longer hovered.
190    pub fn on_hover_lost(mut self, on_hover_lost: Message) -> Self
191    where
192        Message: Clone + 'a,
193    {
194        self.on_hover_lost = Some(Box::new(move || on_hover_lost.clone()));
195        self
196    }
197
198    /// Sets the message that will be produced when a link of the [`Rich`] text
199    /// is no longer hovered.
200    pub fn on_hover_lost_with(
201        mut self,
202        on_hover_lost: impl Fn() -> Message + 'a,
203    ) -> Self {
204        self.on_hover_lost = Some(Box::new(on_hover_lost));
205        self
206    }
207
208    /// Sets the default style of the [`Rich`] text.
209    pub fn style(mut self, style: impl Fn(&Theme) -> Style + 'a) -> Self
210    where
211        Theme::Class<'a>: From<StyleFn<'a, Theme>>,
212    {
213        self.class = (Box::new(style) as StyleFn<'a, Theme>).into();
214        self
215    }
216
217    /// Sets the default style class of the [`Rich`] text.
218    pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self {
219        self.class = class.into();
220        self
221    }
222}
223
224impl<'a, Link, Message, Theme, Renderer> Default
225    for Rich<'a, Link, Message, Theme, Renderer>
226where
227    Link: Clone + 'a,
228    Theme: Catalog,
229    Renderer: core::text::Renderer<Paragraph = Paragraph, Font = Font>,
230    Renderer::Font: 'a,
231{
232    fn default() -> Self {
233        Self::new()
234    }
235}
236
237struct State<Link> {
238    spans: Vec<Span<'static, Link, Font>>,
239    span_pressed: Option<usize>,
240    hovered_link: Option<usize>,
241    paragraph: Paragraph,
242    is_hovered: bool,
243    selection: Selection,
244    dragging: Option<Dragging>,
245    last_click: Option<click::Click>,
246    keyboard_modifiers: keyboard::Modifiers,
247    visual_lines_bounds: Vec<core::Rectangle>,
248}
249
250impl<Link> State<Link> {
251    fn grapheme_line_and_index(
252        &self,
253        point: Point,
254        bounds: core::Rectangle,
255    ) -> Option<(usize, usize)> {
256        let bounded_x = if point.y < bounds.y {
257            bounds.x
258        } else if point.y > bounds.y + bounds.height {
259            bounds.x + bounds.width
260        } else {
261            point.x.max(bounds.x).min(bounds.x + bounds.width)
262        };
263        let bounded_y = point.y.max(bounds.y).min(bounds.y + bounds.height);
264        let bounded_point = Point::new(bounded_x, bounded_y);
265        let mut relative_point =
266            bounded_point - core::Vector::new(bounds.x, bounds.y);
267
268        let buffer = self.paragraph.buffer();
269        let line_height = buffer.metrics().line_height;
270        let visual_line = (relative_point.y / line_height).floor() as usize;
271        let visual_line_start_offset = self
272            .visual_lines_bounds
273            .get(visual_line)
274            .map(|r| r.x)
275            .unwrap_or_default();
276        let visual_line_end = self
277            .visual_lines_bounds
278            .get(visual_line)
279            .map(|r| r.x + r.width)
280            .unwrap_or_default();
281
282        if relative_point.x < visual_line_start_offset {
283            relative_point.x = visual_line_start_offset;
284        }
285
286        if relative_point.x > visual_line_end {
287            relative_point.x = visual_line_end;
288        }
289
290        let cursor = buffer.hit(relative_point.x, relative_point.y)?;
291        let value = buffer.lines[cursor.line].text();
292
293        Some((
294            cursor.line,
295            unicode_segmentation::UnicodeSegmentation::graphemes(
296                &value[..cursor.index.min(value.len())],
297                true,
298            )
299            .count(),
300        ))
301    }
302
303    fn selection(&self) -> Vec<core::Rectangle> {
304        let Selection { start, end, .. } = self.selection;
305
306        let buffer = self.paragraph.buffer();
307        let line_height = self.paragraph.buffer().metrics().line_height;
308        let selected_lines = end.line - start.line + 1;
309
310        let visual_lines_offset = visual_lines_offset(start.line, buffer);
311
312        buffer
313            .lines
314            .iter()
315            .skip(start.line)
316            .take(selected_lines)
317            .enumerate()
318            .flat_map(|(i, line)| {
319                highlight_line(
320                    line,
321                    if i == 0 { start.index } else { 0 },
322                    if i == selected_lines - 1 {
323                        end.index
324                    } else {
325                        line.text().len()
326                    },
327                )
328            })
329            .enumerate()
330            .filter_map(|(visual_line, (x, width))| {
331                if width > 0.0 {
332                    Some(core::Rectangle {
333                        x,
334                        width,
335                        y: (visual_line as i32 + visual_lines_offset) as f32
336                            * line_height
337                            - buffer.scroll().vertical,
338                        height: line_height,
339                    })
340                } else {
341                    None
342                }
343            })
344            .collect()
345    }
346
347    fn update_visual_bounds(&mut self) {
348        let buffer = self.paragraph.buffer();
349        let line_height = buffer.metrics().line_height;
350        self.visual_lines_bounds = buffer
351            .lines
352            .iter()
353            .flat_map(|line| highlight_line(line, 0, line.text().len()))
354            .enumerate()
355            .map(|(visual_line, (x, width))| core::Rectangle {
356                x,
357                width,
358                y: visual_line as f32 * line_height - buffer.scroll().vertical,
359                height: line_height,
360            })
361            .collect();
362    }
363}
364
365impl<Link, Message, Theme, Renderer> Widget<Message, Theme, Renderer>
366    for Rich<'_, Link, Message, Theme, Renderer>
367where
368    Link: Clone + 'static,
369    Theme: Catalog,
370    Renderer: core::text::Renderer<Paragraph = Paragraph, Font = Font>,
371{
372    fn tag(&self) -> tree::Tag {
373        tree::Tag::of::<State<Link>>()
374    }
375
376    fn state(&self) -> tree::State {
377        tree::State::new(State::<Link> {
378            spans: Vec::new(),
379            span_pressed: None,
380            hovered_link: None,
381            paragraph: Paragraph::default(),
382            is_hovered: false,
383            selection: Selection::default(),
384            dragging: None,
385            last_click: None,
386            keyboard_modifiers: keyboard::Modifiers::default(),
387            visual_lines_bounds: Vec::new(),
388        })
389    }
390
391    fn size(&self) -> Size<Length> {
392        Size {
393            width: self.width,
394            height: self.height,
395        }
396    }
397
398    fn layout(
399        &mut self,
400        tree: &mut Tree,
401        renderer: &Renderer,
402        limits: &layout::Limits,
403    ) -> layout::Node {
404        layout(
405            tree.state.downcast_mut::<State<Link>>(),
406            renderer,
407            limits,
408            self.width,
409            self.height,
410            self.spans.as_ref().as_ref(),
411            self.line_height,
412            self.size,
413            self.font,
414            self.align_x,
415            self.align_y,
416            self.wrapping,
417            self.ellipsis,
418        )
419    }
420
421    fn draw(
422        &self,
423        tree: &Tree,
424        renderer: &mut Renderer,
425        theme: &Theme,
426        defaults: &renderer::Style,
427        layout: Layout<'_>,
428        _cursor: mouse::Cursor,
429        viewport: &Rectangle,
430    ) {
431        if !layout.bounds().intersects(viewport) {
432            return;
433        }
434
435        let state = tree.state.downcast_ref::<State<Link>>();
436
437        let style = theme.style(&self.class);
438
439        for (index, span) in self.spans.as_ref().as_ref().iter().enumerate() {
440            let is_hovered_link = self.on_link_click.is_some()
441                && Some(index) == state.hovered_link;
442
443            if span.highlight.is_some()
444                || span.underline
445                || span.strikethrough
446                || is_hovered_link
447            {
448                let translation = layout.position() - Point::ORIGIN;
449                let regions = state.paragraph.span_bounds(index);
450
451                if let Some(highlight) = span.highlight {
452                    for bounds in &regions {
453                        let bounds = Rectangle::new(
454                            bounds.position()
455                                - Vector::new(
456                                    span.padding.left,
457                                    span.padding.top,
458                                ),
459                            bounds.size()
460                                + Size::new(span.padding.x(), span.padding.y()),
461                        );
462
463                        renderer.fill_quad(
464                            renderer::Quad {
465                                bounds: bounds + translation,
466                                border: highlight.border,
467                                ..Default::default()
468                            },
469                            highlight.background,
470                        );
471                    }
472                }
473
474                if span.underline || span.strikethrough || is_hovered_link {
475                    let size = span
476                        .size
477                        .or(self.size)
478                        .unwrap_or(renderer.default_size());
479
480                    let line_height = span
481                        .line_height
482                        .unwrap_or(self.line_height)
483                        .to_absolute(size);
484
485                    let color = span
486                        .color
487                        .or(style.color)
488                        .unwrap_or(defaults.text_color);
489
490                    let baseline = translation
491                        + Vector::new(
492                            0.0,
493                            size.0 + (line_height.0 - size.0) / 2.0,
494                        );
495
496                    if span.underline || is_hovered_link {
497                        for bounds in &regions {
498                            renderer.fill_quad(
499                                renderer::Quad {
500                                    bounds: Rectangle::new(
501                                        bounds.position() + baseline
502                                            - Vector::new(0.0, size.0 * 0.08),
503                                        Size::new(bounds.width, 1.0),
504                                    ),
505                                    ..Default::default()
506                                },
507                                color,
508                            );
509                        }
510                    }
511
512                    if span.strikethrough {
513                        for bounds in &regions {
514                            renderer.fill_quad(
515                                renderer::Quad {
516                                    bounds: Rectangle::new(
517                                        bounds.position() + baseline
518                                            - Vector::new(0.0, size.0 / 2.0),
519                                        Size::new(bounds.width, 1.0),
520                                    ),
521                                    ..Default::default()
522                                },
523                                color,
524                            );
525                        }
526                    }
527                }
528            }
529        }
530
531        if !state.selection.is_empty() {
532            let bounds = layout.bounds();
533            let translation = bounds.position() - Point::ORIGIN;
534            let ranges = state.selection();
535
536            for range in ranges
537                .into_iter()
538                .filter_map(|range| bounds.intersection(&(range + translation)))
539            {
540                renderer.fill_quad(
541                    renderer::Quad {
542                        bounds: range,
543                        ..renderer::Quad::default()
544                    },
545                    style.selection,
546                );
547            }
548        }
549
550        crate::text::draw(
551            renderer,
552            defaults,
553            layout.bounds(),
554            &state.paragraph,
555            style,
556            viewport,
557        );
558    }
559
560    fn update(
561        &mut self,
562        tree: &mut Tree,
563        event: &Event,
564        layout: Layout<'_>,
565        cursor: mouse::Cursor,
566        _renderer: &Renderer,
567        shell: &mut Shell<'_, Message>,
568        viewport: &Rectangle,
569    ) {
570        let state = tree.state.downcast_mut::<State<Link>>();
571
572        let bounds = layout.bounds();
573        let click_position = cursor.position_in(bounds);
574
575        if viewport.intersection(&bounds).is_none()
576            && state.selection.is_empty()
577            && state.dragging.is_none()
578        {
579            return;
580        }
581
582        let was_hovered = state.is_hovered;
583        let hovered_link_before = state.hovered_link;
584        let selection_before = state.selection;
585
586        state.is_hovered = click_position.is_some();
587
588        if let Some(position) = click_position {
589            state.hovered_link =
590                state.paragraph.hit_span(position).and_then(|span| {
591                    if self.spans.as_ref().as_ref().get(span)?.link.is_some() {
592                        Some(span)
593                    } else {
594                        None
595                    }
596                });
597        } else {
598            state.hovered_link = None;
599        }
600
601        match event {
602            Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
603            | Event::Touch(touch::Event::FingerPressed { .. }) => {
604                if state.hovered_link.is_some() {
605                    state.span_pressed = state.hovered_link;
606                    shell.capture_event();
607                }
608
609                if let Some(position) = cursor.position_over(bounds) {
610                    let click = click::Click::new(
611                        position,
612                        mouse::Button::Left,
613                        state.last_click,
614                        self.click_interval,
615                    );
616
617                    let (line, index) = state
618                        .grapheme_line_and_index(position, bounds)
619                        .unwrap_or((0, 0));
620
621                    match click.kind() {
622                        click::Kind::Single => {
623                            let new_end = SelectionEnd { line, index };
624
625                            if state.keyboard_modifiers.shift() {
626                                state.selection.change_selection(new_end);
627                            } else {
628                                state.selection.select_range(new_end, new_end);
629                            }
630
631                            state.dragging = Some(Dragging::Grapheme);
632                        }
633                        click::Kind::Double => {
634                            state.selection.select_word(
635                                line,
636                                index,
637                                &state.paragraph,
638                            );
639                            state.dragging = Some(Dragging::Word);
640                        }
641                        click::Kind::Triple => {
642                            state.selection.select_line(line, &state.paragraph);
643                            state.dragging = Some(Dragging::Line);
644                        }
645                    }
646
647                    state.last_click = Some(click);
648
649                    shell.capture_event();
650                } else {
651                    state.selection = Selection::default();
652                }
653            }
654            Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
655            | Event::Touch(touch::Event::FingerLifted { .. })
656            | Event::Touch(touch::Event::FingerLost { .. }) => {
657                state.dragging = None;
658                if !matches!(
659                    event,
660                    Event::Touch(touch::Event::FingerLost { .. })
661                ) && state.selection.is_empty()
662                {
663                    match state.span_pressed {
664                        Some(span) if Some(span) == state.hovered_link => {
665                            if let Some((link, on_link_clicked)) = self
666                                .spans
667                                .as_ref()
668                                .as_ref()
669                                .get(span)
670                                .and_then(|span| span.link.clone())
671                                .zip(self.on_link_click.as_deref())
672                            {
673                                shell.publish(on_link_clicked(link));
674                            }
675                        }
676                        _ => {}
677                    }
678
679                    state.span_pressed = None;
680                }
681            }
682            Event::Mouse(mouse::Event::CursorMoved { .. })
683            | Event::Touch(touch::Event::FingerMoved { .. }) => {
684                if let Some(position) = cursor.land().position()
685                    && let Some(dragging) = state.dragging
686                {
687                    let (line, index) = state
688                        .grapheme_line_and_index(position, bounds)
689                        .unwrap_or((0, 0));
690
691                    match dragging {
692                        Dragging::Grapheme => {
693                            let new_end = SelectionEnd { line, index };
694
695                            state.selection.change_selection(new_end);
696                        }
697                        Dragging::Word => {
698                            let new_end = SelectionEnd { line, index };
699
700                            state.selection.change_selection_by_word(
701                                new_end,
702                                &state.paragraph,
703                            );
704                        }
705                        Dragging::Line => {
706                            state.selection.change_selection_by_line(
707                                line,
708                                &state.paragraph,
709                            );
710                        }
711                    };
712                }
713            }
714            Event::Keyboard(keyboard::Event::KeyPressed { key, .. }) => {
715                match key.as_ref() {
716                    keyboard::Key::Character("c")
717                        if state.keyboard_modifiers.command()
718                            && !state.selection.is_empty() =>
719                    {
720                        shell.write_clipboard(
721                            state.selection.text(&state.paragraph).into(),
722                        );
723
724                        shell.capture_event();
725                    }
726                    keyboard::Key::Character("a")
727                        if state.keyboard_modifiers.command()
728                            && !state.selection.is_empty() =>
729                    {
730                        state.selection.select_all(&state.paragraph);
731
732                        shell.capture_event();
733                    }
734                    keyboard::Key::Named(key::Named::Home)
735                        if state.keyboard_modifiers.shift()
736                            && !state.selection.is_empty() =>
737                    {
738                        if state.keyboard_modifiers.jump() {
739                            state.selection.select_beginning();
740                        } else {
741                            state.selection.select_line_beginning();
742                        }
743
744                        shell.capture_event();
745                    }
746                    keyboard::Key::Named(key::Named::End)
747                        if state.keyboard_modifiers.shift()
748                            && !state.selection.is_empty() =>
749                    {
750                        if state.keyboard_modifiers.jump() {
751                            state.selection.select_end(&state.paragraph);
752                        } else {
753                            state.selection.select_line_end(&state.paragraph);
754                        }
755
756                        shell.capture_event();
757                    }
758                    keyboard::Key::Named(key::Named::ArrowLeft)
759                        if state.keyboard_modifiers.shift()
760                            && !state.selection.is_empty() =>
761                    {
762                        if state.keyboard_modifiers.macos_command() {
763                            state.selection.select_line_beginning();
764                        } else if state.keyboard_modifiers.jump() {
765                            state
766                                .selection
767                                .select_left_by_words(&state.paragraph);
768                        } else {
769                            state.selection.select_left(&state.paragraph);
770                        }
771
772                        shell.capture_event();
773                    }
774                    keyboard::Key::Named(key::Named::ArrowRight)
775                        if state.keyboard_modifiers.shift()
776                            && !state.selection.is_empty() =>
777                    {
778                        if state.keyboard_modifiers.macos_command() {
779                            state.selection.select_line_end(&state.paragraph);
780                        } else if state.keyboard_modifiers.jump() {
781                            state
782                                .selection
783                                .select_right_by_words(&state.paragraph);
784                        } else {
785                            state.selection.select_right(&state.paragraph);
786                        }
787
788                        shell.capture_event();
789                    }
790                    keyboard::Key::Named(key::Named::ArrowUp)
791                        if state.keyboard_modifiers.shift()
792                            && !state.selection.is_empty() =>
793                    {
794                        if state.keyboard_modifiers.macos_command() {
795                            state.selection.select_beginning();
796                        } else if state.keyboard_modifiers.jump() {
797                            state.selection.select_line_beginning();
798                        } else {
799                            state.selection.select_up(&state.paragraph);
800                        }
801
802                        shell.capture_event();
803                    }
804                    keyboard::Key::Named(key::Named::ArrowDown)
805                        if state.keyboard_modifiers.shift()
806                            && !state.selection.is_empty() =>
807                    {
808                        if state.keyboard_modifiers.macos_command() {
809                            state.selection.select_end(&state.paragraph);
810                        } else if state.keyboard_modifiers.jump() {
811                            state.selection.select_line_end(&state.paragraph);
812                        } else {
813                            state.selection.select_down(&state.paragraph);
814                        }
815
816                        shell.capture_event();
817                    }
818                    keyboard::Key::Named(key::Named::Escape) => {
819                        state.dragging = None;
820                        state.selection = Selection::default();
821
822                        state.keyboard_modifiers =
823                            keyboard::Modifiers::default();
824
825                        if state.selection != selection_before {
826                            shell.capture_event();
827                        }
828                    }
829                    _ => {}
830                }
831            }
832            Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) => {
833                state.keyboard_modifiers = *modifiers;
834            }
835            _ => {}
836        }
837
838        if state.is_hovered != was_hovered
839            || state.selection != selection_before
840            || state.hovered_link != hovered_link_before
841        {
842            if let Some(span) = state.hovered_link {
843                if let Some((link, on_link_hovered)) = self
844                    .spans
845                    .as_ref()
846                    .as_ref()
847                    .get(span)
848                    .and_then(|span| span.link.clone())
849                    .zip(self.on_link_hover.as_deref())
850                {
851                    shell.publish(on_link_hovered(link));
852                }
853            } else if let Some(on_hover_lost) = self.on_hover_lost.as_deref() {
854                shell.publish(on_hover_lost());
855            }
856
857            shell.request_redraw();
858        }
859    }
860
861    fn mouse_interaction(
862        &self,
863        tree: &Tree,
864        layout: Layout<'_>,
865        cursor: mouse::Cursor,
866        _viewport: &Rectangle,
867        _renderer: &Renderer,
868    ) -> mouse::Interaction {
869        let state = tree.state.downcast_ref::<State<Link>>();
870
871        if state.hovered_link.is_some() {
872            mouse::Interaction::Pointer
873        } else if cursor.is_over(layout.bounds()) || state.dragging.is_some() {
874            mouse::Interaction::Text
875        } else {
876            mouse::Interaction::None
877        }
878    }
879}
880
881#[allow(clippy::too_many_arguments)]
882fn layout<Link, Renderer>(
883    state: &mut State<Link>,
884    renderer: &Renderer,
885    limits: &layout::Limits,
886    width: Length,
887    height: Length,
888    spans: &[Span<'_, Link, Renderer::Font>],
889    line_height: LineHeight,
890    size: Option<Pixels>,
891    font: Option<Renderer::Font>,
892    align_x: Alignment,
893    align_y: alignment::Vertical,
894    wrapping: Wrapping,
895    ellipsis: Ellipsis,
896) -> layout::Node
897where
898    Link: Clone,
899    Renderer: core::text::Renderer<Paragraph = Paragraph, Font = Font>,
900{
901    layout::sized(limits, width, height, |limits| {
902        let bounds = limits.max();
903
904        let size = size.unwrap_or_else(|| renderer.default_size());
905        let font = font.unwrap_or_else(|| renderer.default_font());
906
907        let text_with_spans = || core::Text {
908            content: spans,
909            bounds,
910            size,
911            line_height,
912            font,
913            align_x,
914            align_y,
915            shaping: Shaping::Advanced,
916            wrapping,
917            ellipsis,
918            hint_factor: renderer.scale_factor(),
919        };
920
921        if state.spans != spans {
922            state.paragraph =
923                Renderer::Paragraph::with_spans(text_with_spans());
924            state.spans = spans.iter().cloned().map(Span::to_static).collect();
925            state.update_visual_bounds();
926        } else {
927            match state.paragraph.compare(core::Text {
928                content: (),
929                bounds,
930                size,
931                line_height,
932                font,
933                align_x,
934                align_y,
935                shaping: Shaping::Advanced,
936                wrapping,
937                ellipsis,
938                hint_factor: renderer.scale_factor(),
939            }) {
940                core::text::Difference::None => {}
941                core::text::Difference::Bounds => {
942                    state.paragraph.resize(bounds);
943                    state.update_visual_bounds();
944                }
945                core::text::Difference::Shape => {
946                    state.paragraph =
947                        Renderer::Paragraph::with_spans(text_with_spans());
948                    state.update_visual_bounds();
949                }
950            }
951        }
952
953        state.paragraph.min_bounds()
954    })
955}
956
957impl<'a, Link, Message, Theme, Renderer>
958    FromIterator<Span<'a, Link, Renderer::Font>>
959    for Rich<'a, Link, Message, Theme, Renderer>
960where
961    Link: Clone + 'a,
962    Theme: Catalog,
963    Renderer: core::text::Renderer<Paragraph = Paragraph, Font = Font>,
964    Renderer::Font: 'a,
965{
966    fn from_iter<T: IntoIterator<Item = Span<'a, Link, Renderer::Font>>>(
967        spans: T,
968    ) -> Self {
969        Self::with_spans(spans.into_iter().collect::<Vec<_>>())
970    }
971}
972
973impl<'a, Link, Message, Theme, Renderer>
974    From<Rich<'a, Link, Message, Theme, Renderer>>
975    for Element<'a, Message, Theme, Renderer>
976where
977    Message: 'a,
978    Link: Clone + 'a,
979    Theme: Catalog + 'a,
980    Renderer: core::text::Renderer<Paragraph = Paragraph, Font = Font> + 'a,
981{
982    fn from(
983        text: Rich<'a, Link, Message, Theme, Renderer>,
984    ) -> Element<'a, Message, Theme, Renderer> {
985        Element::new(text)
986    }
987}
988
989fn highlight_line(
990    line: &cosmic_text::BufferLine,
991    from: usize,
992    to: usize,
993) -> impl Iterator<Item = (f32, f32)> + '_ {
994    let layout = line.layout_opt().map(Vec::as_slice).unwrap_or_default();
995
996    // Check for multi codepoint glyphs for each previous visual line
997    let mut previous_diff = 0;
998    let previous_lines_diff = line
999        .layout_opt()
1000        .map(Vec::as_slice)
1001        .unwrap_or_default()
1002        .iter()
1003        .enumerate()
1004        .map(move |(line_nr, visual_line)| {
1005            if line_nr == 0 {
1006                let current_diff = previous_diff
1007                    + visual_line.glyphs.iter().fold(0, |d, g| {
1008                        (d + g.start.abs_diff(g.end)).saturating_sub(1)
1009                    });
1010                previous_diff = current_diff;
1011                0
1012            } else {
1013                let current_diff = previous_diff
1014                    + visual_line
1015                        .glyphs
1016                        .iter()
1017                        .fold(0, |d, g| d + g.start.abs_diff(g.end) - 1);
1018                let previous_diff_temp = previous_diff;
1019                previous_diff = current_diff;
1020                previous_diff_temp
1021            }
1022        });
1023
1024    layout.iter().zip(previous_lines_diff).map(
1025        move |(visual_line, previous_lines_diff)| {
1026            let start = visual_line
1027                .glyphs
1028                .first()
1029                .map(|glyph| glyph.start)
1030                .unwrap_or(0);
1031            let end = visual_line
1032                .glyphs
1033                .last()
1034                .map(|glyph| glyph.end)
1035                .unwrap_or(0);
1036
1037            let to = to + previous_lines_diff;
1038            let mut range = start.max(from)..end.min(to);
1039
1040            let x_offset = visual_line
1041                .glyphs
1042                .first()
1043                .map(|glyph| glyph.x)
1044                .unwrap_or_default();
1045
1046            if range.is_empty() {
1047                (x_offset, 0.0)
1048            } else if range.start == start && range.end == end {
1049                (x_offset, visual_line.w)
1050            } else {
1051                let mut x = 0.0;
1052                let mut width = 0.0;
1053                for glyph in &visual_line.glyphs {
1054                    let glyph_count = glyph.start.abs_diff(glyph.end);
1055
1056                    // Check for multi codepoint glyphs before or within the range
1057                    if glyph_count > 1 {
1058                        if range.start > glyph.start {
1059                            range.start += glyph_count - 1;
1060                            range.end += glyph_count - 1;
1061                        } else if range.end > glyph.start {
1062                            range.end += glyph_count - 1;
1063                        }
1064                    }
1065
1066                    if range.start > glyph.start {
1067                        x += glyph.w;
1068                    }
1069
1070                    if range.start <= glyph.start && range.end > glyph.start {
1071                        width += glyph.w;
1072                    } else if range.end <= glyph.start {
1073                        break;
1074                    }
1075                }
1076
1077                (x_offset + x, width)
1078            }
1079        },
1080    )
1081}
1082
1083fn visual_lines_offset(line: usize, buffer: &cosmic_text::Buffer) -> i32 {
1084    let scroll = buffer.scroll();
1085
1086    let start = scroll.line.min(line);
1087    let end = scroll.line.max(line);
1088
1089    let visual_lines_offset: usize = buffer.lines[start..]
1090        .iter()
1091        .take(end - start)
1092        .map(|line| line.layout_opt().map(Vec::len).unwrap_or_default())
1093        .sum();
1094
1095    visual_lines_offset as i32 * if scroll.line < line { 1 } else { -1 }
1096}