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                // The surrounding area counts presses on the probe's clock;
604                // without one, a text counts none.
605                let annotation = icedwright_probe::Annotation::new()
606                    .click_clock(icedwright_probe::ClickClock::Probe)
607                    .text_size(size)
608                    .text_geometry(carets.into_iter().map(|(at, point)| (at, point.into())))
609                    .component("iced_cube::selectable_text");
610                if lines > 1 {
611                    annotation
612                        .role(icedwright_probe::role::Paragraph)
613                        .to_static()
614                } else {
615                    annotation.role(icedwright_probe::role::Text).to_static()
616                }
617            });
618            // Nests the text under the annotation for recorders.
619            let text = &state.text;
620            let body = &mut state.body;
621            operation.traverse(&mut |operation| {
622                operation.text(None, layout.bounds(), text);
623                operation.custom(None, layout.bounds(), body);
624            });
625        }
626        #[cfg(not(feature = "icedwright"))]
627        {
628            operation.text(None, layout.bounds(), &state.text);
629            operation.custom(None, layout.bounds(), &mut state.body);
630        }
631    }
632
633    fn update(
634        &mut self,
635        tree: &mut Tree,
636        event: &Event,
637        layout: Layout<'_>,
638        cursor: mouse::Cursor,
639        _renderer: &Renderer,
640        _clipboard: &mut dyn Clipboard,
641        shell: &mut Shell<'_, Message>,
642        viewport: &Rectangle,
643    ) {
644        let event = match event {
645            Event::Mouse(event) => Some(event),
646            // A frame drawn while a drag scrolls the page moves the text
647            // under a pointer that has not moved.
648            Event::Window(window::Event::RedrawRequested(_)) => None,
649            _ => return,
650        };
651        let state = tree.state.downcast_mut::<State<Link>>();
652        let bounds = layout.bounds();
653        // A cursor outside a scrolled parent still says where a drag has
654        // reached, but only as far as the edge of what the parent shows:
655        // text scrolled out of view is never under the pointer.
656        state.body.direct = cursor.position().is_some();
657        state.body.pointer = cursor.land().position().map(|at| {
658            let at = if state.body.direct {
659                at
660            } else {
661                clamp(at, *viewport)
662            };
663            Point::new(at.x - bounds.x, at.y - bounds.y)
664        });
665        let Some(event) = event else {
666            return;
667        };
668
669        let hovered = cursor
670            .position_in(bounds)
671            .and_then(|at| state.body.paragraph.hit_span(at))
672            .filter(|span| self.link(*span).is_some());
673        if hovered != state.hovered {
674            state.hovered = hovered;
675            shell.request_redraw();
676        }
677
678        match event {
679            mouse::Event::ButtonPressed(mouse::Button::Left) => state.pressed = state.hovered,
680            mouse::Event::ButtonReleased(mouse::Button::Left) => {
681                let pressed = state.pressed.take();
682                // A drag that ends on the link it began on is a selection,
683                // not a click.
684                if pressed.is_none() || pressed != state.hovered || state.body.selection.is_some() {
685                    return;
686                }
687                let link = pressed.and_then(|span| self.link(span));
688                if let (Some(link), Some(on_link_click)) = (link, &self.on_link_click) {
689                    shell.publish(on_link_click(link.clone()));
690                }
691            }
692            _ => {}
693        }
694    }
695
696    fn draw(
697        &self,
698        tree: &Tree,
699        renderer: &mut Renderer,
700        theme: &Theme,
701        defaults: &renderer::Style,
702        layout: Layout<'_>,
703        _cursor: mouse::Cursor,
704        viewport: &Rectangle,
705    ) {
706        let bounds = layout.bounds();
707        if !bounds.intersects(viewport) {
708            return;
709        }
710        let state = tree.state.downcast_ref::<State<Link>>();
711        let origin = bounds.position() - Point::ORIGIN;
712
713        // Inline code has an opaque background, so the selection goes over
714        // it.
715        self.draw_decorations(state, renderer, defaults, origin);
716        if let Some((from, to)) = state.body.selection {
717            let colour = match &self.style {
718                Some(style) => style(theme),
719                None => style(&Tokens::of(theme)),
720            }
721            .selection;
722            for rectangle in state.body.rectangles(from, to) {
723                renderer.fill_quad(
724                    renderer::Quad {
725                        bounds: rectangle + origin,
726                        ..renderer::Quad::default()
727                    },
728                    colour,
729                );
730            }
731        }
732        widget::text::draw(
733            renderer,
734            defaults,
735            bounds,
736            &state.body.paragraph,
737            widget::text::Style { color: self.colour },
738            viewport,
739        );
740    }
741
742    fn mouse_interaction(
743        &self,
744        tree: &Tree,
745        layout: Layout<'_>,
746        cursor: mouse::Cursor,
747        _viewport: &Rectangle,
748        _renderer: &Renderer,
749    ) -> mouse::Interaction {
750        let state = tree.state.downcast_ref::<State<Link>>();
751        if state.hovered.is_some() && self.on_link_click.is_some() {
752            return mouse::Interaction::Pointer;
753        }
754        if cursor.is_over(layout.bounds()) {
755            return mouse::Interaction::Text;
756        }
757        mouse::Interaction::None
758    }
759}
760
761impl<'a, Link, Message> From<SelectableText<'a, Link, Message>> for Element<'a, Message>
762where
763    Link: Clone + PartialEq + 'static,
764    Message: 'a,
765{
766    fn from(text: SelectableText<'a, Link, Message>) -> Self {
767        Element::new(text)
768    }
769}
770
771/// A drag past the edge of a scrollable: where the pointer is and how long
772/// the frame took.
773#[derive(Clone, Copy)]
774struct Pull {
775    pointer: Point,
776    elapsed: Duration,
777}
778
779/// Calls `each` with every [`Body`] it meets, numbered in drawing order, and
780/// scrolls the scrollables a [`Pull`] is past the edge of.
781struct Visit<'f> {
782    index: usize,
783    each: &'f mut (dyn FnMut(usize, Rectangle, &mut Body) + Send),
784    pull: Option<Pull>,
785    /// Whether the pointer is past the edge of a scrollable.
786    pulling: bool,
787    /// How far the scrollables around the widgets being visited have
788    /// scrolled, which is how far their layout is from the window's.
789    scrolled: Vector,
790    /// The scroll of the scrollable whose content is visited next.
791    entering: Option<Vector>,
792}
793
794impl Operation for Visit<'_> {
795    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
796        // A scrollable announces itself just before its content is visited.
797        let entered = self.entering.take().unwrap_or(Vector::ZERO);
798        self.scrolled += entered;
799        operate(self);
800        self.scrolled -= entered;
801    }
802
803    fn custom(&mut self, _id: Option<&Id>, bounds: Rectangle, state: &mut dyn Any) {
804        let Some(body) = state.downcast_mut::<Body>() else {
805            return;
806        };
807        (self.each)(self.index, bounds, body);
808        self.index += 1;
809    }
810
811    fn scrollable(
812        &mut self,
813        _id: Option<&Id>,
814        bounds: Rectangle,
815        content_bounds: Rectangle,
816        translation: Vector,
817        state: &mut dyn Scrollable,
818    ) {
819        self.entering = Some(translation);
820        let Some(pull) = self.pull else {
821            return;
822        };
823        if content_bounds.height <= bounds.height {
824            return;
825        }
826        // The pointer in the space this scrollable is laid out in.
827        let pointer = pull.pointer + self.scrolled;
828        let above = bounds.y - pointer.y;
829        let below = pointer.y - (bounds.y + bounds.height);
830        let (distance, direction) = if above > 0.0 {
831            (above, -1.0)
832        } else if below > 0.0 {
833            (below, 1.0)
834        } else {
835            return;
836        };
837        self.pulling = true;
838        let y = direction * scroll_speed(distance) * pull.elapsed.as_secs_f32();
839        state.scroll_by(AbsoluteOffset { x: 0.0, y }, bounds, content_bounds);
840    }
841}
842
843/// What a task asks of the area with its id.
844#[derive(Default)]
845struct Request {
846    select_all: bool,
847    read: bool,
848}
849
850/// The selected text, handed back to the task that asked.
851struct Reply(String);
852
853struct Command {
854    target: Id,
855    select_all: bool,
856    text: Option<String>,
857}
858
859impl Operation<String> for Command {
860    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<String>)) {
861        operate(self);
862    }
863
864    fn custom(&mut self, id: Option<&Id>, _bounds: Rectangle, state: &mut dyn Any) {
865        if id != Some(&self.target) {
866            return;
867        }
868        if let Some(request) = state.downcast_mut::<Request>() {
869            request.select_all = self.select_all;
870            request.read = true;
871        }
872        if let Some(Reply(text)) = state.downcast_mut::<Reply>() {
873            self.text = Some(std::mem::take(text));
874        }
875    }
876
877    fn finish(&self) -> Outcome<String> {
878        self.text.clone().map_or(Outcome::None, Outcome::Some)
879    }
880}
881
882/// The widget operations behind [`selected`] and [`select_all`], for apps
883/// that run operations themselves.
884pub mod operation {
885    use super::{Command, Id, Operation};
886
887    /// Produces the text selected in the area with this id.
888    pub fn selected(id: impl Into<Id>) -> impl Operation<String> {
889        Command {
890            target: id.into(),
891            select_all: false,
892            text: None,
893        }
894    }
895
896    /// Selects every text in the area with this id and produces it.
897    pub fn select_all(id: impl Into<Id>) -> impl Operation<String> {
898        Command {
899            target: id.into(),
900            select_all: true,
901            text: None,
902        }
903    }
904}
905
906/// Produces the text selected in the area with this id, which is empty when
907/// nothing is. Produces nothing when no such area is on screen.
908pub fn selected(id: impl Into<Id>) -> Task<String> {
909    widget::operate(operation::selected(id.into()))
910}
911
912/// Selects every text in the area with this id and produces it.
913pub fn select_all(id: impl Into<Id>) -> Task<String> {
914    widget::operate(operation::select_all(id.into()))
915}
916
917#[derive(Default)]
918struct AreaState {
919    anchor: Option<Position>,
920    dragging: bool,
921    /// Whether the last press landed in the area, so Select all is meant
922    /// for it.
923    active: bool,
924    last_click: Option<Click>,
925    /// When the drag last scrolled a scrollable.
926    last_pull: Option<Instant>,
927}
928
929/// Lets the [`SelectableText`]s inside it be selected together. Convert it
930/// into an [`Element`] to render.
931pub struct SelectionArea<'a, Message> {
932    content: Element<'a, Message>,
933    id: Option<Id>,
934    keymap: Keymap<Action>,
935    double_click: Duration,
936    on_copy: Option<Box<dyn Fn(String) -> Message + 'a>>,
937    on_select: Option<Box<dyn Fn(String) -> Message + 'a>>,
938}
939
940impl<Message> fmt::Debug for SelectionArea<'_, Message> {
941    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
942        f.debug_struct("SelectionArea")
943            .field("id", &self.id)
944            .field("keymap", &self.keymap)
945            .finish_non_exhaustive()
946    }
947}
948
949/// An area in which the selectable texts of `content` are selected
950/// together.
951pub fn selection_area<'a, Message>(
952    content: impl Into<Element<'a, Message>>,
953) -> SelectionArea<'a, Message> {
954    SelectionArea {
955        content: content.into(),
956        id: None,
957        keymap: default_keymap(),
958        double_click: DOUBLE_CLICK,
959        on_copy: None,
960        on_select: None,
961    }
962}
963
964impl<'a, Message> SelectionArea<'a, Message> {
965    /// The id [`selected`] and [`select_all`] find the area by.
966    pub fn id(mut self, id: impl Into<Id>) -> Self {
967        self.id = Some(id.into());
968        self
969    }
970
971    /// Replaces the default shortcuts.
972    pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
973        self.keymap = keymap;
974        self
975    }
976
977    /// How soon a press must follow the last to count as a double or triple
978    /// click. Defaults to [`DOUBLE_CLICK`].
979    pub fn double_click(mut self, interval: Duration) -> Self {
980        self.double_click = interval;
981        self
982    }
983
984    /// The message for the selected text when the Copy shortcut is pressed.
985    pub fn on_copy(mut self, on_copy: impl Fn(String) -> Message + 'a) -> Self {
986        self.on_copy = Some(Box::new(on_copy));
987        self
988    }
989
990    /// The message for the selected text each time a selection is finished:
991    /// a drag is released, a word or block is clicked or everything is
992    /// selected from the keyboard.
993    pub fn on_select(mut self, on_select: impl Fn(String) -> Message + 'a) -> Self {
994        self.on_select = Some(Box::new(on_select));
995        self
996    }
997
998    fn visit(
999        &mut self,
1000        tree: &mut Tree,
1001        layout: Layout<'_>,
1002        renderer: &Renderer,
1003        pull: Option<Pull>,
1004        each: &mut (dyn FnMut(usize, Rectangle, &mut Body) + Send),
1005    ) -> bool {
1006        let mut visit = Visit {
1007            index: 0,
1008            each,
1009            pull,
1010            pulling: false,
1011            scrolled: Vector::ZERO,
1012            entering: None,
1013        };
1014        self.content
1015            .as_widget_mut()
1016            .operate(&mut tree.children[0], layout, renderer, &mut visit);
1017        visit.pulling
1018    }
1019
1020    /// Where the pointer is among the texts, or `None` when no text has
1021    /// seen it.
1022    fn locate(
1023        &mut self,
1024        tree: &mut Tree,
1025        layout: Layout<'_>,
1026        renderer: &Renderer,
1027    ) -> Option<Position> {
1028        let mut seen = false;
1029        let mut count = 0;
1030        // Texts the pointer can really be over come first. The rest sit in
1031        // a scrollable the pointer is outside, and count only when a drag
1032        // has left every text behind.
1033        let mut direct = Search::default();
1034        let mut any = Search::default();
1035        self.visit(tree, layout, renderer, None, &mut |index, bounds, body| {
1036            count = index + 1;
1037            let Some(pointer) = body.pointer else {
1038                return;
1039            };
1040            seen = true;
1041            let body = &*body;
1042            if body.direct {
1043                direct.feed(index, bounds.size(), pointer, || body.hit(pointer));
1044            }
1045            any.feed(index, bounds.size(), pointer, || body.hit(pointer));
1046        });
1047        seen.then(|| direct.result().or(any.result()).unwrap_or((count, START)))
1048    }
1049
1050    fn select(
1051        &mut self,
1052        tree: &mut Tree,
1053        layout: Layout<'_>,
1054        renderer: &Renderer,
1055        from: Position,
1056        to: Position,
1057    ) -> bool {
1058        let (start, end) = if from <= to { (from, to) } else { (to, from) };
1059        let mut changed = false;
1060        self.visit(tree, layout, renderer, None, &mut |index, _, body| {
1061            let first = if index == start.0 { start.1 } else { START };
1062            let last = if index == end.0 { end.1 } else { END };
1063            let inside = index >= start.0 && index <= end.0 && first < last;
1064            let selection = inside.then_some((first, last));
1065            changed |= body.selection != selection;
1066            body.selection = selection;
1067        });
1068        changed
1069    }
1070
1071    fn select_everything(&mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer) {
1072        let _ = self.select(tree, layout, renderer, (0, START), (usize::MAX, END));
1073    }
1074
1075    /// Drops the selection and says whether there was one.
1076    fn clear(&mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer) -> bool {
1077        let state = tree.state.downcast_mut::<AreaState>();
1078        state.active = false;
1079        state.dragging = false;
1080        state.last_pull = None;
1081        self.select(tree, layout, renderer, (0, START), (0, START))
1082    }
1083
1084    fn select_word(
1085        &mut self,
1086        tree: &mut Tree,
1087        layout: Layout<'_>,
1088        renderer: &Renderer,
1089        at: Position,
1090    ) {
1091        self.visit(tree, layout, renderer, None, &mut |index, _, body| {
1092            body.selection = (index == at.0).then(|| body.word(at.1)).flatten();
1093        });
1094    }
1095
1096    fn selected(&mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer) -> String {
1097        let mut parts = Vec::new();
1098        self.visit(tree, layout, renderer, None, &mut |_, _, body| {
1099            parts.extend(body.selected());
1100        });
1101        parts.join("\n")
1102    }
1103
1104    fn announce(
1105        &mut self,
1106        tree: &mut Tree,
1107        layout: Layout<'_>,
1108        renderer: &Renderer,
1109        shell: &mut Shell<'_, Message>,
1110    ) {
1111        if self.on_select.is_none() {
1112            return;
1113        }
1114        let text = self.selected(tree, layout, renderer);
1115        if text.is_empty() {
1116            return;
1117        }
1118        if let Some(on_select) = &self.on_select {
1119            shell.publish(on_select(text));
1120        }
1121    }
1122
1123    fn pressed(
1124        &mut self,
1125        tree: &mut Tree,
1126        layout: Layout<'_>,
1127        cursor: mouse::Cursor,
1128        renderer: &Renderer,
1129        shell: &mut Shell<'_, Message>,
1130    ) {
1131        let Some(position) = cursor.position_over(layout.bounds()) else {
1132            if tree.state.downcast_ref::<AreaState>().active && self.clear(tree, layout, renderer) {
1133                shell.request_redraw();
1134            }
1135            return;
1136        };
1137        // A button inside the area took the press.
1138        if shell.is_event_captured() {
1139            return;
1140        }
1141        let Some(at) = self.locate(tree, layout, renderer) else {
1142            return;
1143        };
1144        let state = tree.state.downcast_mut::<AreaState>();
1145        let now = crate::time::now();
1146        let count = click_count(state.last_click, position, now, self.double_click);
1147        state.last_click = Some(Click {
1148            position,
1149            at: now,
1150            count,
1151        });
1152        state.active = true;
1153        state.anchor = Some(at);
1154        state.dragging = count == 1;
1155        state.last_pull = None;
1156
1157        match count {
1158            1 => {
1159                let _ = self.select(tree, layout, renderer, at, at);
1160            }
1161            2 => self.select_word(tree, layout, renderer, at),
1162            _ => {
1163                let _ = self.select(tree, layout, renderer, (at.0, START), (at.0, END));
1164            }
1165        }
1166        if count > 1 {
1167            self.announce(tree, layout, renderer, shell);
1168        }
1169        shell.request_redraw();
1170    }
1171
1172    /// Extends the selection to the pointer and scrolls a scrollable the
1173    /// pointer has been dragged past the edge of. `now` is set on a frame,
1174    /// which is when the scrolling happens.
1175    fn dragged(
1176        &mut self,
1177        tree: &mut Tree,
1178        layout: Layout<'_>,
1179        cursor: mouse::Cursor,
1180        renderer: &Renderer,
1181        shell: &mut Shell<'_, Message>,
1182        now: Option<Instant>,
1183    ) {
1184        let anchor = tree.state.downcast_ref::<AreaState>().anchor;
1185        let focus = self.locate(tree, layout, renderer);
1186        if let (Some(anchor), Some(focus)) = (anchor, focus)
1187            && self.select(tree, layout, renderer, anchor, focus)
1188        {
1189            shell.request_redraw();
1190        }
1191
1192        let Some(pointer) = cursor.land().position() else {
1193            return;
1194        };
1195        let state = tree.state.downcast_mut::<AreaState>();
1196        let elapsed = match (now, state.last_pull) {
1197            (Some(now), Some(last)) => now.saturating_duration_since(last).min(MAX_FRAME),
1198            _ => Duration::ZERO,
1199        };
1200        let pull = Pull { pointer, elapsed };
1201        let pulling = self.visit(tree, layout, renderer, Some(pull), &mut |_, _, _| {});
1202        let state = tree.state.downcast_mut::<AreaState>();
1203        if !pulling {
1204            state.last_pull = None;
1205            return;
1206        }
1207        if now.is_some() || state.last_pull.is_none() {
1208            state.last_pull = now.or_else(|| Some(crate::time::now()));
1209        }
1210        // The next frame scrolls further and moves the selection with it.
1211        shell.request_redraw();
1212    }
1213
1214    fn key_pressed(
1215        &mut self,
1216        tree: &mut Tree,
1217        layout: Layout<'_>,
1218        renderer: &Renderer,
1219        shell: &mut Shell<'_, Message>,
1220        action: Option<Action>,
1221        elsewhere: bool,
1222    ) {
1223        // A focused field that used the key keeps it.
1224        if shell.is_event_captured() {
1225            return;
1226        }
1227        match action {
1228            Some(Action::Copy) => {
1229                let text = self.selected(tree, layout, renderer);
1230                if text.is_empty() {
1231                    return;
1232                }
1233                if let Some(on_copy) = &self.on_copy {
1234                    shell.publish(on_copy(text));
1235                    shell.capture_event();
1236                }
1237            }
1238            Some(Action::SelectAll) => {
1239                if !tree.state.downcast_ref::<AreaState>().active {
1240                    return;
1241                }
1242                self.select_everything(tree, layout, renderer);
1243                self.announce(tree, layout, renderer, shell);
1244                shell.capture_event();
1245                shell.request_redraw();
1246            }
1247            Some(Action::Clear) => {
1248                if !tree.state.downcast_ref::<AreaState>().active {
1249                    return;
1250                }
1251                // With nothing selected the key is left for whatever is
1252                // around the area, such as a dialog.
1253                if self.clear(tree, layout, renderer) {
1254                    shell.capture_event();
1255                    shell.request_redraw();
1256                }
1257            }
1258            // The key belongs to something else, so the selection steps
1259            // aside.
1260            None if elsewhere
1261                && tree.state.downcast_ref::<AreaState>().active
1262                && self.clear(tree, layout, renderer) =>
1263            {
1264                shell.request_redraw();
1265            }
1266            None => {}
1267        }
1268    }
1269}
1270
1271impl<Message> Widget<Message, Theme, Renderer> for SelectionArea<'_, Message> {
1272    fn tag(&self) -> tree::Tag {
1273        tree::Tag::of::<AreaState>()
1274    }
1275
1276    fn state(&self) -> tree::State {
1277        tree::State::new(AreaState::default())
1278    }
1279
1280    fn children(&self) -> Vec<Tree> {
1281        vec![Tree::new(&self.content)]
1282    }
1283
1284    fn diff(&self, tree: &mut Tree) {
1285        tree.diff_children(std::slice::from_ref(&self.content));
1286    }
1287
1288    fn size(&self) -> Size<Length> {
1289        self.content.as_widget().size()
1290    }
1291
1292    fn layout(
1293        &mut self,
1294        tree: &mut Tree,
1295        renderer: &Renderer,
1296        limits: &layout::Limits,
1297    ) -> layout::Node {
1298        self.content
1299            .as_widget_mut()
1300            .layout(&mut tree.children[0], renderer, limits)
1301    }
1302
1303    fn operate(
1304        &mut self,
1305        tree: &mut Tree,
1306        layout: Layout<'_>,
1307        renderer: &Renderer,
1308        operation: &mut dyn Operation,
1309    ) {
1310        if self.id.is_some() {
1311            let mut request = Request::default();
1312            operation.custom(self.id.as_ref(), layout.bounds(), &mut request);
1313            if request.select_all {
1314                tree.state.downcast_mut::<AreaState>().active = true;
1315                self.select_everything(tree, layout, renderer);
1316            }
1317            if request.read {
1318                let mut reply = Reply(self.selected(tree, layout, renderer));
1319                operation.custom(self.id.as_ref(), layout.bounds(), &mut reply);
1320            }
1321        }
1322        self.content
1323            .as_widget_mut()
1324            .operate(&mut tree.children[0], layout, renderer, operation);
1325    }
1326
1327    fn update(
1328        &mut self,
1329        tree: &mut Tree,
1330        event: &Event,
1331        layout: Layout<'_>,
1332        cursor: mouse::Cursor,
1333        renderer: &Renderer,
1334        clipboard: &mut dyn Clipboard,
1335        shell: &mut Shell<'_, Message>,
1336        viewport: &Rectangle,
1337    ) {
1338        let dragging = tree.state.downcast_ref::<AreaState>().dragging;
1339        let frame = match event {
1340            Event::Window(window::Event::RedrawRequested(now)) => Some(*now),
1341            _ => None,
1342        };
1343        let left_pressed = matches!(
1344            event,
1345            Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
1346        );
1347        let moved = matches!(event, Event::Mouse(mouse::Event::CursorMoved { .. }));
1348        let dragged = dragging && (moved || frame.is_some());
1349        if left_pressed || dragged {
1350            // Only texts this event reaches may say where the pointer is.
1351            self.visit(tree, layout, renderer, None, &mut |_, _, body| {
1352                body.pointer = None;
1353            });
1354        }
1355
1356        self.content.as_widget_mut().update(
1357            &mut tree.children[0],
1358            event,
1359            layout,
1360            cursor,
1361            renderer,
1362            clipboard,
1363            shell,
1364            viewport,
1365        );
1366
1367        match event {
1368            Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => {
1369                self.pressed(tree, layout, cursor, renderer, shell);
1370            }
1371            _ if dragged => self.dragged(tree, layout, cursor, renderer, shell, frame),
1372            Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) if dragging => {
1373                let state = tree.state.downcast_mut::<AreaState>();
1374                state.dragging = false;
1375                state.last_pull = None;
1376                self.announce(tree, layout, renderer, shell);
1377            }
1378            Event::Keyboard(keyboard::Event::KeyPressed {
1379                key,
1380                modifiers,
1381                text,
1382                ..
1383            }) => {
1384                // Typing, Tab and an app's own chords are meant for something
1385                // other than the text being read.
1386                let elsewhere = text.is_some()
1387                    || modifiers.command()
1388                    || *key == keyboard::Key::Named(Named::Tab);
1389                let action = self.keymap.resolve(key, *modifiers);
1390                self.key_pressed(tree, layout, renderer, shell, action, elsewhere);
1391            }
1392            // A release that never arrives must not leave a drag running.
1393            Event::Mouse(mouse::Event::CursorLeft) if dragging => {
1394                let state = tree.state.downcast_mut::<AreaState>();
1395                state.dragging = false;
1396                state.last_pull = None;
1397            }
1398            _ => {}
1399        }
1400    }
1401
1402    fn draw(
1403        &self,
1404        tree: &Tree,
1405        renderer: &mut Renderer,
1406        theme: &Theme,
1407        style: &renderer::Style,
1408        layout: Layout<'_>,
1409        cursor: mouse::Cursor,
1410        viewport: &Rectangle,
1411    ) {
1412        self.content.as_widget().draw(
1413            &tree.children[0],
1414            renderer,
1415            theme,
1416            style,
1417            layout,
1418            cursor,
1419            viewport,
1420        );
1421    }
1422
1423    fn mouse_interaction(
1424        &self,
1425        tree: &Tree,
1426        layout: Layout<'_>,
1427        cursor: mouse::Cursor,
1428        viewport: &Rectangle,
1429        renderer: &Renderer,
1430    ) -> mouse::Interaction {
1431        self.content.as_widget().mouse_interaction(
1432            &tree.children[0],
1433            layout,
1434            cursor,
1435            viewport,
1436            renderer,
1437        )
1438    }
1439
1440    fn overlay<'b>(
1441        &'b mut self,
1442        tree: &'b mut Tree,
1443        layout: Layout<'b>,
1444        renderer: &Renderer,
1445        viewport: &Rectangle,
1446        translation: Vector,
1447    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
1448        self.content.as_widget_mut().overlay(
1449            &mut tree.children[0],
1450            layout,
1451            renderer,
1452            viewport,
1453            translation,
1454        )
1455    }
1456}
1457
1458impl<'a, Message: 'a> From<SelectionArea<'a, Message>> for Element<'a, Message> {
1459    fn from(area: SelectionArea<'a, Message>) -> Self {
1460        let element = Element::new(area);
1461        #[cfg(feature = "icedwright")]
1462        let element = icedwright_probe::semantic(element)
1463            .role(icedwright_probe::role::Document)
1464            .click_clock(icedwright_probe::ClickClock::Probe)
1465            .component("iced_cube::selection_area")
1466            .into();
1467        element
1468    }
1469}
1470
1471/// The number of laid out lines, and the caret top at the start and end of
1472/// every glyph, as byte offsets into the whole text and points relative to
1473/// the text's corner.
1474#[cfg(feature = "icedwright")]
1475fn geometry(body: &Body) -> (usize, Vec<(usize, Point)>) {
1476    let Some(buffer) = body.paragraph.shaped() else {
1477        return (0, Vec::new());
1478    };
1479    let mut starts = Vec::with_capacity(buffer.lines.len());
1480    let mut offset = 0;
1481    for line in &buffer.lines {
1482        starts.push(offset);
1483        offset += line.text().len() + 1;
1484    }
1485    let mut lines = 0;
1486    let mut carets: Vec<(usize, Point)> = Vec::new();
1487    for run in buffer.layout_runs() {
1488        lines += 1;
1489        let start = starts.get(run.line_i).copied().unwrap_or_default();
1490        for glyph in run.glyphs {
1491            carets.push((start + glyph.start, Point::new(glyph.x, run.line_top)));
1492            carets.push((
1493                start + glyph.end,
1494                Point::new(glyph.x + glyph.w, run.line_top),
1495            ));
1496        }
1497    }
1498    // The first caret at an offset wins, so a glyph's start beats the end of
1499    // the glyph before it on a new line.
1500    carets.sort_by_key(|(at, _)| *at);
1501    carets.dedup_by_key(|(at, _)| *at);
1502    (lines, carets)
1503}
1504
1505#[cfg(test)]
1506mod tests {
1507    use iced::keyboard::Key;
1508
1509    use super::*;
1510    use crate::theme::{dark, light};
1511
1512    #[test]
1513    fn word_bounds_find_the_word_under_the_caret() {
1514        assert_eq!(word_bounds("alpha beta", 7), Some((6, 10)));
1515        assert_eq!(word_bounds("alpha beta", 0), Some((0, 5)));
1516        assert_eq!(word_bounds("snake_case here", 3), Some((0, 10)));
1517    }
1518
1519    #[test]
1520    fn word_bounds_take_one_character_between_words() {
1521        assert_eq!(word_bounds("alpha beta", 5), Some((5, 6)));
1522        assert_eq!(word_bounds("a, b", 1), Some((1, 2)));
1523    }
1524
1525    #[test]
1526    fn word_bounds_respect_characters_of_several_bytes() {
1527        assert_eq!(word_bounds("caf\u{e9} noir", 4), Some((0, 5)));
1528        assert_eq!(word_bounds("caf\u{e9} noir", 100), Some((6, 10)));
1529        assert_eq!(word_bounds("", 0), None);
1530    }
1531
1532    #[test]
1533    fn presses_in_a_row_count_up_to_three_then_start_again() {
1534        let interval = Duration::from_millis(400);
1535        let start = Instant::now();
1536        let at = Point::new(10.0, 10.0);
1537        let click = |count, after: u64| {
1538            Some(Click {
1539                position: at,
1540                at: start + Duration::from_millis(after),
1541                count,
1542            })
1543        };
1544        let soon = start + Duration::from_millis(100);
1545
1546        assert_eq!(click_count(None, at, start, interval), 1);
1547        assert_eq!(click_count(click(1, 0), at, soon, interval), 2);
1548        assert_eq!(click_count(click(2, 0), at, soon, interval), 3);
1549        assert_eq!(click_count(click(3, 0), at, soon, interval), 1);
1550    }
1551
1552    #[test]
1553    fn a_late_or_distant_press_is_a_single_click() {
1554        let interval = Duration::from_millis(400);
1555        let start = Instant::now();
1556        let at = Point::new(10.0, 10.0);
1557        let previous = Some(Click {
1558            position: at,
1559            at: start,
1560            count: 1,
1561        });
1562
1563        let late = start + Duration::from_millis(401);
1564        assert_eq!(click_count(previous, at, late, interval), 1);
1565        let on_time = start + Duration::from_millis(400);
1566        assert_eq!(click_count(previous, at, on_time, interval), 2);
1567        let far = Point::new(10.0 + CLICK_SLOP + 1.0, 10.0);
1568        assert_eq!(click_count(previous, far, start, interval), 1);
1569    }
1570
1571    #[test]
1572    fn a_point_is_clamped_to_the_nearest_point_of_a_rectangle() {
1573        let bounds = Rectangle::new(Point::new(10.0, 20.0), Size::new(100.0, 50.0));
1574        assert_eq!(
1575            clamp(Point::new(50.0, 40.0), bounds),
1576            Point::new(50.0, 40.0)
1577        );
1578        assert_eq!(clamp(Point::new(0.0, 0.0), bounds), Point::new(10.0, 20.0));
1579        assert_eq!(
1580            clamp(Point::new(500.0, 500.0), bounds),
1581            Point::new(110.0, 70.0)
1582        );
1583    }
1584
1585    /// Feeds `pointer`, given in window coordinates, to texts laid out at
1586    /// `rows`, and returns the text found and the caret column asked for.
1587    fn search(rows: &[Rectangle], pointer: Point) -> Option<Position> {
1588        let mut search = Search::default();
1589        for (index, row) in rows.iter().enumerate() {
1590            let local = Point::new(pointer.x - row.x, pointer.y - row.y);
1591            search.feed(index, row.size(), local, || (0, local.x as usize));
1592        }
1593        search.result()
1594    }
1595
1596    #[test]
1597    fn the_pointer_finds_the_text_it_is_over_beside_or_above() {
1598        let row = |y: f32, width: f32| Rectangle::new(Point::new(0.0, y), Size::new(width, 20.0));
1599        let rows = [row(0.0, 100.0), row(30.0, 40.0), row(60.0, 100.0)];
1600
1601        assert_eq!(search(&rows, Point::new(50.0, 10.0)), Some((0, (0, 50))));
1602        // Beside a short line: that line, not the one below.
1603        assert_eq!(search(&rows, Point::new(80.0, 40.0)), Some((1, (0, 80))));
1604        // In the gap between lines: the start of the next one.
1605        assert_eq!(search(&rows, Point::new(50.0, 55.0)), Some((2, START)));
1606        // Below everything: nothing, which the area reads as the end.
1607        assert_eq!(search(&rows, Point::new(50.0, 500.0)), None);
1608    }
1609
1610    #[test]
1611    fn cells_side_by_side_are_read_in_order() {
1612        let cell = |x: f32, y: f32| Rectangle::new(Point::new(x, y), Size::new(100.0, 20.0));
1613        let cells = [
1614            cell(0.0, 0.0),
1615            cell(120.0, 0.0),
1616            cell(0.0, 30.0),
1617            cell(120.0, 30.0),
1618        ];
1619
1620        assert_eq!(search(&cells, Point::new(130.0, 10.0)), Some((1, (0, 10))));
1621        assert_eq!(search(&cells, Point::new(10.0, 40.0)), Some((2, (0, 10))));
1622        // Between two cells: the start of the one on the right.
1623        assert_eq!(search(&cells, Point::new(110.0, 40.0)), Some((3, START)));
1624        // Right of the last cell in a row: the end of that cell.
1625        assert_eq!(search(&cells, Point::new(300.0, 10.0)), Some((1, (0, 180))));
1626    }
1627
1628    #[test]
1629    fn the_selection_is_a_faded_primary_in_both_themes() {
1630        for theme in [light(), dark()] {
1631            let tokens = Tokens::of(&theme);
1632            let selection = style(&tokens).selection;
1633            assert_eq!(selection, fade(tokens.primary, 0.25));
1634            assert!(selection.a < 1.0, "the text must show through");
1635        }
1636    }
1637
1638    #[test]
1639    fn a_drag_scrolls_faster_the_further_past_the_edge_it_is() {
1640        assert_eq!(scroll_speed(0.0), SCROLL_SPEED);
1641        assert_eq!(scroll_speed(-20.0), SCROLL_SPEED);
1642        assert!(scroll_speed(10.0) > scroll_speed(1.0));
1643        assert_eq!(scroll_speed(10_000.0), MAX_SCROLL_SPEED);
1644    }
1645
1646    #[test]
1647    fn default_keymap_and_overrides() {
1648        let c = Key::Character("c".into());
1649        let a = Key::Character("a".into());
1650        let escape = Key::Named(Named::Escape);
1651        let command = keyboard::Modifiers::COMMAND;
1652        let keymap = default_keymap();
1653        assert_eq!(keymap.resolve(&c, command), Some(Action::Copy));
1654        assert_eq!(keymap.resolve(&a, command), Some(Action::SelectAll));
1655        assert_eq!(
1656            keymap.resolve(&escape, keyboard::Modifiers::empty()),
1657            Some(Action::Clear)
1658        );
1659        assert_eq!(keymap.resolve(&c, keyboard::Modifiers::empty()), None);
1660
1661        let custom = keymap
1662            .unbind(&Chord::character('a').command())
1663            .bind(Chord::character('e').command(), Action::SelectAll);
1664        assert_eq!(custom.resolve(&a, command), None);
1665        assert_eq!(
1666            custom.resolve(&Key::Character("e".into()), command),
1667            Some(Action::SelectAll)
1668        );
1669    }
1670
1671    #[test]
1672    fn every_action_is_documented_and_bound() {
1673        use keys::Action as _;
1674        let keymap = Action::defaults();
1675        for action in Action::ALL {
1676            assert!(!action.name().is_empty());
1677            assert!(action.description().ends_with('.'));
1678            assert!(!keymap.chords(action).is_empty(), "{action:?} has no chord");
1679        }
1680    }
1681
1682    #[test]
1683    fn a_task_reads_only_the_area_with_its_id() {
1684        let mut command = Command {
1685            target: Id::new("notes"),
1686            select_all: true,
1687            text: None,
1688        };
1689        let bounds = Rectangle::new(Point::ORIGIN, Size::new(10.0, 10.0));
1690
1691        let mut other = Request::default();
1692        command.custom(Some(&Id::new("other")), bounds, &mut other);
1693        assert!(!other.read && !other.select_all);
1694
1695        let mut request = Request::default();
1696        command.custom(Some(&Id::new("notes")), bounds, &mut request);
1697        assert!(request.read && request.select_all);
1698
1699        assert!(matches!(command.finish(), Outcome::None));
1700        command.custom(
1701            Some(&Id::new("notes")),
1702            bounds,
1703            &mut Reply("text".to_owned()),
1704        );
1705        assert!(matches!(command.finish(), Outcome::Some(text) if text == "text"));
1706    }
1707}