1use 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
74pub const SCROLL_SPEED: f32 = 200.0;
77pub const SCROLL_GAIN: f32 = 12.0;
79pub const MAX_SCROLL_SPEED: f32 = 2400.0;
81const MAX_FRAME: Duration = Duration::from_millis(50);
83pub const DOUBLE_CLICK: Duration = Duration::from_millis(400);
86const CLICK_SLOP: f32 = 6.0;
88
89type Caret = (usize, usize);
91type Position = (usize, Caret);
94
95const START: Caret = (0, 0);
96const END: Caret = (usize::MAX, usize::MAX);
97
98#[derive(Debug, Clone, Copy, PartialEq)]
100pub struct Style {
101 pub selection: Color,
103}
104
105pub fn style(tokens: &Tokens) -> Style {
107 Style {
108 selection: fade(tokens.primary, 0.25),
109 }
110}
111
112pub fn scroll_speed(distance: f32) -> f32 {
115 (SCROLL_SPEED + SCROLL_GAIN * distance.max(0.0)).min(MAX_SCROLL_SPEED)
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
120pub enum Action {
121 Copy,
123 SelectAll,
125 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
153pub 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
167struct Body {
169 paragraph: Paragraph,
170 pointer: Option<Point>,
173 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 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
252fn 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#[derive(Default)]
263struct Search {
264 found: Option<Position>,
265 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
295fn 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
318fn 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 text: String,
345 hovered: Option<usize>,
346 pressed: Option<usize>,
347 body: Body,
348}
349
350pub 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
375pub 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 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 pub fn font(mut self, font: impl Into<Font>) -> Self {
407 self.font = Some(font.into());
408 self
409 }
410
411 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 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 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 ®ions {
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 ®ions {
491 renderer.fill_quad(
492 renderer::Quad {
493 bounds: Rectangle::new(
494 bounds.position() + baseline - Vector::new(0.0, rise),
495 Size::new(bounds.width, 1.0),
496 ),
497 ..renderer::Quad::default()
498 },
499 colour,
500 );
501 }
502 };
503 if span.underline || hovered_link {
504 line(renderer, size.0 * 0.08);
505 }
506 if span.strikethrough {
507 line(renderer, size.0 / 2.0);
508 }
509 }
510 }
511}
512
513impl<Link, Message> Widget<Message, Theme, Renderer> for SelectableText<'_, Link, Message>
514where
515 Link: Clone + PartialEq + 'static,
516{
517 fn tag(&self) -> tree::Tag {
518 tree::Tag::of::<State<Link>>()
519 }
520
521 fn state(&self) -> tree::State {
522 tree::State::new(State::<Link> {
523 spans: Vec::new(),
524 text: String::new(),
525 hovered: None,
526 pressed: None,
527 body: Body {
528 paragraph: Paragraph::default(),
529 pointer: None,
530 direct: false,
531 selection: None,
532 },
533 })
534 }
535
536 fn size(&self) -> Size<Length> {
537 Size::new(self.width, Length::Shrink)
538 }
539
540 fn layout(
541 &mut self,
542 tree: &mut Tree,
543 renderer: &Renderer,
544 limits: &layout::Limits,
545 ) -> layout::Node {
546 let state = tree.state.downcast_mut::<State<Link>>();
547 let spans = self.spans.as_ref().as_ref();
548 let size = self
549 .size
550 .unwrap_or_else(|| text::Renderer::default_size(renderer));
551 let font = self
552 .font
553 .unwrap_or_else(|| text::Renderer::default_font(renderer));
554 let line_height = self.line_height;
555
556 layout::sized(limits, self.width, Length::Shrink, |limits| {
557 let bounds = limits.max();
558 let shape = text::Text {
559 content: (),
560 bounds,
561 size,
562 line_height,
563 font,
564 align_x: text::Alignment::Default,
565 align_y: iced::alignment::Vertical::Top,
566 shaping: text::Shaping::Advanced,
567 wrapping: text::Wrapping::default(),
568 };
569 let shaped = || Paragraph::with_spans(shape.with_content(spans));
570
571 if state.spans != spans {
572 state.body.paragraph = shaped();
573 state.spans = spans.iter().cloned().map(Span::to_static).collect();
574 state.text = spans.iter().map(|span| &*span.text).collect();
575 state.body.selection = None;
576 } else {
577 match state.body.paragraph.compare(shape) {
578 text::Difference::None => {}
579 text::Difference::Bounds => state.body.paragraph.resize(bounds),
580 text::Difference::Shape => state.body.paragraph = shaped(),
581 }
582 }
583 state.body.paragraph.min_bounds()
584 })
585 }
586
587 fn operate(
588 &mut self,
589 tree: &mut Tree,
590 layout: Layout<'_>,
591 _renderer: &Renderer,
592 operation: &mut dyn Operation,
593 ) {
594 let state = tree.state.downcast_mut::<State<Link>>();
595 #[cfg(feature = "icedwright")]
596 {
597 let size = self
598 .size
599 .unwrap_or_else(|| text::Renderer::default_size(_renderer));
600 let body = &state.body;
601 icedwright_probe::report(operation, layout.bounds(), || {
602 let (lines, carets) = geometry(body);
603 let annotation = icedwright_probe::Annotation::new()
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 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 Event::Window(window::Event::RedrawRequested(_)) => None,
649 _ => return,
650 };
651 let state = tree.state.downcast_mut::<State<Link>>();
652 let bounds = layout.bounds();
653 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 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 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#[derive(Clone, Copy)]
774struct Pull {
775 pointer: Point,
776 elapsed: Duration,
777}
778
779struct Visit<'f> {
782 index: usize,
783 each: &'f mut (dyn FnMut(usize, Rectangle, &mut Body) + Send),
784 pull: Option<Pull>,
785 pulling: bool,
787 scrolled: Vector,
790 entering: Option<Vector>,
792}
793
794impl Operation for Visit<'_> {
795 fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
796 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 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#[derive(Default)]
845struct Request {
846 select_all: bool,
847 read: bool,
848}
849
850struct 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
882pub mod operation {
885 use super::{Command, Id, Operation};
886
887 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 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
906pub fn selected(id: impl Into<Id>) -> Task<String> {
909 widget::operate(operation::selected(id.into()))
910}
911
912pub 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 active: bool,
924 last_click: Option<Click>,
925 last_pull: Option<Instant>,
927}
928
929pub 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
949pub 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 pub fn id(mut self, id: impl Into<Id>) -> Self {
967 self.id = Some(id.into());
968 self
969 }
970
971 pub fn keymap(mut self, keymap: Keymap<Action>) -> Self {
973 self.keymap = keymap;
974 self
975 }
976
977 pub fn double_click(mut self, interval: Duration) -> Self {
980 self.double_click = interval;
981 self
982 }
983
984 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 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 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 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 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 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 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 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 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 if self.clear(tree, layout, renderer) {
1254 shell.capture_event();
1255 shell.request_redraw();
1256 }
1257 }
1258 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 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 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 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#[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 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 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 assert_eq!(search(&rows, Point::new(80.0, 40.0)), Some((1, (0, 80))));
1604 assert_eq!(search(&rows, Point::new(50.0, 55.0)), Some((2, START)));
1606 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 assert_eq!(search(&cells, Point::new(110.0, 40.0)), Some((3, START)));
1624 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}