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