1use std::any::{Any, TypeId};
8use std::fmt;
9use std::rc::Rc;
10
11use waft_embedder::{
12 BoxHeightStyle, BoxWidthStyle, ClipOp, Color, FontCollection, Matrix4, Offset, Paint,
13 PlaceholderAlignment, Rect, Size, TextAffinity, TextAlign, TextBaseline, TextBox,
14 TextDirection, TextHeightBehavior, TextPosition, TextRange, TextSelection,
15};
16use waft_foundation::{App, ChangeNotifier, ChangeNotifierData, Handle, Ref};
17use waft_painting::{
18 ClipContext, InlineSpanRef, PaintingBinding, PlaceholderDimensions, PlaceholderSpan,
19 RenderComparison, StrutStyle, TextOverflow, TextPainter, TextScaler, TextWidthBasis,
20};
21
22use crate::box_::{AnyRenderBox, BoxConstraints, BoxHitTestResult, RenderBox, RenderBoxData};
23use crate::layer::{ContainerLayer, LayerLink, LeaderLayer};
24use crate::layout_helper::{ChildBaselineGetter, ChildLayoutHelper, ChildLayouter};
25use crate::object::{
26 AnyRenderObject, Constraints, ContainerParentData, ContainerParentDataMixin,
27 ContainerRenderObjectData, ContainerRenderObjectMixin, ParentData, RenderHandle, RenderObject,
28 RenderObjectData,
29};
30use crate::painting_context::PaintingContext;
31use crate::pipeline_owner::PipelineOwner;
32use crate::selection::{
33 AnySelectable, AnySelectionRegistrar, Selectable, SelectedContent, SelectedContentRange,
34 SelectionEvent, SelectionExtendDirection, SelectionGeometry, SelectionHandler, SelectionPoint,
35 SelectionRegistrarRef, SelectionResult, SelectionStatus, SelectionUtils, TextGranularity,
36 TextSelectionHandleType,
37};
38use crate::text_boundary::WordBoundary;
39use crate::{RelayoutWhenSystemFontsChangeData, RelayoutWhenSystemFontsChangeMixin};
40use waft_services::{CharacterBoundary, DocumentBoundary, ParagraphBoundary, TextBoundary};
41
42#[derive(Clone, Copy, Debug)]
44struct TextBoundaryRecord {
45 boundary_start: TextPosition,
46 boundary_end: TextPosition,
47}
48
49impl TextBoundaryRecord {
50 fn new(boundary_start: TextPosition, boundary_end: TextPosition) -> TextBoundaryRecord {
51 TextBoundaryRecord {
52 boundary_start,
53 boundary_end,
54 }
55 }
56}
57
58type TextBoundaryAtPosition =
61 fn(Handle<SelectableFragment>, &mut App, TextPosition) -> TextBoundaryRecord;
62
63type TextBoundaryAtPositionInText =
66 fn(Handle<SelectableFragment>, &mut App, TextPosition, &str) -> TextBoundaryRecord;
67
68const K_ELLIPSIS: &str = "\u{2026}";
69
70#[derive(Debug, Default)]
73pub struct TextParentData {
74 container_parent_data: ContainerParentData<AnyRenderBox>,
75 offset: Option<Offset>,
76
77 pub span: Option<Rc<dyn PlaceholderSpan>>,
82}
83
84impl TextParentData {
85 pub fn offset(&self) -> Option<Offset> {
90 self.offset
91 }
92}
93
94impl ParentData for TextParentData {
95 fn detach(&mut self) {
96 self.span = None;
97 self.offset = None;
98 ContainerParentDataMixin::detach(self);
99 }
100
101 fn provide(&self, id: TypeId) -> Option<&dyn Any> {
102 (id == TypeId::of::<TextParentData>()).then_some(self)
103 }
104
105 fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
106 (id == TypeId::of::<TextParentData>()).then_some(self)
107 }
108}
109
110impl ContainerParentDataMixin for TextParentData {
111 type ChildType = AnyRenderBox;
112
113 fn container_parent_data(&self) -> &ContainerParentData<AnyRenderBox> {
114 &self.container_parent_data
115 }
116
117 fn container_parent_data_mut(&mut self) -> &mut ContainerParentData<AnyRenderBox> {
118 &mut self.container_parent_data
119 }
120}
121
122impl fmt::Display for TextParentData {
123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 write!(f, "widget: {:?}, ", self.span)?;
125 match self.offset {
126 None => f.write_str("not laid out"),
127 Some(offset) => write!(f, "offset: {offset:?}"),
128 }
129 }
130}
131
132pub trait RenderInlineChildrenContainerDefaults:
165 RenderBox + ContainerRenderObjectMixin<ChildType = AnyRenderBox, ParentDataType = TextParentData>
166{
167 fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
169 if !child.parent_data_is::<TextParentData>(app) {
170 child.set_parent_data(app, TextParentData::default());
171 }
172 }
173
174 fn layout_inline_children(
192 self: RenderHandle<Self>,
193 app: &mut App,
194 max_width: f64,
195 layout_child: ChildLayouter,
196 get_child_baseline: ChildBaselineGetter,
197 ) -> Vec<PlaceholderDimensions> {
198 let constraints = BoxConstraints::new().max_width(max_width);
199 let mut dimensions = Vec::new();
200 let mut child = self.first_child(app);
201 while let Some(current) = child {
202 dimensions.push(layout_child_inline(
203 app,
204 current,
205 constraints,
206 layout_child,
207 get_child_baseline,
208 ));
209 child = self.child_after(app, current);
210 }
211 dimensions
212 }
213
214 fn position_inline_children(self: RenderHandle<Self>, app: &mut App, boxes: &[TextBox]) {
228 let mut child = self.first_child(app);
229 for text_box in boxes {
230 let Some(current) = child else {
231 debug_assert!(
232 false,
233 "Invalid number of boxes provided to positionInlineChildren. The number of \
234 boxes ({}) exceeds the number of child render objects ({}).",
235 boxes.len(),
236 self.child_count(app)
237 );
238 return;
239 };
240 text_parent_data_mut(app, current).offset =
241 Some(Offset::new(text_box.left, text_box.top));
242 child = self.child_after(app, current);
243 }
244 while let Some(current) = child {
245 text_parent_data_mut(app, current).offset = None;
246 child = self.child_after(app, current);
247 }
248 }
249
250 fn default_apply_paint_transform(
256 self: RenderHandle<Self>,
257 app: &App,
258 child: AnyRenderObject,
259 transform: &mut Matrix4,
260 ) {
261 match child.parent_data_of::<TextParentData>(app).offset {
262 None => *transform = crate::object::zero_matrix(),
263 Some(offset) => crate::object::translate(transform, offset.dx(), offset.dy()),
264 }
265 }
266
267 fn paint_inline_children(
272 self: RenderHandle<Self>,
273 app: &mut App,
274 context: &mut PaintingContext,
275 offset: Offset,
276 ) {
277 let mut child = self.first_child(app);
278 while let Some(current) = child {
279 let Some(child_offset) = text_parent_data(app, current).offset else {
280 return;
281 };
282 context.paint_child(app, current.as_object(), child_offset + offset);
283 child = self.child_after(app, current);
284 }
285 }
286
287 fn hit_test_inline_children(
292 self: RenderHandle<Self>,
293 app: &mut App,
294 result: &mut BoxHitTestResult<'_>,
295 position: Offset,
296 ) -> bool {
297 let mut child = self.first_child(app);
298 while let Some(current) = child {
299 let Some(child_offset) = text_parent_data(app, current).offset else {
300 return false;
301 };
302 let is_hit = result.add_with_paint_offset(
303 Some(child_offset),
304 position,
305 |result, transformed| current.hit_test(app, result, transformed),
306 );
307 if is_hit {
308 return true;
309 }
310 child = self.child_after(app, current);
311 }
312 false
313 }
314}
315
316fn layout_child_inline(
319 app: &mut App,
320 child: AnyRenderBox,
321 child_constraints: BoxConstraints,
322 layout_child: ChildLayouter,
323 get_baseline: ChildBaselineGetter,
324) -> PlaceholderDimensions {
325 let span = text_parent_data(app, child).span.clone();
326 debug_assert!(span.is_some());
327 let Some(span) = span else {
328 return PlaceholderDimensions::EMPTY;
329 };
330 let size = layout_child(app, child, child_constraints);
331 let baseline_offset = match span.alignment() {
332 PlaceholderAlignment::AboveBaseline
333 | PlaceholderAlignment::BelowBaseline
334 | PlaceholderAlignment::Bottom
335 | PlaceholderAlignment::Middle
336 | PlaceholderAlignment::Top => None,
337 PlaceholderAlignment::Baseline => get_baseline(
338 app,
339 child,
340 child_constraints,
341 span.baseline()
342 .expect("a baseline-aligned placeholder names its baseline"),
343 ),
344 };
345 PlaceholderDimensions {
346 size,
347 alignment: span.alignment(),
348 baseline: span.baseline(),
349 baseline_offset,
350 }
351}
352
353fn text_parent_data(app: &App, child: AnyRenderBox) -> &TextParentData {
354 child.as_object().parent_data_of::<TextParentData>(app)
355}
356
357fn text_parent_data_mut(app: &mut App, child: AnyRenderBox) -> &mut TextParentData {
358 child.as_object().parent_data_of_mut::<TextParentData>(app)
359}
360
361pub struct RenderParagraph {
368 render_object: RenderObjectData,
369 render_box: RenderBoxData,
370 container: ContainerRenderObjectData<AnyRenderBox>,
371 text_painter: TextPainter,
372 text_intrinsics: Option<TextPainter>,
373 fonts_override: Option<Handle<FontCollection>>,
374 soft_wrap: bool,
375 overflow: TextOverflow,
376 device_pixel_ratio: f64,
377 needs_clipping: bool,
378 placeholder_dimensions: Option<Vec<PlaceholderDimensions>>,
384 system_fonts: RelayoutWhenSystemFontsChangeData,
385 selection_color: Option<Color>,
386 last_selectable_fragments: Option<Vec<Ref<SelectableFragment>>>,
389 registrar: Option<SelectionRegistrarRef>,
390}
391
392impl RenderParagraph {
393 pub fn new(
395 app: &mut App,
396 text: InlineSpanRef,
397 text_direction: TextDirection,
398 fonts: Option<Handle<FontCollection>>,
399 ) -> RenderHandle<Self> {
400 debug_assert!(text.debug_assert_is_valid());
401 let mut text_painter = TextPainter::new();
402 text_painter.set_text(Some(text));
403 text_painter.set_text_direction(Some(text_direction));
404 RenderHandle::new_box(
405 app,
406 RenderParagraph {
407 render_object: RenderObjectData::new(),
408 render_box: RenderBoxData::new(),
409 container: ContainerRenderObjectData::new(),
410 text_painter,
411 text_intrinsics: None,
412 fonts_override: fonts,
413 soft_wrap: true,
414 overflow: TextOverflow::Clip,
415 device_pixel_ratio: 1.0,
416 needs_clipping: false,
417 placeholder_dimensions: None,
418 system_fonts: RelayoutWhenSystemFontsChangeData::new(),
419 selection_color: None,
420 last_selectable_fragments: None,
421 registrar: None,
422 },
423 )
424 }
425
426 fn painter(self: RenderHandle<Self>, app: &App) -> &TextPainter {
427 &self.get(app).text_painter
428 }
429
430 fn painter_mut(self: RenderHandle<Self>, app: &mut App) -> &mut TextPainter {
431 &mut self.get_mut(app).text_painter
432 }
433
434 pub fn fonts(self: RenderHandle<Self>, app: &mut App) -> Handle<FontCollection> {
436 match self.get(app).fonts_override {
437 Some(fonts) => fonts,
438 None => PaintingBinding::instance(app).fonts(app),
439 }
440 }
441
442 fn painter_with_fonts(
444 self: RenderHandle<Self>,
445 app: &mut App,
446 ) -> (&mut TextPainter, &mut FontCollection) {
447 let fonts = self.fonts(app);
448 let (this, fonts) = app.get_disjoint_mut(self.handle(), fonts);
449 (&mut this.text_painter, fonts)
450 }
451
452 pub fn text(self: RenderHandle<Self>, app: &App) -> InlineSpanRef {
454 self.painter(app)
455 .text()
456 .cloned()
457 .expect("a paragraph always has text")
458 }
459
460 pub fn set_text(self: RenderHandle<Self>, app: &mut App, value: InlineSpanRef) {
462 match self.text(app).compare_to(&*value) {
463 RenderComparison::Identical => {}
464 RenderComparison::Metadata => {
465 self.painter_mut(app).set_text(Some(value));
466 }
467 RenderComparison::Paint => {
468 self.painter_mut(app).set_text(Some(value));
469 self.mark_needs_paint(app);
470 }
471 RenderComparison::Layout => {
472 self.painter_mut(app).set_text(Some(value));
473 self.mark_needs_layout(app);
474 self.remove_selection_registrar_subscription(app);
475 self.dispose_selectable_fragments(app);
476 self.update_selection_registrar_subscription(app);
477 }
478 }
479 }
480
481 pub fn text_align(self: RenderHandle<Self>, app: &App) -> TextAlign {
483 self.painter(app).text_align()
484 }
485
486 pub fn set_text_align(self: RenderHandle<Self>, app: &mut App, value: TextAlign) {
488 if self.painter(app).text_align() == value {
489 return;
490 }
491 self.painter_mut(app).set_text_align(value);
492 self.mark_needs_paint(app);
493 }
494
495 pub fn text_direction(self: RenderHandle<Self>, app: &App) -> TextDirection {
506 self.painter(app)
507 .text_direction()
508 .expect("a paragraph always has a direction")
509 }
510
511 pub fn set_text_direction(self: RenderHandle<Self>, app: &mut App, value: TextDirection) {
513 if self.painter(app).text_direction() == Some(value) {
514 return;
515 }
516 self.painter_mut(app).set_text_direction(Some(value));
517 self.mark_needs_layout(app);
518 }
519
520 pub fn soft_wrap(self: RenderHandle<Self>, app: &App) -> bool {
528 self.get(app).soft_wrap
529 }
530
531 pub fn set_soft_wrap(self: RenderHandle<Self>, app: &mut App, value: bool) {
533 if self.get(app).soft_wrap == value {
534 return;
535 }
536 self.get_mut(app).soft_wrap = value;
537 self.mark_needs_layout(app);
538 }
539
540 pub fn overflow(self: RenderHandle<Self>, app: &App) -> TextOverflow {
542 self.get(app).overflow
543 }
544
545 pub fn set_overflow(self: RenderHandle<Self>, app: &mut App, value: TextOverflow) {
547 if self.get(app).overflow == value {
548 return;
549 }
550 self.get_mut(app).overflow = value;
551 let ellipsis = (value == TextOverflow::Ellipsis).then(|| K_ELLIPSIS.to_owned());
552 self.painter_mut(app).set_ellipsis(ellipsis);
553 self.mark_needs_layout(app);
554 }
555
556 pub fn text_scaler(self: RenderHandle<Self>, app: &App) -> TextScaler {
558 self.painter(app).text_scaler().clone()
559 }
560
561 pub fn set_text_scaler(self: RenderHandle<Self>, app: &mut App, value: TextScaler) {
563 if *self.painter(app).text_scaler() == value {
564 return;
565 }
566 self.painter_mut(app).set_text_scaler(value);
567 self.mark_needs_layout(app);
568 }
569
570 pub fn device_pixel_ratio(self: RenderHandle<Self>, app: &App) -> f64 {
574 self.get(app).device_pixel_ratio
575 }
576
577 pub fn set_device_pixel_ratio(self: RenderHandle<Self>, app: &mut App, value: f64) {
579 if self.get(app).device_pixel_ratio == value {
580 return;
581 }
582 self.get_mut(app).device_pixel_ratio = value;
583 }
584
585 pub fn max_lines(self: RenderHandle<Self>, app: &App) -> Option<i32> {
590 self.painter(app).max_lines()
591 }
592
593 pub fn set_max_lines(self: RenderHandle<Self>, app: &mut App, value: Option<i32>) {
596 debug_assert!(value.is_none_or(|value| value > 0));
597 if self.painter(app).max_lines() == value {
598 return;
599 }
600 self.painter_mut(app).set_max_lines(value);
601 self.mark_needs_layout(app);
602 }
603
604 pub fn text_width_basis(self: RenderHandle<Self>, app: &App) -> TextWidthBasis {
606 self.painter(app).text_width_basis()
607 }
608
609 pub fn set_text_width_basis(self: RenderHandle<Self>, app: &mut App, value: TextWidthBasis) {
611 if self.painter(app).text_width_basis() == value {
612 return;
613 }
614 self.painter_mut(app).set_text_width_basis(value);
615 self.mark_needs_layout(app);
616 }
617
618 pub fn text_height_behavior(self: RenderHandle<Self>, app: &App) -> Option<TextHeightBehavior> {
620 self.painter(app).text_height_behavior()
621 }
622
623 pub fn set_text_height_behavior(
625 self: RenderHandle<Self>,
626 app: &mut App,
627 value: Option<TextHeightBehavior>,
628 ) {
629 if self.painter(app).text_height_behavior() == value {
630 return;
631 }
632 self.painter_mut(app).set_text_height_behavior(value);
633 self.mark_needs_layout(app);
634 }
635
636 pub fn strut_style(self: RenderHandle<Self>, app: &App) -> Option<&StrutStyle> {
638 self.painter(app).strut_style()
639 }
640
641 pub fn set_strut_style(self: RenderHandle<Self>, app: &mut App, value: Option<StrutStyle>) {
643 if self.painter(app).strut_style() == value.as_ref() {
644 return;
645 }
646 self.painter_mut(app).set_strut_style(value);
647 self.mark_needs_layout(app);
648 }
649
650 pub fn preferred_line_height(self: RenderHandle<Self>, app: &mut App) -> f64 {
652 let (painter, fonts) = self.painter_with_fonts(app);
653 painter.preferred_line_height(fonts)
654 }
655
656 fn text_intrinsics_with_fonts(
662 self: RenderHandle<Self>,
663 app: &mut App,
664 ) -> (&mut TextPainter, &mut FontCollection) {
665 let fonts = self.fonts(app);
666 let (this, fonts) = app.get_disjoint_mut(self.handle(), fonts);
667 let painter = &this.text_painter;
668 let intrinsics = this.text_intrinsics.get_or_insert_with(TextPainter::new);
669 intrinsics.set_text(painter.text().cloned());
670 intrinsics.set_text_align(painter.text_align());
671 intrinsics.set_text_direction(painter.text_direction());
672 intrinsics.set_text_scaler(painter.text_scaler().clone());
673 intrinsics.set_max_lines(painter.max_lines());
674 intrinsics.set_ellipsis(painter.ellipsis().map(str::to_owned));
675 intrinsics.set_text_width_basis(painter.text_width_basis());
676 intrinsics.set_text_height_behavior(painter.text_height_behavior());
677 intrinsics.set_strut_style(painter.strut_style().cloned());
678 (intrinsics, fonts)
679 }
680
681 fn compute_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
683 let placeholder_dimensions = self.layout_inline_children(
684 app,
685 width,
686 ChildLayoutHelper::dry_layout_child,
687 ChildLayoutHelper::get_dry_baseline,
688 );
689 let max_width = self.adjust_max_width(app, width);
690 let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
691 intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
692 intrinsics.layout(fonts, width, max_width);
693 intrinsics.height()
694 }
695
696 fn adjust_max_width(self: RenderHandle<Self>, app: &App, max_width: f64) -> f64 {
697 if self.get(app).soft_wrap || self.get(app).overflow == TextOverflow::Ellipsis {
698 max_width
699 } else {
700 f64::INFINITY
701 }
702 }
703
704 fn layout_text_with_constraints(
705 self: RenderHandle<Self>,
706 app: &mut App,
707 constraints: BoxConstraints,
708 ) {
709 let max_width = self.adjust_max_width(app, constraints.max_width);
710 let placeholder_dimensions = self.get(app).placeholder_dimensions.clone();
711 let (painter, fonts) = self.painter_with_fonts(app);
712 painter.set_placeholder_dimensions(placeholder_dimensions);
713 painter.layout(fonts, constraints.min_width, max_width);
714 }
715
716 pub fn get_offset_for_caret(
720 self: RenderHandle<Self>,
721 app: &mut App,
722 position: TextPosition,
723 caret_prototype: Rect,
724 ) -> Offset {
725 debug_assert!(!self.debug_needs_layout(app));
726 let constraints = self.constraints(app);
727 self.layout_text_with_constraints(app, constraints);
728 let (painter, fonts) = self.painter_with_fonts(app);
729 painter.get_offset_for_caret(fonts, position, caret_prototype)
730 }
731
732 pub fn get_full_height_for_caret(
736 self: RenderHandle<Self>,
737 app: &mut App,
738 position: TextPosition,
739 ) -> f64 {
740 debug_assert!(!self.debug_needs_layout(app));
741 let constraints = self.constraints(app);
742 self.layout_text_with_constraints(app, constraints);
743 let (painter, fonts) = self.painter_with_fonts(app);
744 painter.get_full_height_for_caret(fonts, position, Rect::ZERO)
745 }
746
747 pub fn get_boxes_for_selection(
758 self: RenderHandle<Self>,
759 app: &mut App,
760 selection: TextSelection,
761 box_height_style: BoxHeightStyle,
762 box_width_style: BoxWidthStyle,
763 ) -> Vec<TextBox> {
764 debug_assert!(!self.debug_needs_layout(app));
765 let constraints = self.constraints(app);
766 self.layout_text_with_constraints(app, constraints);
767 self.painter(app)
768 .get_boxes_for_selection(selection, box_height_style, box_width_style)
769 }
770
771 pub fn get_position_for_offset(
775 self: RenderHandle<Self>,
776 app: &mut App,
777 offset: Offset,
778 ) -> TextPosition {
779 debug_assert!(!self.debug_needs_layout(app));
780 let constraints = self.constraints(app);
781 self.layout_text_with_constraints(app, constraints);
782 self.painter(app).get_position_for_offset(offset)
783 }
784
785 pub fn get_word_boundary(
794 self: RenderHandle<Self>,
795 app: &mut App,
796 position: TextPosition,
797 ) -> TextRange {
798 debug_assert!(!self.debug_needs_layout(app));
799 let constraints = self.constraints(app);
800 self.layout_text_with_constraints(app, constraints);
801 self.painter(app).get_word_boundary(position)
802 }
803
804 pub fn selections(self: RenderHandle<Self>, app: &App) -> Vec<TextSelection> {
809 let Some(fragments) = &self.get(app).last_selectable_fragments else {
810 return Vec::new();
811 };
812 fragments
813 .iter()
814 .filter_map(|fragment| {
815 let this = app.get(fragment);
816 Some(TextSelection::new(
817 this.text_selection_start?.offset,
818 this.text_selection_end?.offset,
819 ))
820 })
821 .collect()
822 }
823
824 pub fn registrar(self: RenderHandle<Self>, app: &App) -> Option<AnySelectionRegistrar> {
827 self.get(app)
828 .registrar
829 .as_ref()
830 .map(SelectionRegistrarRef::handle)
831 }
832
833 pub fn set_registrar(
835 self: RenderHandle<Self>,
836 app: &mut App,
837 value: Option<SelectionRegistrarRef>,
838 ) {
839 if value.as_ref().map(SelectionRegistrarRef::handle) == self.registrar(app) {
840 return;
841 }
842 self.remove_selection_registrar_subscription(app);
843 self.dispose_selectable_fragments(app);
844 self.get_mut(app).registrar = value;
845 self.update_selection_registrar_subscription(app);
846 }
847
848 fn update_selection_registrar_subscription(self: RenderHandle<Self>, app: &mut App) {
849 let Some(registrar) = self.registrar(app) else {
850 return;
851 };
852 if self.get(app).last_selectable_fragments.is_none() {
853 let fragments = self.get_selectable_fragments(app);
854 self.get_mut(app).last_selectable_fragments = Some(fragments);
855 }
856 let fragments = self
857 .get(app)
858 .last_selectable_fragments
859 .clone()
860 .expect("assigned just now");
861 for fragment in &fragments {
862 registrar.add(app, fragment.as_selectable());
863 }
864 if !fragments.is_empty() {
865 self.as_object().mark_needs_compositing_bits_update(app);
866 }
867 }
868
869 fn remove_selection_registrar_subscription(self: RenderHandle<Self>, app: &mut App) {
870 let (Some(registrar), Some(fragments)) = (
871 self.registrar(app),
872 self.get(app).last_selectable_fragments.clone(),
873 ) else {
874 return;
875 };
876 for fragment in &fragments {
877 registrar.remove(app, fragment.as_selectable());
878 }
879 }
880
881 fn get_selectable_fragments(
882 self: RenderHandle<Self>,
883 app: &mut App,
884 ) -> Vec<Ref<SelectableFragment>> {
885 let plain_text = self.text(app).to_plain_text(false, true);
886 let code_units: Vec<u16> = plain_text.encode_utf16().collect();
887 let mut result = Vec::new();
888 let mut start = 0usize;
889 while start < code_units.len() {
890 let mut end = code_units[start..]
891 .iter()
892 .position(|unit| *unit == waft_painting::PLACEHOLDER_CODE_UNIT)
893 .map_or(-1, |offset| (start + offset) as i32);
894 if start as i32 != end {
895 if end == -1 {
896 end = code_units.len() as i32;
897 }
898 result.push(app.create(SelectableFragment::new(
899 self,
900 TextRange::new(start as i32, end),
901 plain_text.clone(),
902 )));
903 start = end as usize;
904 }
905 start += 1;
906 }
907 result
908 }
909
910 pub fn selectable_belongs_to_paragraph(
912 self: RenderHandle<Self>,
913 app: &App,
914 selectable: AnySelectable,
915 ) -> bool {
916 self.get(app)
917 .last_selectable_fragments
918 .as_ref()
919 .is_some_and(|fragments| {
920 fragments
921 .iter()
922 .any(|f| f.as_selectable().id() == selectable.id())
923 })
924 }
925
926 fn dispose_selectable_fragments(self: RenderHandle<Self>, app: &mut App) {
927 let Some(fragments) = self.get_mut(app).last_selectable_fragments.take() else {
928 return;
929 };
930 for fragment in fragments {
931 fragment.dispose_selectable(app);
932 }
933 }
934
935 pub fn selection_color(self: RenderHandle<Self>, app: &App) -> Option<Color> {
940 self.get(app).selection_color
941 }
942
943 pub fn set_selection_color(self: RenderHandle<Self>, app: &mut App, value: Option<Color>) {
945 if self.get(app).selection_color == value {
946 return;
947 }
948 self.get_mut(app).selection_color = value;
949 let has_selection = self
950 .get(app)
951 .last_selectable_fragments
952 .as_ref()
953 .is_some_and(|fragments| {
954 fragments
955 .iter()
956 .any(|fragment| app.get(fragment).selection_geometry.has_selection())
957 });
958 if has_selection {
959 self.mark_needs_paint(app);
960 }
961 }
962
963 fn get_offset_for_position(
964 self: RenderHandle<Self>,
965 app: &mut App,
966 position: TextPosition,
967 ) -> Offset {
968 self.get_offset_for_caret(app, position, Rect::ZERO)
969 + Offset::new(0.0, self.get_full_height_for_caret(app, position))
970 }
971
972 pub fn get_line_at_offset(
974 self: RenderHandle<Self>,
975 app: &mut App,
976 position: TextPosition,
977 ) -> TextSelection {
978 let constraints = self.constraints(app);
979 self.layout_text_with_constraints(app, constraints);
980 let line = self.painter(app).get_line_boundary(position);
981 TextSelection::new(line.start, line.end)
982 }
983
984 pub fn get_text_position_above(
986 self: RenderHandle<Self>,
987 app: &mut App,
988 position: TextPosition,
989 ) -> TextPosition {
990 let line_height = self.preferred_line_height(app);
991 self.get_text_position_vertical(app, position, -0.5 * line_height)
992 }
993
994 pub fn get_text_position_below(
996 self: RenderHandle<Self>,
997 app: &mut App,
998 position: TextPosition,
999 ) -> TextPosition {
1000 let line_height = self.preferred_line_height(app);
1001 self.get_text_position_vertical(app, position, 1.5 * line_height)
1002 }
1003
1004 fn get_text_position_vertical(
1005 self: RenderHandle<Self>,
1006 app: &mut App,
1007 position: TextPosition,
1008 vertical_offset: f64,
1009 ) -> TextPosition {
1010 let (painter, fonts) = self.painter_with_fonts(app);
1011 let caret_offset = painter.get_offset_for_caret(fonts, position, Rect::ZERO);
1012 painter.get_position_for_offset(caret_offset.translate(0.0, vertical_offset))
1013 }
1014
1015 pub fn text_size(self: RenderHandle<Self>, app: &App) -> Size {
1026 debug_assert!(!self.debug_needs_layout(app));
1027 self.painter(app).size()
1028 }
1029
1030 pub fn did_exceed_max_lines(self: RenderHandle<Self>, app: &App) -> bool {
1037 debug_assert!(!self.debug_needs_layout(app));
1038 self.painter(app).did_exceed_max_lines()
1039 }
1040}
1041
1042impl RelayoutWhenSystemFontsChangeMixin for RenderParagraph {
1043 fn relayout_when_system_fonts_change_data(
1044 self: RenderHandle<Self>,
1045 app: &App,
1046 ) -> &RelayoutWhenSystemFontsChangeData {
1047 &self.get(app).system_fonts
1048 }
1049
1050 fn relayout_when_system_fonts_change_data_mut(
1051 self: RenderHandle<Self>,
1052 app: &mut App,
1053 ) -> &mut RelayoutWhenSystemFontsChangeData {
1054 &mut self.get_mut(app).system_fonts
1055 }
1056
1057 fn system_fonts_did_change(self: RenderHandle<Self>, app: &mut App) {
1058 self.as_render_object(app).mark_needs_layout(app);
1059 self.painter_mut(app).mark_needs_layout();
1060 }
1061}
1062
1063impl ContainerRenderObjectMixin for RenderParagraph {
1064 type ChildType = AnyRenderBox;
1065 type ParentDataType = TextParentData;
1066
1067 fn container_data(
1068 self: RenderHandle<Self>,
1069 app: &App,
1070 ) -> &ContainerRenderObjectData<AnyRenderBox> {
1071 &self.get(app).container
1072 }
1073
1074 fn container_data_mut(
1075 self: RenderHandle<Self>,
1076 app: &mut App,
1077 ) -> &mut ContainerRenderObjectData<AnyRenderBox> {
1078 &mut self.get_mut(app).container
1079 }
1080}
1081
1082impl RenderInlineChildrenContainerDefaults for RenderParagraph {}
1083
1084impl RenderObject for RenderParagraph {
1085 crate::render_object_accessors!();
1086
1087 fn visit_children(
1088 self: RenderHandle<Self>,
1089 app: &App,
1090 visitor: &mut dyn FnMut(AnyRenderObject),
1091 ) {
1092 ContainerRenderObjectMixin::visit_children(self, app, visitor)
1093 }
1094
1095 fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
1096 ContainerRenderObjectMixin::did_attach(self, app, owner);
1097 RelayoutWhenSystemFontsChangeMixin::attach_system_fonts(self, app);
1098 }
1099
1100 fn did_detach(self: RenderHandle<Self>, app: &mut App) {
1101 RelayoutWhenSystemFontsChangeMixin::detach_system_fonts(self, app);
1102 ContainerRenderObjectMixin::did_detach(self, app);
1103 }
1104
1105 fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
1106 ContainerRenderObjectMixin::redepth_children(self, app)
1107 }
1108
1109 fn always_needs_compositing(self: RenderHandle<Self>, app: &App) -> bool {
1110 self.get(app)
1111 .last_selectable_fragments
1112 .as_ref()
1113 .is_some_and(|fragments| !fragments.is_empty())
1114 }
1115
1116 fn dispose(self: RenderHandle<Self>, app: &mut App) {
1117 self.remove_selection_registrar_subscription(app);
1118 self.dispose_selectable_fragments(app);
1119 self.painter_mut(app).dispose();
1120 if let Some(mut intrinsics) = self.get_mut(app).text_intrinsics.take() {
1121 intrinsics.dispose();
1122 }
1123 crate::object::RenderObjectBase::dispose(self, app);
1124 }
1125
1126 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1127 let constraints = self.constraints(app);
1128 let placeholder_dimensions = self.layout_inline_children(
1129 app,
1130 constraints.max_width,
1131 ChildLayoutHelper::layout_child,
1132 ChildLayoutHelper::get_baseline,
1133 );
1134 self.get_mut(app).placeholder_dimensions = Some(placeholder_dimensions);
1135 self.layout_text_with_constraints(app, constraints);
1136 let boxes = self
1137 .painter_mut(app)
1138 .inline_placeholder_boxes()
1139 .expect("laid out just now");
1140 self.position_inline_children(app, &boxes);
1141 let text_size = self.painter(app).size();
1142 let size = constraints.constrain(text_size);
1143 self.set_size(app, size);
1144
1145 let did_overflow_height =
1146 size.height() < text_size.height() || self.painter(app).did_exceed_max_lines();
1147 let did_overflow_width = size.width() < text_size.width();
1148 let has_visual_overflow = did_overflow_width || did_overflow_height;
1154 let needs_clipping = has_visual_overflow
1155 && match self.get(app).overflow {
1156 TextOverflow::Visible => false,
1157 TextOverflow::Clip | TextOverflow::Ellipsis | TextOverflow::Fade => true,
1159 };
1160 self.get_mut(app).needs_clipping = needs_clipping;
1161 }
1162
1163 fn paint(
1164 self: RenderHandle<Self>,
1165 app: &mut App,
1166 context: &mut PaintingContext,
1167 offset: Offset,
1168 ) {
1169 let constraints = self.constraints(app);
1180 self.layout_text_with_constraints(app, constraints);
1181
1182 let needs_clipping = self.get(app).needs_clipping;
1183 if let Some(fragments) = self.get(app).last_selectable_fragments.clone() {
1184 if needs_clipping {
1185 context.canvas().save();
1186 context
1187 .canvas()
1188 .clip_rect(offset & self.size(app), ClipOp::Intersect, true);
1189 }
1190 for fragment in fragments {
1191 fragment.paint_selection(app, context, offset);
1192 }
1193 if needs_clipping {
1194 context.canvas().restore();
1195 }
1196 }
1197
1198 if needs_clipping {
1199 let bounds = offset & self.size(app);
1201 context.canvas().save();
1202 context.canvas().clip_rect(bounds, ClipOp::Intersect, true);
1203 }
1204
1205 let (painter, fonts) = self.painter_with_fonts(app);
1206 painter.paint(fonts, context.canvas(), offset);
1207
1208 self.paint_inline_children(app, context, offset);
1209
1210 if needs_clipping {
1211 context.canvas().restore();
1212 }
1213
1214 if let Some(fragments) = self.get(app).last_selectable_fragments.clone() {
1215 for fragment in fragments {
1216 fragment.paint_handles(app, context, offset);
1217 }
1218 }
1219 }
1220}
1221
1222impl RenderBox for RenderParagraph {
1223 crate::render_box_accessors!();
1224
1225 fn mark_needs_layout(self: RenderHandle<Self>, app: &mut App) {
1226 if let Some(fragments) = self.get(app).last_selectable_fragments.clone() {
1227 for fragment in fragments {
1228 fragment.did_change_paragraph_layout(app);
1229 }
1230 }
1231 crate::box_::RenderBoxBase::mark_needs_layout(self, app);
1232 }
1233
1234 fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1235 RenderInlineChildrenContainerDefaults::setup_parent_data(self, app, child);
1236 }
1237
1238 fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, _height: f64) -> f64 {
1239 let placeholder_dimensions = self.layout_inline_children(
1240 app,
1241 f64::INFINITY,
1242 |app, child, _| Size::new(child.get_min_intrinsic_width(app, f64::INFINITY), 0.0),
1243 ChildLayoutHelper::get_dry_baseline,
1244 );
1245 let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
1246 intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
1247 intrinsics.layout(fonts, 0.0, f64::INFINITY);
1248 intrinsics.min_intrinsic_width()
1249 }
1250
1251 fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, _height: f64) -> f64 {
1252 let placeholder_dimensions = self.layout_inline_children(
1253 app,
1254 f64::INFINITY,
1255 |app, child, _| Size::new(child.get_max_intrinsic_width(app, f64::INFINITY), 0.0),
1258 ChildLayoutHelper::get_dry_baseline,
1259 );
1260 let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
1261 intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
1262 intrinsics.layout(fonts, 0.0, f64::INFINITY);
1263 intrinsics.max_intrinsic_width()
1264 }
1265
1266 fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1267 self.compute_intrinsic_height(app, width)
1268 }
1269
1270 fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1271 self.compute_intrinsic_height(app, width)
1272 }
1273
1274 fn compute_dry_layout(
1275 self: RenderHandle<Self>,
1276 app: &mut App,
1277 constraints: BoxConstraints,
1278 ) -> Size {
1279 let placeholder_dimensions = self.layout_inline_children(
1280 app,
1281 constraints.max_width,
1282 ChildLayoutHelper::dry_layout_child,
1283 ChildLayoutHelper::get_dry_baseline,
1284 );
1285 let max_width = self.adjust_max_width(app, constraints.max_width);
1286 let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
1287 intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
1288 intrinsics.layout(fonts, constraints.min_width, max_width);
1289 let size = intrinsics.size();
1290 constraints.constrain(size)
1291 }
1292
1293 fn compute_distance_to_actual_baseline(
1294 self: RenderHandle<Self>,
1295 app: &mut App,
1296 _baseline: TextBaseline,
1297 ) -> Option<f64> {
1298 debug_assert!(!self.as_object().debug_needs_layout(app));
1299 let constraints = self.constraints(app);
1300 debug_assert!(constraints.debug_assert_is_valid(false));
1301 self.layout_text_with_constraints(app, constraints);
1302 Some(
1306 self.painter(app)
1307 .compute_distance_to_actual_baseline(TextBaseline::Alphabetic),
1308 )
1309 }
1310
1311 fn compute_dry_baseline(
1312 self: RenderHandle<Self>,
1313 app: &mut App,
1314 constraints: BoxConstraints,
1315 _baseline: TextBaseline,
1316 ) -> Option<f64> {
1317 debug_assert!(constraints.debug_assert_is_valid(false));
1318 let placeholder_dimensions = self.layout_inline_children(
1319 app,
1320 constraints.max_width,
1321 ChildLayoutHelper::dry_layout_child,
1322 ChildLayoutHelper::get_dry_baseline,
1323 );
1324 let max_width = self.adjust_max_width(app, constraints.max_width);
1325 let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
1326 intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
1327 intrinsics.layout(fonts, constraints.min_width, max_width);
1328 Some(intrinsics.compute_distance_to_actual_baseline(TextBaseline::Alphabetic))
1329 }
1330
1331 fn apply_paint_transform(
1332 self: RenderHandle<Self>,
1333 app: &App,
1334 child: AnyRenderObject,
1335 transform: &mut Matrix4,
1336 ) {
1337 self.default_apply_paint_transform(app, child, transform);
1338 }
1339
1340 fn hit_test_self(self: RenderHandle<Self>, _app: &App, _position: Offset) -> bool {
1341 true
1342 }
1343
1344 fn hit_test_children(
1345 self: RenderHandle<Self>,
1346 app: &mut App,
1347 result: &mut BoxHitTestResult<'_>,
1348 position: Offset,
1349 ) -> bool {
1350 let painter = self.painter(app);
1351 let glyph = painter.get_closest_glyph_for_offset(position);
1352 let span_hit = glyph
1358 .filter(|glyph| glyph.grapheme_cluster_layout_bounds.contains(position))
1359 .and_then(|glyph| {
1360 painter
1361 .text()
1362 .expect("a paragraph always has text")
1363 .clone()
1364 .get_span_for_position(TextPosition::new(
1365 glyph.grapheme_cluster_code_unit_range.start,
1366 ))
1367 .and_then(|span| span.to_hit_test_target())
1368 });
1369 match span_hit {
1370 Some(span) => {
1371 result.add(span.into());
1372 true
1373 }
1374 None => self.hit_test_inline_children(app, result, position),
1375 }
1376 }
1377}
1378
1379struct SelectableFragment {
1385 change_notifier: ChangeNotifierData,
1386 range: TextRange,
1387 paragraph: RenderHandle<RenderParagraph>,
1388 full_text: String,
1389 text_selection_start: Option<TextPosition>,
1390 text_selection_end: Option<TextPosition>,
1391 selectable_contains_origin_text_boundary: bool,
1392 start_handle_layer_link: Option<Ref<LayerLink>>,
1393 end_handle_layer_link: Option<Ref<LayerLink>>,
1394 selection_geometry: SelectionGeometry,
1395 cached_bounding_boxes: Option<Vec<Rect>>,
1396 cached_rect: Option<Rect>,
1397}
1398
1399#[allow(
1400 clippy::unnecessary_unwrap,
1401 clippy::collapsible_if,
1402 clippy::too_many_arguments
1403)]
1404impl SelectableFragment {
1405 fn new(
1406 paragraph: RenderHandle<RenderParagraph>,
1407 range: TextRange,
1408 full_text: String,
1409 ) -> SelectableFragment {
1410 debug_assert!(range.is_valid() && !range.is_collapsed() && range.is_normalized());
1411 SelectableFragment {
1412 change_notifier: ChangeNotifierData::new(),
1413 range,
1414 paragraph,
1415 full_text,
1416 text_selection_start: None,
1417 text_selection_end: None,
1418 selectable_contains_origin_text_boundary: false,
1419 start_handle_layer_link: None,
1420 end_handle_layer_link: None,
1421 selection_geometry: SelectionGeometry::new(SelectionStatus::None, true),
1422 cached_bounding_boxes: None,
1423 cached_rect: None,
1424 }
1425 }
1426
1427 fn update_selection_geometry(self: Handle<Self>, app: &mut App) {
1428 let new_value = self.get_selection_geometry(app);
1429 if app.get(self).selection_geometry == new_value {
1430 return;
1431 }
1432 app.get_mut(self).selection_geometry = new_value;
1433 self.notify_listeners(app);
1434 }
1435
1436 fn get_selection_geometry(self: Handle<Self>, app: &mut App) -> SelectionGeometry {
1437 let (Some(selection_start), Some(selection_end)) = (
1438 app.get(self).text_selection_start,
1439 app.get(self).text_selection_end,
1440 ) else {
1441 return SelectionGeometry::new(SelectionStatus::None, true);
1442 };
1443 let paragraph = app.get(self).paragraph;
1444 let is_reversed = selection_start.offset > selection_end.offset;
1445 let start_offset_in_paragraph_coordinates =
1446 paragraph.get_offset_for_position(app, selection_start);
1447 let end_offset_in_paragraph_coordinates = if selection_start.offset == selection_end.offset
1448 {
1449 start_offset_in_paragraph_coordinates
1450 } else {
1451 paragraph.get_offset_for_position(app, selection_end)
1452 };
1453 let flip_handles = is_reversed != (paragraph.text_direction(app) == TextDirection::Rtl);
1454 let selection = TextSelection::new(selection_start.offset, selection_end.offset);
1455 let selection_rects: Vec<Rect> = paragraph
1456 .get_boxes_for_selection(app, selection, BoxHeightStyle::Tight, BoxWidthStyle::Tight)
1457 .into_iter()
1458 .map(|text_box| text_box.to_rect())
1459 .collect();
1460 let selection_collapsed = selection_start.offset == selection_end.offset;
1461 let (start_selection_handle_type, end_selection_handle_type) = if selection_collapsed {
1462 (
1463 TextSelectionHandleType::Collapsed,
1464 TextSelectionHandleType::Collapsed,
1465 )
1466 } else if flip_handles {
1467 (
1468 TextSelectionHandleType::Right,
1469 TextSelectionHandleType::Left,
1470 )
1471 } else {
1472 (
1473 TextSelectionHandleType::Left,
1474 TextSelectionHandleType::Right,
1475 )
1476 };
1477 let line_height = paragraph.preferred_line_height(app);
1478 let status = if selection_collapsed {
1479 SelectionStatus::Collapsed
1480 } else {
1481 SelectionStatus::Uncollapsed
1482 };
1483 SelectionGeometry::new(status, true)
1484 .start_selection_point(Some(SelectionPoint::new(
1485 start_offset_in_paragraph_coordinates,
1486 line_height,
1487 start_selection_handle_type,
1488 )))
1489 .end_selection_point(Some(SelectionPoint::new(
1490 end_offset_in_paragraph_coordinates,
1491 line_height,
1492 end_selection_handle_type,
1493 )))
1494 .selection_rects(selection_rects)
1495 }
1496
1497 fn did_change_selection(self: Handle<Self>, app: &mut App) {
1498 app.get(self).paragraph.mark_needs_paint(app);
1499 self.update_selection_geometry(app);
1500 }
1501
1502 fn set_selection_position(
1503 self: Handle<Self>,
1504 app: &mut App,
1505 position: Option<TextPosition>,
1506 is_end: bool,
1507 ) {
1508 if is_end {
1509 app.get_mut(self).text_selection_end = position;
1510 } else {
1511 app.get_mut(self).text_selection_start = position;
1512 }
1513 }
1514
1515 fn handle_clear_selection(self: Handle<Self>, app: &mut App) -> SelectionResult {
1516 let this = app.get_mut(self);
1517 this.text_selection_start = None;
1518 this.text_selection_end = None;
1519 this.selectable_contains_origin_text_boundary = false;
1520 SelectionResult::None
1521 }
1522
1523 fn handle_select_all(self: Handle<Self>, app: &mut App) -> SelectionResult {
1524 let range = app.get(self).range;
1525 let this = app.get_mut(self);
1526 this.text_selection_start = Some(TextPosition::new(range.start));
1527 this.text_selection_end = Some(TextPosition::with_affinity(
1528 range.end,
1529 TextAffinity::Upstream,
1530 ));
1531 SelectionResult::None
1532 }
1533
1534 fn handle_select_text_boundary(
1535 self: Handle<Self>,
1536 app: &mut App,
1537 text_boundary: TextBoundaryRecord,
1538 ) -> SelectionResult {
1539 let range = app.get(self).range;
1540 if text_boundary.boundary_start.offset < range.start
1541 && text_boundary.boundary_end.offset <= range.start
1542 {
1543 return SelectionResult::Previous;
1544 } else if text_boundary.boundary_start.offset >= range.end
1545 && text_boundary.boundary_end.offset > range.end
1546 {
1547 return SelectionResult::Next;
1548 }
1549 debug_assert!(
1550 text_boundary.boundary_start.offset >= range.start
1551 && text_boundary.boundary_end.offset <= range.end
1552 );
1553 let this = app.get_mut(self);
1554 this.text_selection_start = Some(text_boundary.boundary_start);
1555 this.text_selection_end = Some(text_boundary.boundary_end);
1556 this.selectable_contains_origin_text_boundary = true;
1557 SelectionResult::End
1558 }
1559
1560 fn intersect(a: TextRange, b: TextRange) -> Option<TextRange> {
1561 debug_assert!(a.is_normalized());
1562 debug_assert!(b.is_normalized());
1563 let start_max = a.start.max(b.start);
1564 let end_min = a.end.min(b.end);
1565 (start_max <= end_min).then(|| TextRange::new(start_max, end_min))
1566 }
1567
1568 fn handle_select_multi_fragment_text_boundary(
1569 self: Handle<Self>,
1570 app: &mut App,
1571 text_boundary: TextBoundaryRecord,
1572 ) -> SelectionResult {
1573 let range = app.get(self).range;
1574 if text_boundary.boundary_start.offset < range.start
1575 && text_boundary.boundary_end.offset <= range.start
1576 {
1577 return SelectionResult::Previous;
1578 } else if text_boundary.boundary_start.offset >= range.end
1579 && text_boundary.boundary_end.offset > range.end
1580 {
1581 return SelectionResult::Next;
1582 }
1583 let boundary_as_range = TextRange::new(
1584 text_boundary.boundary_start.offset,
1585 text_boundary.boundary_end.offset,
1586 );
1587 let Some(intersect_range) = Self::intersect(range, boundary_as_range) else {
1588 return SelectionResult::None;
1589 };
1590 let this = app.get_mut(self);
1591 this.text_selection_start = Some(TextPosition::new(intersect_range.start));
1592 this.text_selection_end = Some(TextPosition::new(intersect_range.end));
1593 this.selectable_contains_origin_text_boundary = true;
1594 if range.end < text_boundary.boundary_end.offset {
1595 return SelectionResult::Next;
1596 }
1597 SelectionResult::End
1598 }
1599
1600 fn adjust_text_boundary_at_position(
1601 text_boundary: TextRange,
1602 position: TextPosition,
1603 ) -> TextBoundaryRecord {
1604 if position.offset > text_boundary.end {
1605 let at = TextPosition::new(position.offset);
1606 TextBoundaryRecord::new(at, at)
1607 } else {
1608 TextBoundaryRecord::new(
1609 TextPosition::new(text_boundary.start),
1610 TextPosition::with_affinity(text_boundary.end, TextAffinity::Upstream),
1611 )
1612 }
1613 }
1614
1615 fn handle_select_word(
1616 self: Handle<Self>,
1617 app: &mut App,
1618 global_position: Offset,
1619 ) -> SelectionResult {
1620 let paragraph = app.get(self).paragraph;
1621 let local_position = paragraph
1622 .as_box()
1623 .global_to_local(app, global_position, None);
1624 let position = paragraph.get_position_for_offset(app, local_position);
1625 if self.position_is_within_current_selection(app, position)
1626 && app.get(self).text_selection_start != app.get(self).text_selection_end
1627 {
1628 return SelectionResult::End;
1629 }
1630 let word_boundary = self.get_word_boundary_at_position(app, position);
1631 self.handle_select_text_boundary(app, word_boundary)
1632 }
1633
1634 fn get_word_boundary_at_position(
1635 self: Handle<Self>,
1636 app: &mut App,
1637 position: TextPosition,
1638 ) -> TextBoundaryRecord {
1639 let word = app.get(self).paragraph.get_word_boundary(app, position);
1640 debug_assert!(word.is_normalized());
1641 Self::adjust_text_boundary_at_position(word, position)
1642 }
1643
1644 fn handle_select_paragraph(
1645 self: Handle<Self>,
1646 app: &mut App,
1647 global_position: Offset,
1648 ) -> SelectionResult {
1649 let paragraph = app.get(self).paragraph;
1650 let local_position = paragraph
1651 .as_box()
1652 .global_to_local(app, global_position, None);
1653 let position = paragraph.get_position_for_offset(app, local_position);
1654 let full_text = app.get(self).full_text.clone();
1655 let paragraph_boundary = self.get_paragraph_boundary_at_position(app, position, &full_text);
1656 self.handle_select_multi_fragment_text_boundary(app, paragraph_boundary)
1657 }
1658
1659 fn get_position_in_paragraph(
1660 self: Handle<Self>,
1661 app: &mut App,
1662 target_paragraph: RenderHandle<RenderParagraph>,
1663 ) -> TextPosition {
1664 let paragraph = app.get(self).paragraph;
1665 let transform = paragraph
1666 .as_object()
1667 .get_transform_to(app, Some(target_paragraph.as_object()));
1668 let local_center = paragraph.as_object().paint_bounds(app).center_left();
1669 let local_pos = waft_painting::transform_point(&transform, local_center);
1670 target_paragraph.get_position_for_offset(app, local_pos)
1671 }
1672
1673 fn get_paragraph_boundary_at_position(
1674 self: Handle<Self>,
1675 app: &mut App,
1676 position: TextPosition,
1677 text: &str,
1678 ) -> TextBoundaryRecord {
1679 let paragraph_boundary = ParagraphBoundary::new(text);
1680 let paragraph_start = paragraph_boundary
1681 .get_leading_text_boundary_at(
1682 app,
1683 if position.offset == text.encode_utf16().count() as i32
1684 || position.affinity == TextAffinity::Upstream
1685 {
1686 position.offset - 1
1687 } else {
1688 position.offset
1689 },
1690 )
1691 .unwrap_or(0);
1692 let paragraph_end = paragraph_boundary
1693 .get_trailing_text_boundary_at(app, position.offset)
1694 .unwrap_or(text.encode_utf16().count() as i32);
1695 let paragraph_range = TextRange::new(paragraph_start, paragraph_end);
1696 debug_assert!(paragraph_range.is_normalized());
1697 Self::adjust_text_boundary_at_position(paragraph_range, position)
1698 }
1699
1700 fn get_clamped_paragraph_boundary_at_position(
1701 self: Handle<Self>,
1702 app: &mut App,
1703 position: TextPosition,
1704 ) -> TextBoundaryRecord {
1705 let full_text = app.get(self).full_text.clone();
1706 let range = app.get(self).range;
1707 let paragraph_boundary = ParagraphBoundary::new(&full_text);
1708 let mut paragraph_start = paragraph_boundary
1709 .get_leading_text_boundary_at(
1710 app,
1711 if position.offset == full_text.encode_utf16().count() as i32
1712 || position.affinity == TextAffinity::Upstream
1713 {
1714 position.offset - 1
1715 } else {
1716 position.offset
1717 },
1718 )
1719 .unwrap_or(0);
1720 let mut paragraph_end = paragraph_boundary
1721 .get_trailing_text_boundary_at(app, position.offset)
1722 .unwrap_or(full_text.encode_utf16().count() as i32);
1723 paragraph_start = if paragraph_start < range.start {
1724 range.start
1725 } else if paragraph_start > range.end {
1726 range.end
1727 } else {
1728 paragraph_start
1729 };
1730 paragraph_end = if paragraph_end > range.end {
1731 range.end
1732 } else if paragraph_end < range.start {
1733 range.start
1734 } else {
1735 paragraph_end
1736 };
1737 let paragraph_range = TextRange::new(paragraph_start, paragraph_end);
1738 debug_assert!(paragraph_range.is_normalized());
1739 Self::adjust_text_boundary_at_position(paragraph_range, position)
1740 }
1741
1742 fn closest_text_boundary(
1743 text_boundary: TextBoundaryRecord,
1744 position: TextPosition,
1745 ) -> TextPosition {
1746 let difference_a = (position.offset - text_boundary.boundary_start.offset).abs();
1747 let difference_b = (position.offset - text_boundary.boundary_end.offset).abs();
1748 if difference_a < difference_b {
1749 text_boundary.boundary_start
1750 } else {
1751 text_boundary.boundary_end
1752 }
1753 }
1754
1755 fn is_placeholder(self: Handle<Self>, app: &App) -> bool {
1756 let mut current = app.get(self).paragraph.as_object().parent(app);
1757 while let Some(object) = current {
1758 if object.downcast::<RenderParagraph>(app).is_some() {
1759 return true;
1760 }
1761 current = object.parent(app);
1762 }
1763 false
1764 }
1765
1766 fn get_origin_paragraph(self: Handle<Self>, app: &App) -> RenderHandle<RenderParagraph> {
1767 debug_assert!(app.get(self).selectable_contains_origin_text_boundary);
1768 let paragraph = app.get(self).paragraph;
1769 let mut current = paragraph.as_object().parent(app);
1770 let mut origin_paragraph = None;
1771 while let Some(object) = current {
1772 if let Some(candidate) = object.downcast::<RenderParagraph>(app) {
1773 if let Some(fragments) = &app.get(candidate.handle()).last_selectable_fragments {
1774 let mut paragraph_contains_origin = false;
1775 for fragment in fragments {
1776 if app.get(fragment).selectable_contains_origin_text_boundary {
1777 paragraph_contains_origin = true;
1778 origin_paragraph = Some(candidate);
1779 break;
1780 }
1781 }
1782 if !paragraph_contains_origin {
1783 return origin_paragraph.unwrap_or(paragraph);
1784 }
1785 }
1786 }
1787 current = object.parent(app);
1788 }
1789 origin_paragraph.unwrap_or(paragraph)
1790 }
1791
1792 fn get_paragraph_containing_position(
1793 self: Handle<Self>,
1794 app: &App,
1795 global_position: Offset,
1796 ) -> Option<(RenderHandle<RenderParagraph>, Offset)> {
1797 let mut current = Some(app.get(self).paragraph.as_object());
1798 while let Some(object) = current {
1799 if let Some(paragraph) = object.downcast::<RenderParagraph>(app) {
1800 let local = global_to_paragraph(app, paragraph, global_position);
1801 if paragraph.as_object().paint_bounds(app).contains(local) {
1802 return Some((paragraph, local));
1803 }
1804 }
1805 current = object.parent(app);
1806 }
1807 None
1808 }
1809
1810 fn bounding_boxes_contain(self: Handle<Self>, app: &mut App, position: Offset) -> bool {
1811 self.bounding_boxes(app)
1812 .iter()
1813 .any(|rect| rect.contains(position))
1814 }
1815
1816 fn clamp_text_position(self: Handle<Self>, app: &App, position: TextPosition) -> TextPosition {
1817 let range = app.get(self).range;
1818 if position.offset > range.end
1819 || (position.offset == range.end && position.affinity == TextAffinity::Downstream)
1820 {
1821 return TextPosition::with_affinity(range.end, TextAffinity::Upstream);
1822 }
1823 if position.offset < range.start {
1824 return TextPosition::new(range.start);
1825 }
1826 position
1827 }
1828
1829 fn compare_text_positions(position: TextPosition, other_position: TextPosition) -> i32 {
1830 if position.offset < other_position.offset {
1831 1
1832 } else if position.offset > other_position.offset {
1833 -1
1834 } else if position.affinity == other_position.affinity {
1835 0
1836 } else if position.affinity == TextAffinity::Upstream {
1837 1
1838 } else {
1839 -1
1840 }
1841 }
1842
1843 fn position_is_within_current_selection(
1844 self: Handle<Self>,
1845 app: &App,
1846 position: TextPosition,
1847 ) -> bool {
1848 let (Some(start), Some(end)) = (
1849 app.get(self).text_selection_start,
1850 app.get(self).text_selection_end,
1851 ) else {
1852 return false;
1853 };
1854 let (current_start, current_end) = if Self::compare_text_positions(start, end) > 0 {
1855 (start, end)
1856 } else {
1857 (end, start)
1858 };
1859 Self::compare_text_positions(current_start, position) >= 0
1860 && Self::compare_text_positions(current_end, position) <= 0
1861 }
1862
1863 fn rect(self: Handle<Self>, app: &mut App) -> Rect {
1864 if let Some(cached) = app.get(self).cached_rect {
1865 return cached;
1866 }
1867 let range = app.get(self).range;
1868 let paragraph = app.get(self).paragraph;
1869 let boxes = paragraph.get_boxes_for_selection(
1870 app,
1871 TextSelection::new(range.start, range.end),
1872 BoxHeightStyle::Max,
1873 BoxWidthStyle::Tight,
1874 );
1875 let rect = if let Some(first) = boxes.first() {
1876 boxes
1877 .iter()
1878 .skip(1)
1879 .fold(first.to_rect(), |result, text_box| {
1880 result.expand_to_include(text_box.to_rect())
1881 })
1882 } else {
1883 let offset = paragraph.get_offset_for_position(app, TextPosition::new(range.start));
1884 let line_height = paragraph.preferred_line_height(app);
1885 Rect::from_ltrb(
1886 offset.dx(),
1887 offset.dy() - line_height,
1888 offset.dx(),
1889 offset.dy(),
1890 )
1891 };
1892 app.get_mut(self).cached_rect = Some(rect);
1893 rect
1894 }
1895
1896 fn did_change_paragraph_layout(self: Handle<Self>, app: &mut App) {
1898 let this = app.get_mut(self);
1899 this.cached_rect = None;
1900 this.cached_bounding_boxes = None;
1901 }
1902
1903 fn local_position(self: Handle<Self>, app: &App, global_position: Offset) -> Offset {
1905 let paragraph = app.get(self).paragraph;
1906 global_to_paragraph(app, paragraph, global_position)
1907 }
1908
1909 fn update_selection_edge(
1910 self: Handle<Self>,
1911 app: &mut App,
1912 global_position: Offset,
1913 is_end: bool,
1914 ) -> SelectionResult {
1915 self.set_selection_position(app, None, is_end);
1916 let local_position = self.local_position(app, global_position);
1917 let rect = self.rect(app);
1918 let range = app.get(self).range;
1919 if rect.is_empty() {
1920 let result = SelectionUtils::get_result_based_on_rect(rect, local_position);
1921 let position = if result == SelectionResult::Next {
1922 TextPosition::new(range.end)
1923 } else {
1924 TextPosition::with_affinity(range.start, TextAffinity::Upstream)
1925 };
1926 self.set_selection_position(app, Some(position), is_end);
1927 return result;
1928 }
1929 let direction = app.get(self).paragraph.text_direction(app);
1930 let adjusted_offset = SelectionUtils::adjust_drag_offset(rect, local_position, direction);
1931 let paragraph = app.get(self).paragraph;
1932 let position = paragraph.get_position_for_offset(app, adjusted_offset);
1933 let position = self.clamp_text_position(app, position);
1934 self.set_selection_position(app, Some(position), is_end);
1935 if position.offset == range.end {
1936 return SelectionResult::Next;
1937 }
1938 if position.offset == range.start {
1939 return SelectionResult::Previous;
1940 }
1941 SelectionUtils::get_result_based_on_rect(rect, local_position)
1942 }
1943
1944 fn update_selection_edge_by_text_boundary(
1945 self: Handle<Self>,
1946 app: &mut App,
1947 global_position: Offset,
1948 is_end: bool,
1949 get_text_boundary: TextBoundaryAtPosition,
1950 ) -> SelectionResult {
1951 let existing_selection_start = app.get(self).text_selection_start;
1952 let existing_selection_end = app.get(self).text_selection_end;
1953 self.set_selection_position(app, None, is_end);
1954 let local_position = self.local_position(app, global_position);
1955 let rect = self.rect(app);
1956 let range = app.get(self).range;
1957 if rect.is_empty() {
1958 let result = SelectionUtils::get_result_based_on_rect(rect, local_position);
1959 let position = if result == SelectionResult::Next {
1960 TextPosition::new(range.end)
1961 } else {
1962 TextPosition::with_affinity(range.start, TextAffinity::Upstream)
1963 };
1964 self.set_selection_position(app, Some(position), is_end);
1965 return result;
1966 }
1967 let direction = app.get(self).paragraph.text_direction(app);
1968 let adjusted_offset = SelectionUtils::adjust_drag_offset(rect, local_position, direction);
1969 let paragraph = app.get(self).paragraph;
1970 let position = paragraph.get_position_for_offset(app, adjusted_offset);
1971 let mut text_boundary = if rect.contains(local_position) {
1972 Some(get_text_boundary(self, app, position))
1973 } else {
1974 None
1975 };
1976 if let Some(boundary) = text_boundary {
1977 if (boundary.boundary_start.offset < range.start
1978 && boundary.boundary_end.offset <= range.start)
1979 || (boundary.boundary_start.offset >= range.end
1980 && boundary.boundary_end.offset > range.end)
1981 {
1982 text_boundary = None;
1983 }
1984 }
1985 let edge_position = if is_end {
1986 self.update_selection_end_edge_by_text_boundary(
1987 app,
1988 text_boundary,
1989 get_text_boundary,
1990 position,
1991 existing_selection_start,
1992 existing_selection_end,
1993 )
1994 } else {
1995 self.update_selection_start_edge_by_text_boundary(
1996 app,
1997 text_boundary,
1998 get_text_boundary,
1999 position,
2000 existing_selection_start,
2001 existing_selection_end,
2002 )
2003 };
2004 let target_position = self.clamp_text_position(app, edge_position);
2005 self.set_selection_position(app, Some(target_position), is_end);
2006 if target_position.offset == range.end {
2007 return SelectionResult::Next;
2008 }
2009 if target_position.offset == range.start {
2010 return SelectionResult::Previous;
2011 }
2012 SelectionUtils::get_result_based_on_rect(rect, local_position)
2013 }
2014
2015 fn update_selection_start_edge_by_text_boundary(
2016 self: Handle<Self>,
2017 app: &mut App,
2018 text_boundary: Option<TextBoundaryRecord>,
2019 get_text_boundary: TextBoundaryAtPosition,
2020 position: TextPosition,
2021 existing_selection_start: Option<TextPosition>,
2022 existing_selection_end: Option<TextPosition>,
2023 ) -> TextPosition {
2024 let range = app.get(self).range;
2025 let contains_origin = app.get(self).selectable_contains_origin_text_boundary;
2026 let mut target_position = None;
2027
2028 if contains_origin
2029 && existing_selection_start.is_some()
2030 && existing_selection_end.is_some()
2031 && text_boundary.is_some()
2032 {
2033 let text_boundary = text_boundary.unwrap();
2034 let existing_start = existing_selection_start.unwrap();
2035 let existing_end = existing_selection_end.unwrap();
2036 debug_assert!(
2037 text_boundary.boundary_start.offset >= range.start
2038 && text_boundary.boundary_end.offset <= range.end
2039 );
2040 let is_same_position = position.offset == existing_end.offset;
2041 let is_selection_inverted = existing_start.offset > existing_end.offset;
2042 let should_swap_edges = !is_same_position
2043 && (is_selection_inverted != (position.offset > existing_end.offset));
2044 if should_swap_edges {
2045 target_position = Some(if position.offset < existing_end.offset {
2046 text_boundary.boundary_start
2047 } else {
2048 text_boundary.boundary_end
2049 });
2050 let local_text_boundary = get_text_boundary(self, app, existing_end);
2051 debug_assert!(
2052 local_text_boundary.boundary_start.offset >= range.start
2053 && local_text_boundary.boundary_end.offset <= range.end
2054 );
2055 self.set_selection_position(
2056 app,
2057 Some(
2058 if existing_end.offset == local_text_boundary.boundary_start.offset {
2059 local_text_boundary.boundary_end
2060 } else {
2061 local_text_boundary.boundary_start
2062 },
2063 ),
2064 true,
2065 );
2066 } else if position.offset < existing_end.offset {
2067 target_position = Some(text_boundary.boundary_start);
2068 } else if position.offset > existing_end.offset {
2069 target_position = Some(text_boundary.boundary_end);
2070 } else {
2071 target_position = Some(existing_start);
2072 }
2073 } else if let Some(text_boundary) = text_boundary {
2074 if let Some(existing_end) = existing_selection_end {
2075 if position.offset < existing_end.offset {
2076 target_position = Some(text_boundary.boundary_start);
2077 } else {
2078 target_position = Some(text_boundary.boundary_end);
2079 }
2080 } else {
2081 target_position = Some(Self::closest_text_boundary(text_boundary, position));
2082 }
2083 } else if contains_origin
2084 && existing_selection_start.is_some()
2085 && existing_selection_end.is_some()
2086 {
2087 let existing_start = existing_selection_start.unwrap();
2088 let existing_end = existing_selection_end.unwrap();
2089 let is_same_position = position.offset == existing_end.offset;
2090 let is_selection_inverted = existing_start.offset > existing_end.offset;
2091 let should_swap_edges = !is_same_position
2092 && (is_selection_inverted != (position.offset > existing_end.offset));
2093 if should_swap_edges {
2094 let local_text_boundary = get_text_boundary(self, app, existing_end);
2095 debug_assert!(
2096 local_text_boundary.boundary_start.offset >= range.start
2097 && local_text_boundary.boundary_end.offset <= range.end
2098 );
2099 self.set_selection_position(
2100 app,
2101 Some(if is_selection_inverted {
2102 local_text_boundary.boundary_end
2103 } else {
2104 local_text_boundary.boundary_start
2105 }),
2106 true,
2107 );
2108 }
2109 }
2110 target_position.unwrap_or(position)
2111 }
2112
2113 fn update_selection_end_edge_by_text_boundary(
2114 self: Handle<Self>,
2115 app: &mut App,
2116 text_boundary: Option<TextBoundaryRecord>,
2117 get_text_boundary: TextBoundaryAtPosition,
2118 position: TextPosition,
2119 existing_selection_start: Option<TextPosition>,
2120 existing_selection_end: Option<TextPosition>,
2121 ) -> TextPosition {
2122 let range = app.get(self).range;
2123 let contains_origin = app.get(self).selectable_contains_origin_text_boundary;
2124 let mut target_position = None;
2125
2126 if contains_origin
2127 && existing_selection_start.is_some()
2128 && existing_selection_end.is_some()
2129 && text_boundary.is_some()
2130 {
2131 let text_boundary = text_boundary.unwrap();
2132 let existing_start = existing_selection_start.unwrap();
2133 let existing_end = existing_selection_end.unwrap();
2134 debug_assert!(
2135 text_boundary.boundary_start.offset >= range.start
2136 && text_boundary.boundary_end.offset <= range.end
2137 );
2138 let is_same_position = position.offset == existing_start.offset;
2139 let is_selection_inverted = existing_start.offset > existing_end.offset;
2140 let should_swap_edges = !is_same_position
2141 && (is_selection_inverted != (position.offset < existing_start.offset));
2142 if should_swap_edges {
2143 target_position = Some(if position.offset < existing_start.offset {
2144 text_boundary.boundary_start
2145 } else {
2146 text_boundary.boundary_end
2147 });
2148 let local_text_boundary = get_text_boundary(self, app, existing_start);
2149 debug_assert!(
2150 local_text_boundary.boundary_start.offset >= range.start
2151 && local_text_boundary.boundary_end.offset <= range.end
2152 );
2153 self.set_selection_position(
2154 app,
2155 Some(
2156 if existing_start.offset == local_text_boundary.boundary_start.offset {
2157 local_text_boundary.boundary_end
2158 } else {
2159 local_text_boundary.boundary_start
2160 },
2161 ),
2162 false,
2163 );
2164 } else if position.offset < existing_start.offset {
2165 target_position = Some(text_boundary.boundary_start);
2166 } else if position.offset > existing_start.offset {
2167 target_position = Some(text_boundary.boundary_end);
2168 } else {
2169 target_position = Some(existing_end);
2170 }
2171 } else if let Some(text_boundary) = text_boundary {
2172 if let Some(existing_start) = existing_selection_start {
2173 if position.offset < existing_start.offset {
2174 target_position = Some(text_boundary.boundary_start);
2175 } else {
2176 target_position = Some(text_boundary.boundary_end);
2177 }
2178 } else {
2179 target_position = Some(Self::closest_text_boundary(text_boundary, position));
2180 }
2181 } else if contains_origin
2182 && existing_selection_start.is_some()
2183 && existing_selection_end.is_some()
2184 {
2185 let existing_start = existing_selection_start.unwrap();
2186 let existing_end = existing_selection_end.unwrap();
2187 let is_same_position = position.offset == existing_start.offset;
2188 let is_selection_inverted = existing_start.offset > existing_end.offset;
2189 let should_swap_edges = is_selection_inverted
2190 != (position.offset < existing_start.offset)
2191 || is_same_position;
2192 if should_swap_edges {
2193 let local_text_boundary = get_text_boundary(self, app, existing_start);
2194 debug_assert!(
2195 local_text_boundary.boundary_start.offset >= range.start
2196 && local_text_boundary.boundary_end.offset <= range.end
2197 );
2198 self.set_selection_position(
2199 app,
2200 Some(if is_selection_inverted {
2201 local_text_boundary.boundary_start
2202 } else {
2203 local_text_boundary.boundary_end
2204 }),
2205 false,
2206 );
2207 }
2208 }
2209 target_position.unwrap_or(position)
2210 }
2211
2212 fn update_selection_start_edge_by_multi_selectable_text_boundary(
2213 self: Handle<Self>,
2214 app: &mut App,
2215 get_text_boundary: TextBoundaryAtPositionInText,
2216 paragraph_contains_position: bool,
2217 position: TextPosition,
2218 existing_selection_start: Option<TextPosition>,
2219 existing_selection_end: Option<TextPosition>,
2220 ) -> Option<SelectionResult> {
2221 let is_end = false;
2222 let range = app.get(self).range;
2223 let full_text = app.get(self).full_text.clone();
2224 if app.get(self).selectable_contains_origin_text_boundary
2225 && existing_selection_start.is_some()
2226 && existing_selection_end.is_some()
2227 {
2228 let existing_start = existing_selection_start.unwrap();
2229 let existing_end = existing_selection_end.unwrap();
2230 let forward_selection = existing_end.offset >= existing_start.offset;
2231 if paragraph_contains_position {
2232 let boundary_at_position = get_text_boundary(self, app, position, &full_text);
2233 let origin_text_boundary = get_text_boundary(
2234 self,
2235 app,
2236 if forward_selection {
2237 TextPosition::with_affinity(existing_end.offset - 1, existing_end.affinity)
2238 } else {
2239 existing_end
2240 },
2241 &full_text,
2242 );
2243 let pivot_offset = if forward_selection {
2244 origin_text_boundary.boundary_end.offset
2245 } else {
2246 origin_text_boundary.boundary_start.offset
2247 };
2248 let should_swap_edges = !forward_selection != (position.offset > pivot_offset);
2249 let target_position = if position.offset < pivot_offset {
2250 boundary_at_position.boundary_start
2251 } else if position.offset > pivot_offset {
2252 boundary_at_position.boundary_end
2253 } else {
2254 if forward_selection {
2255 existing_start
2256 } else {
2257 existing_end
2258 }
2259 };
2260 if should_swap_edges {
2261 let clamped = self.clamp_text_position(
2262 app,
2263 if forward_selection {
2264 origin_text_boundary.boundary_start
2265 } else {
2266 origin_text_boundary.boundary_end
2267 },
2268 );
2269 self.set_selection_position(app, Some(clamped), true);
2270 }
2271 let clamped = self.clamp_text_position(app, target_position);
2272 self.set_selection_position(app, Some(clamped), is_end);
2273 let final_selection_is_forward = app.get(self).text_selection_end.unwrap().offset
2274 >= app.get(self).text_selection_start.unwrap().offset;
2275 if boundary_at_position.boundary_start.offset > range.end
2276 && boundary_at_position.boundary_end.offset > range.end
2277 {
2278 return Some(SelectionResult::Next);
2279 }
2280 if boundary_at_position.boundary_start.offset < range.start
2281 && boundary_at_position.boundary_end.offset < range.start
2282 {
2283 return Some(SelectionResult::Previous);
2284 }
2285 if final_selection_is_forward {
2286 if boundary_at_position.boundary_start.offset
2287 >= origin_text_boundary.boundary_start.offset
2288 {
2289 return Some(SelectionResult::End);
2290 }
2291 if boundary_at_position.boundary_start.offset
2292 < origin_text_boundary.boundary_start.offset
2293 {
2294 return Some(SelectionResult::Previous);
2295 }
2296 } else {
2297 if boundary_at_position.boundary_end.offset
2298 <= origin_text_boundary.boundary_end.offset
2299 {
2300 return Some(SelectionResult::End);
2301 }
2302 if boundary_at_position.boundary_end.offset
2303 > origin_text_boundary.boundary_end.offset
2304 {
2305 return Some(SelectionResult::Next);
2306 }
2307 }
2308 } else {
2309 let clamped_position = self.clamp_text_position(app, position);
2310 let origin_text_boundary = get_text_boundary(
2311 self,
2312 app,
2313 if forward_selection {
2314 TextPosition::with_affinity(existing_end.offset - 1, existing_end.affinity)
2315 } else {
2316 existing_end
2317 },
2318 &full_text,
2319 );
2320 if forward_selection && clamped_position.offset == range.start {
2321 self.set_selection_position(app, Some(clamped_position), is_end);
2322 return Some(SelectionResult::Previous);
2323 }
2324 if !forward_selection && clamped_position.offset == range.end {
2325 self.set_selection_position(app, Some(clamped_position), is_end);
2326 return Some(SelectionResult::Next);
2327 }
2328 if forward_selection && clamped_position.offset == range.end {
2329 let clamped =
2330 self.clamp_text_position(app, origin_text_boundary.boundary_start);
2331 self.set_selection_position(app, Some(clamped), true);
2332 self.set_selection_position(app, Some(clamped_position), is_end);
2333 return Some(SelectionResult::Next);
2334 }
2335 if !forward_selection && clamped_position.offset == range.start {
2336 let clamped = self.clamp_text_position(app, origin_text_boundary.boundary_end);
2337 self.set_selection_position(app, Some(clamped), true);
2338 self.set_selection_position(app, Some(clamped_position), is_end);
2339 return Some(SelectionResult::Previous);
2340 }
2341 }
2342 } else {
2343 let position_on_placeholder = app
2344 .get(self)
2345 .paragraph
2346 .get_word_boundary(app, position)
2347 .text_inside(&full_text)
2348 == "\u{FFFC}";
2349 if !paragraph_contains_position || position_on_placeholder {
2350 return None;
2351 }
2352 if let Some(existing_end) = existing_selection_end {
2353 let boundary_at_position = get_text_boundary(self, app, position, &full_text);
2354 let backward_selection = (existing_selection_start.is_none()
2355 && existing_end.offset == range.start)
2356 || (existing_selection_start == existing_selection_end
2357 && existing_end.offset == range.start)
2358 || (existing_selection_start.is_some()
2359 && existing_selection_start.unwrap().offset > existing_end.offset);
2360 if boundary_at_position.boundary_start.offset < range.start
2361 && boundary_at_position.boundary_end.offset < range.start
2362 {
2363 self.set_selection_position(app, Some(TextPosition::new(range.start)), is_end);
2364 return Some(SelectionResult::Previous);
2365 }
2366 if boundary_at_position.boundary_start.offset > range.end
2367 && boundary_at_position.boundary_end.offset > range.end
2368 {
2369 self.set_selection_position(app, Some(TextPosition::new(range.end)), is_end);
2370 return Some(SelectionResult::Next);
2371 }
2372 if backward_selection {
2373 if boundary_at_position.boundary_end.offset <= range.end {
2374 let clamped =
2375 self.clamp_text_position(app, boundary_at_position.boundary_end);
2376 self.set_selection_position(app, Some(clamped), is_end);
2377 return Some(SelectionResult::End);
2378 }
2379 if boundary_at_position.boundary_end.offset > range.end {
2380 self.set_selection_position(
2381 app,
2382 Some(TextPosition::new(range.end)),
2383 is_end,
2384 );
2385 return Some(SelectionResult::Next);
2386 }
2387 } else {
2388 let clamped =
2389 self.clamp_text_position(app, boundary_at_position.boundary_start);
2390 self.set_selection_position(app, Some(clamped), is_end);
2391 if boundary_at_position.boundary_start.offset < range.start {
2392 return Some(SelectionResult::Previous);
2393 }
2394 if boundary_at_position.boundary_start.offset >= range.start {
2395 return Some(SelectionResult::End);
2396 }
2397 }
2398 }
2399 }
2400 None
2401 }
2402
2403 fn update_selection_end_edge_by_multi_selectable_text_boundary(
2404 self: Handle<Self>,
2405 app: &mut App,
2406 get_text_boundary: TextBoundaryAtPositionInText,
2407 paragraph_contains_position: bool,
2408 position: TextPosition,
2409 existing_selection_start: Option<TextPosition>,
2410 existing_selection_end: Option<TextPosition>,
2411 ) -> Option<SelectionResult> {
2412 let is_end = true;
2413 let range = app.get(self).range;
2414 let full_text = app.get(self).full_text.clone();
2415 if app.get(self).selectable_contains_origin_text_boundary
2416 && existing_selection_start.is_some()
2417 && existing_selection_end.is_some()
2418 {
2419 let existing_start = existing_selection_start.unwrap();
2420 let existing_end = existing_selection_end.unwrap();
2421 let forward_selection = existing_end.offset >= existing_start.offset;
2422 if paragraph_contains_position {
2423 let boundary_at_position = get_text_boundary(self, app, position, &full_text);
2424 let origin_text_boundary = get_text_boundary(
2425 self,
2426 app,
2427 if forward_selection {
2428 existing_start
2429 } else {
2430 TextPosition::with_affinity(
2431 existing_start.offset - 1,
2432 existing_start.affinity,
2433 )
2434 },
2435 &full_text,
2436 );
2437 let pivot_offset = if forward_selection {
2438 origin_text_boundary.boundary_start.offset
2439 } else {
2440 origin_text_boundary.boundary_end.offset
2441 };
2442 let should_swap_edges = !forward_selection != (position.offset < pivot_offset);
2443 let target_position = if position.offset < pivot_offset {
2444 boundary_at_position.boundary_start
2445 } else if position.offset > pivot_offset {
2446 boundary_at_position.boundary_end
2447 } else {
2448 if forward_selection {
2449 existing_end
2450 } else {
2451 existing_start
2452 }
2453 };
2454 if should_swap_edges {
2455 let clamped = self.clamp_text_position(
2456 app,
2457 if forward_selection {
2458 origin_text_boundary.boundary_end
2459 } else {
2460 origin_text_boundary.boundary_start
2461 },
2462 );
2463 self.set_selection_position(app, Some(clamped), false);
2464 }
2465 let clamped = self.clamp_text_position(app, target_position);
2466 self.set_selection_position(app, Some(clamped), is_end);
2467 let final_selection_is_forward = app.get(self).text_selection_end.unwrap().offset
2468 >= app.get(self).text_selection_start.unwrap().offset;
2469 if boundary_at_position.boundary_start.offset > range.end
2470 && boundary_at_position.boundary_end.offset > range.end
2471 {
2472 return Some(SelectionResult::Next);
2473 }
2474 if boundary_at_position.boundary_start.offset < range.start
2475 && boundary_at_position.boundary_end.offset < range.start
2476 {
2477 return Some(SelectionResult::Previous);
2478 }
2479 if final_selection_is_forward {
2480 if boundary_at_position.boundary_end.offset
2481 <= origin_text_boundary.boundary_end.offset
2482 {
2483 return Some(SelectionResult::End);
2484 }
2485 if boundary_at_position.boundary_end.offset
2486 > origin_text_boundary.boundary_end.offset
2487 {
2488 return Some(SelectionResult::Next);
2489 }
2490 } else {
2491 if boundary_at_position.boundary_start.offset
2492 >= origin_text_boundary.boundary_start.offset
2493 {
2494 return Some(SelectionResult::End);
2495 }
2496 if boundary_at_position.boundary_start.offset
2497 < origin_text_boundary.boundary_start.offset
2498 {
2499 return Some(SelectionResult::Previous);
2500 }
2501 }
2502 } else {
2503 let clamped_position = self.clamp_text_position(app, position);
2504 let origin_text_boundary = get_text_boundary(
2505 self,
2506 app,
2507 if forward_selection {
2508 existing_start
2509 } else {
2510 TextPosition::with_affinity(
2511 existing_start.offset - 1,
2512 existing_start.affinity,
2513 )
2514 },
2515 &full_text,
2516 );
2517 if forward_selection && clamped_position.offset == range.start {
2518 let clamped = self.clamp_text_position(app, origin_text_boundary.boundary_end);
2519 self.set_selection_position(app, Some(clamped), false);
2520 self.set_selection_position(app, Some(clamped_position), is_end);
2521 return Some(SelectionResult::Previous);
2522 }
2523 if !forward_selection && clamped_position.offset == range.end {
2524 let clamped =
2525 self.clamp_text_position(app, origin_text_boundary.boundary_start);
2526 self.set_selection_position(app, Some(clamped), false);
2527 self.set_selection_position(app, Some(clamped_position), is_end);
2528 return Some(SelectionResult::Next);
2529 }
2530 if forward_selection && clamped_position.offset == range.end {
2531 self.set_selection_position(app, Some(clamped_position), is_end);
2532 return Some(SelectionResult::Next);
2533 }
2534 if !forward_selection && clamped_position.offset == range.start {
2535 self.set_selection_position(app, Some(clamped_position), is_end);
2536 return Some(SelectionResult::Previous);
2537 }
2538 }
2539 } else {
2540 let position_on_placeholder = app
2541 .get(self)
2542 .paragraph
2543 .get_word_boundary(app, position)
2544 .text_inside(&full_text)
2545 == "\u{FFFC}";
2546 if !paragraph_contains_position || position_on_placeholder {
2547 return None;
2548 }
2549 if let Some(existing_start) = existing_selection_start {
2550 let boundary_at_position = get_text_boundary(self, app, position, &full_text);
2551 let backward_selection = (existing_selection_end.is_none()
2552 && existing_start.offset == range.end)
2553 || (existing_selection_start == existing_selection_end
2554 && existing_start.offset == range.end)
2555 || (existing_selection_end.is_some()
2556 && existing_start.offset > existing_selection_end.unwrap().offset);
2557 if boundary_at_position.boundary_start.offset < range.start
2558 && boundary_at_position.boundary_end.offset < range.start
2559 {
2560 self.set_selection_position(app, Some(TextPosition::new(range.start)), is_end);
2561 return Some(SelectionResult::Previous);
2562 }
2563 if boundary_at_position.boundary_start.offset > range.end
2564 && boundary_at_position.boundary_end.offset > range.end
2565 {
2566 self.set_selection_position(app, Some(TextPosition::new(range.end)), is_end);
2567 return Some(SelectionResult::Next);
2568 }
2569 if backward_selection {
2570 let clamped =
2571 self.clamp_text_position(app, boundary_at_position.boundary_start);
2572 self.set_selection_position(app, Some(clamped), is_end);
2573 if boundary_at_position.boundary_start.offset < range.start {
2574 return Some(SelectionResult::Previous);
2575 }
2576 if boundary_at_position.boundary_start.offset >= range.start {
2577 return Some(SelectionResult::End);
2578 }
2579 } else {
2580 if boundary_at_position.boundary_end.offset <= range.end {
2581 let clamped =
2582 self.clamp_text_position(app, boundary_at_position.boundary_end);
2583 self.set_selection_position(app, Some(clamped), is_end);
2584 return Some(SelectionResult::End);
2585 }
2586 if boundary_at_position.boundary_end.offset > range.end {
2587 self.set_selection_position(
2588 app,
2589 Some(TextPosition::new(range.end)),
2590 is_end,
2591 );
2592 return Some(SelectionResult::Next);
2593 }
2594 }
2595 }
2596 }
2597 None
2598 }
2599
2600 fn update_selection_edge_by_multi_selectable_text_boundary(
2601 self: Handle<Self>,
2602 app: &mut App,
2603 global_position: Offset,
2604 is_end: bool,
2605 get_text_boundary: TextBoundaryAtPositionInText,
2606 ) -> SelectionResult {
2607 let existing_selection_start = app.get(self).text_selection_start;
2608 let existing_selection_end = app.get(self).text_selection_end;
2609 self.set_selection_position(app, None, is_end);
2610 let local_position = self.local_position(app, global_position);
2611 let rect = self.rect(app);
2612 let range = app.get(self).range;
2613 if rect.is_empty() {
2614 let result = SelectionUtils::get_result_based_on_rect(rect, local_position);
2615 let position = if result == SelectionResult::Next {
2616 TextPosition::new(range.end)
2617 } else {
2618 TextPosition::with_affinity(range.start, TextAffinity::Upstream)
2619 };
2620 self.set_selection_position(app, Some(position), is_end);
2621 return result;
2622 }
2623 let paragraph = app.get(self).paragraph;
2624 let direction = paragraph.text_direction(app);
2625 let adjusted_offset = SelectionUtils::adjust_drag_offset(rect, local_position, direction);
2626 let paint_bounds = paragraph.as_object().paint_bounds(app);
2627 let adjusted_offset_relative_to_paragraph =
2628 SelectionUtils::adjust_drag_offset(paint_bounds, local_position, direction);
2629 let position = paragraph.get_position_for_offset(app, adjusted_offset);
2630 let position_in_full_text =
2631 paragraph.get_position_for_offset(app, adjusted_offset_relative_to_paragraph);
2632 let paragraph_contains_position = paint_bounds.contains(local_position);
2633 let result = if self.is_placeholder(app) {
2634 if is_end {
2635 self.update_selection_end_edge_at_placeholder(
2636 app,
2637 get_text_boundary,
2638 global_position,
2639 paragraph_contains_position,
2640 position_in_full_text,
2641 existing_selection_start,
2642 existing_selection_end,
2643 )
2644 } else {
2645 self.update_selection_start_edge_at_placeholder(
2646 app,
2647 get_text_boundary,
2648 global_position,
2649 paragraph_contains_position,
2650 position_in_full_text,
2651 existing_selection_start,
2652 existing_selection_end,
2653 )
2654 }
2655 } else if is_end {
2656 self.update_selection_end_edge_by_multi_selectable_text_boundary(
2657 app,
2658 get_text_boundary,
2659 paragraph_contains_position,
2660 position_in_full_text,
2661 existing_selection_start,
2662 existing_selection_end,
2663 )
2664 } else {
2665 self.update_selection_start_edge_by_multi_selectable_text_boundary(
2666 app,
2667 get_text_boundary,
2668 paragraph_contains_position,
2669 position_in_full_text,
2670 existing_selection_start,
2671 existing_selection_end,
2672 )
2673 };
2674 if let Some(result) = result {
2675 return result;
2676 }
2677 let mut text_boundary = if self.bounding_boxes_contain(app, local_position) {
2678 Some(self.get_clamped_paragraph_boundary_at_position(app, position))
2679 } else {
2680 None
2681 };
2682 if let Some(boundary) = text_boundary {
2683 if (boundary.boundary_start.offset < range.start
2684 && boundary.boundary_end.offset <= range.start)
2685 || (boundary.boundary_start.offset >= range.end
2686 && boundary.boundary_end.offset > range.end)
2687 {
2688 text_boundary = None;
2689 }
2690 }
2691 let edge_position = if is_end {
2692 self.update_selection_end_edge_by_text_boundary(
2693 app,
2694 text_boundary,
2695 Self::get_clamped_paragraph_boundary_at_position,
2696 position,
2697 existing_selection_start,
2698 existing_selection_end,
2699 )
2700 } else {
2701 self.update_selection_start_edge_by_text_boundary(
2702 app,
2703 text_boundary,
2704 Self::get_clamped_paragraph_boundary_at_position,
2705 position,
2706 existing_selection_start,
2707 existing_selection_end,
2708 )
2709 };
2710 let target_position = self.clamp_text_position(app, edge_position);
2711 self.set_selection_position(app, Some(target_position), is_end);
2712 if target_position.offset == range.end {
2713 return SelectionResult::Next;
2714 }
2715 if target_position.offset == range.start {
2716 return SelectionResult::Previous;
2717 }
2718 SelectionUtils::get_result_based_on_rect(rect, local_position)
2719 }
2720
2721 fn update_selection_start_edge_at_placeholder(
2722 self: Handle<Self>,
2723 app: &mut App,
2724 get_text_boundary: TextBoundaryAtPositionInText,
2725 global_position: Offset,
2726 paragraph_contains_position: bool,
2727 position: TextPosition,
2728 existing_selection_start: Option<TextPosition>,
2729 existing_selection_end: Option<TextPosition>,
2730 ) -> Option<SelectionResult> {
2731 let is_end = false;
2732 let range = app.get(self).range;
2733 if app.get(self).selectable_contains_origin_text_boundary
2734 && existing_selection_start.is_some()
2735 && existing_selection_end.is_some()
2736 {
2737 let existing_start = existing_selection_start.unwrap();
2738 let existing_end = existing_selection_end.unwrap();
2739 let forward_selection = existing_end.offset >= existing_start.offset;
2740 let origin_paragraph = self.get_origin_paragraph(app);
2741 if origin_paragraph == app.get(self).paragraph {
2742 return self.update_selection_start_edge_by_multi_selectable_text_boundary(
2743 app,
2744 get_text_boundary,
2745 paragraph_contains_position,
2746 position,
2747 existing_selection_start,
2748 existing_selection_end,
2749 );
2750 }
2751 let origin_local = global_to_paragraph(app, origin_paragraph, global_position);
2752 let within_origin = origin_paragraph
2753 .as_object()
2754 .paint_bounds(app)
2755 .contains(origin_local);
2756 let origin_position = origin_paragraph.get_position_for_offset(app, origin_local);
2757 if within_origin {
2758 let origin_text = origin_paragraph.text(app).to_plain_text(false, true);
2759 let boundary = get_text_boundary(self, app, origin_position, &origin_text);
2760 let origin_placeholder_position =
2761 self.get_position_in_paragraph(app, origin_paragraph);
2762 let origin_boundary =
2763 get_text_boundary(self, app, origin_placeholder_position, &origin_text);
2764 let pivot = if forward_selection {
2765 origin_boundary.boundary_end.offset
2766 } else {
2767 origin_boundary.boundary_start.offset
2768 };
2769 let swap = !forward_selection != (origin_position.offset > pivot);
2770 let target = if origin_position.offset < pivot {
2771 boundary.boundary_start
2772 } else if origin_position.offset > pivot {
2773 boundary.boundary_end
2774 } else {
2775 existing_start
2776 };
2777 if swap {
2778 self.set_selection_position(app, Some(existing_start), true);
2779 }
2780 let target = self.clamp_text_position(app, target);
2781 self.set_selection_position(app, Some(target), is_end);
2782 let forward = app.get(self).text_selection_end.unwrap().offset
2783 >= app.get(self).text_selection_start.unwrap().offset;
2784 let placeholder = self.get_position_in_paragraph(app, origin_paragraph);
2785 let placeholder_range = TextRange::new(placeholder.offset, placeholder.offset + 1);
2786 if boundary.boundary_start.offset > placeholder_range.end
2787 && boundary.boundary_end.offset > placeholder_range.end
2788 {
2789 return Some(SelectionResult::Next);
2790 }
2791 if boundary.boundary_start.offset < placeholder_range.start
2792 && boundary.boundary_end.offset < placeholder_range.start
2793 {
2794 return Some(SelectionResult::Previous);
2795 }
2796 if forward {
2797 if boundary.boundary_end.offset <= origin_boundary.boundary_end.offset {
2798 return Some(SelectionResult::End);
2799 }
2800 if boundary.boundary_end.offset > origin_boundary.boundary_end.offset {
2801 return Some(SelectionResult::Next);
2802 }
2803 } else {
2804 if boundary.boundary_start.offset >= origin_boundary.boundary_start.offset {
2805 return Some(SelectionResult::End);
2806 }
2807 if boundary.boundary_start.offset < origin_boundary.boundary_start.offset {
2808 return Some(SelectionResult::Previous);
2809 }
2810 }
2811 } else {
2812 let direction = app.get(self).paragraph.text_direction(app);
2813 let adjusted = SelectionUtils::adjust_drag_offset(
2814 origin_paragraph.as_object().paint_bounds(app),
2815 origin_local,
2816 direction,
2817 );
2818 let adjusted_position = origin_paragraph.get_position_for_offset(app, adjusted);
2819 let placeholder = self.get_position_in_paragraph(app, origin_paragraph);
2820 let placeholder_range = TextRange::new(placeholder.offset, placeholder.offset + 1);
2821 if forward_selection && adjusted_position.offset <= placeholder_range.start {
2822 self.set_selection_position(app, Some(TextPosition::new(range.start)), is_end);
2823 return Some(SelectionResult::Previous);
2824 }
2825 if !forward_selection && adjusted_position.offset >= placeholder_range.end {
2826 self.set_selection_position(app, Some(TextPosition::new(range.end)), is_end);
2827 return Some(SelectionResult::Next);
2828 }
2829 if forward_selection && adjusted_position.offset >= placeholder_range.end {
2830 self.set_selection_position(app, Some(existing_start), true);
2831 self.set_selection_position(app, Some(TextPosition::new(range.end)), is_end);
2832 return Some(SelectionResult::Next);
2833 }
2834 if !forward_selection && adjusted_position.offset <= placeholder_range.start {
2835 self.set_selection_position(app, Some(existing_start), true);
2836 self.set_selection_position(app, Some(TextPosition::new(range.start)), is_end);
2837 return Some(SelectionResult::Previous);
2838 }
2839 }
2840 } else {
2841 if paragraph_contains_position {
2842 return self.update_selection_start_edge_by_multi_selectable_text_boundary(
2843 app,
2844 get_text_boundary,
2845 paragraph_contains_position,
2846 position,
2847 existing_selection_start,
2848 existing_selection_end,
2849 );
2850 }
2851 if existing_selection_end.is_some() {
2852 let (target_paragraph, target_local) =
2853 self.get_paragraph_containing_position(app, global_position)?;
2854 let target_position = target_paragraph.get_position_for_offset(app, target_local);
2855 let target_text = target_paragraph.text(app).to_plain_text(false, true);
2856 if target_paragraph
2857 .get_word_boundary(app, target_position)
2858 .text_inside(&target_text)
2859 == "\u{FFFC}"
2860 {
2861 return None;
2862 }
2863 let existing_end = existing_selection_end.unwrap();
2864 let backward = (existing_selection_start.is_none()
2865 && existing_end.offset == range.start)
2866 || (existing_selection_start == existing_selection_end
2867 && existing_end.offset == range.start)
2868 || (existing_selection_start.is_some()
2869 && existing_selection_start.unwrap().offset > existing_end.offset);
2870 let boundary = get_text_boundary(self, app, target_position, &target_text);
2871 let placeholder = self.get_position_in_paragraph(app, target_paragraph);
2872 let placeholder_range = TextRange::new(placeholder.offset, placeholder.offset + 1);
2873 if boundary.boundary_start.offset < placeholder_range.start
2874 && boundary.boundary_end.offset < placeholder_range.start
2875 {
2876 self.set_selection_position(app, Some(TextPosition::new(range.start)), is_end);
2877 return Some(SelectionResult::Previous);
2878 }
2879 if boundary.boundary_start.offset > placeholder_range.end
2880 && boundary.boundary_end.offset > placeholder_range.end
2881 {
2882 self.set_selection_position(app, Some(TextPosition::new(range.end)), is_end);
2883 return Some(SelectionResult::Next);
2884 }
2885 if backward {
2886 if boundary.boundary_end.offset <= placeholder_range.end {
2887 self.set_selection_position(
2888 app,
2889 Some(TextPosition::new(range.end)),
2890 is_end,
2891 );
2892 return Some(SelectionResult::End);
2893 }
2894 if boundary.boundary_end.offset > placeholder_range.end {
2895 self.set_selection_position(
2896 app,
2897 Some(TextPosition::new(range.end)),
2898 is_end,
2899 );
2900 return Some(SelectionResult::Next);
2901 }
2902 } else {
2903 if boundary.boundary_start.offset >= placeholder_range.start {
2904 self.set_selection_position(
2905 app,
2906 Some(TextPosition::new(range.start)),
2907 is_end,
2908 );
2909 return Some(SelectionResult::End);
2910 }
2911 if boundary.boundary_start.offset < placeholder_range.start {
2912 self.set_selection_position(
2913 app,
2914 Some(TextPosition::new(range.start)),
2915 is_end,
2916 );
2917 return Some(SelectionResult::Previous);
2918 }
2919 }
2920 }
2921 }
2922 None
2923 }
2924
2925 fn update_selection_end_edge_at_placeholder(
2926 self: Handle<Self>,
2927 app: &mut App,
2928 get_text_boundary: TextBoundaryAtPositionInText,
2929 global_position: Offset,
2930 paragraph_contains_position: bool,
2931 position: TextPosition,
2932 existing_selection_start: Option<TextPosition>,
2933 existing_selection_end: Option<TextPosition>,
2934 ) -> Option<SelectionResult> {
2935 let is_end = true;
2936 let range = app.get(self).range;
2937 if app.get(self).selectable_contains_origin_text_boundary
2938 && existing_selection_start.is_some()
2939 && existing_selection_end.is_some()
2940 {
2941 let existing_start = existing_selection_start.unwrap();
2942 let existing_end = existing_selection_end.unwrap();
2943 let forward_selection = existing_end.offset >= existing_start.offset;
2944 let origin_paragraph = self.get_origin_paragraph(app);
2945 if origin_paragraph == app.get(self).paragraph {
2946 return self.update_selection_end_edge_by_multi_selectable_text_boundary(
2947 app,
2948 get_text_boundary,
2949 paragraph_contains_position,
2950 position,
2951 existing_selection_start,
2952 existing_selection_end,
2953 );
2954 }
2955 let origin_local = global_to_paragraph(app, origin_paragraph, global_position);
2956 let within_origin = origin_paragraph
2957 .as_object()
2958 .paint_bounds(app)
2959 .contains(origin_local);
2960 let origin_position = origin_paragraph.get_position_for_offset(app, origin_local);
2961 if within_origin {
2962 let origin_text = origin_paragraph.text(app).to_plain_text(false, true);
2963 let boundary = get_text_boundary(self, app, origin_position, &origin_text);
2964 let origin_placeholder_position =
2965 self.get_position_in_paragraph(app, origin_paragraph);
2966 let origin_boundary =
2967 get_text_boundary(self, app, origin_placeholder_position, &origin_text);
2968 let pivot = if forward_selection {
2969 origin_boundary.boundary_start.offset
2970 } else {
2971 origin_boundary.boundary_end.offset
2972 };
2973 let swap = !forward_selection != (origin_position.offset < pivot);
2974 let target = if origin_position.offset < pivot {
2975 boundary.boundary_start
2976 } else if origin_position.offset > pivot {
2977 boundary.boundary_end
2978 } else {
2979 existing_end
2980 };
2981 if swap {
2982 self.set_selection_position(app, Some(existing_end), false);
2983 }
2984 let target = self.clamp_text_position(app, target);
2985 self.set_selection_position(app, Some(target), is_end);
2986 let forward = app.get(self).text_selection_end.unwrap().offset
2987 >= app.get(self).text_selection_start.unwrap().offset;
2988 let placeholder = self.get_position_in_paragraph(app, origin_paragraph);
2989 let placeholder_range = TextRange::new(placeholder.offset, placeholder.offset + 1);
2990 if boundary.boundary_start.offset > placeholder_range.end
2991 && boundary.boundary_end.offset > placeholder_range.end
2992 {
2993 return Some(SelectionResult::Next);
2994 }
2995 if boundary.boundary_start.offset < placeholder_range.start
2996 && boundary.boundary_end.offset < placeholder_range.start
2997 {
2998 return Some(SelectionResult::Previous);
2999 }
3000 if forward {
3001 if boundary.boundary_end.offset <= origin_boundary.boundary_end.offset {
3002 return Some(SelectionResult::End);
3003 }
3004 if boundary.boundary_end.offset > origin_boundary.boundary_end.offset {
3005 return Some(SelectionResult::Next);
3006 }
3007 } else {
3008 if boundary.boundary_start.offset >= origin_boundary.boundary_start.offset {
3009 return Some(SelectionResult::End);
3010 }
3011 if boundary.boundary_start.offset < origin_boundary.boundary_start.offset {
3012 return Some(SelectionResult::Previous);
3013 }
3014 }
3015 } else {
3016 let direction = app.get(self).paragraph.text_direction(app);
3017 let adjusted = SelectionUtils::adjust_drag_offset(
3018 origin_paragraph.as_object().paint_bounds(app),
3019 origin_local,
3020 direction,
3021 );
3022 let adjusted_position = origin_paragraph.get_position_for_offset(app, adjusted);
3023 let placeholder = self.get_position_in_paragraph(app, origin_paragraph);
3024 let placeholder_range = TextRange::new(placeholder.offset, placeholder.offset + 1);
3025 if forward_selection && adjusted_position.offset <= placeholder_range.start {
3026 self.set_selection_position(app, Some(existing_end), false);
3027 self.set_selection_position(app, Some(TextPosition::new(range.start)), is_end);
3028 return Some(SelectionResult::Previous);
3029 }
3030 if !forward_selection && adjusted_position.offset >= placeholder_range.end {
3031 self.set_selection_position(app, Some(existing_end), false);
3032 self.set_selection_position(app, Some(TextPosition::new(range.end)), is_end);
3033 return Some(SelectionResult::Next);
3034 }
3035 if forward_selection && adjusted_position.offset >= placeholder_range.end {
3036 self.set_selection_position(app, Some(TextPosition::new(range.end)), is_end);
3037 return Some(SelectionResult::Next);
3038 }
3039 if !forward_selection && adjusted_position.offset <= placeholder_range.start {
3040 self.set_selection_position(app, Some(TextPosition::new(range.start)), is_end);
3041 return Some(SelectionResult::Previous);
3042 }
3043 }
3044 } else {
3045 if paragraph_contains_position {
3046 return self.update_selection_end_edge_by_multi_selectable_text_boundary(
3047 app,
3048 get_text_boundary,
3049 paragraph_contains_position,
3050 position,
3051 existing_selection_start,
3052 existing_selection_end,
3053 );
3054 }
3055 if existing_selection_start.is_some() {
3056 let (target_paragraph, target_local) =
3057 self.get_paragraph_containing_position(app, global_position)?;
3058 let target_position = target_paragraph.get_position_for_offset(app, target_local);
3059 let target_text = target_paragraph.text(app).to_plain_text(false, true);
3060 if target_paragraph
3061 .get_word_boundary(app, target_position)
3062 .text_inside(&target_text)
3063 == "\u{FFFC}"
3064 {
3065 return None;
3066 }
3067 let existing_start = existing_selection_start.unwrap();
3068 let backward = (existing_selection_end.is_none()
3069 && existing_start.offset == range.end)
3070 || (existing_selection_start == existing_selection_end
3071 && existing_start.offset == range.end)
3072 || (existing_selection_end.is_some()
3073 && existing_start.offset > existing_selection_end.unwrap().offset);
3074 let boundary = get_text_boundary(self, app, target_position, &target_text);
3075 let placeholder = self.get_position_in_paragraph(app, target_paragraph);
3076 let placeholder_range = TextRange::new(placeholder.offset, placeholder.offset + 1);
3077 if boundary.boundary_start.offset < placeholder_range.start
3078 && boundary.boundary_end.offset < placeholder_range.start
3079 {
3080 self.set_selection_position(app, Some(TextPosition::new(range.start)), is_end);
3081 return Some(SelectionResult::Previous);
3082 }
3083 if boundary.boundary_start.offset > placeholder_range.end
3084 && boundary.boundary_end.offset > placeholder_range.end
3085 {
3086 self.set_selection_position(app, Some(TextPosition::new(range.end)), is_end);
3087 return Some(SelectionResult::Next);
3088 }
3089 if backward {
3090 if boundary.boundary_start.offset >= placeholder_range.start {
3091 self.set_selection_position(
3092 app,
3093 Some(TextPosition::new(range.start)),
3094 is_end,
3095 );
3096 return Some(SelectionResult::End);
3097 }
3098 if boundary.boundary_start.offset < placeholder_range.start {
3099 self.set_selection_position(
3100 app,
3101 Some(TextPosition::new(range.start)),
3102 is_end,
3103 );
3104 return Some(SelectionResult::Previous);
3105 }
3106 } else {
3107 if boundary.boundary_end.offset <= placeholder_range.end {
3108 self.set_selection_position(
3109 app,
3110 Some(TextPosition::new(range.end)),
3111 is_end,
3112 );
3113 return Some(SelectionResult::End);
3114 }
3115 if boundary.boundary_end.offset > placeholder_range.end {
3116 self.set_selection_position(
3117 app,
3118 Some(TextPosition::new(range.end)),
3119 is_end,
3120 );
3121 return Some(SelectionResult::Next);
3122 }
3123 }
3124 }
3125 }
3126 None
3127 }
3128 fn handle_granularly_extend_selection(
3129 self: Handle<Self>,
3130 app: &mut App,
3131 forward: bool,
3132 is_extent: bool,
3133 granularity: TextGranularity,
3134 ) -> SelectionResult {
3135 let range = app.get(self).range;
3136 if app.get(self).text_selection_end.is_none() {
3137 app.get_mut(self).text_selection_end = Some(if forward {
3138 TextPosition::new(range.start)
3139 } else {
3140 TextPosition::with_affinity(range.end, TextAffinity::Upstream)
3141 });
3142 }
3143 if app.get(self).text_selection_start.is_none() {
3144 let end = app.get(self).text_selection_end.unwrap();
3145 app.get_mut(self).text_selection_start = Some(end);
3146 }
3147 let targeted_edge = if is_extent {
3148 app.get(self).text_selection_end.unwrap()
3149 } else {
3150 app.get(self).text_selection_start.unwrap()
3151 };
3152 if forward && targeted_edge.offset == range.end {
3153 return SelectionResult::Next;
3154 }
3155 if !forward && targeted_edge.offset == range.start {
3156 return SelectionResult::Previous;
3157 }
3158 let (new_position, result) = match granularity {
3159 TextGranularity::Character => {
3160 let text = range.text_inside(&app.get(self).full_text).to_owned();
3161 (
3162 self.move_beyond_text_boundary_at_direction(
3163 app,
3164 targeted_edge,
3165 forward,
3166 &CharacterBoundary::new(text),
3167 ),
3168 SelectionResult::End,
3169 )
3170 }
3171 TextGranularity::Word => {
3172 let paragraph = app.get(self).paragraph;
3173 let text = paragraph.text(app);
3174 let boundary = WordBoundary::for_paragraph(text, paragraph);
3175 (
3176 self.move_beyond_text_boundary_at_direction(
3177 app,
3178 targeted_edge,
3179 forward,
3180 &*boundary.move_by_word_boundary(),
3181 ),
3182 SelectionResult::End,
3183 )
3184 }
3185 TextGranularity::Paragraph => {
3186 let text = range.text_inside(&app.get(self).full_text).to_owned();
3187 (
3188 self.move_beyond_text_boundary_at_direction(
3189 app,
3190 targeted_edge,
3191 forward,
3192 &ParagraphBoundary::new(&text),
3193 ),
3194 SelectionResult::End,
3195 )
3196 }
3197 TextGranularity::Line => {
3198 let boundary = FragmentLineBoundary { fragment: self };
3199 (
3200 self.move_to_text_boundary_at_direction(app, targeted_edge, forward, &boundary),
3201 SelectionResult::End,
3202 )
3203 }
3204 TextGranularity::Document => {
3205 let text = range.text_inside(&app.get(self).full_text).to_owned();
3206 let position = self.move_beyond_text_boundary_at_direction(
3207 app,
3208 targeted_edge,
3209 forward,
3210 &DocumentBoundary::new(text),
3211 );
3212 let result = if forward && position.offset == range.end {
3213 SelectionResult::Next
3214 } else if !forward && position.offset == range.start {
3215 SelectionResult::Previous
3216 } else {
3217 SelectionResult::End
3218 };
3219 (position, result)
3220 }
3221 };
3222 if is_extent {
3223 app.get_mut(self).text_selection_end = Some(new_position);
3224 } else {
3225 app.get_mut(self).text_selection_start = Some(new_position);
3226 }
3227 result
3228 }
3229
3230 fn move_beyond_text_boundary_at_direction(
3231 self: Handle<Self>,
3232 app: &mut App,
3233 end: TextPosition,
3234 forward: bool,
3235 text_boundary: &dyn TextBoundary,
3236 ) -> TextPosition {
3237 let range = app.get(self).range;
3238 let new_offset = if forward {
3239 text_boundary
3240 .get_trailing_text_boundary_at(app, end.offset)
3241 .unwrap_or(range.end)
3242 } else {
3243 text_boundary
3244 .get_leading_text_boundary_at(app, end.offset - 1)
3245 .unwrap_or(range.start)
3246 };
3247 TextPosition::new(new_offset)
3248 }
3249
3250 fn move_to_text_boundary_at_direction(
3251 self: Handle<Self>,
3252 app: &mut App,
3253 end: TextPosition,
3254 forward: bool,
3255 text_boundary: &dyn TextBoundary,
3256 ) -> TextPosition {
3257 let range = app.get(self).range;
3258 debug_assert!(end.offset >= 0);
3259 let caret_offset = match end.affinity {
3260 TextAffinity::Upstream => {
3261 if end.offset < 1 && !forward {
3262 debug_assert_eq!(end.offset, 0);
3263 return TextPosition::new(0);
3264 }
3265 let full_text = app.get(self).full_text.clone();
3266 let character_boundary = CharacterBoundary::new(full_text);
3267 character_boundary
3268 .get_leading_text_boundary_at(app, range.start + end.offset)
3269 .unwrap_or(range.start)
3270 .max(0)
3271 - 1
3272 }
3273 TextAffinity::Downstream => end.offset,
3274 };
3275 let offset = if forward {
3276 text_boundary
3277 .get_trailing_text_boundary_at(app, caret_offset)
3278 .unwrap_or(range.end)
3279 } else {
3280 text_boundary
3281 .get_leading_text_boundary_at(app, caret_offset)
3282 .unwrap_or(range.start)
3283 };
3284 TextPosition::new(offset)
3285 }
3286
3287 fn handle_vertical_movement(
3288 self: Handle<Self>,
3289 app: &mut App,
3290 position: TextPosition,
3291 horizontal_baseline_in_paragraph_coordinates: f64,
3292 below: bool,
3293 ) -> (TextPosition, SelectionResult) {
3294 let range = app.get(self).range;
3295 let paragraph = app.get(self).paragraph;
3296 let constraints = paragraph.constraints(app);
3297 paragraph.layout_text_with_constraints(app, constraints);
3298 let lines = paragraph.painter_mut(app).compute_line_metrics();
3299 let offset = paragraph.get_offset_for_caret(app, position, Rect::ZERO);
3300 let mut current_line = lines.len() as i32 - 1;
3301 for line_metrics in &lines {
3302 if line_metrics.baseline > offset.dy() {
3303 current_line = line_metrics.line_number;
3304 break;
3305 }
3306 }
3307 let new_position = if below && current_line == lines.len() as i32 - 1 {
3308 TextPosition::with_affinity(range.end, TextAffinity::Upstream)
3309 } else if !below && current_line == 0 {
3310 TextPosition::new(range.start)
3311 } else {
3312 let new_line = if below {
3313 current_line + 1
3314 } else {
3315 current_line - 1
3316 };
3317 let position = paragraph.get_position_for_offset(
3318 app,
3319 Offset::new(
3320 horizontal_baseline_in_paragraph_coordinates,
3321 lines[new_line as usize].baseline,
3322 ),
3323 );
3324 self.clamp_text_position(app, position)
3325 };
3326 let result = if new_position.offset == range.start {
3327 SelectionResult::Previous
3328 } else if new_position.offset == range.end {
3329 SelectionResult::Next
3330 } else {
3331 SelectionResult::End
3332 };
3333 debug_assert!(result != SelectionResult::Next || below);
3334 debug_assert!(result != SelectionResult::Previous || !below);
3335 (new_position, result)
3336 }
3337
3338 fn handle_directionally_extend_selection(
3339 self: Handle<Self>,
3340 app: &mut App,
3341 horizontal_baseline: f64,
3342 is_extent: bool,
3343 movement: SelectionExtendDirection,
3344 ) -> SelectionResult {
3345 let transform = app
3346 .get(self)
3347 .paragraph
3348 .as_object()
3349 .get_transform_to(app, None);
3350 let Some(inverse) = transform.invert() else {
3351 return match movement {
3352 SelectionExtendDirection::PreviousLine | SelectionExtendDirection::Backward => {
3353 SelectionResult::Previous
3354 }
3355 SelectionExtendDirection::NextLine | SelectionExtendDirection::Forward => {
3356 SelectionResult::Next
3357 }
3358 };
3359 };
3360 let baseline_in_paragraph_coordinates =
3361 waft_painting::transform_point(&inverse, Offset::new(horizontal_baseline, 0.0)).dx();
3362 debug_assert!(!baseline_in_paragraph_coordinates.is_nan());
3363 let (new_position, result) = match movement {
3364 SelectionExtendDirection::PreviousLine | SelectionExtendDirection::NextLine => {
3365 debug_assert!(app.get(self).text_selection_end.is_some());
3366 debug_assert!(app.get(self).text_selection_start.is_some());
3367 let targeted_edge = if is_extent {
3368 app.get(self).text_selection_end.unwrap()
3369 } else {
3370 app.get(self).text_selection_start.unwrap()
3371 };
3372 self.handle_vertical_movement(
3373 app,
3374 targeted_edge,
3375 baseline_in_paragraph_coordinates,
3376 movement == SelectionExtendDirection::NextLine,
3377 )
3378 }
3379 SelectionExtendDirection::Forward | SelectionExtendDirection::Backward => {
3380 if app.get(self).text_selection_end.is_none() {
3381 app.get_mut(self).text_selection_end =
3382 Some(if movement == SelectionExtendDirection::Forward {
3383 TextPosition::new(app.get(self).range.start)
3384 } else {
3385 TextPosition::with_affinity(
3386 app.get(self).range.end,
3387 TextAffinity::Upstream,
3388 )
3389 });
3390 }
3391 if app.get(self).text_selection_start.is_none() {
3392 let end = app.get(self).text_selection_end.unwrap();
3393 app.get_mut(self).text_selection_start = Some(end);
3394 }
3395 let targeted_edge = if is_extent {
3396 app.get(self).text_selection_end.unwrap()
3397 } else {
3398 app.get(self).text_selection_start.unwrap()
3399 };
3400 let edge_offset = app
3401 .get(self)
3402 .paragraph
3403 .get_offset_for_position(app, targeted_edge);
3404 let line_height = app.get(self).paragraph.preferred_line_height(app);
3405 let baseline_offset = Offset::new(
3406 baseline_in_paragraph_coordinates,
3407 edge_offset.dy() - line_height / 2.0,
3408 );
3409 let new_position = app
3410 .get(self)
3411 .paragraph
3412 .get_position_for_offset(app, baseline_offset);
3413 (new_position, SelectionResult::End)
3414 }
3415 };
3416 if is_extent {
3417 app.get_mut(self).text_selection_end = Some(new_position);
3418 } else {
3419 app.get_mut(self).text_selection_start = Some(new_position);
3420 }
3421 result
3422 }
3423
3424 fn paint_selection(
3425 self: Handle<Self>,
3426 app: &mut App,
3427 context: &mut PaintingContext,
3428 offset: Offset,
3429 ) {
3430 let (Some(start), Some(end)) = (
3431 app.get(self).text_selection_start,
3432 app.get(self).text_selection_end,
3433 ) else {
3434 return;
3435 };
3436 let paragraph = app.get(self).paragraph;
3437 let Some(selection_color) = paragraph.selection_color(app) else {
3438 return;
3439 };
3440 let selection = TextSelection::new(start.offset, end.offset);
3441 let selection_paint = Paint::from_color(selection_color.into());
3442 let boxes = paragraph.get_boxes_for_selection(
3443 app,
3444 selection,
3445 BoxHeightStyle::Tight,
3446 BoxWidthStyle::Tight,
3447 );
3448 for text_box in boxes {
3449 context
3450 .canvas()
3451 .draw_rect(text_box.to_rect().shift(offset), &selection_paint);
3452 }
3453 }
3454
3455 fn paint_handles(
3456 self: Handle<Self>,
3457 app: &mut App,
3458 context: &mut PaintingContext,
3459 offset: Offset,
3460 ) {
3461 if app.get(self).text_selection_start.is_none()
3462 || app.get(self).text_selection_end.is_none()
3463 {
3464 return;
3465 }
3466 let geometry = app.get(self).selection_geometry.clone();
3467 let start_link = app.get(self).start_handle_layer_link.clone();
3468 let end_link = app.get(self).end_handle_layer_link.clone();
3469 if let (Some(link), Some(point)) = (start_link, geometry.start_selection_point) {
3470 let layer = LeaderLayer::new(app, link);
3471 layer.set_offset(app, offset + point.local_position);
3472 context.push_layer(
3473 app,
3474 ContainerLayer::as_container_layer(layer),
3475 |_, _, _| {},
3476 Offset::ZERO,
3477 None,
3478 );
3479 }
3480 if let (Some(link), Some(point)) = (end_link, geometry.end_selection_point) {
3481 let layer = LeaderLayer::new(app, link);
3482 layer.set_offset(app, offset + point.local_position);
3483 context.push_layer(
3484 app,
3485 ContainerLayer::as_container_layer(layer),
3486 |_, _, _| {},
3487 Offset::ZERO,
3488 None,
3489 );
3490 }
3491 }
3492}
3493fn global_to_paragraph(
3497 app: &App,
3498 paragraph: RenderHandle<RenderParagraph>,
3499 global_position: Offset,
3500) -> Offset {
3501 let transform = paragraph.as_object().get_transform_to(app, None);
3502 let inverse = transform.invert().unwrap_or(transform);
3503 waft_painting::transform_point(&inverse, global_position)
3504}
3505
3506struct FragmentLineBoundary {
3508 fragment: Handle<SelectableFragment>,
3509}
3510
3511impl TextBoundary for FragmentLineBoundary {
3512 fn get_text_boundary_at(&self, app: &mut App, position: i32) -> TextRange {
3513 let selection = self
3514 .fragment
3515 .get_line_at_offset(app, TextPosition::new(position.max(0)));
3516 selection.range()
3517 }
3518}
3519
3520impl SelectableFragment {
3521 fn get_line_at_offset(
3522 self: Handle<Self>,
3523 app: &mut App,
3524 position: TextPosition,
3525 ) -> TextSelection {
3526 let range = app.get(self).range;
3527 let line = app.get(self).paragraph.get_line_at_offset(app, position);
3528 TextSelection::new(
3529 line.base_offset.clamp(range.start, range.end),
3530 line.extent_offset.clamp(range.start, range.end),
3531 )
3532 }
3533
3534 fn bounding_boxes(self: Handle<Self>, app: &mut App) -> Vec<Rect> {
3535 if let Some(cached) = &app.get(self).cached_bounding_boxes {
3536 return cached.clone();
3537 }
3538 let range = app.get(self).range;
3539 let paragraph = app.get(self).paragraph;
3540 let boxes = paragraph.get_boxes_for_selection(
3541 app,
3542 TextSelection::new(range.start, range.end),
3543 BoxHeightStyle::Max,
3544 BoxWidthStyle::Tight,
3545 );
3546 let rects: Vec<Rect> = if boxes.is_empty() {
3547 let offset = paragraph.get_offset_for_position(app, TextPosition::new(range.start));
3548 let line_height = paragraph.preferred_line_height(app);
3549 vec![Rect::from_ltrb(
3550 offset.dx(),
3551 offset.dy() - line_height,
3552 offset.dx(),
3553 offset.dy(),
3554 )]
3555 } else {
3556 boxes
3557 .into_iter()
3558 .map(|text_box| text_box.to_rect())
3559 .collect()
3560 };
3561 app.get_mut(self).cached_bounding_boxes = Some(rects.clone());
3562 rects
3563 }
3564}
3565
3566impl ChangeNotifier for SelectableFragment {
3567 fn change_notifier_data(&self) -> &ChangeNotifierData {
3568 &self.change_notifier
3569 }
3570
3571 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
3572 &mut self.change_notifier
3573 }
3574}
3575
3576impl SelectionHandler for SelectableFragment {
3577 fn value(self: Handle<Self>, app: &App) -> SelectionGeometry {
3578 app.get(self).selection_geometry.clone()
3579 }
3580
3581 fn push_handle_layers(
3582 self: Handle<Self>,
3583 app: &mut App,
3584 start_handle: Option<Ref<LayerLink>>,
3585 end_handle: Option<Ref<LayerLink>>,
3586 ) {
3587 let paragraph = app.get(self).paragraph;
3588 if !paragraph.as_object().attached(app) {
3589 debug_assert!(
3590 start_handle.is_none() && end_handle.is_none(),
3591 "Only clean up can be called."
3592 );
3593 return;
3594 }
3595 let mut needs_paint = false;
3596 if app.get(self).start_handle_layer_link != start_handle {
3597 app.get_mut(self).start_handle_layer_link = start_handle;
3598 needs_paint = true;
3599 }
3600 if app.get(self).end_handle_layer_link != end_handle {
3601 app.get_mut(self).end_handle_layer_link = end_handle;
3602 needs_paint = true;
3603 }
3604 if needs_paint {
3605 paragraph.mark_needs_paint(app);
3606 }
3607 }
3608
3609 fn selected_content(self: Handle<Self>, app: &App) -> Option<SelectedContent> {
3610 let this = app.get(self);
3611 let start = this.text_selection_start?;
3612 let end = this.text_selection_end?;
3613 let range = TextRange::new(start.offset.min(end.offset), start.offset.max(end.offset));
3614 Some(SelectedContent::new(range.text_inside(&this.full_text)))
3615 }
3616
3617 fn selection(self: Handle<Self>, app: &App) -> Option<SelectedContentRange> {
3618 let this = app.get(self);
3619 Some(SelectedContentRange::new(
3620 this.text_selection_start?.offset,
3621 this.text_selection_end?.offset,
3622 ))
3623 }
3624
3625 fn dispatch_selection_event(
3626 self: Handle<Self>,
3627 app: &mut App,
3628 event: &SelectionEvent,
3629 ) -> SelectionResult {
3630 let existing_start = app.get(self).text_selection_start;
3631 let existing_end = app.get(self).text_selection_end;
3632 let result = match event {
3633 SelectionEvent::StartEdgeUpdate {
3634 global_position,
3635 granularity,
3636 }
3637 | SelectionEvent::EndEdgeUpdate {
3638 global_position,
3639 granularity,
3640 } => {
3641 let is_end = matches!(event, SelectionEvent::EndEdgeUpdate { .. });
3642 match granularity {
3643 TextGranularity::Character => {
3644 self.update_selection_edge(app, *global_position, is_end)
3645 }
3646 TextGranularity::Word => self.update_selection_edge_by_text_boundary(
3647 app,
3648 *global_position,
3649 is_end,
3650 Self::get_word_boundary_at_position,
3651 ),
3652 TextGranularity::Paragraph => self
3653 .update_selection_edge_by_multi_selectable_text_boundary(
3654 app,
3655 *global_position,
3656 is_end,
3657 Self::get_paragraph_boundary_at_position,
3658 ),
3659 TextGranularity::Document | TextGranularity::Line => {
3660 debug_assert!(
3661 false,
3662 "Moving the selection edge by line or document is not supported."
3663 );
3664 unreachable!()
3665 }
3666 }
3667 }
3668 SelectionEvent::Clear => self.handle_clear_selection(app),
3669 SelectionEvent::SelectAll => self.handle_select_all(app),
3670 SelectionEvent::SelectWord { global_position } => {
3671 self.handle_select_word(app, *global_position)
3672 }
3673 SelectionEvent::SelectParagraph {
3674 global_position,
3675 absorb,
3676 } => {
3677 if *absorb {
3678 self.handle_select_all(app);
3679 app.get_mut(self).selectable_contains_origin_text_boundary = true;
3680 SelectionResult::Next
3681 } else {
3682 self.handle_select_paragraph(app, *global_position)
3683 }
3684 }
3685 SelectionEvent::GranularlyExtendSelection {
3686 forward,
3687 is_end,
3688 granularity,
3689 } => self.handle_granularly_extend_selection(app, *forward, *is_end, *granularity),
3690 SelectionEvent::DirectionallyExtendSelection {
3691 dx,
3692 is_end,
3693 direction,
3694 } => self.handle_directionally_extend_selection(app, *dx, *is_end, *direction),
3695 };
3696 if existing_start != app.get(self).text_selection_start
3697 || existing_end != app.get(self).text_selection_end
3698 {
3699 self.did_change_selection(app);
3700 }
3701 result
3702 }
3703
3704 fn content_length(self: Handle<Self>, app: &App) -> usize {
3705 let range = app.get(self).range;
3706 (range.end - range.start) as usize
3707 }
3708}
3709
3710impl Selectable for SelectableFragment {
3711 fn get_transform_to(
3712 self: Handle<Self>,
3713 app: &App,
3714 ancestor: Option<AnyRenderObject>,
3715 ) -> Matrix4 {
3716 app.get(self)
3717 .paragraph
3718 .as_object()
3719 .get_transform_to(app, ancestor)
3720 }
3721
3722 fn size(self: Handle<Self>, app: &mut App) -> Size {
3723 self.rect(app).size()
3724 }
3725
3726 fn bounding_boxes(self: Handle<Self>, app: &mut App) -> Vec<Rect> {
3727 SelectableFragment::bounding_boxes(self, app)
3728 }
3729
3730 fn dispose_selectable(self: Handle<Self>, app: &mut App) {
3731 ChangeNotifierData::dispose(app, self);
3732 }
3733}
3734
3735#[cfg(test)]
3736mod tests {
3737 use waft_embedder::Color;
3738 use waft_foundation::AppCell;
3739 use waft_gestures::HitTestResult;
3740 use waft_painting::{AlignmentGeometry, TextSpan, TextStyle};
3741
3742 use super::*;
3743 use crate::proxy_box::RenderRepaintBoundary;
3744 use crate::testing::{EnginePhase, layout_with, pump_frame, test_render_root};
3745
3746 fn span(text: &str) -> InlineSpanRef {
3747 TextSpan::new()
3748 .text(text)
3749 .style(TextStyle::new().font_size(20.0))
3750 .into_span()
3751 }
3752
3753 fn laid_out(
3754 app: &mut App,
3755 text: &str,
3756 constraints: BoxConstraints,
3757 ) -> RenderHandle<RenderParagraph> {
3758 laid_out_span(app, span(text), constraints)
3759 }
3760
3761 fn laid_out_span(
3764 app: &mut App,
3765 text: InlineSpanRef,
3766 constraints: BoxConstraints,
3767 ) -> RenderHandle<RenderParagraph> {
3768 let paragraph = RenderParagraph::new(app, text, TextDirection::Ltr, None);
3769 lay_out_at_the_top_left(app, paragraph, constraints);
3770 paragraph
3771 }
3772
3773 fn lay_out_at_the_top_left(
3774 app: &mut App,
3775 paragraph: RenderHandle<RenderParagraph>,
3776 constraints: BoxConstraints,
3777 ) {
3778 layout_with(
3779 app,
3780 paragraph.as_box(),
3781 Some(constraints),
3782 AlignmentGeometry::TOP_LEFT,
3783 EnginePhase::Layout,
3784 );
3785 }
3786
3787 #[test]
3790 fn paragraph_intrinsics_come_from_the_text() {
3791 let cell = AppCell::new();
3792 let mut app = cell.borrow_mut();
3793 crate::testing::install_test_fonts(&mut app);
3794 let paragraph = RenderParagraph::new(
3795 &mut app,
3796 span("one two three four"),
3797 TextDirection::Ltr,
3798 None,
3799 );
3800 let box_ = paragraph.as_box();
3801 let min_width = box_.get_min_intrinsic_width(&mut app, f64::INFINITY);
3802 let max_width = box_.get_max_intrinsic_width(&mut app, f64::INFINITY);
3803 assert!(min_width > 0.0);
3804 assert!(
3805 min_width < max_width,
3806 "the widest word is narrower than the whole text"
3807 );
3808
3809 let one_line = box_.get_min_intrinsic_height(&mut app, max_width);
3810 let wrapped = box_.get_min_intrinsic_height(&mut app, max_width / 2.0);
3811 assert!(wrapped > one_line, "half the width takes more lines");
3812 assert_eq!(box_.get_max_intrinsic_height(&mut app, max_width), one_line);
3813 }
3814
3815 #[test]
3817 fn strut_style_affects_intrinsics() {
3818 let cell = AppCell::new();
3819 let mut app = cell.borrow_mut();
3820 crate::testing::install_test_fonts(&mut app);
3821 let paragraph = RenderParagraph::new(
3822 &mut app,
3823 TextSpan::new()
3824 .text("Hello World")
3825 .style(TextStyle::new().font_size(10.0))
3826 .into_span(),
3827 TextDirection::Ltr,
3828 None,
3829 );
3830
3831 assert_eq!(
3832 paragraph
3833 .as_box()
3834 .get_max_intrinsic_height(&mut app, f64::INFINITY),
3835 10.0
3836 );
3837
3838 paragraph.set_strut_style(
3839 &mut app,
3840 Some(StrutStyle::new().font_size(100.0).force_strut_height(true)),
3841 );
3842 assert_eq!(
3843 paragraph
3844 .as_box()
3845 .get_max_intrinsic_height(&mut app, f64::INFINITY),
3846 100.0
3847 );
3848 }
3849
3850 #[test]
3853 fn paragraph_dry_layout_and_baseline_match_its_layout() {
3854 let cell = AppCell::new();
3855 let mut app = cell.borrow_mut();
3856 crate::testing::install_test_fonts(&mut app);
3857 let constraints = BoxConstraints::new().max_width(200.0).max_height(1000.0);
3858 let paragraph =
3859 RenderParagraph::new(&mut app, span("one two three"), TextDirection::Ltr, None);
3860 let dry = paragraph.as_box().get_dry_layout(&mut app, constraints);
3861 let dry_baseline =
3862 paragraph
3863 .as_box()
3864 .get_dry_baseline(&mut app, constraints, TextBaseline::Alphabetic);
3865
3866 let paragraph = laid_out(&mut app, "one two three", constraints);
3867 assert_eq!(dry, paragraph.size(&app));
3868 let baseline =
3869 paragraph
3870 .as_box()
3871 .get_distance_to_baseline(&mut app, TextBaseline::Alphabetic, true);
3872 assert_eq!(dry_baseline, baseline);
3873 assert!(baseline.is_some_and(|baseline| baseline > 0.0));
3874 }
3875
3876 #[test]
3877 fn a_paragraph_sizes_itself_to_its_text_within_loose_constraints() {
3878 let cell = AppCell::new();
3879 let mut app = cell.borrow_mut();
3880 let loose = BoxConstraints::new().max_width(1000.0).max_height(1000.0);
3881 let paragraph = laid_out(&mut app, "Hello", loose);
3882 let size = paragraph.size(&app);
3883 assert!(size.width() > 0.0 && size.width() < 1000.0);
3884 assert_eq!(size, paragraph.text_size(&app));
3885 assert!(!paragraph.did_exceed_max_lines(&app));
3886 }
3887
3888 #[test]
3889 fn narrow_constraints_wrap_the_text() {
3890 let cell = AppCell::new();
3891 let mut app = cell.borrow_mut();
3892 let loose = BoxConstraints::new().max_width(1000.0).max_height(1000.0);
3893 let wide = laid_out(&mut app, "one two three four", loose);
3894 let natural = wide.size(&app);
3895 let narrow = BoxConstraints::new()
3896 .max_width(natural.width() / 2.0)
3897 .max_height(1000.0);
3898 let wrapped = laid_out(&mut app, "one two three four", narrow);
3899 assert!(wrapped.size(&app).height() > natural.height());
3900 assert!(wrapped.size(&app).width() <= natural.width() / 2.0);
3901 }
3902
3903 #[test]
3904 fn soft_wrap_off_lets_the_text_overflow_and_clips_it() {
3905 let cell = AppCell::new();
3906 let mut app = cell.borrow_mut();
3907 let loose = BoxConstraints::new().max_width(1000.0).max_height(1000.0);
3908 let wide = laid_out(&mut app, "one two three four", loose);
3909 let natural = wide.size(&app);
3910 let paragraph = RenderParagraph::new(
3911 &mut app,
3912 span("one two three four"),
3913 TextDirection::Ltr,
3914 None,
3915 );
3916 paragraph.set_soft_wrap(&mut app, false);
3917 let narrow = BoxConstraints::new()
3918 .max_width(natural.width() / 2.0)
3919 .max_height(1000.0);
3920 lay_out_at_the_top_left(&mut app, paragraph, narrow);
3921 assert_eq!(paragraph.size(&app).width(), natural.width() / 2.0);
3922 assert_eq!(
3923 paragraph.text_size(&app).width(),
3924 natural.width(),
3925 "laid out unwrapped"
3926 );
3927 assert!(paragraph.get(&app).needs_clipping);
3928
3929 paragraph.set_overflow(&mut app, TextOverflow::Visible);
3930 pump_frame(&mut app, EnginePhase::Layout);
3931 assert!(!paragraph.get(&app).needs_clipping);
3932 }
3933
3934 #[test]
3935 fn ellipsis_overflow_reports_exceeded_lines() {
3936 let cell = AppCell::new();
3937 let mut app = cell.borrow_mut();
3938 let loose = BoxConstraints::new().max_width(1000.0).max_height(1000.0);
3939 let wide = laid_out(&mut app, "one two three four", loose);
3940 let natural = wide.size(&app);
3941 let paragraph = RenderParagraph::new(
3942 &mut app,
3943 span("one two three four"),
3944 TextDirection::Ltr,
3945 None,
3946 );
3947 paragraph.set_max_lines(&mut app, Some(1));
3948 paragraph.set_overflow(&mut app, TextOverflow::Ellipsis);
3949 lay_out_at_the_top_left(
3950 &mut app,
3951 paragraph,
3952 BoxConstraints::new()
3953 .max_width(natural.width() / 2.0)
3954 .max_height(1000.0),
3955 );
3956 assert!(paragraph.did_exceed_max_lines(&app));
3957 assert_eq!(paragraph.size(&app).height(), natural.height());
3958 }
3959
3960 #[test]
3961 fn setting_text_marks_layout_or_paint_by_the_comparison() {
3962 let cell = AppCell::new();
3963 let mut app = cell.borrow_mut();
3964 let loose = BoxConstraints::new().max_width(1000.0).max_height(1000.0);
3965 let paragraph = laid_out(&mut app, "Hello", loose);
3966 pump_frame(&mut app, EnginePhase::Paint);
3967 assert!(!paragraph.debug_needs_layout(&app));
3968
3969 let recolored = TextSpan::new()
3970 .text("Hello")
3971 .style(
3972 TextStyle::new()
3973 .font_size(20.0)
3974 .color(Color::from_argb(255, 255, 0, 0)),
3975 )
3976 .into_span();
3977 paragraph.set_text(&mut app, recolored);
3978 assert!(
3979 !paragraph.debug_needs_layout(&app),
3980 "a color change is paint only"
3981 );
3982 assert!(paragraph.as_object().debug_needs_paint(&app));
3983
3984 paragraph.set_text(&mut app, span("Hello there"));
3985 assert!(paragraph.debug_needs_layout(&app));
3986 }
3987
3988 #[test]
3989 fn painting_records_glyphs_and_hit_testing_lands_on_the_span_and_the_paragraph() {
3990 let cell = AppCell::new();
3991 let mut app = cell.borrow_mut();
3992 let loose = BoxConstraints::new().max_width(1000.0).max_height(1000.0);
3993 let paragraph = laid_out(&mut app, "Hello", loose);
3994 pump_frame(&mut app, EnginePhase::Paint);
3995 assert!(!paragraph.as_object().debug_needs_paint(&app));
3996
3997 let mut result = HitTestResult::new();
3998 let hit = paragraph.hit_test(
3999 &mut app,
4000 &mut BoxHitTestResult::wrap(&mut result),
4001 Offset::new(2.0, 2.0),
4002 );
4003 assert!(hit);
4004 assert_eq!(result.path().len(), 2, "the span, then the paragraph");
4005 let position = paragraph.get_position_for_offset(&mut app, Offset::new(0.0, 1.0));
4006 assert_eq!(position.offset, 0);
4007 assert_eq!(
4008 paragraph.get_word_boundary(&mut app, TextPosition::new(1)),
4009 TextRange::new(0, 5)
4010 );
4011 }
4012
4013 fn boxes_of(
4017 app: &mut App,
4018 paragraph: RenderHandle<RenderParagraph>,
4019 start: i32,
4020 end: i32,
4021 ) -> Vec<TextBox> {
4022 paragraph.get_boxes_for_selection(
4023 app,
4024 TextSelection::new(start, end),
4025 BoxHeightStyle::Tight,
4026 BoxWidthStyle::Tight,
4027 )
4028 }
4029
4030 fn center_of(text_box: &TextBox) -> Offset {
4031 Offset::new(
4032 (text_box.left + text_box.right) / 2.0,
4033 (text_box.top + text_box.bottom) / 2.0,
4034 )
4035 }
4036
4037 fn spans_hit(
4039 app: &mut App,
4040 paragraph: RenderHandle<RenderParagraph>,
4041 position: Offset,
4042 ) -> (bool, Vec<String>) {
4043 let mut result = HitTestResult::new();
4044 let hit = paragraph.hit_test(app, &mut BoxHitTestResult::wrap(&mut result), position);
4045 let spans = result
4046 .path()
4047 .iter()
4048 .filter_map(|entry| {
4049 let target: &dyn Any = entry.target();
4050 target.downcast_ref::<TextSpan>()?.text.clone()
4051 })
4052 .collect();
4053 (hit, spans)
4054 }
4055
4056 #[test]
4059 fn a_hit_on_a_glyph_adds_its_span_and_a_hit_off_the_glyphs_adds_none() {
4060 let cell = AppCell::new();
4061 let mut app = cell.borrow_mut();
4062 let text = TextSpan::new()
4063 .style(TextStyle::new().font_size(10.0))
4064 .children(vec![
4065 TextSpan::new().text("A".repeat(10)).into_span(),
4066 TextSpan::new()
4067 .text("BC")
4068 .style(TextStyle::new().letter_spacing(26.0))
4069 .into_span(),
4070 ])
4071 .into_span();
4072 let paragraph = laid_out_span(&mut app, text, BoxConstraints::tight_for(Some(300.0), None));
4073
4074 let first_a = center_of(&boxes_of(&mut app, paragraph, 0, 1)[0]);
4075 let last_a = center_of(&boxes_of(&mut app, paragraph, 9, 10)[0]);
4076 let b = boxes_of(&mut app, paragraph, 10, 11)[0];
4077 let c = center_of(&boxes_of(&mut app, paragraph, 11, 12)[0]);
4078 for position in [first_a, last_a] {
4079 assert_eq!(
4080 spans_hit(&mut app, paragraph, position),
4081 (true, vec!["A".repeat(10)])
4082 );
4083 }
4084 let between_b_and_c = Offset::new(b.right - 1.0, center_of(&b).dy());
4086 for position in [center_of(&b), between_b_and_c, c] {
4087 assert_eq!(
4088 spans_hit(&mut app, paragraph, position),
4089 (true, vec!["BC".to_owned()])
4090 );
4091 }
4092
4093 let after_c = Offset::new(299.0, c.dy());
4094 assert_eq!(
4095 spans_hit(&mut app, paragraph, after_c),
4096 (true, Vec::new()),
4097 "the paragraph hits itself, and no span is under the pointer"
4098 );
4099 assert_eq!(
4100 spans_hit(&mut app, paragraph, Offset::new(9999.0, 9999.0)),
4101 (false, Vec::new())
4102 );
4103 }
4104
4105 struct RootHitTester {
4108 root: RenderHandle<RenderRepaintBoundary>,
4109 }
4110
4111 impl waft_gestures::GestureBindingOverridesObject for RootHitTester {
4112 fn hit_test_in_view(
4113 self: Handle<Self>,
4114 app: &mut App,
4115 result: &mut HitTestResult,
4116 position: Offset,
4117 _view_id: waft_embedder::ViewId,
4118 ) {
4119 let root = app.get(self).root;
4120 root.hit_test(app, &mut BoxHitTestResult::wrap(result), position);
4121 }
4122
4123 fn will_dispatch_event(
4124 self: Handle<Self>,
4125 _app: &mut App,
4126 _event: &waft_gestures::PointerEvent,
4127 _hit_test_result: Option<&HitTestResult>,
4128 ) {
4129 }
4130 }
4131
4132 fn tap_at(app: &mut App, position: Offset) {
4133 use waft_gestures::{GestureBinding, PointerDownEvent, PointerEvent, PointerUpEvent};
4134 let binding = GestureBinding::instance(app);
4135 binding.handle_pointer_event(
4136 app,
4137 PointerEvent::Down(PointerDownEvent {
4138 position,
4139 ..PointerDownEvent::default()
4140 }),
4141 );
4142 app.drain_microtasks();
4143 binding.handle_pointer_event(
4144 app,
4145 PointerEvent::Up(PointerUpEvent {
4146 position,
4147 ..PointerUpEvent::default()
4148 }),
4149 );
4150 app.drain_microtasks();
4151 }
4152
4153 #[test]
4156 fn a_tap_on_a_span_runs_its_recognizer_and_a_tap_beside_it_does_not() {
4157 use waft_gestures::{GestureBinding, GestureRecognizerLeaf, TapGestureRecognizer};
4158
4159 let cell = AppCell::new();
4160 let mut app = cell.borrow_mut();
4161 let taps = Rc::new(std::cell::Cell::new(0));
4162 let recognizer = TapGestureRecognizer::new(&mut app);
4163 let counter = Rc::clone(&taps);
4164 recognizer.set_on_tap(
4165 &mut app,
4166 Some(waft_foundation::Listener::new(move |_app| {
4167 counter.set(counter.get() + 1)
4168 })),
4169 );
4170 let text = TextSpan::new()
4171 .style(TextStyle::new().font_size(20.0))
4172 .children(vec![
4173 TextSpan::new().text("Tap ").into_span(),
4174 TextSpan::new()
4175 .text("here")
4176 .recognizer(recognizer.erase())
4177 .into_span(),
4178 TextSpan::new().text(" please").into_span(),
4179 ])
4180 .into_span();
4181 let paragraph = laid_out_span(
4182 &mut app,
4183 text,
4184 BoxConstraints::new().max_width(1000.0).max_height(1000.0),
4185 );
4186 let root = test_render_root(&mut app);
4187 let hit_tester = app.create(RootHitTester { root });
4188 GestureBinding::instance(&mut app).set_overrides(&mut app, Rc::new(hit_tester));
4189
4190 let here = center_of(&boxes_of(&mut app, paragraph, 4, 8)[0]);
4191 tap_at(&mut app, here);
4192 assert_eq!(taps.get(), 1);
4193
4194 let beside = center_of(&boxes_of(&mut app, paragraph, 0, 3)[0]);
4195 tap_at(&mut app, beside);
4196 assert_eq!(taps.get(), 1, "the plain span has no recognizer");
4197 recognizer.as_recognizer().dispose(&mut app);
4198 }
4199
4200 #[test]
4203 fn the_mouse_shows_the_cursor_of_the_span_under_it() {
4204 use waft_gestures::{
4205 GestureRecognizerLeaf, PointerAddedEvent, PointerEvent, PointerHoverEvent,
4206 TapGestureRecognizer,
4207 };
4208 use waft_services::{MouseCursorRef, SystemMouseCursors};
4209
4210 use crate::mouse_tracker::MouseTracker;
4211
4212 let cell = AppCell::new();
4213 let mut app = cell.borrow_mut();
4214 let recognizer = TapGestureRecognizer::new(&mut app);
4215 let text = TextSpan::new()
4216 .style(TextStyle::new().font_size(20.0))
4217 .children(vec![
4218 TextSpan::new().text("plain ").into_span(),
4219 TextSpan::new()
4220 .text("link")
4221 .recognizer(recognizer.erase())
4222 .into_span(),
4223 TextSpan::new()
4224 .text(" forbidden")
4225 .mouse_cursor(SystemMouseCursors::FORBIDDEN)
4226 .into_span(),
4227 ])
4228 .into_span();
4229 let paragraph = laid_out_span(
4230 &mut app,
4231 text,
4232 BoxConstraints::new().max_width(1000.0).max_height(1000.0),
4233 );
4234 let root = test_render_root(&mut app);
4235 let tracker = MouseTracker::new(
4236 &mut app,
4237 Rc::new(move |app: &mut App, position: Offset, _view| {
4238 let mut result = HitTestResult::new();
4239 root.hit_test(app, &mut BoxHitTestResult::wrap(&mut result), position);
4240 result
4241 }),
4242 );
4243 let plain = center_of(&boxes_of(&mut app, paragraph, 0, 5)[0]);
4244 let link = center_of(&boxes_of(&mut app, paragraph, 6, 10)[0]);
4245 let forbidden = center_of(&boxes_of(&mut app, paragraph, 11, 20)[0]);
4246 tracker.update_with_event(
4247 &mut app,
4248 &PointerEvent::Added(PointerAddedEvent {
4249 kind: waft_embedder::PointerDeviceKind::Mouse,
4250 position: plain,
4251 ..PointerAddedEvent::default()
4252 }),
4253 None,
4254 );
4255 let cursor_at = |app: &mut App, position: Offset| -> MouseCursorRef {
4256 tracker.update_with_event(
4257 app,
4258 &PointerEvent::Hover(PointerHoverEvent {
4259 kind: waft_embedder::PointerDeviceKind::Mouse,
4260 position,
4261 ..PointerHoverEvent::default()
4262 }),
4263 None,
4264 );
4265 tracker.debug_device_active_cursor(app, 0).unwrap()
4266 };
4267 let basic: MouseCursorRef = SystemMouseCursors::BASIC.into();
4268 let click: MouseCursorRef = SystemMouseCursors::CLICK.into();
4269 let forbidden_cursor: MouseCursorRef = SystemMouseCursors::FORBIDDEN.into();
4270 assert!(*cursor_at(&mut app, link) == *click);
4271 assert!(*cursor_at(&mut app, plain) == *basic, "a plain span defers");
4272 assert!(*cursor_at(&mut app, forbidden) == *forbidden_cursor);
4273 recognizer.as_recognizer().dispose(&mut app);
4274 }
4275
4276 #[test]
4279 fn a_wrapped_span_is_entered_once_across_its_lines() {
4280 use std::cell::RefCell;
4281
4282 use waft_gestures::{
4283 PointerAddedEvent, PointerEnterEvent, PointerEvent, PointerExitEvent, PointerHoverEvent,
4284 };
4285
4286 use crate::mouse_tracker::MouseTracker;
4287
4288 let cell = AppCell::new();
4289 let mut app = cell.borrow_mut();
4290 let log: Rc<RefCell<Vec<&str>>> = Rc::default();
4291 let enter_log = Rc::clone(&log);
4292 let exit_log = Rc::clone(&log);
4293 let words = "one two three four five six seven eight";
4294 let text = TextSpan::new()
4295 .text(words)
4296 .style(TextStyle::new().font_size(20.0))
4297 .on_enter(Rc::new(move |_app: &mut App, _event: PointerEnterEvent| {
4298 enter_log.borrow_mut().push("enter")
4299 }))
4300 .on_exit(Rc::new(move |_app: &mut App, _event: PointerExitEvent| {
4301 exit_log.borrow_mut().push("exit")
4302 }))
4303 .into_span();
4304 let paragraph = laid_out_span(
4305 &mut app,
4306 text,
4307 BoxConstraints::new().max_width(120.0).max_height(1000.0),
4308 );
4309 let boxes = boxes_of(&mut app, paragraph, 0, 3);
4310 let first_line = center_of(&boxes[0]);
4311 let last = words.len() as i32;
4312 let last_box = *boxes_of(&mut app, paragraph, last - 1, last)
4313 .last()
4314 .unwrap();
4315 assert!(last_box.top > boxes[0].bottom - 1.0, "the span wraps");
4316 let last_line = center_of(&last_box);
4317 let root = test_render_root(&mut app);
4318 let tracker = MouseTracker::new(
4319 &mut app,
4320 Rc::new(move |app: &mut App, position: Offset, _view| {
4321 let mut result = HitTestResult::new();
4322 root.hit_test(app, &mut BoxHitTestResult::wrap(&mut result), position);
4323 result
4324 }),
4325 );
4326 let mouse = |position: Offset| {
4327 PointerEvent::Hover(PointerHoverEvent {
4328 kind: waft_embedder::PointerDeviceKind::Mouse,
4329 position,
4330 ..PointerHoverEvent::default()
4331 })
4332 };
4333 tracker.update_with_event(
4334 &mut app,
4335 &PointerEvent::Added(PointerAddedEvent {
4336 kind: waft_embedder::PointerDeviceKind::Mouse,
4337 position: Offset::new(5000.0, 5000.0),
4338 ..PointerAddedEvent::default()
4339 }),
4340 None,
4341 );
4342 tracker.update_with_event(&mut app, &mouse(first_line), None);
4343 tracker.update_with_event(&mut app, &mouse(last_line), None);
4344 assert_eq!(*log.borrow(), ["enter"]);
4345 tracker.update_with_event(&mut app, &mouse(Offset::new(5000.0, 5000.0)), None);
4346 assert_eq!(*log.borrow(), ["enter", "exit"]);
4347 }
4348}
4349
4350#[cfg(test)]
4351mod selection_tests {
4352 use waft_embedder::valo::Op;
4358 use waft_embedder::{Color, Offset, Rect, TextPosition};
4359 use waft_foundation::{AppCell, Handle};
4360 use waft_painting::TextSpan;
4361
4362 use super::*;
4363 use crate::layer::{AnyLayer, OffsetLayer, PictureLayer};
4364 use crate::selection::{
4365 AnySelectable, SelectionEvent, SelectionExtendDirection, SelectionRegistrar,
4366 TextGranularity,
4367 };
4368 use crate::testing::EnginePhase;
4369
4370 struct TestSelectionRegistrar {
4372 selectables: Vec<AnySelectable>,
4373 }
4374
4375 impl SelectionRegistrar for TestSelectionRegistrar {
4376 fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
4377 app.get_mut(self).selectables.push(selectable);
4378 }
4379
4380 fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
4381 app.get_mut(self).selectables.retain(|s| *s != selectable);
4382 }
4383 }
4384
4385 const SELECTION_COLOR: Color = Color::from_argb(0xAF, 0x66, 0x94, 0xE8);
4386
4387 fn span(text: &str) -> InlineSpanRef {
4388 TextSpan::new().text(text).into_span()
4389 }
4390
4391 fn nested_span(text: &str) -> InlineSpanRef {
4393 TextSpan::new().children(vec![span(text)]).into_span()
4394 }
4395
4396 fn registrar(app: &mut App) -> Ref<TestSelectionRegistrar> {
4397 app.create(TestSelectionRegistrar {
4398 selectables: Vec::new(),
4399 })
4400 }
4401
4402 fn selectables(app: &App, registrar: &Ref<TestSelectionRegistrar>) -> Vec<AnySelectable> {
4403 app.get(registrar).selectables.clone()
4404 }
4405
4406 fn paragraph_with_registrar(
4407 app: &mut App,
4408 text: InlineSpanRef,
4409 registrar: &Ref<TestSelectionRegistrar>,
4410 ) -> RenderHandle<RenderParagraph> {
4411 let paragraph = RenderParagraph::new(app, text, TextDirection::Ltr, None);
4412 paragraph.set_registrar(app, Some(registrar.erase()));
4413 paragraph
4414 }
4415
4416 fn selection_paragraph(
4418 app: &mut App,
4419 paragraph: RenderHandle<RenderParagraph>,
4420 registrar: &Ref<TestSelectionRegistrar>,
4421 start: TextPosition,
4422 end: TextPosition,
4423 ) {
4424 for selectable in selectables(app, registrar) {
4425 let start_offset =
4426 paragraph.get_offset_for_caret(app, start, Rect::ZERO) + Offset::new(0.0, 5.0);
4427 selectable
4428 .dispatch_selection_event(app, &SelectionEvent::for_start(start_offset, None));
4429 let end_offset =
4430 paragraph.get_offset_for_caret(app, end, Rect::ZERO) + Offset::new(0.0, 5.0);
4431 selectable.dispatch_selection_event(app, &SelectionEvent::for_end(end_offset, None));
4432 }
4433 }
4434
4435 fn the_selection(app: &App, paragraph: RenderHandle<RenderParagraph>) -> (i32, i32) {
4437 let selections = paragraph.selections(app);
4438 assert_eq!(selections.len(), 1);
4439 (selections[0].start(), selections[0].end())
4440 }
4441
4442 fn lay_out(
4444 app: &mut App,
4445 paragraph: RenderHandle<RenderParagraph>,
4446 constraints: Option<BoxConstraints>,
4447 ) {
4448 crate::testing::layout_with(
4449 app,
4450 paragraph.as_box(),
4451 constraints,
4452 waft_painting::AlignmentGeometry::CENTER,
4453 EnginePhase::Layout,
4454 );
4455 }
4456
4457 fn drawn_rects(ops: &[Op]) -> Vec<(Rect, Color)> {
4458 ops.iter()
4459 .filter_map(|op| match op {
4460 Op::DrawRect { rect, paint, .. } => Some((
4461 Rect::from_ltrb(
4462 rect.x as f64,
4463 rect.y as f64,
4464 (rect.x + rect.width) as f64,
4465 (rect.y + rect.height) as f64,
4466 ),
4467 paint.color.into(),
4468 )),
4469 _ => None,
4470 })
4471 .collect()
4472 }
4473
4474 fn assert_same_color_as(actual: Color, expected: Color) {
4476 let step = 1.0 / 255.0;
4477 assert!(
4478 actual.color_space == expected.color_space
4479 && (actual.a - expected.a).abs() <= step
4480 && (actual.r - expected.r).abs() <= step
4481 && (actual.g - expected.g).abs() <= step
4482 && (actual.b - expected.b).abs() <= step,
4483 "{actual:?} is not {expected:?}"
4484 );
4485 }
4486
4487 #[test]
4489 fn subscribe_to_selection_registrar() {
4490 let cell = AppCell::new();
4491 let mut app = cell.borrow_mut();
4492 let registrar = registrar(&mut app);
4493 let paragraph = paragraph_with_registrar(&mut app, span("1234567"), ®istrar);
4494 assert_eq!(selectables(&app, ®istrar).len(), 1);
4495
4496 paragraph.set_text(&mut app, span(""));
4497 assert_eq!(selectables(&app, ®istrar).len(), 0);
4498 }
4499
4500 #[test]
4502 fn paints_selection_highlight() {
4503 let cell = AppCell::new();
4504 let mut app = cell.borrow_mut();
4505 let registrar = registrar(&mut app);
4506 let paragraph = paragraph_with_registrar(&mut app, span("1234567"), ®istrar);
4507 paragraph.set_selection_color(&mut app, Some(SELECTION_COLOR));
4508 lay_out(&mut app, paragraph, None);
4509 let ops = crate::testing::painted_ops(&mut app, paragraph.as_object());
4510 assert!(drawn_rects(&ops).is_empty());
4511 selection_paragraph(
4512 &mut app,
4513 paragraph,
4514 ®istrar,
4515 TextPosition::new(1),
4516 TextPosition::new(5),
4517 );
4518
4519 let ops = crate::testing::painted_ops(&mut app, paragraph.as_object());
4520 let drawn = drawn_rects(&ops);
4521 assert_eq!(drawn.len(), 1);
4522 assert_eq!(drawn[0].0, Rect::from_ltwh(14.0, 0.0, 56.0, 14.0));
4523 assert_same_color_as(drawn[0].1, SELECTION_COLOR);
4524 let drawn_items: Vec<&str> = ops
4526 .iter()
4527 .filter_map(|op| match op {
4528 Op::DrawRect { .. } => Some("Rect"),
4529 Op::GlyphRun { .. } => Some("Paragraph"),
4530 _ => None,
4531 })
4532 .collect();
4533 assert_eq!(drawn_items.first(), Some(&"Rect"));
4534 assert!(drawn_items[1..].iter().all(|item| *item == "Paragraph"));
4535
4536 selection_paragraph(
4537 &mut app,
4538 paragraph,
4539 ®istrar,
4540 TextPosition::new(2),
4541 TextPosition::new(4),
4542 );
4543 let ops = crate::testing::painted_ops(&mut app, paragraph.as_object());
4544 let drawn = drawn_rects(&ops);
4545 let last = drawn.last().expect("a selection rect");
4546 assert_eq!(last.0, Rect::from_ltwh(28.0, 0.0, 28.0, 14.0));
4547 assert_same_color_as(last.1, SELECTION_COLOR);
4548 }
4549
4550 #[test]
4554 fn paints_selection_highlights_outside_fade_layer_and_handles_after_text() {
4555 let cell = AppCell::new();
4556 let mut app = cell.borrow_mut();
4557 let registrar = registrar(&mut app);
4558 let paragraph = paragraph_with_registrar(&mut app, span("a\na\na\na"), ®istrar);
4559 paragraph.set_selection_color(&mut app, Some(SELECTION_COLOR));
4560 paragraph.set_max_lines(&mut app, Some(3));
4561 paragraph.set_overflow(&mut app, TextOverflow::Fade);
4562 lay_out(
4563 &mut app,
4564 paragraph,
4565 Some(BoxConstraints::new().max_width(100.0)),
4566 );
4567
4568 for selectable in selectables(&app, ®istrar) {
4569 selectable.dispatch_selection_event(&mut app, &SelectionEvent::SelectAll);
4570 let start = LayerLink::new(&mut app);
4571 let end = LayerLink::new(&mut app);
4572 selectable.push_handle_layers(&mut app, Some(start), Some(end));
4573 }
4574
4575 let layer = OffsetLayer::new(&mut app, Offset::ZERO);
4576 let container = layer.as_container_layer();
4577 let bounds = paragraph.as_object().paint_bounds(&app);
4578 let mut context = PaintingContext::new(container, bounds);
4579 paragraph
4580 .as_object()
4581 .paint(&mut app, &mut context, Offset::ZERO);
4582 context.stop_recording_if_needed(&mut app);
4583
4584 let mut children: Vec<AnyLayer> = Vec::new();
4585 let mut child = container.first_child(&app);
4586 while let Some(layer) = child {
4587 children.push(layer);
4588 child = layer.next_sibling(&app);
4589 }
4590 assert_eq!(children.len(), 3);
4592 let picture = app
4593 .handle::<PictureLayer>(children[0].id())
4594 .and_then(|picture| picture.picture(&app))
4595 .expect("the text's picture");
4596 let ops = waft_embedder::flattened_ops(picture);
4597 let first_glyph = ops
4598 .iter()
4599 .position(|op| matches!(op, Op::GlyphRun { .. }))
4600 .expect("the text");
4601 assert!(
4602 ops[..first_glyph]
4603 .iter()
4604 .any(|op| matches!(op, Op::DrawRect { .. }))
4605 );
4606 assert!(
4607 !ops[first_glyph..]
4608 .iter()
4609 .any(|op| matches!(op, Op::DrawRect { .. }))
4610 );
4611 let leaders = children[1..]
4612 .iter()
4613 .filter(|layer| app.handle::<LeaderLayer>(layer.id()).is_some())
4614 .count();
4615 assert_eq!(leaders, 2);
4616 }
4617
4618 #[test]
4620 fn paints_selection_when_tap_at_chinese_character() {
4621 let cell = AppCell::new();
4622 let mut app = cell.borrow_mut();
4623 let registrar = registrar(&mut app);
4624 let paragraph = paragraph_with_registrar(&mut app, span("\u{4F60}\u{597D}"), ®istrar);
4625 paragraph.set_selection_color(&mut app, Some(SELECTION_COLOR));
4626 lay_out(&mut app, paragraph, None);
4627 let ops = crate::testing::painted_ops(&mut app, paragraph.as_object());
4628 assert!(drawn_rects(&ops).is_empty());
4629
4630 for selectable in selectables(&app, ®istrar) {
4631 selectable.dispatch_selection_event(
4632 &mut app,
4633 &SelectionEvent::SelectWord {
4634 global_position: Offset::new(7.0, 0.0),
4635 },
4636 );
4637 }
4638
4639 let ops = crate::testing::painted_ops(&mut app, paragraph.as_object());
4640 let (rect, color) = *drawn_rects(&ops).last().expect("a selection rect");
4641 assert!(!rect.is_empty());
4642 assert_same_color_as(color, SELECTION_COLOR);
4643 }
4644
4645 #[test]
4647 fn get_position_for_offset_works() {
4648 let cell = AppCell::new();
4649 let mut app = cell.borrow_mut();
4650 let paragraph = RenderParagraph::new(&mut app, span("1234567"), TextDirection::Ltr, None);
4651 lay_out(&mut app, paragraph, None);
4652 assert_eq!(
4653 paragraph.get_position_for_offset(&mut app, Offset::new(42.0, 14.0)),
4654 TextPosition::new(3)
4655 );
4656 }
4657
4658 fn granularly_extend(
4659 app: &mut App,
4660 registrar: &Ref<TestSelectionRegistrar>,
4661 forward: bool,
4662 granularity: TextGranularity,
4663 ) {
4664 selectables(app, registrar)[0].dispatch_selection_event(
4665 app,
4666 &SelectionEvent::GranularlyExtendSelection {
4667 forward,
4668 is_end: true,
4669 granularity,
4670 },
4671 );
4672 }
4673
4674 fn how_are_you(
4676 app: &mut App,
4677 registrar: &Ref<TestSelectionRegistrar>,
4678 ) -> RenderHandle<RenderParagraph> {
4679 let paragraph = paragraph_with_registrar(
4680 app,
4681 nested_span("how are you\nI am fine\nThank you"),
4682 registrar,
4683 );
4684 lay_out(app, paragraph, None);
4685 assert_eq!(selectables(app, registrar).len(), 1);
4686 paragraph
4687 }
4688
4689 #[test]
4691 fn can_granularly_extend_selection_character() {
4692 let cell = AppCell::new();
4693 let mut app = cell.borrow_mut();
4694 let registrar = registrar(&mut app);
4695 let paragraph = how_are_you(&mut app, ®istrar);
4696 selection_paragraph(
4697 &mut app,
4698 paragraph,
4699 ®istrar,
4700 TextPosition::new(4),
4701 TextPosition::new(5),
4702 );
4703 assert_eq!(the_selection(&app, paragraph), (4, 5)); granularly_extend(&mut app, ®istrar, true, TextGranularity::Character);
4707 assert_eq!(the_selection(&app, paragraph), (4, 6)); granularly_extend(&mut app, ®istrar, false, TextGranularity::Character);
4711 assert_eq!(the_selection(&app, paragraph), (4, 5)); }
4713
4714 #[test]
4716 fn can_granularly_extend_selection_word() {
4717 let cell = AppCell::new();
4718 let mut app = cell.borrow_mut();
4719 let registrar = registrar(&mut app);
4720 let paragraph = how_are_you(&mut app, ®istrar);
4721 selection_paragraph(
4722 &mut app,
4723 paragraph,
4724 ®istrar,
4725 TextPosition::new(4),
4726 TextPosition::new(5),
4727 );
4728 assert_eq!(the_selection(&app, paragraph), (4, 5)); granularly_extend(&mut app, ®istrar, true, TextGranularity::Word);
4732 assert_eq!(the_selection(&app, paragraph), (4, 7)); granularly_extend(&mut app, ®istrar, false, TextGranularity::Word);
4736 assert_eq!(the_selection(&app, paragraph), (4, 4)); granularly_extend(&mut app, ®istrar, false, TextGranularity::Word);
4740 assert_eq!(the_selection(&app, paragraph), (0, 4)); }
4742
4743 #[test]
4745 fn can_granularly_extend_selection_line() {
4746 let cell = AppCell::new();
4747 let mut app = cell.borrow_mut();
4748 let registrar = registrar(&mut app);
4749 let paragraph = how_are_you(&mut app, ®istrar);
4750 selection_paragraph(
4751 &mut app,
4752 paragraph,
4753 ®istrar,
4754 TextPosition::new(4),
4755 TextPosition::new(5),
4756 );
4757 assert_eq!(the_selection(&app, paragraph), (4, 5)); granularly_extend(&mut app, ®istrar, true, TextGranularity::Line);
4761 assert_eq!(the_selection(&app, paragraph), (4, 11));
4763
4764 granularly_extend(&mut app, ®istrar, false, TextGranularity::Line);
4766 assert_eq!(the_selection(&app, paragraph), (0, 4));
4768 }
4769
4770 #[test]
4772 fn can_granularly_extend_selection_document() {
4773 let cell = AppCell::new();
4774 let mut app = cell.borrow_mut();
4775 let registrar = registrar(&mut app);
4776 let paragraph = how_are_you(&mut app, ®istrar);
4777 selection_paragraph(
4778 &mut app,
4779 paragraph,
4780 ®istrar,
4781 TextPosition::new(14),
4782 TextPosition::new(15),
4783 );
4784 assert_eq!(the_selection(&app, paragraph), (14, 15));
4787
4788 granularly_extend(&mut app, ®istrar, true, TextGranularity::Document);
4790 assert_eq!(the_selection(&app, paragraph), (14, 31));
4794
4795 granularly_extend(&mut app, ®istrar, false, TextGranularity::Document);
4797 assert_eq!(the_selection(&app, paragraph), (0, 14));
4800 }
4801
4802 #[test]
4804 fn can_granularly_extend_selection_when_no_active_selection() {
4805 let cell = AppCell::new();
4806 let mut app = cell.borrow_mut();
4807 let registrar = registrar(&mut app);
4808 let paragraph = how_are_you(&mut app, ®istrar);
4809 assert!(paragraph.selections(&app).is_empty());
4810
4811 granularly_extend(&mut app, ®istrar, true, TextGranularity::Word);
4813 assert_eq!(the_selection(&app, paragraph), (0, 3));
4815
4816 selectables(&app, ®istrar)[0].dispatch_selection_event(&mut app, &SelectionEvent::Clear);
4818 assert!(paragraph.selections(&app).is_empty());
4819
4820 granularly_extend(&mut app, ®istrar, false, TextGranularity::Word);
4822 assert_eq!(the_selection(&app, paragraph), (28, 31));
4826 }
4827
4828 fn directionally_extend(
4829 app: &mut App,
4830 registrar: &Ref<TestSelectionRegistrar>,
4831 dx: f64,
4832 direction: SelectionExtendDirection,
4833 ) {
4834 selectables(app, registrar)[0].dispatch_selection_event(
4835 app,
4836 &SelectionEvent::DirectionallyExtendSelection {
4837 dx,
4838 is_end: true,
4839 direction,
4840 },
4841 );
4842 }
4843
4844 fn transformed_dx(transform: &Matrix4, point: Offset) -> f64 {
4846 waft_painting::transform_point(transform, point).dx()
4847 }
4848
4849 #[test]
4851 fn can_directionally_extend_selection() {
4852 let cell = AppCell::new();
4853 let mut app = cell.borrow_mut();
4854 let registrar = registrar(&mut app);
4855 let paragraph = how_are_you(&mut app, ®istrar);
4856 selection_paragraph(
4857 &mut app,
4858 paragraph,
4859 ®istrar,
4860 TextPosition::new(14),
4861 TextPosition::new(15),
4862 );
4863 assert_eq!(the_selection(&app, paragraph), (14, 15));
4866
4867 let selectable = selectables(&app, ®istrar)[0];
4868 let baseline = transformed_dx(
4869 &selectable.get_transform_to(&app, None),
4870 selectable
4871 .value(&app)
4872 .end_selection_point
4873 .expect("a selection")
4874 .local_position,
4875 );
4876
4877 directionally_extend(
4879 &mut app,
4880 ®istrar,
4881 baseline,
4882 SelectionExtendDirection::NextLine,
4883 );
4884 assert_eq!(the_selection(&app, paragraph), (14, 25));
4888
4889 directionally_extend(
4891 &mut app,
4892 ®istrar,
4893 baseline,
4894 SelectionExtendDirection::PreviousLine,
4895 );
4896 assert_eq!(the_selection(&app, paragraph), (14, 15));
4899 }
4900
4901 #[test]
4903 fn can_directionally_extend_selection_when_no_selection() {
4904 let cell = AppCell::new();
4905 let mut app = cell.borrow_mut();
4906 let registrar = registrar(&mut app);
4907 let paragraph = how_are_you(&mut app, ®istrar);
4908 assert!(paragraph.selections(&app).is_empty());
4909
4910 let selectable = selectables(&app, ®istrar)[0];
4911 let size = selectable.size(&mut app);
4912 let baseline = transformed_dx(
4913 &selectable.get_transform_to(&app, None),
4914 Offset::new(size.width() / 2.0, 0.0),
4915 );
4916
4917 directionally_extend(
4919 &mut app,
4920 ®istrar,
4921 baseline,
4922 SelectionExtendDirection::Forward,
4923 );
4924 assert_eq!(the_selection(&app, paragraph), (0, 6));
4927
4928 selectable.dispatch_selection_event(&mut app, &SelectionEvent::Clear);
4930 assert!(paragraph.selections(&app).is_empty());
4931
4932 directionally_extend(
4934 &mut app,
4935 ®istrar,
4936 baseline,
4937 SelectionExtendDirection::Backward,
4938 );
4939 assert_eq!(the_selection(&app, paragraph), (28, 31));
4943 }
4944}