Skip to main content

iced_cube/data/
selectable_text.rs

1//! Rich text that can be selected with the mouse and copied.
2//!
3//! [`selectable_text`] takes the spans iced's rich text takes and draws its
4//! own part of a selection. A [`selection_area`] around any number of them
5//! owns the selection, so a drag can run from one paragraph into the next:
6//! drag to select, double click for a word, triple click for a block.
7//! Links still open on a plain click.
8//!
9//! The area sends the selected text through `on_select` each time a
10//! selection is finished and through `on_copy` when the Copy shortcut is
11//! pressed; the app writes it to the clipboard. Keyboard shortcuts resolve
12//! through a [`Keymap`] of [`Action`]s; see [`default_keymap`]. Typing, Tab
13//! or another Ctrl or Cmd chord drops the selection, as the keys then
14//! belong to something else. A field given focus without a key or a press,
15//! by a task, does not: clear the selection then if the two share chords.
16//!
17//! Put the scrollable inside the area, not around it, and a drag past its
18//! top or bottom edge scrolls it.
19//!
20//! For a context menu, give the area an id and wrap it in a context menu
21//! whose items run [`selected`] and [`select_all`].
22//!
23//! ```no_run
24//! use iced::widget::{column, span};
25//! use iced::{Element, Task};
26//! use iced_cube::data::selectable_text::{selectable_text, selection_area};
27//!
28//! #[derive(Debug, Clone)]
29//! enum Message {
30//!     Copy(String),
31//!     Open(String),
32//! }
33//!
34//! fn view<'a>() -> Element<'a, Message> {
35//!     selection_area(column![
36//!         selectable_text(vec![span("Read the "), span("guide").link("guide".to_owned())])
37//!             .on_link_click(Message::Open),
38//!         selectable_text::<String, _>(vec![span("A second paragraph.")]),
39//!     ])
40//!     .on_copy(Message::Copy)
41//!     .into()
42//! }
43//!
44//! fn update(message: Message) -> Task<Message> {
45//!     match message {
46//!         Message::Copy(text) => iced::clipboard::write(text),
47//!         Message::Open(_) => Task::none(),
48//!     }
49//! }
50//! ```
51
52use std::any::Any;
53use std::fmt;
54
55use iced::advanced::graphics::text::cosmic_text;
56use iced::advanced::layout::{self, Layout};
57use iced::advanced::renderer::{self, Renderer as _};
58use iced::advanced::text::{self, Paragraph as _, Span};
59use iced::advanced::widget::operation::{Operation, Outcome, Scrollable};
60use iced::advanced::widget::{self, Id, Tree, tree};
61use iced::advanced::{Clipboard, Shell, Widget, mouse, overlay};
62use iced::keyboard::{self, key::Named};
63use iced::time::{Duration, Instant};
64use iced::widget::scrollable::AbsoluteOffset;
65use iced::{
66    Color, Element, Event, Font, Length, Pixels, Point, Rectangle, Renderer, Size, Task, Theme,
67    Vector, window,
68};
69
70use crate::keys::{self, Chord, Keymap};
71use crate::shaped::{Paragraph, Shaped};
72use crate::theme::{Tokens, fade};
73
74/// How fast a drag just past the edge of a scrollable scrolls it, in pixels
75/// a second.
76pub const SCROLL_SPEED: f32 = 200.0;
77/// How much faster it scrolls for each pixel the pointer is past the edge.
78pub const SCROLL_GAIN: f32 = 12.0;
79/// The fastest a drag scrolls, in pixels a second.
80pub const MAX_SCROLL_SPEED: f32 = 2400.0;
81/// The longest gap between frames that still counts as scrolling time.
82const MAX_FRAME: Duration = Duration::from_millis(50);
83/// How soon a press must follow the last to count as a double or triple
84/// click.
85pub const DOUBLE_CLICK: Duration = Duration::from_millis(400);
86/// How far apart the presses of a double click may be, in pixels.
87const CLICK_SLOP: f32 = 6.0;
88
89/// A place in one text: the line, then the byte within it.
90type Caret = (usize, usize);
91/// A place in an area: which text, counted in drawing order, then where in
92/// it.
93type Position = (usize, Caret);
94
95const START: Caret = (0, 0);
96const END: Caret = (usize::MAX, usize::MAX);
97
98/// How selected text looks.
99#[derive(Debug, Clone, Copy, PartialEq)]
100pub struct Style {
101    /// Drawn over the selected text.
102    pub selection: Color,
103}
104
105/// The selection colour, matching a text field's.
106pub fn style(tokens: &Tokens) -> Style {
107    Style {
108        selection: fade(tokens.primary, 0.25),
109    }
110}
111
112/// How fast a drag `distance` pixels past the edge of a scrollable scrolls
113/// it, in pixels a second.
114pub fn scroll_speed(distance: f32) -> f32 {
115    (SCROLL_SPEED + SCROLL_GAIN * distance.max(0.0)).min(MAX_SCROLL_SPEED)
116}
117
118/// What a selection area's keyboard shortcut does.
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
120pub enum Action {
121    /// Sends the selected text through `on_copy`.
122    Copy,
123    /// Selects every text in the area.
124    SelectAll,
125    /// Drops the selection.
126    Clear,
127}
128
129impl keys::Action for Action {
130    const ALL: &'static [Self] = &[Action::Copy, Action::SelectAll, Action::Clear];
131
132    fn defaults() -> Keymap<Self> {
133        default_keymap()
134    }
135
136    fn name(self) -> &'static str {
137        match self {
138            Action::Copy => "Copy",
139            Action::SelectAll => "Select all",
140            Action::Clear => "Clear",
141        }
142    }
143
144    fn description(self) -> &'static str {
145        match self {
146            Action::Copy => "Copies the selected text.",
147            Action::SelectAll => "Selects all the text in the area that was last clicked.",
148            Action::Clear => "Drops the selection.",
149        }
150    }
151}
152
153/// The default selection shortcuts. Mod is Cmd on macOS and Ctrl elsewhere.
154///
155/// | Keys | Action |
156/// | --- | --- |
157/// | `Mod+C` | [`Action::Copy`] |
158/// | `Mod+A` | [`Action::SelectAll`] |
159/// | `Escape` | [`Action::Clear`] |
160pub fn default_keymap() -> Keymap<Action> {
161    Keymap::new()
162        .bind(Chord::character('c').command(), Action::Copy)
163        .bind(Chord::character('a').command(), Action::SelectAll)
164        .bind(Chord::named(Named::Escape), Action::Clear)
165}
166
167/// What a [`SelectionArea`] reads and writes in each text under it.
168struct Body {
169    paragraph: Paragraph,
170    /// Where the pointer was at the last event, relative to the text's
171    /// corner.
172    pointer: Option<Point>,
173    /// Whether the pointer was inside every scrollable around the text.
174    direct: bool,
175    selection: Option<(Caret, Caret)>,
176}
177
178impl Body {
179    fn hit(&self, point: Point) -> Caret {
180        let cursor = self
181            .paragraph
182            .shaped()
183            .and_then(|buffer| buffer.hit(point.x, point.y));
184        match cursor {
185            Some(cursor) => (cursor.line, cursor.index),
186            None if point.y < 0.0 => START,
187            None => END,
188        }
189    }
190
191    fn rectangles(&self, from: Caret, to: Caret) -> Vec<Rectangle> {
192        let Some(buffer) = self.paragraph.shaped() else {
193            return Vec::new();
194        };
195        let start = cosmic_text::Cursor::new(from.0, from.1);
196        let end = cosmic_text::Cursor::new(to.0, to.1);
197        buffer
198            .layout_runs()
199            .filter_map(|run| {
200                let (x, width) = run.highlight(start, end)?;
201                (width > 0.0).then(|| {
202                    Rectangle::new(
203                        Point::new(x, run.line_top),
204                        Size::new(width, run.line_height),
205                    )
206                })
207            })
208            .collect()
209    }
210
211    fn text(&self, from: Caret, to: Caret) -> String {
212        let Some(buffer) = self.paragraph.shaped() else {
213            return String::new();
214        };
215        let mut lines = Vec::new();
216        for (index, line) in buffer.lines.iter().enumerate() {
217            if index < from.0 || index > to.0 {
218                continue;
219            }
220            let text = line.text();
221            let start = if index == from.0 {
222                from.1.min(text.len())
223            } else {
224                0
225            };
226            let end = if index == to.0 {
227                to.1.min(text.len())
228            } else {
229                text.len()
230            };
231            lines.push(text.get(start..end).unwrap_or_default());
232        }
233        lines.join("\n")
234    }
235
236    fn selected(&self) -> Option<String> {
237        let (from, to) = self.selection?;
238        let text = self.text(from, to);
239        (!text.is_empty()).then_some(text)
240    }
241
242    /// The word around `at`, or the single character there when it is not
243    /// part of one.
244    fn word(&self, at: Caret) -> Option<(Caret, Caret)> {
245        let buffer = self.paragraph.shaped()?;
246        let line = at.0.min(buffer.lines.len().checked_sub(1)?);
247        let (start, end) = word_bounds(buffer.lines.get(line)?.text(), at.1)?;
248        Some(((line, start), (line, end)))
249    }
250}
251
252/// The point of `bounds` nearest to `point`.
253fn clamp(point: Point, bounds: Rectangle) -> Point {
254    Point::new(
255        point.x.clamp(bounds.x, bounds.x + bounds.width.max(0.0)),
256        point.y.clamp(bounds.y, bounds.y + bounds.height.max(0.0)),
257    )
258}
259
260/// Finds the text the pointer is on from the texts in drawing order: the
261/// one it is over, else the one it is beside, else the next one below it.
262#[derive(Default)]
263struct Search {
264    found: Option<Position>,
265    /// The last text level with the pointer, for when the pointer is beside
266    /// it.
267    level: Option<Position>,
268}
269
270impl Search {
271    fn feed(&mut self, index: usize, size: Size, pointer: Point, hit: impl FnOnce() -> Caret) {
272        if self.found.is_some() {
273            return;
274        }
275        if pointer.y < 0.0 {
276            self.found = self.level.or(Some((index, START)));
277            return;
278        }
279        if pointer.y >= size.height {
280            return;
281        }
282        let here = Some((index, hit()));
283        if pointer.x < size.width {
284            self.found = here;
285        } else {
286            self.level = here;
287        }
288    }
289
290    fn result(&self) -> Option<Position> {
291        self.found.or(self.level)
292    }
293}
294
295/// How many presses in a row this one makes: one, two for a double click or
296/// three for a triple click. A fourth press starts again.
297fn click_count(previous: Option<Click>, position: Point, now: Instant, interval: Duration) -> u8 {
298    let Some(previous) = previous else {
299        return 1;
300    };
301    let repeated = previous.count < 3
302        && position.distance(previous.position) <= CLICK_SLOP
303        && now.saturating_duration_since(previous.at) <= interval;
304    if repeated { previous.count + 1 } else { 1 }
305}
306
307#[derive(Debug, Clone, Copy)]
308struct Click {
309    position: Point,
310    at: Instant,
311    count: u8,
312}
313
314fn is_word(character: char) -> bool {
315    character.is_alphanumeric() || character == '_'
316}
317
318/// The byte range of the word at `index`, or of the character there when it
319/// is not a letter, digit or underscore.
320fn word_bounds(text: &str, index: usize) -> Option<(usize, usize)> {
321    let (at, character) = text
322        .char_indices()
323        .take_while(|(start, _)| *start <= index)
324        .last()?;
325    if !is_word(character) {
326        return Some((at, at + character.len_utf8()));
327    }
328    let start = text[..at]
329        .char_indices()
330        .rev()
331        .take_while(|(_, c)| is_word(*c))
332        .last()
333        .map_or(at, |(start, _)| start);
334    let end = text[at..]
335        .char_indices()
336        .find(|(_, c)| !is_word(*c))
337        .map_or(text.len(), |(offset, _)| at + offset);
338    Some((start, end))
339}
340
341struct State<Link> {
342    spans: Vec<Span<'static, Link>>,
343    /// The spans' text in one piece, for operations that look for text.
344    text: String,
345    hovered: Option<usize>,
346    pressed: Option<usize>,
347    body: Body,
348}
349
350/// Rich text whose links can be clicked and whose text can be selected
351/// inside a [`SelectionArea`]. Convert it into an [`Element`] to render.
352pub struct SelectableText<'a, Link, Message> {
353    spans: Box<dyn AsRef<[Span<'a, Link>]> + 'a>,
354    size: Option<Pixels>,
355    line_height: text::LineHeight,
356    font: Option<Font>,
357    colour: Option<Color>,
358    width: Length,
359    on_link_click: Option<Box<dyn Fn(Link) -> Message + 'a>>,
360    style: Option<StyleFn<'a>>,
361}
362
363type StyleFn<'a> = Box<dyn Fn(&Theme) -> Style + 'a>;
364
365impl<Link, Message> fmt::Debug for SelectableText<'_, Link, Message> {
366    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367        f.debug_struct("SelectableText")
368            .field("spans", &self.spans.as_ref().as_ref().len())
369            .field("size", &self.size)
370            .field("width", &self.width)
371            .finish_non_exhaustive()
372    }
373}
374
375/// Selectable rich text made of `spans`, as iced's rich text takes them.
376/// Text without links needs the link type named:
377/// `selectable_text::<String, _>(...)`.
378pub fn selectable_text<'a, Link, Message>(
379    spans: impl AsRef<[Span<'a, Link>]> + 'a,
380) -> SelectableText<'a, Link, Message> {
381    SelectableText {
382        spans: Box::new(spans),
383        size: None,
384        line_height: text::LineHeight::default(),
385        font: None,
386        colour: None,
387        width: Length::Shrink,
388        on_link_click: None,
389        style: None,
390    }
391}
392
393impl<'a, Link, Message> SelectableText<'a, Link, Message> {
394    /// The text size of spans that set none.
395    pub fn size(mut self, size: impl Into<Pixels>) -> Self {
396        self.size = Some(size.into());
397        self
398    }
399
400    pub fn line_height(mut self, line_height: impl Into<text::LineHeight>) -> Self {
401        self.line_height = line_height.into();
402        self
403    }
404
405    /// The font of spans that set none.
406    pub fn font(mut self, font: impl Into<Font>) -> Self {
407        self.font = Some(font.into());
408        self
409    }
410
411    /// The colour of spans that set none. Defaults to the text colour around
412    /// the widget.
413    pub fn color(mut self, colour: impl Into<Color>) -> Self {
414        self.colour = Some(colour.into());
415        self
416    }
417
418    pub fn width(mut self, width: impl Into<Length>) -> Self {
419        self.width = width.into();
420        self
421    }
422
423    /// The message for a link that is clicked. Without it links are drawn
424    /// but do nothing.
425    pub fn on_link_click(mut self, on_link_click: impl Fn(Link) -> Message + 'a) -> Self {
426        self.on_link_click = Some(Box::new(on_link_click));
427        self
428    }
429
430    /// Replaces the default look, which is [`style`].
431    pub fn style(mut self, style: impl Fn(&Theme) -> Style + 'a) -> Self {
432        self.style = Some(Box::new(style));
433        self
434    }
435
436    fn spans(&self) -> &[Span<'a, Link>] {
437        self.spans.as_ref().as_ref()
438    }
439
440    fn link(&self, span: usize) -> Option<&Link> {
441        self.spans().get(span)?.link.as_ref()
442    }
443
444    fn draw_decorations(
445        &self,
446        state: &State<Link>,
447        renderer: &mut Renderer,
448        defaults: &renderer::Style,
449        origin: Vector,
450    ) {
451        for (index, span) in self.spans().iter().enumerate() {
452            let hovered_link = self.on_link_click.is_some() && state.hovered == Some(index);
453            let lined = span.underline || span.strikethrough || hovered_link;
454            if span.highlight.is_none() && !lined {
455                continue;
456            }
457            let regions = state.body.paragraph.span_bounds(index);
458
459            if let Some(highlight) = span.highlight {
460                for bounds in &regions {
461                    let padded = Rectangle::new(
462                        bounds.position() - Vector::new(span.padding.left, span.padding.top),
463                        bounds.size() + Size::new(span.padding.x(), span.padding.y()),
464                    );
465                    renderer.fill_quad(
466                        renderer::Quad {
467                            bounds: padded + origin,
468                            border: highlight.border,
469                            ..renderer::Quad::default()
470                        },
471                        highlight.background,
472                    );
473                }
474            }
475            if !lined {
476                continue;
477            }
478
479            let size = span
480                .size
481                .or(self.size)
482                .unwrap_or(text::Renderer::default_size(renderer));
483            let line_height = span
484                .line_height
485                .unwrap_or(self.line_height)
486                .to_absolute(size);
487            let colour = span.color.or(self.colour).unwrap_or(defaults.text_color);
488            let baseline = origin + Vector::new(0.0, size.0 + (line_height.0 - size.0) / 2.0);
489            let line = |renderer: &mut Renderer, rise: f32| {
490                for bounds in &regions {
491                    renderer.fill_quad(
492                        renderer::Quad {
493                            bounds: Rectangle::new(
494                                bounds.position() + baseline - Vector::new(0.0, rise),
495                                Size::new(bounds.width, 1.0),
496                            ),
497                            ..renderer::Quad::default()
498                        },
499                        colour,
500                    );
501                }
502            };
503            if span.underline || hovered_link {
504                line(renderer, size.0 * 0.08);
505            }
506            if span.strikethrough {
507                line(renderer, size.0 / 2.0);
508            }
509        }
510    }
511}
512
513impl<Link, Message> Widget<Message, Theme, Renderer> for SelectableText<'_, Link, Message>
514where
515    Link: Clone + PartialEq + 'static,
516{
517    fn tag(&self) -> tree::Tag {
518        tree::Tag::of::<State<Link>>()
519    }
520
521    fn state(&self) -> tree::State {
522        tree::State::new(State::<Link> {
523            spans: Vec::new(),
524            text: String::new(),
525            hovered: None,
526            pressed: None,
527            body: Body {
528                paragraph: Paragraph::default(),
529                pointer: None,
530                direct: false,
531                selection: None,
532            },
533        })
534    }
535
536    fn size(&self) -> Size<Length> {
537        Size::new(self.width, Length::Shrink)
538    }
539
540    fn layout(
541        &mut self,
542        tree: &mut Tree,
543        renderer: &Renderer,
544        limits: &layout::Limits,
545    ) -> layout::Node {
546        let state = tree.state.downcast_mut::<State<Link>>();
547        let spans = self.spans.as_ref().as_ref();
548        let size = self
549            .size
550            .unwrap_or_else(|| text::Renderer::default_size(renderer));
551        let font = self
552            .font
553            .unwrap_or_else(|| text::Renderer::default_font(renderer));
554        let line_height = self.line_height;
555
556        layout::sized(limits, self.width, Length::Shrink, |limits| {
557            let bounds = limits.max();
558            let shape = text::Text {
559                content: (),
560                bounds,
561                size,
562                line_height,
563                font,
564                align_x: text::Alignment::Default,
565                align_y: iced::alignment::Vertical::Top,
566                shaping: text::Shaping::Advanced,
567                wrapping: text::Wrapping::default(),
568            };
569            let shaped = || Paragraph::with_spans(shape.with_content(spans));
570
571            if state.spans != spans {
572                state.body.paragraph = shaped();
573                state.spans = spans.iter().cloned().map(Span::to_static).collect();
574                state.text = spans.iter().map(|span| &*span.text).collect();
575                state.body.selection = None;
576            } else {
577                match state.body.paragraph.compare(shape) {
578                    text::Difference::None => {}
579                    text::Difference::Bounds => state.body.paragraph.resize(bounds),
580                    text::Difference::Shape => state.body.paragraph = shaped(),
581                }
582            }
583            state.body.paragraph.min_bounds()
584        })
585    }
586
587    fn operate(
588        &mut self,
589        tree: &mut Tree,
590        layout: Layout<'_>,
591        _renderer: &Renderer,
592        operation: &mut dyn Operation,
593    ) {
594        let state = tree.state.downcast_mut::<State<Link>>();
595        #[cfg(feature = "icedwright")]
596        {
597            let size = self
598                .size
599                .unwrap_or_else(|| text::Renderer::default_size(_renderer));
600            let body = &state.body;
601            icedwright_probe::report(operation, layout.bounds(), || {
602                let (lines, carets) = geometry(body);
603                let annotation = icedwright_probe::Annotation::new()
604                    .text_size(size)
605                    .text_geometry(carets.into_iter().map(|(at, point)| (at, point.into())))
606                    .component("iced_cube::selectable_text");
607                if lines > 1 {
608                    annotation
609                        .role(icedwright_probe::role::Paragraph)
610                        .to_static()
611                } else {
612                    annotation.role(icedwright_probe::role::Text).to_static()
613                }
614            });
615            // Nests the text under the annotation for recorders.
616            let text = &state.text;
617            let body = &mut state.body;
618            operation.traverse(&mut |operation| {
619                operation.text(None, layout.bounds(), text);
620                operation.custom(None, layout.bounds(), body);
621            });
622        }
623        #[cfg(not(feature = "icedwright"))]
624        {
625            operation.text(None, layout.bounds(), &state.text);
626            operation.custom(None, layout.bounds(), &mut state.body);
627        }
628    }
629
630    fn update(
631        &mut self,
632        tree: &mut Tree,
633        event: &Event,
634        layout: Layout<'_>,
635        cursor: mouse::Cursor,
636        _renderer: &Renderer,
637        _clipboard: &mut dyn Clipboard,
638        shell: &mut Shell<'_, Message>,
639        viewport: &Rectangle,
640    ) {
641        let event = match event {
642            Event::Mouse(event) => Some(event),
643            // A frame drawn while a drag scrolls the page moves the text
644            // under a pointer that has not moved.
645            Event::Window(window::Event::RedrawRequested(_)) => None,
646            _ => return,
647        };
648        let state = tree.state.downcast_mut::<State<Link>>();
649        let bounds = layout.bounds();
650        // A cursor outside a scrolled parent still says where a drag has
651        // reached, but only as far as the edge of what the parent shows:
652        // text scrolled out of view is never under the pointer.
653        state.body.direct = cursor.position().is_some();
654        state.body.pointer = cursor.land().position().map(|at| {
655            let at = if state.body.direct {
656                at
657            } else {
658                clamp(at, *viewport)
659            };
660            Point::new(at.x - bounds.x, at.y - bounds.y)
661        });
662        let Some(event) = event else {
663            return;
664        };
665
666        let hovered = cursor
667            .position_in(bounds)
668            .and_then(|at| state.body.paragraph.hit_span(at))
669            .filter(|span| self.link(*span).is_some());
670        if hovered != state.hovered {
671            state.hovered = hovered;
672            shell.request_redraw();
673        }
674
675        match event {
676            mouse::Event::ButtonPressed(mouse::Button::Left) => state.pressed = state.hovered,
677            mouse::Event::ButtonReleased(mouse::Button::Left) => {
678                let pressed = state.pressed.take();
679                // A drag that ends on the link it began on is a selection,
680                // not a click.
681                if pressed.is_none() || pressed != state.hovered || state.body.selection.is_some() {
682                    return;
683                }
684                let link = pressed.and_then(|span| self.link(span));
685                if let (Some(link), Some(on_link_click)) = (link, &self.on_link_click) {
686                    shell.publish(on_link_click(link.clone()));
687                }
688            }
689            _ => {}
690        }
691    }
692
693    fn draw(
694        &self,
695        tree: &Tree,
696        renderer: &mut Renderer,
697        theme: &Theme,
698        defaults: &renderer::Style,
699        layout: Layout<'_>,
700        _cursor: mouse::Cursor,
701        viewport: &Rectangle,
702    ) {
703        let bounds = layout.bounds();
704        if !bounds.intersects(viewport) {
705            return;
706        }
707        let state = tree.state.downcast_ref::<State<Link>>();
708        let origin = bounds.position() - Point::ORIGIN;
709
710        // Inline code has an opaque background, so the selection goes over
711        // it.
712        self.draw_decorations(state, renderer, defaults, origin);
713        if let Some((from, to)) = state.body.selection {
714            let colour = match &self.style {
715                Some(style) => style(theme),
716                None => style(&Tokens::of(theme)),
717            }
718            .selection;
719            for rectangle in state.body.rectangles(from, to) {
720                renderer.fill_quad(
721                    renderer::Quad {
722                        bounds: rectangle + origin,
723                        ..renderer::Quad::default()
724                    },
725                    colour,
726                );
727            }
728        }
729        widget::text::draw(
730            renderer,
731            defaults,
732            bounds,
733            &state.body.paragraph,
734            widget::text::Style { color: self.colour },
735            viewport,
736        );
737    }
738
739    fn mouse_interaction(
740        &self,
741        tree: &Tree,
742        layout: Layout<'_>,
743        cursor: mouse::Cursor,
744        _viewport: &Rectangle,
745        _renderer: &Renderer,
746    ) -> mouse::Interaction {
747        let state = tree.state.downcast_ref::<State<Link>>();
748        if state.hovered.is_some() && self.on_link_click.is_some() {
749            return mouse::Interaction::Pointer;
750        }
751        if cursor.is_over(layout.bounds()) {
752            return mouse::Interaction::Text;
753        }
754        mouse::Interaction::None
755    }
756}
757
758impl<'a, Link, Message> From<SelectableText<'a, Link, Message>> for Element<'a, Message>
759where
760    Link: Clone + PartialEq + 'static,
761    Message: 'a,
762{
763    fn from(text: SelectableText<'a, Link, Message>) -> Self {
764        Element::new(text)
765    }
766}
767
768/// A drag past the edge of a scrollable: where the pointer is and how long
769/// the frame took.
770#[derive(Clone, Copy)]
771struct Pull {
772    pointer: Point,
773    elapsed: Duration,
774}
775
776/// Calls `each` with every [`Body`] it meets, numbered in drawing order, and
777/// scrolls the scrollables a [`Pull`] is past the edge of.
778struct Visit<'f> {
779    index: usize,
780    each: &'f mut (dyn FnMut(usize, Rectangle, &mut Body) + Send),
781    pull: Option<Pull>,
782    /// Whether the pointer is past the edge of a scrollable.
783    pulling: bool,
784    /// How far the scrollables around the widgets being visited have
785    /// scrolled, which is how far their layout is from the window's.
786    scrolled: Vector,
787    /// The scroll of the scrollable whose content is visited next.
788    entering: Option<Vector>,
789}
790
791impl Operation for Visit<'_> {
792    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
793        // A scrollable announces itself just before its content is visited.
794        let entered = self.entering.take().unwrap_or(Vector::ZERO);
795        self.scrolled += entered;
796        operate(self);
797        self.scrolled -= entered;
798    }
799
800    fn custom(&mut self, _id: Option<&Id>, bounds: Rectangle, state: &mut dyn Any) {
801        let Some(body) = state.downcast_mut::<Body>() else {
802            return;
803        };
804        (self.each)(self.index, bounds, body);
805        self.index += 1;
806    }
807
808    fn scrollable(
809        &mut self,
810        _id: Option<&Id>,
811        bounds: Rectangle,
812        content_bounds: Rectangle,
813        translation: Vector,
814        state: &mut dyn Scrollable,
815    ) {
816        self.entering = Some(translation);
817        let Some(pull) = self.pull else {
818            return;
819        };
820        if content_bounds.height <= bounds.height {
821            return;
822        }
823        // The pointer in the space this scrollable is laid out in.
824        let pointer = pull.pointer + self.scrolled;
825        let above = bounds.y - pointer.y;
826        let below = pointer.y - (bounds.y + bounds.height);
827        let (distance, direction) = if above > 0.0 {
828            (above, -1.0)
829        } else if below > 0.0 {
830            (below, 1.0)
831        } else {
832            return;
833        };
834        self.pulling = true;
835        let y = direction * scroll_speed(distance) * pull.elapsed.as_secs_f32();
836        state.scroll_by(AbsoluteOffset { x: 0.0, y }, bounds, content_bounds);
837    }
838}
839
840/// What a task asks of the area with its id.
841#[derive(Default)]
842struct Request {
843    select_all: bool,
844    read: bool,
845}
846
847/// The selected text, handed back to the task that asked.
848struct Reply(String);
849
850struct Command {
851    target: Id,
852    select_all: bool,
853    text: Option<String>,
854}
855
856impl Operation<String> for Command {
857    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<String>)) {
858        operate(self);
859    }
860
861    fn custom(&mut self, id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Any) {
862        if id != Some(&self.target) {
863            return;
864        }
865        if let Some(request) = state.downcast_mut::<Request>() {
866            request.select_all = self.select_all;
867            request.read = true;
868        }
869        if let Some(Reply(text)) = state.downcast_mut::<Reply>() {
870            self.text = Some(std::mem::take(text));
871        }
872    }
873
874    fn finish(&self) -> Outcome<String> {
875        self.text.clone().map_or(Outcome::None, Outcome::Some)
876    }
877}
878
879/// The widget operations behind [`selected`] and [`select_all`], for apps
880/// that run operations themselves.
881pub mod operation {
882    use super::{Command, Id, Operation};
883
884    /// Produces the text selected in the area with this id.
885    pub fn selected(id: impl Into<Id>) -> impl Operation<String> {
886        Command {
887            target: id.into(),
888            select_all: false,
889            text: None,
890        }
891    }
892
893    /// Selects every text in the area with this id and produces it.
894    pub fn select_all(id: impl Into<Id>) -> impl Operation<String> {
895        Command {
896            target: id.into(),
897            select_all: true,
898            text: None,
899        }
900    }
901}
902
903/// Produces the text selected in the area with this id, which is empty when
904/// nothing is. Produces nothing when no such area is on screen.
905pub fn selected(id: impl Into<Id>) -> Task<String> {
906    widget::operate(operation::selected(id.into()))
907}
908
909/// Selects every text in the area with this id and produces it.
910pub fn select_all(id: impl Into<Id>) -> Task<String> {
911    widget::operate(operation::select_all(id.into()))
912}
913
914#[derive(Default)]
915struct AreaState {
916    anchor: Option<Position>,
917    dragging: bool,
918    /// Whether the last press landed in the area, so Select all is meant
919    /// for it.
920    active: bool,
921    last_click: Option<Click>,
922    /// When the drag last scrolled a scrollable.
923    last_pull: Option<Instant>,
924}
925
926/// Lets the [`SelectableText`]s inside it be selected together. Convert it
927/// into an [`Element`] to render.
928pub struct SelectionArea<'a, Message> {
929    content: Element<'a, Message>,
930    id: Option<Id>,
931    keymap: Keymap<Action>,
932    double_click: Duration,
933    on_copy: Option<Box<dyn Fn(String) -> Message + 'a>>,
934    on_select: Option<Box<dyn Fn(String) -> Message + 'a>>,
935}
936
937impl<Message> fmt::Debug for SelectionArea<'_, Message> {
938    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
939        f.debug_struct("SelectionArea")
940            .field("id", &self.id)
941            .field("keymap", &self.keymap)
942            .finish_non_exhaustive()
943    }
944}
945
946/// An area in which the selectable texts of `content` are selected
947/// together.
948pub fn selection_area<'a, Message>(
949    content: impl Into<Element<'a, Message>>,
950) -> SelectionArea<'a, Message> {
951    SelectionArea {
952        content: content.into(),
953        id: None,
954        keymap: default_keymap(),
955        double_click: DOUBLE_CLICK,
956        on_copy: None,
957        on_select: None,
958    }
959}
960
961impl<'a, Message> SelectionArea<'a, Message> {
962    /// The id [`selected`] and [`select_all`] find the area by.
963    pub fn id(mut self, id: impl Into<Id>) -> Self {
964        self.id = Some(id.into());
965        self
966    }
967
968    /// Replaces the default shortcuts.
969    pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
970        self.keymap = keymap;
971        self
972    }
973
974    /// How soon a press must follow the last to count as a double or triple
975    /// click. Defaults to [`DOUBLE_CLICK`].
976    pub fn double_click(mut self, interval: Duration) -> Self {
977        self.double_click = interval;
978        self
979    }
980
981    /// The message for the selected text when the Copy shortcut is pressed.
982    pub fn on_copy(mut self, on_copy: impl Fn(String) -> Message + 'a) -> Self {
983        self.on_copy = Some(Box::new(on_copy));
984        self
985    }
986
987    /// The message for the selected text each time a selection is finished:
988    /// a drag is released, a word or block is clicked or everything is
989    /// selected from the keyboard.
990    pub fn on_select(mut self, on_select: impl Fn(String) -> Message + 'a) -> Self {
991        self.on_select = Some(Box::new(on_select));
992        self
993    }
994
995    fn visit(
996        &mut self,
997        tree: &mut Tree,
998        layout: Layout<'_>,
999        renderer: &Renderer,
1000        pull: Option<Pull>,
1001        each: &mut (dyn FnMut(usize, Rectangle, &mut Body) + Send),
1002    ) -> bool {
1003        let mut visit = Visit {
1004            index: 0,
1005            each,
1006            pull,
1007            pulling: false,
1008            scrolled: Vector::ZERO,
1009            entering: None,
1010        };
1011        self.content
1012            .as_widget_mut()
1013            .operate(&mut tree.children[0], layout, renderer, &mut visit);
1014        visit.pulling
1015    }
1016
1017    /// Where the pointer is among the texts, or `None` when no text has
1018    /// seen it.
1019    fn locate(
1020        &mut self,
1021        tree: &mut Tree,
1022        layout: Layout<'_>,
1023        renderer: &Renderer,
1024    ) -> Option<Position> {
1025        let mut seen = false;
1026        let mut count = 0;
1027        // Texts the pointer can really be over come first. The rest sit in
1028        // a scrollable the pointer is outside, and count only when a drag
1029        // has left every text behind.
1030        let mut direct = Search::default();
1031        let mut any = Search::default();
1032        self.visit(tree, layout, renderer, None, &mut |index, bounds, body| {
1033            count = index + 1;
1034            let Some(pointer) = body.pointer else {
1035                return;
1036            };
1037            seen = true;
1038            let body = &*body;
1039            if body.direct {
1040                direct.feed(index, bounds.size(), pointer, || body.hit(pointer));
1041            }
1042            any.feed(index, bounds.size(), pointer, || body.hit(pointer));
1043        });
1044        seen.then(|| direct.result().or(any.result()).unwrap_or((count, START)))
1045    }
1046
1047    fn select(
1048        &mut self,
1049        tree: &mut Tree,
1050        layout: Layout<'_>,
1051        renderer: &Renderer,
1052        from: Position,
1053        to: Position,
1054    ) -> bool {
1055        let (start, end) = if from <= to { (from, to) } else { (to, from) };
1056        let mut changed = false;
1057        self.visit(tree, layout, renderer, None, &mut |index, _, body| {
1058            let first = if index == start.0 { start.1 } else { START };
1059            let last = if index == end.0 { end.1 } else { END };
1060            let inside = index >= start.0 && index <= end.0 && first < last;
1061            let selection = inside.then_some((first, last));
1062            changed |= body.selection != selection;
1063            body.selection = selection;
1064        });
1065        changed
1066    }
1067
1068    fn select_everything(&mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer) {
1069        let _ = self.select(tree, layout, renderer, (0, START), (usize::MAX, END));
1070    }
1071
1072    /// Drops the selection and says whether there was one.
1073    fn clear(&mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer) -> bool {
1074        let state = tree.state.downcast_mut::<AreaState>();
1075        state.active = false;
1076        state.dragging = false;
1077        state.last_pull = None;
1078        self.select(tree, layout, renderer, (0, START), (0, START))
1079    }
1080
1081    fn select_word(
1082        &mut self,
1083        tree: &mut Tree,
1084        layout: Layout<'_>,
1085        renderer: &Renderer,
1086        at: Position,
1087    ) {
1088        self.visit(tree, layout, renderer, None, &mut |index, _, body| {
1089            body.selection = (index == at.0).then(|| body.word(at.1)).flatten();
1090        });
1091    }
1092
1093    fn selected(&mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer) -> String {
1094        let mut parts = Vec::new();
1095        self.visit(tree, layout, renderer, None, &mut |_, _, body| {
1096            parts.extend(body.selected());
1097        });
1098        parts.join("\n")
1099    }
1100
1101    fn announce(
1102        &mut self,
1103        tree: &mut Tree,
1104        layout: Layout<'_>,
1105        renderer: &Renderer,
1106        shell: &mut Shell<'_, Message>,
1107    ) {
1108        if self.on_select.is_none() {
1109            return;
1110        }
1111        let text = self.selected(tree, layout, renderer);
1112        if text.is_empty() {
1113            return;
1114        }
1115        if let Some(on_select) = &self.on_select {
1116            shell.publish(on_select(text));
1117        }
1118    }
1119
1120    fn pressed(
1121        &mut self,
1122        tree: &mut Tree,
1123        layout: Layout<'_>,
1124        cursor: mouse::Cursor,
1125        renderer: &Renderer,
1126        shell: &mut Shell<'_, Message>,
1127    ) {
1128        let Some(position) = cursor.position_over(layout.bounds()) else {
1129            if tree.state.downcast_ref::<AreaState>().active && self.clear(tree, layout, renderer) {
1130                shell.request_redraw();
1131            }
1132            return;
1133        };
1134        // A button inside the area took the press.
1135        if shell.is_event_captured() {
1136            return;
1137        }
1138        let Some(at) = self.locate(tree, layout, renderer) else {
1139            return;
1140        };
1141        let state = tree.state.downcast_mut::<AreaState>();
1142        let now = crate::time::now();
1143        let count = click_count(state.last_click, position, now, self.double_click);
1144        state.last_click = Some(Click {
1145            position,
1146            at: now,
1147            count,
1148        });
1149        state.active = true;
1150        state.anchor = Some(at);
1151        state.dragging = count == 1;
1152        state.last_pull = None;
1153
1154        match count {
1155            1 => {
1156                let _ = self.select(tree, layout, renderer, at, at);
1157            }
1158            2 => self.select_word(tree, layout, renderer, at),
1159            _ => {
1160                let _ = self.select(tree, layout, renderer, (at.0, START), (at.0, END));
1161            }
1162        }
1163        if count > 1 {
1164            self.announce(tree, layout, renderer, shell);
1165        }
1166        shell.request_redraw();
1167    }
1168
1169    /// Extends the selection to the pointer and scrolls a scrollable the
1170    /// pointer has been dragged past the edge of. `now` is set on a frame,
1171    /// which is when the scrolling happens.
1172    fn dragged(
1173        &mut self,
1174        tree: &mut Tree,
1175        layout: Layout<'_>,
1176        cursor: mouse::Cursor,
1177        renderer: &Renderer,
1178        shell: &mut Shell<'_, Message>,
1179        now: Option<Instant>,
1180    ) {
1181        let anchor = tree.state.downcast_ref::<AreaState>().anchor;
1182        let focus = self.locate(tree, layout, renderer);
1183        if let (Some(anchor), Some(focus)) = (anchor, focus)
1184            && self.select(tree, layout, renderer, anchor, focus)
1185        {
1186            shell.request_redraw();
1187        }
1188
1189        let Some(pointer) = cursor.land().position() else {
1190            return;
1191        };
1192        let state = tree.state.downcast_mut::<AreaState>();
1193        let elapsed = match (now, state.last_pull) {
1194            (Some(now), Some(last)) => now.saturating_duration_since(last).min(MAX_FRAME),
1195            _ => Duration::ZERO,
1196        };
1197        let pull = Pull { pointer, elapsed };
1198        let pulling = self.visit(tree, layout, renderer, Some(pull), &mut |_, _, _| {});
1199        let state = tree.state.downcast_mut::<AreaState>();
1200        if !pulling {
1201            state.last_pull = None;
1202            return;
1203        }
1204        if now.is_some() || state.last_pull.is_none() {
1205            state.last_pull = now.or_else(|| Some(crate::time::now()));
1206        }
1207        // The next frame scrolls further and moves the selection with it.
1208        shell.request_redraw();
1209    }
1210
1211    fn key_pressed(
1212        &mut self,
1213        tree: &mut Tree,
1214        layout: Layout<'_>,
1215        renderer: &Renderer,
1216        shell: &mut Shell<'_, Message>,
1217        action: Option<Action>,
1218        elsewhere: bool,
1219    ) {
1220        // A focused field that used the key keeps it.
1221        if shell.is_event_captured() {
1222            return;
1223        }
1224        match action {
1225            Some(Action::Copy) => {
1226                let text = self.selected(tree, layout, renderer);
1227                if text.is_empty() {
1228                    return;
1229                }
1230                if let Some(on_copy) = &self.on_copy {
1231                    shell.publish(on_copy(text));
1232                    shell.capture_event();
1233                }
1234            }
1235            Some(Action::SelectAll) => {
1236                if !tree.state.downcast_ref::<AreaState>().active {
1237                    return;
1238                }
1239                self.select_everything(tree, layout, renderer);
1240                self.announce(tree, layout, renderer, shell);
1241                shell.capture_event();
1242                shell.request_redraw();
1243            }
1244            Some(Action::Clear) => {
1245                if !tree.state.downcast_ref::<AreaState>().active {
1246                    return;
1247                }
1248                // With nothing selected the key is left for whatever is
1249                // around the area, such as a dialog.
1250                if self.clear(tree, layout, renderer) {
1251                    shell.capture_event();
1252                    shell.request_redraw();
1253                }
1254            }
1255            // The key belongs to something else, so the selection steps
1256            // aside.
1257            None if elsewhere
1258                && tree.state.downcast_ref::<AreaState>().active
1259                && self.clear(tree, layout, renderer) =>
1260            {
1261                shell.request_redraw();
1262            }
1263            None => {}
1264        }
1265    }
1266}
1267
1268impl<Message> Widget<Message, Theme, Renderer> for SelectionArea<'_, Message> {
1269    fn tag(&self) -> tree::Tag {
1270        tree::Tag::of::<AreaState>()
1271    }
1272
1273    fn state(&self) -> tree::State {
1274        tree::State::new(AreaState::default())
1275    }
1276
1277    fn children(&self) -> Vec<Tree> {
1278        vec![Tree::new(&self.content)]
1279    }
1280
1281    fn diff(&self, tree: &mut Tree) {
1282        tree.diff_children(std::slice::from_ref(&self.content));
1283    }
1284
1285    fn size(&self) -> Size<Length> {
1286        self.content.as_widget().size()
1287    }
1288
1289    fn layout(
1290        &mut self,
1291        tree: &mut Tree,
1292        renderer: &Renderer,
1293        limits: &layout::Limits,
1294    ) -> layout::Node {
1295        self.content
1296            .as_widget_mut()
1297            .layout(&mut tree.children[0], renderer, limits)
1298    }
1299
1300    fn operate(
1301        &mut self,
1302        tree: &mut Tree,
1303        layout: Layout<'_>,
1304        renderer: &Renderer,
1305        operation: &mut dyn Operation,
1306    ) {
1307        if self.id.is_some() {
1308            let mut request = Request::default();
1309            operation.custom(self.id.as_ref(), layout.bounds(), &mut request);
1310            if request.select_all {
1311                tree.state.downcast_mut::<AreaState>().active = true;
1312                self.select_everything(tree, layout, renderer);
1313            }
1314            if request.read {
1315                let mut reply = Reply(self.selected(tree, layout, renderer));
1316                operation.custom(self.id.as_ref(), layout.bounds(), &mut reply);
1317            }
1318        }
1319        self.content
1320            .as_widget_mut()
1321            .operate(&mut tree.children[0], layout, renderer, operation);
1322    }
1323
1324    fn update(
1325        &mut self,
1326        tree: &mut Tree,
1327        event: &Event,
1328        layout: Layout<'_>,
1329        cursor: mouse::Cursor,
1330        renderer: &Renderer,
1331        clipboard: &mut dyn Clipboard,
1332        shell: &mut Shell<'_, Message>,
1333        viewport: &Rectangle,
1334    ) {
1335        let dragging = tree.state.downcast_ref::<AreaState>().dragging;
1336        let frame = match event {
1337            Event::Window(window::Event::RedrawRequested(now)) => Some(*now),
1338            _ => None,
1339        };
1340        let left_pressed = matches!(
1341            event,
1342            Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
1343        );
1344        let moved = matches!(event, Event::Mouse(mouse::Event::CursorMoved { .. }));
1345        let dragged = dragging && (moved || frame.is_some());
1346        if left_pressed || dragged {
1347            // Only texts this event reaches may say where the pointer is.
1348            self.visit(tree, layout, renderer, None, &mut |_, _, body| {
1349                body.pointer = None;
1350            });
1351        }
1352
1353        self.content.as_widget_mut().update(
1354            &mut tree.children[0],
1355            event,
1356            layout,
1357            cursor,
1358            renderer,
1359            clipboard,
1360            shell,
1361            viewport,
1362        );
1363
1364        match event {
1365            Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => {
1366                self.pressed(tree, layout, cursor, renderer, shell);
1367            }
1368            _ if dragged => self.dragged(tree, layout, cursor, renderer, shell, frame),
1369            Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) if dragging => {
1370                let state = tree.state.downcast_mut::<AreaState>();
1371                state.dragging = false;
1372                state.last_pull = None;
1373                self.announce(tree, layout, renderer, shell);
1374            }
1375            Event::Keyboard(keyboard::Event::KeyPressed {
1376                key,
1377                modifiers,
1378                text,
1379                ..
1380            }) => {
1381                // Typing, Tab and an app's own chords are meant for something
1382                // other than the text being read.
1383                let elsewhere = text.is_some()
1384                    || modifiers.command()
1385                    || *key == keyboard::Key::Named(Named::Tab);
1386                let action = self.keymap.resolve(key, *modifiers);
1387                self.key_pressed(tree, layout, renderer, shell, action, elsewhere);
1388            }
1389            // A release that never arrives must not leave a drag running.
1390            Event::Mouse(mouse::Event::CursorLeft) if dragging => {
1391                let state = tree.state.downcast_mut::<AreaState>();
1392                state.dragging = false;
1393                state.last_pull = None;
1394            }
1395            _ => {}
1396        }
1397    }
1398
1399    fn draw(
1400        &self,
1401        tree: &Tree,
1402        renderer: &mut Renderer,
1403        theme: &Theme,
1404        style: &renderer::Style,
1405        layout: Layout<'_>,
1406        cursor: mouse::Cursor,
1407        viewport: &Rectangle,
1408    ) {
1409        self.content.as_widget().draw(
1410            &tree.children[0],
1411            renderer,
1412            theme,
1413            style,
1414            layout,
1415            cursor,
1416            viewport,
1417        );
1418    }
1419
1420    fn mouse_interaction(
1421        &self,
1422        tree: &Tree,
1423        layout: Layout<'_>,
1424        cursor: mouse::Cursor,
1425        viewport: &Rectangle,
1426        renderer: &Renderer,
1427    ) -> mouse::Interaction {
1428        self.content.as_widget().mouse_interaction(
1429            &tree.children[0],
1430            layout,
1431            cursor,
1432            viewport,
1433            renderer,
1434        )
1435    }
1436
1437    fn overlay<'b>(
1438        &'b mut self,
1439        tree: &'b mut Tree,
1440        layout: Layout<'b>,
1441        renderer: &Renderer,
1442        viewport: &Rectangle,
1443        translation: Vector,
1444    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
1445        self.content.as_widget_mut().overlay(
1446            &mut tree.children[0],
1447            layout,
1448            renderer,
1449            viewport,
1450            translation,
1451        )
1452    }
1453}
1454
1455impl<'a, Message: 'a> From<SelectionArea<'a, Message>> for Element<'a, Message> {
1456    fn from(area: SelectionArea<'a, Message>) -> Self {
1457        let element = Element::new(area);
1458        #[cfg(feature = "icedwright")]
1459        let element = icedwright_probe::semantic(element)
1460            .role(icedwright_probe::role::Document)
1461            .component("iced_cube::selection_area")
1462            .into();
1463        element
1464    }
1465}
1466
1467/// The number of laid out lines, and the caret top at the start and end of
1468/// every glyph, as byte offsets into the whole text and points relative to
1469/// the text's corner.
1470#[cfg(feature = "icedwright")]
1471fn geometry(body: &Body) -> (usize, Vec<(usize, Point)>) {
1472    let Some(buffer) = body.paragraph.shaped() else {
1473        return (0, Vec::new());
1474    };
1475    let mut starts = Vec::with_capacity(buffer.lines.len());
1476    let mut offset = 0;
1477    for line in &buffer.lines {
1478        starts.push(offset);
1479        offset += line.text().len() + 1;
1480    }
1481    let mut lines = 0;
1482    let mut carets: Vec<(usize, Point)> = Vec::new();
1483    for run in buffer.layout_runs() {
1484        lines += 1;
1485        let start = starts.get(run.line_i).copied().unwrap_or_default();
1486        for glyph in run.glyphs {
1487            carets.push((start + glyph.start, Point::new(glyph.x, run.line_top)));
1488            carets.push((
1489                start + glyph.end,
1490                Point::new(glyph.x + glyph.w, run.line_top),
1491            ));
1492        }
1493    }
1494    // The first caret at an offset wins, so a glyph's start beats the end of
1495    // the glyph before it on a new line.
1496    carets.sort_by_key(|(at, _)| *at);
1497    carets.dedup_by_key(|(at, _)| *at);
1498    (lines, carets)
1499}
1500
1501#[cfg(test)]
1502mod tests {
1503    use iced::keyboard::Key;
1504
1505    use super::*;
1506    use crate::theme::{dark, light};
1507
1508    #[test]
1509    fn word_bounds_find_the_word_under_the_caret() {
1510        assert_eq!(word_bounds("alpha beta", 7), Some((6, 10)));
1511        assert_eq!(word_bounds("alpha beta", 0), Some((0, 5)));
1512        assert_eq!(word_bounds("snake_case here", 3), Some((0, 10)));
1513    }
1514
1515    #[test]
1516    fn word_bounds_take_one_character_between_words() {
1517        assert_eq!(word_bounds("alpha beta", 5), Some((5, 6)));
1518        assert_eq!(word_bounds("a, b", 1), Some((1, 2)));
1519    }
1520
1521    #[test]
1522    fn word_bounds_respect_characters_of_several_bytes() {
1523        assert_eq!(word_bounds("caf\u{e9} noir", 4), Some((0, 5)));
1524        assert_eq!(word_bounds("caf\u{e9} noir", 100), Some((6, 10)));
1525        assert_eq!(word_bounds("", 0), None);
1526    }
1527
1528    #[test]
1529    fn presses_in_a_row_count_up_to_three_then_start_again() {
1530        let interval = Duration::from_millis(400);
1531        let start = Instant::now();
1532        let at = Point::new(10.0, 10.0);
1533        let click = |count, after: u64| {
1534            Some(Click {
1535                position: at,
1536                at: start + Duration::from_millis(after),
1537                count,
1538            })
1539        };
1540        let soon = start + Duration::from_millis(100);
1541
1542        assert_eq!(click_count(None, at, start, interval), 1);
1543        assert_eq!(click_count(click(1, 0), at, soon, interval), 2);
1544        assert_eq!(click_count(click(2, 0), at, soon, interval), 3);
1545        assert_eq!(click_count(click(3, 0), at, soon, interval), 1);
1546    }
1547
1548    #[test]
1549    fn a_late_or_distant_press_is_a_single_click() {
1550        let interval = Duration::from_millis(400);
1551        let start = Instant::now();
1552        let at = Point::new(10.0, 10.0);
1553        let previous = Some(Click {
1554            position: at,
1555            at: start,
1556            count: 1,
1557        });
1558
1559        let late = start + Duration::from_millis(401);
1560        assert_eq!(click_count(previous, at, late, interval), 1);
1561        let on_time = start + Duration::from_millis(400);
1562        assert_eq!(click_count(previous, at, on_time, interval), 2);
1563        let far = Point::new(10.0 + CLICK_SLOP + 1.0, 10.0);
1564        assert_eq!(click_count(previous, far, start, interval), 1);
1565    }
1566
1567    #[test]
1568    fn a_point_is_clamped_to_the_nearest_point_of_a_rectangle() {
1569        let bounds = Rectangle::new(Point::new(10.0, 20.0), Size::new(100.0, 50.0));
1570        assert_eq!(
1571            clamp(Point::new(50.0, 40.0), bounds),
1572            Point::new(50.0, 40.0)
1573        );
1574        assert_eq!(clamp(Point::new(0.0, 0.0), bounds), Point::new(10.0, 20.0));
1575        assert_eq!(
1576            clamp(Point::new(500.0, 500.0), bounds),
1577            Point::new(110.0, 70.0)
1578        );
1579    }
1580
1581    /// Feeds `pointer`, given in window coordinates, to texts laid out at
1582    /// `rows`, and returns the text found and the caret column asked for.
1583    fn search(rows: &[Rectangle], pointer: Point) -> Option<Position> {
1584        let mut search = Search::default();
1585        for (index, row) in rows.iter().enumerate() {
1586            let local = Point::new(pointer.x - row.x, pointer.y - row.y);
1587            search.feed(index, row.size(), local, || (0, local.x as usize));
1588        }
1589        search.result()
1590    }
1591
1592    #[test]
1593    fn the_pointer_finds_the_text_it_is_over_beside_or_above() {
1594        let row = |y: f32, width: f32| Rectangle::new(Point::new(0.0, y), Size::new(width, 20.0));
1595        let rows = [row(0.0, 100.0), row(30.0, 40.0), row(60.0, 100.0)];
1596
1597        assert_eq!(search(&rows, Point::new(50.0, 10.0)), Some((0, (0, 50))));
1598        // Beside a short line: that line, not the one below.
1599        assert_eq!(search(&rows, Point::new(80.0, 40.0)), Some((1, (0, 80))));
1600        // In the gap between lines: the start of the next one.
1601        assert_eq!(search(&rows, Point::new(50.0, 55.0)), Some((2, START)));
1602        // Below everything: nothing, which the area reads as the end.
1603        assert_eq!(search(&rows, Point::new(50.0, 500.0)), None);
1604    }
1605
1606    #[test]
1607    fn cells_side_by_side_are_read_in_order() {
1608        let cell = |x: f32, y: f32| Rectangle::new(Point::new(x, y), Size::new(100.0, 20.0));
1609        let cells = [
1610            cell(0.0, 0.0),
1611            cell(120.0, 0.0),
1612            cell(0.0, 30.0),
1613            cell(120.0, 30.0),
1614        ];
1615
1616        assert_eq!(search(&cells, Point::new(130.0, 10.0)), Some((1, (0, 10))));
1617        assert_eq!(search(&cells, Point::new(10.0, 40.0)), Some((2, (0, 10))));
1618        // Between two cells: the start of the one on the right.
1619        assert_eq!(search(&cells, Point::new(110.0, 40.0)), Some((3, START)));
1620        // Right of the last cell in a row: the end of that cell.
1621        assert_eq!(search(&cells, Point::new(300.0, 10.0)), Some((1, (0, 180))));
1622    }
1623
1624    #[test]
1625    fn the_selection_is_a_faded_primary_in_both_themes() {
1626        for theme in [light(), dark()] {
1627            let tokens = Tokens::of(&theme);
1628            let selection = style(&tokens).selection;
1629            assert_eq!(selection, fade(tokens.primary, 0.25));
1630            assert!(selection.a < 1.0, "the text must show through");
1631        }
1632    }
1633
1634    #[test]
1635    fn a_drag_scrolls_faster_the_further_past_the_edge_it_is() {
1636        assert_eq!(scroll_speed(0.0), SCROLL_SPEED);
1637        assert_eq!(scroll_speed(-20.0), SCROLL_SPEED);
1638        assert!(scroll_speed(10.0) > scroll_speed(1.0));
1639        assert_eq!(scroll_speed(10_000.0), MAX_SCROLL_SPEED);
1640    }
1641
1642    #[test]
1643    fn default_keymap_and_overrides() {
1644        let c = Key::Character("c".into());
1645        let a = Key::Character("a".into());
1646        let escape = Key::Named(Named::Escape);
1647        let command = keyboard::Modifiers::COMMAND;
1648        let keymap = default_keymap();
1649        assert_eq!(keymap.resolve(&c, command), Some(Action::Copy));
1650        assert_eq!(keymap.resolve(&a, command), Some(Action::SelectAll));
1651        assert_eq!(
1652            keymap.resolve(&escape, keyboard::Modifiers::empty()),
1653            Some(Action::Clear)
1654        );
1655        assert_eq!(keymap.resolve(&c, keyboard::Modifiers::empty()), None);
1656
1657        let custom = keymap
1658            .unbind(&Chord::character('a').command())
1659            .bind(Chord::character('e').command(), Action::SelectAll);
1660        assert_eq!(custom.resolve(&a, command), None);
1661        assert_eq!(
1662            custom.resolve(&Key::Character("e".into()), command),
1663            Some(Action::SelectAll)
1664        );
1665    }
1666
1667    #[test]
1668    fn every_action_is_documented_and_bound() {
1669        use keys::Action as _;
1670        let keymap = Action::defaults();
1671        for action in Action::ALL {
1672            assert!(!action.name().is_empty());
1673            assert!(action.description().ends_with('.'));
1674            assert!(!keymap.chords(action).is_empty(), "{action:?} has no chord");
1675        }
1676    }
1677
1678    #[test]
1679    fn a_task_reads_only_the_area_with_its_id() {
1680        let mut command = Command {
1681            target: Id::new("notes"),
1682            select_all: true,
1683            text: None,
1684        };
1685        let bounds = Rectangle::new(Point::ORIGIN, Size::new(10.0, 10.0));
1686
1687        let mut other = Request::default();
1688        command.custom(Some(&Id::new("other")), bounds, &mut other);
1689        assert!(!other.read && !other.select_all);
1690
1691        let mut request = Request::default();
1692        command.custom(Some(&Id::new("notes")), bounds, &mut request);
1693        assert!(request.read && request.select_all);
1694
1695        assert!(matches!(command.finish(), Outcome::None));
1696        command.custom(
1697            Some(&Id::new("notes")),
1698            bounds,
1699            &mut Reply("text".to_owned()),
1700        );
1701        assert!(matches!(command.finish(), Outcome::Some(text) if text == "text"));
1702    }
1703}