1use waft_embedder::{Matrix4, Offset, Rect, Size, TextDirection};
12use waft_foundation::{
13 App, Handle, HandleId, ListenableHandle, ListenableObject, Listener, Ref, Retained,
14};
15
16use crate::layer::LayerLink;
17use crate::object::AnyRenderObject;
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum SelectionResult {
25 Next,
28 Previous,
30 End,
32 Pending,
34 None,
36}
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
40pub struct SelectedContentRange {
41 pub start_offset: i32,
43 pub end_offset: i32,
45}
46
47impl SelectedContentRange {
48 pub fn new(start_offset: i32, end_offset: i32) -> SelectedContentRange {
50 debug_assert!(start_offset >= 0 && end_offset >= 0);
51 SelectedContentRange {
52 start_offset,
53 end_offset,
54 }
55 }
56}
57
58#[derive(Clone, Debug)]
60pub struct SelectedContent {
61 pub plain_text: String,
63}
64
65impl SelectedContent {
66 pub fn new(plain_text: impl Into<String>) -> SelectedContent {
68 SelectedContent {
69 plain_text: plain_text.into(),
70 }
71 }
72}
73
74pub trait SelectionHandler: ListenableObject {
80 fn value(self: Handle<Self>, app: &App) -> SelectionGeometry;
82
83 fn push_handle_layers(
86 self: Handle<Self>,
87 app: &mut App,
88 start_handle: Option<Ref<LayerLink>>,
89 end_handle: Option<Ref<LayerLink>>,
90 );
91
92 fn selected_content(self: Handle<Self>, app: &App) -> Option<SelectedContent>;
94
95 fn selection(self: Handle<Self>, app: &App) -> Option<SelectedContentRange>;
97
98 fn dispatch_selection_event(
100 self: Handle<Self>,
101 app: &mut App,
102 event: &SelectionEvent,
103 ) -> SelectionResult;
104
105 fn content_length(self: Handle<Self>, app: &App) -> usize;
107}
108
109pub trait Selectable: SelectionHandler {
115 fn as_selectable(self: Handle<Self>) -> AnySelectable {
117 AnySelectable {
118 id: self.id(),
119 vtable: const { &SelectableVTable::of::<Self>() },
120 }
121 }
122
123 fn get_transform_to(
125 self: Handle<Self>,
126 app: &App,
127 ancestor: Option<AnyRenderObject>,
128 ) -> Matrix4;
129
130 fn size(self: Handle<Self>, app: &mut App) -> Size;
132
133 fn bounding_boxes(self: Handle<Self>, app: &mut App) -> Vec<Rect>;
135
136 fn dispose_selectable(self: Handle<Self>, app: &mut App);
138}
139
140#[derive(Clone, Copy)]
143pub struct AnySelectable {
144 id: HandleId,
145 vtable: &'static SelectableVTable,
146}
147
148pub type PushHandleLayers = fn(&mut App, HandleId, Option<Ref<LayerLink>>, Option<Ref<LayerLink>>);
150
151struct SelectableVTable {
152 value: fn(&App, HandleId) -> SelectionGeometry,
153 push_handle_layers: PushHandleLayers,
154 selected_content: fn(&App, HandleId) -> Option<SelectedContent>,
155 selection: fn(&App, HandleId) -> Option<SelectedContentRange>,
156 dispatch_selection_event: fn(&mut App, HandleId, &SelectionEvent) -> SelectionResult,
157 content_length: fn(&App, HandleId) -> usize,
158 get_transform_to: fn(&App, HandleId, Option<AnyRenderObject>) -> Matrix4,
159 size: fn(&mut App, HandleId) -> Size,
160 bounding_boxes: fn(&mut App, HandleId) -> Vec<Rect>,
161 dispose_selectable: fn(&mut App, HandleId),
162}
163
164impl SelectableVTable {
165 const fn of<A: Selectable>() -> SelectableVTable {
166 SelectableVTable {
167 value: |app, id| A::value(resolve(id), app),
168 push_handle_layers: |app, id, start, end| {
169 A::push_handle_layers(resolve(id), app, start, end)
170 },
171 selected_content: |app, id| A::selected_content(resolve(id), app),
172 selection: |app, id| A::selection(resolve(id), app),
173 dispatch_selection_event: |app, id, event| {
174 A::dispatch_selection_event(resolve(id), app, event)
175 },
176 content_length: |app, id| A::content_length(resolve(id), app),
177 get_transform_to: |app, id, ancestor| A::get_transform_to(resolve(id), app, ancestor),
178 size: |app, id| A::size(resolve(id), app),
179 bounding_boxes: |app, id| A::bounding_boxes(resolve(id), app),
180 dispose_selectable: |app, id| A::dispose_selectable(resolve(id), app),
181 }
182 }
183}
184
185fn resolve<A: 'static>(id: HandleId) -> Handle<A> {
186 Handle::from_id(id)
187}
188
189impl AnySelectable {
190 pub fn id(self) -> HandleId {
192 self.id
193 }
194
195 pub fn value(self, app: &App) -> SelectionGeometry {
197 (self.vtable.value)(app, self.id)
198 }
199
200 pub fn push_handle_layers(
202 self,
203 app: &mut App,
204 start_handle: Option<Ref<LayerLink>>,
205 end_handle: Option<Ref<LayerLink>>,
206 ) {
207 (self.vtable.push_handle_layers)(app, self.id, start_handle, end_handle)
208 }
209
210 pub fn selected_content(self, app: &App) -> Option<SelectedContent> {
212 (self.vtable.selected_content)(app, self.id)
213 }
214
215 pub fn selection(self, app: &App) -> Option<SelectedContentRange> {
217 (self.vtable.selection)(app, self.id)
218 }
219
220 pub fn dispatch_selection_event(
222 self,
223 app: &mut App,
224 event: &SelectionEvent,
225 ) -> SelectionResult {
226 (self.vtable.dispatch_selection_event)(app, self.id, event)
227 }
228
229 pub fn content_length(self, app: &App) -> usize {
231 (self.vtable.content_length)(app, self.id)
232 }
233
234 pub fn get_transform_to(self, app: &App, ancestor: Option<AnyRenderObject>) -> Matrix4 {
236 (self.vtable.get_transform_to)(app, self.id, ancestor)
237 }
238
239 pub fn size(self, app: &mut App) -> Size {
241 (self.vtable.size)(app, self.id)
242 }
243
244 pub fn bounding_boxes(self, app: &mut App) -> Vec<Rect> {
246 (self.vtable.bounding_boxes)(app, self.id)
247 }
248
249 pub fn dispose_selectable(self, app: &mut App) {
251 (self.vtable.dispose_selectable)(app, self.id)
252 }
253}
254
255impl std::fmt::Debug for AnySelectable {
256 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
257 f.debug_struct("AnySelectable")
258 .field("id", &self.id)
259 .finish()
260 }
261}
262
263waft_foundation::erased_handle!(AnySelectable: Selectable => Selectable::as_selectable);
264
265#[derive(Debug, Default)]
267pub struct SelectionRegistrantData {
268 registrar: Option<SelectionRegistrarRef>,
269 subscribed_to_selection_registrar: bool,
270}
271
272impl SelectionRegistrantData {
273 pub fn new() -> SelectionRegistrantData {
275 SelectionRegistrantData::default()
276 }
277}
278
279pub trait SelectionRegistrant: Selectable {
284 fn selection_registrant_data(self: Handle<Self>, app: &App) -> &SelectionRegistrantData;
286
287 fn selection_registrant_data_mut(
289 self: Handle<Self>,
290 app: &mut App,
291 ) -> &mut SelectionRegistrantData;
292
293 fn registrar(self: Handle<Self>, app: &App) -> Option<AnySelectionRegistrar> {
295 self.selection_registrant_data(app)
296 .registrar
297 .as_ref()
298 .map(Retained::handle)
299 }
300
301 fn set_registrar(self: Handle<Self>, app: &mut App, value: Option<SelectionRegistrarRef>) {
303 let registrar = self.registrar(app);
304 if value.as_ref().map(Retained::handle) == registrar {
305 return;
306 }
307 let listener = Listener::handle_method(self, Self::update_selection_registrar_subscription);
308 if value.is_none() {
309 self.remove_listener_from(app, &listener);
311 } else if registrar.is_none() {
312 self.add_listener_to(app, listener);
314 }
315 self.remove_selection_registrar_subscription(app);
316 self.selection_registrant_data_mut(app).registrar = value;
317 self.update_selection_registrar_subscription(app);
318 }
319
320 fn update_selection_registrar_subscription(self: Handle<Self>, app: &mut App) {
322 let Some(registrar) = self.registrar(app) else {
323 self.selection_registrant_data_mut(app)
324 .subscribed_to_selection_registrar = false;
325 return;
326 };
327 let has_content = self.value(app).has_content;
328 let subscribed = self
329 .selection_registrant_data(app)
330 .subscribed_to_selection_registrar;
331 if subscribed && !has_content {
332 registrar.remove(app, self.as_selectable());
333 self.selection_registrant_data_mut(app)
334 .subscribed_to_selection_registrar = false;
335 } else if !subscribed && has_content {
336 registrar.add(app, self.as_selectable());
337 self.selection_registrant_data_mut(app)
338 .subscribed_to_selection_registrar = true;
339 }
340 }
341
342 fn remove_selection_registrar_subscription(self: Handle<Self>, app: &mut App) {
344 if self
345 .selection_registrant_data(app)
346 .subscribed_to_selection_registrar
347 {
348 let registrar = self
349 .registrar(app)
350 .expect("a subscribed registrant has a registrar");
351 registrar.remove(app, self.as_selectable());
352 self.selection_registrant_data_mut(app)
353 .subscribed_to_selection_registrar = false;
354 }
355 }
356
357 fn dispose_selection_registrant(self: Handle<Self>, app: &mut App) {
360 self.remove_selection_registrar_subscription(app);
361 }
362}
363
364pub trait SelectionRegistrar: Sized + 'static {
366 fn as_selection_registrar(self: Handle<Self>) -> AnySelectionRegistrar {
368 AnySelectionRegistrar {
369 id: self.id(),
370 vtable: const { &SelectionRegistrarVTable::of::<Self>() },
371 }
372 }
373
374 fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable);
376
377 fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable);
379}
380
381#[derive(Clone, Copy)]
383pub struct AnySelectionRegistrar {
384 id: HandleId,
385 vtable: &'static SelectionRegistrarVTable,
386}
387
388struct SelectionRegistrarVTable {
389 add: fn(&mut App, HandleId, AnySelectable),
390 remove: fn(&mut App, HandleId, AnySelectable),
391}
392
393impl SelectionRegistrarVTable {
394 const fn of<A: SelectionRegistrar>() -> SelectionRegistrarVTable {
395 SelectionRegistrarVTable {
396 add: |app, id, selectable| A::add(resolve(id), app, selectable),
397 remove: |app, id, selectable| A::remove(resolve(id), app, selectable),
398 }
399 }
400}
401
402impl AnySelectionRegistrar {
403 pub fn id(self) -> HandleId {
405 self.id
406 }
407
408 pub fn add(self, app: &mut App, selectable: AnySelectable) {
410 (self.vtable.add)(app, self.id, selectable)
411 }
412
413 pub fn remove(self, app: &mut App, selectable: AnySelectable) {
415 (self.vtable.remove)(app, self.id, selectable)
416 }
417}
418
419impl std::fmt::Debug for AnySelectionRegistrar {
420 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
421 f.debug_struct("AnySelectionRegistrar")
422 .field("id", &self.id)
423 .finish()
424 }
425}
426
427pub type SelectionRegistrarRef = Retained<AnySelectionRegistrar>;
432
433waft_foundation::erased_handle!(AnySelectionRegistrar: SelectionRegistrar => SelectionRegistrar::as_selection_registrar);
434
435#[derive(Clone, Copy, Debug, PartialEq, Eq)]
437pub enum SelectionStatus {
438 Uncollapsed,
440 Collapsed,
442 None,
444}
445
446#[derive(Clone, Debug, PartialEq)]
448pub struct SelectionGeometry {
449 pub start_selection_point: Option<SelectionPoint>,
451 pub end_selection_point: Option<SelectionPoint>,
453 pub status: SelectionStatus,
455 pub selection_rects: Vec<Rect>,
457 pub has_content: bool,
459}
460
461impl SelectionGeometry {
462 pub fn new(status: SelectionStatus, has_content: bool) -> SelectionGeometry {
465 SelectionGeometry {
466 start_selection_point: None,
467 end_selection_point: None,
468 status,
469 selection_rects: Vec::new(),
470 has_content,
471 }
472 }
473
474 pub fn start_selection_point(mut self, value: Option<SelectionPoint>) -> SelectionGeometry {
476 self.start_selection_point = value;
477 self.debug_assert_points_have_selection();
478 self
479 }
480
481 pub fn end_selection_point(mut self, value: Option<SelectionPoint>) -> SelectionGeometry {
483 self.end_selection_point = value;
484 self.debug_assert_points_have_selection();
485 self
486 }
487
488 pub fn selection_rects(mut self, value: Vec<Rect>) -> SelectionGeometry {
490 self.selection_rects = value;
491 self
492 }
493
494 pub fn status(mut self, value: SelectionStatus) -> SelectionGeometry {
496 self.status = value;
497 self
498 }
499
500 pub fn has_content(mut self, value: bool) -> SelectionGeometry {
502 self.has_content = value;
503 self
504 }
505
506 fn debug_assert_points_have_selection(&self) {
507 debug_assert!(
508 (self.start_selection_point.is_none() && self.end_selection_point.is_none())
509 || self.status != SelectionStatus::None
510 );
511 }
512
513 pub fn has_selection(&self) -> bool {
515 self.status != SelectionStatus::None
516 }
517
518 pub fn copy_with(&self) -> SelectionGeometry {
520 self.clone()
521 }
522}
523
524#[derive(Clone, Copy, Debug, PartialEq)]
526pub struct SelectionPoint {
527 pub local_position: Offset,
529 pub line_height: f64,
531 pub handle_type: TextSelectionHandleType,
533}
534
535impl SelectionPoint {
536 pub fn new(
538 local_position: Offset,
539 line_height: f64,
540 handle_type: TextSelectionHandleType,
541 ) -> SelectionPoint {
542 SelectionPoint {
543 local_position,
544 line_height,
545 handle_type,
546 }
547 }
548}
549
550#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
552pub enum TextSelectionHandleType {
553 Left,
555 Right,
557 Collapsed,
559}
560
561pub struct SelectionUtils;
563
564impl SelectionUtils {
565 pub fn get_result_based_on_rect(target_rect: Rect, point: Offset) -> SelectionResult {
570 if target_rect.contains(point) {
571 return SelectionResult::End;
572 }
573 if point.dy() < target_rect.top {
574 return SelectionResult::Previous;
575 }
576 if point.dy() > target_rect.bottom {
577 return SelectionResult::Next;
578 }
579 if point.dx() >= target_rect.right {
580 SelectionResult::Next
581 } else {
582 SelectionResult::Previous
583 }
584 }
585
586 pub fn adjust_drag_offset(
592 target_rect: Rect,
593 point: Offset,
594 direction: TextDirection,
595 ) -> Offset {
596 if target_rect.contains(point) {
597 return point;
598 }
599 if point.dy() <= target_rect.top
600 || point.dy() <= target_rect.bottom && point.dx() <= target_rect.left
601 {
602 if direction == TextDirection::Ltr {
604 Offset::new(target_rect.left, target_rect.top)
605 } else {
606 Offset::new(target_rect.right, target_rect.top)
607 }
608 } else {
609 if direction == TextDirection::Ltr {
611 Offset::new(target_rect.right, target_rect.bottom)
612 } else {
613 Offset::new(target_rect.left, target_rect.bottom)
614 }
615 }
616 }
617}
618
619#[derive(Clone, Copy, Debug, PartialEq, Eq)]
621pub enum TextGranularity {
622 Character,
624 Word,
626 Paragraph,
628 Line,
630 Document,
632}
633
634#[derive(Clone, Copy, Debug, PartialEq, Eq)]
636pub enum SelectionExtendDirection {
637 PreviousLine,
639 NextLine,
641 Forward,
643 Backward,
645}
646
647#[derive(Clone, Debug)]
652pub enum SelectionEvent {
653 StartEdgeUpdate {
655 global_position: Offset,
657 granularity: TextGranularity,
659 },
660 EndEdgeUpdate {
662 global_position: Offset,
664 granularity: TextGranularity,
666 },
667 Clear,
669 SelectAll,
671 SelectWord {
673 global_position: Offset,
675 },
676 SelectParagraph {
678 global_position: Offset,
680 absorb: bool,
682 },
683 GranularlyExtendSelection {
685 forward: bool,
687 is_end: bool,
689 granularity: TextGranularity,
691 },
692 DirectionallyExtendSelection {
694 dx: f64,
696 is_end: bool,
698 direction: SelectionExtendDirection,
700 },
701}
702
703impl SelectionEvent {
704 pub fn ty(&self) -> SelectionEventType {
706 match self {
707 SelectionEvent::StartEdgeUpdate { .. } => SelectionEventType::StartEdgeUpdate,
708 SelectionEvent::EndEdgeUpdate { .. } => SelectionEventType::EndEdgeUpdate,
709 SelectionEvent::Clear => SelectionEventType::Clear,
710 SelectionEvent::SelectAll => SelectionEventType::SelectAll,
711 SelectionEvent::SelectWord { .. } => SelectionEventType::SelectWord,
712 SelectionEvent::SelectParagraph { .. } => SelectionEventType::SelectParagraph,
713 SelectionEvent::GranularlyExtendSelection { .. } => {
714 SelectionEventType::GranularlyExtendSelection
715 }
716 SelectionEvent::DirectionallyExtendSelection { .. } => {
717 SelectionEventType::DirectionallyExtendSelection
718 }
719 }
720 }
721
722 pub fn for_start(
724 global_position: Offset,
725 granularity: Option<TextGranularity>,
726 ) -> SelectionEvent {
727 SelectionEvent::StartEdgeUpdate {
728 global_position,
729 granularity: granularity.unwrap_or(TextGranularity::Character),
730 }
731 }
732
733 pub fn for_end(
735 global_position: Offset,
736 granularity: Option<TextGranularity>,
737 ) -> SelectionEvent {
738 SelectionEvent::EndEdgeUpdate {
739 global_position,
740 granularity: granularity.unwrap_or(TextGranularity::Character),
741 }
742 }
743
744 pub fn copy_with(
746 &self,
747 dx: Option<f64>,
748 is_end: Option<bool>,
749 direction: Option<SelectionExtendDirection>,
750 ) -> SelectionEvent {
751 match self {
752 SelectionEvent::DirectionallyExtendSelection {
753 dx: old_dx,
754 is_end: old_is_end,
755 direction: old_direction,
756 } => SelectionEvent::DirectionallyExtendSelection {
757 dx: dx.unwrap_or(*old_dx),
758 is_end: is_end.unwrap_or(*old_is_end),
759 direction: direction.unwrap_or(*old_direction),
760 },
761 event => event.clone(),
762 }
763 }
764}
765
766#[derive(Clone, Copy, Debug, PartialEq, Eq)]
768pub enum SelectionEventType {
769 StartEdgeUpdate,
771 EndEdgeUpdate,
773 Clear,
775 SelectAll,
777 SelectWord,
779 SelectParagraph,
781 GranularlyExtendSelection,
783 DirectionallyExtendSelection,
785}
786
787#[cfg(test)]
788mod tests {
789 use super::*;
790
791 const RECT: Rect = Rect::from_ltrb(100.0, 100.0, 300.0, 600.0);
792 const OUTSIDE_TOP_LEFT: Offset = Offset::new(50.0, 50.0);
793 const OUTSIDE_LEFT: Offset = Offset::new(50.0, 200.0);
794 const OUTSIDE_BOTTOM_LEFT: Offset = Offset::new(50.0, 700.0);
795 const OUTSIDE_TOP: Offset = Offset::new(200.0, 50.0);
796 const OUTSIDE_TOP_RIGHT: Offset = Offset::new(350.0, 50.0);
797 const OUTSIDE_RIGHT: Offset = Offset::new(350.0, 200.0);
798 const OUTSIDE_BOTTOM_RIGHT: Offset = Offset::new(350.0, 700.0);
799 const OUTSIDE_BOTTOM: Offset = Offset::new(200.0, 700.0);
800 const CENTER: Offset = Offset::new(150.0, 300.0);
801
802 #[test]
804 fn selection_based_on_rect_works() {
805 assert_eq!(
806 SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_TOP_LEFT),
807 SelectionResult::Previous
808 );
809 assert_eq!(
810 SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_LEFT),
811 SelectionResult::Previous
812 );
813 assert_eq!(
814 SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_BOTTOM_LEFT),
815 SelectionResult::Next
816 );
817 assert_eq!(
818 SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_TOP),
819 SelectionResult::Previous
820 );
821 assert_eq!(
822 SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_TOP_RIGHT),
823 SelectionResult::Previous
824 );
825 assert_eq!(
826 SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_RIGHT),
827 SelectionResult::Next
828 );
829 assert_eq!(
830 SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_BOTTOM_RIGHT),
831 SelectionResult::Next
832 );
833 assert_eq!(
834 SelectionUtils::get_result_based_on_rect(RECT, OUTSIDE_BOTTOM),
835 SelectionResult::Next
836 );
837 assert_eq!(
838 SelectionUtils::get_result_based_on_rect(RECT, CENTER),
839 SelectionResult::End
840 );
841 }
842
843 #[test]
845 fn adjust_drag_offset_works() {
846 let top_left = Offset::new(RECT.left, RECT.top);
847 let top_right = Offset::new(RECT.right, RECT.top);
848 let bottom_left = Offset::new(RECT.left, RECT.bottom);
849 let bottom_right = Offset::new(RECT.right, RECT.bottom);
850
851 for (point, expected) in [
853 (OUTSIDE_TOP_LEFT, top_left),
854 (OUTSIDE_LEFT, top_left),
855 (OUTSIDE_BOTTOM_LEFT, bottom_right),
856 (OUTSIDE_TOP, top_left),
857 (OUTSIDE_TOP_RIGHT, top_left),
858 (OUTSIDE_RIGHT, bottom_right),
859 (OUTSIDE_BOTTOM_RIGHT, bottom_right),
860 (OUTSIDE_BOTTOM, bottom_right),
861 (CENTER, CENTER),
862 ] {
863 assert_eq!(
864 SelectionUtils::adjust_drag_offset(RECT, point, TextDirection::Ltr),
865 expected
866 );
867 }
868 for (point, expected) in [
870 (OUTSIDE_TOP_LEFT, top_right),
871 (OUTSIDE_LEFT, top_right),
872 (OUTSIDE_BOTTOM_LEFT, bottom_left),
873 (OUTSIDE_TOP, top_right),
874 (OUTSIDE_TOP_RIGHT, top_right),
875 (OUTSIDE_RIGHT, bottom_left),
876 (OUTSIDE_BOTTOM_RIGHT, bottom_left),
877 (OUTSIDE_BOTTOM, bottom_left),
878 (CENTER, CENTER),
879 ] {
880 assert_eq!(
881 SelectionUtils::adjust_drag_offset(RECT, point, TextDirection::Rtl),
882 expected
883 );
884 }
885 }
886}