1use std::collections::HashMap;
9use std::fmt;
10
11use waft_embedder::{
12 BoxHeightStyle, BoxWidthStyle, Clip, Color, FontCollection, LineMetrics, Matrix4, Offset,
13 Paint, Radius, Rect, Size, TargetPlatform, TextAffinity, TextAlign, TextBaseline, TextBox,
14 TextDirection, TextHeightBehavior, TextPosition, TextRange, TextSelection, clamp_double,
15};
16use waft_foundation::{
17 App, DiagnosticPropertiesBuilder, DiagnosticsNode, DiagnosticsProperty, DiagnosticsTreeStyle,
18 Handle, IntProperty, Listener, ValueNotifier,
19};
20use waft_gestures::TapDownDetails;
21use waft_painting::{
22 ClipContext, ColorProperty, InlineSpanRef, PaintingBinding, PlaceholderDimensions, StrutStyle,
23 TextPainter, TextScaler, TextWidthBasis,
24};
25use waft_services::{
26 AnyTextSelectionDelegate, SelectionChangedCause, TextLayoutMetrics, is_whitespace,
27};
28
29use crate::box_::{AnyRenderBox, BoxConstraints, BoxHitTestResult, RenderBox, RenderBoxData};
30use crate::layer::{ClipRectLayer, ContainerLayer, LayerHandle, LayerLink, LeaderLayer};
31use crate::layout_helper::ChildLayoutHelper;
32use crate::object::{
33 AnyRenderObject, ContainerRenderObjectData, ContainerRenderObjectMixin, RenderHandle,
34 RenderObject, RenderObjectData,
35};
36use crate::painting_context::PaintingContext;
37use crate::paragraph::{RenderInlineChildrenContainerDefaults, TextParentData};
38use crate::pipeline_owner::PipelineOwner;
39use crate::relayout_when_system_fonts_change::{
40 RelayoutWhenSystemFontsChangeData, RelayoutWhenSystemFontsChangeMixin,
41};
42use crate::text_boundary::WordBoundary;
43use crate::viewport_offset::{AnyViewportOffset, ViewportOffsetRef};
44use waft_foundation::ListenableObject;
45use waft_foundation::Ref;
46
47const K_CARET_GAP: f64 = 1.0;
48const K_CARET_HEIGHT_OFFSET: f64 = 2.0;
49
50#[derive(Clone, Copy, Debug, PartialEq)]
54pub struct TextSelectionPoint {
55 pub point: Offset,
58 pub direction: Option<TextDirection>,
60}
61
62impl TextSelectionPoint {
63 pub const fn new(point: Offset, direction: Option<TextDirection>) -> TextSelectionPoint {
65 TextSelectionPoint { point, direction }
66 }
67}
68
69impl fmt::Display for TextSelectionPoint {
70 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71 match self.direction {
72 Some(TextDirection::Ltr) => write!(f, "{:?}-ltr", self.point),
73 Some(TextDirection::Rtl) => write!(f, "{:?}-rtl", self.point),
74 None => write!(f, "{:?}", self.point),
75 }
76 }
77}
78
79pub struct VerticalCaretMovementRun {
84 editable: RenderHandle<RenderEditable>,
85 layout_generation: u64,
86 current_offset: Offset,
87 current_line: i32,
88 current_text_position: TextPosition,
89 line_metrics: Vec<LineMetrics>,
90 position_cache: HashMap<i32, (Offset, TextPosition)>,
91 is_valid: bool,
92}
93
94impl VerticalCaretMovementRun {
95 pub fn is_valid(&mut self, app: &App) -> bool {
97 if !self.is_valid {
98 return false;
99 }
100 if self.editable.get(app).layout_generation != self.layout_generation {
101 self.is_valid = false;
102 }
103 self.is_valid
104 }
105
106 pub fn current(&self) -> TextPosition {
108 debug_assert!(self.is_valid);
109 self.current_text_position
110 }
111
112 fn get_text_position_for_line(
113 &mut self,
114 app: &App,
115 line_number: i32,
116 ) -> (Offset, TextPosition) {
117 debug_assert!(self.is_valid);
118 debug_assert!(line_number >= 0);
119 if let Some(cached) = self.position_cache.get(&line_number) {
120 return *cached;
121 }
122 debug_assert!(line_number != self.current_line);
123 let new_offset = Offset::new(
124 self.current_offset.dx(),
125 self.line_metrics[line_number as usize].baseline,
126 );
127 let closest = self
128 .editable
129 .get(app)
130 .text_painter
131 .get_position_for_offset(new_offset);
132 self.position_cache
133 .insert(line_number, (new_offset, closest));
134 (new_offset, closest)
135 }
136
137 pub fn move_next(&mut self, app: &App) -> bool {
139 debug_assert!(self.is_valid(app));
140 if self.current_line + 1 >= self.line_metrics.len() as i32 {
141 return false;
142 }
143 let (offset, position) = self.get_text_position_for_line(app, self.current_line + 1);
144 self.current_line += 1;
145 self.current_offset = offset;
146 self.current_text_position = position;
147 true
148 }
149
150 pub fn move_previous(&mut self, app: &App) -> bool {
152 debug_assert!(self.is_valid(app));
153 if self.current_line <= 0 {
154 return false;
155 }
156 let (offset, position) = self.get_text_position_for_line(app, self.current_line - 1);
157 self.current_line -= 1;
158 self.current_offset = offset;
159 self.current_text_position = position;
160 true
161 }
162
163 pub fn move_by_offset(&mut self, app: &App, offset: f64) -> bool {
165 let initial_offset = self.current_offset;
166 if offset >= 0.0 {
167 while self.current_offset.dy() < initial_offset.dy() + offset {
168 if !self.move_next(app) {
169 break;
170 }
171 }
172 } else {
173 while self.current_offset.dy() > initial_offset.dy() + offset {
174 if !self.move_previous(app) {
175 break;
176 }
177 }
178 }
179 initial_offset != self.current_offset
180 }
181}
182
183pub struct RenderEditable {
190 render_object: RenderObjectData,
191 render_box: RenderBoxData,
192 container: ContainerRenderObjectData<AnyRenderBox>,
193 text_painter: TextPainter,
194 text_intrinsics: Option<TextPainter>,
195 placeholder_dimensions: Option<Vec<PlaceholderDimensions>>,
201 system_fonts: RelayoutWhenSystemFontsChangeData,
202 fonts_override: Option<Handle<FontCollection>>,
203 show_cursor: Ref<ValueNotifier<bool>>,
204 #[allow(dead_code)]
205 dispose_show_cursor: bool,
206 has_focus: bool,
207 start_handle_layer_link: Ref<LayerLink>,
208 end_handle_layer_link: Ref<LayerLink>,
209 max_lines: Option<i32>,
210 min_lines: Option<i32>,
211 expands: bool,
212 selection_color: Option<Color>,
213 selection: Option<TextSelection>,
214 offset: ViewportOffsetRef,
215 pub ignore_pointer: bool,
218 read_only: bool,
219 force_line: bool,
220 obscuring_character: String,
221 obscure_text: bool,
222 cursor_color: Option<Color>,
223 background_cursor_color: Option<Color>,
224 cursor_width: f64,
225 cursor_height: Option<f64>,
226 cursor_radius: Option<Radius>,
227 paint_cursor_above_text: bool,
228 cursor_offset: Offset,
229 device_pixel_ratio: f64,
230 selection_height_style: BoxHeightStyle,
231 selection_width_style: BoxWidthStyle,
232 enable_interactive_selection: Option<bool>,
233 prompt_rect_range: Option<TextRange>,
234 prompt_rect_color: Option<Color>,
235 clip_behavior: Clip,
236 clip_rect_layer: LayerHandle<Handle<ClipRectLayer>>,
237 leader_layer_handler: LayerHandle<Handle<LeaderLayer>>,
238 text_selection_delegate: AnyTextSelectionDelegate,
239 caret_prototype: Rect,
240 max_scroll_extent: f64,
241 last_tap_down_position: Option<Offset>,
242 last_secondary_tap_down_position: Option<Offset>,
243 layout_generation: u64,
244 selection_start_in_viewport: Ref<ValueNotifier<bool>>,
245 selection_end_in_viewport: Ref<ValueNotifier<bool>>,
246}
247
248impl RenderEditable {
249 pub fn new(
254 app: &mut App,
255 text_direction: TextDirection,
256 start_handle_layer_link: Ref<LayerLink>,
257 end_handle_layer_link: Ref<LayerLink>,
258 offset: ViewportOffsetRef,
259 text_selection_delegate: AnyTextSelectionDelegate,
260 ) -> RenderHandle<Self> {
261 let show_cursor = app.create(ValueNotifier::new(false));
262 let selection_start_in_viewport = app.create(ValueNotifier::new(true));
263 let selection_end_in_viewport = app.create(ValueNotifier::new(true));
264 let mut text_painter = TextPainter::new();
265 text_painter.set_text_direction(Some(text_direction));
266 text_painter.set_max_lines(Some(1));
267 RenderHandle::new_box(
268 app,
269 RenderEditable {
270 render_object: RenderObjectData::new(),
271 render_box: RenderBoxData::new(),
272 container: ContainerRenderObjectData::new(),
273 text_painter,
274 text_intrinsics: None,
275 placeholder_dimensions: None,
276 system_fonts: RelayoutWhenSystemFontsChangeData::new(),
277 fonts_override: None,
278 show_cursor,
279 dispose_show_cursor: true,
280 has_focus: false,
281 start_handle_layer_link,
282 end_handle_layer_link,
283 max_lines: Some(1),
284 min_lines: None,
285 expands: false,
286 selection_color: None,
287 selection: None,
288 offset,
289 ignore_pointer: false,
290 read_only: false,
291 force_line: true,
292 obscuring_character: "\u{2022}".into(),
293 obscure_text: false,
294 cursor_color: None,
295 background_cursor_color: None,
296 cursor_width: 1.0,
297 cursor_height: None,
298 cursor_radius: None,
299 paint_cursor_above_text: false,
300 cursor_offset: Offset::ZERO,
301 device_pixel_ratio: 1.0,
302 selection_height_style: BoxHeightStyle::Max,
303 selection_width_style: BoxWidthStyle::Max,
304 enable_interactive_selection: None,
305 prompt_rect_range: None,
306 prompt_rect_color: None,
307 clip_behavior: Clip::HardEdge,
308 clip_rect_layer: LayerHandle::new(),
309 leader_layer_handler: LayerHandle::new(),
310 text_selection_delegate,
311 caret_prototype: Rect::ZERO,
312 max_scroll_extent: 0.0,
313 last_tap_down_position: None,
314 last_secondary_tap_down_position: None,
315 layout_generation: 0,
316 selection_start_in_viewport,
317 selection_end_in_viewport,
318 },
319 )
320 }
321
322 fn fonts(self: RenderHandle<Self>, app: &mut App) -> Handle<FontCollection> {
323 match self.get(app).fonts_override {
324 Some(fonts) => fonts,
325 None => PaintingBinding::instance(app).fonts(app),
326 }
327 }
328
329 fn painter_with_fonts(
330 self: RenderHandle<Self>,
331 app: &mut App,
332 ) -> (&mut TextPainter, &mut FontCollection) {
333 let fonts = self.fonts(app);
334 let (this, fonts) = app.get_disjoint_mut(self.handle(), fonts);
335 (&mut this.text_painter, fonts)
336 }
337
338 fn text_intrinsics_with_fonts(
339 self: RenderHandle<Self>,
340 app: &mut App,
341 ) -> (&mut TextPainter, &mut FontCollection) {
342 let fonts = self.fonts(app);
343 let (this, fonts) = app.get_disjoint_mut(self.handle(), fonts);
344 let painter = &this.text_painter;
345 let intrinsics = this.text_intrinsics.get_or_insert_with(TextPainter::new);
346 intrinsics.set_text(painter.text().cloned());
347 intrinsics.set_text_align(painter.text_align());
348 intrinsics.set_text_direction(painter.text_direction());
349 intrinsics.set_text_scaler(painter.text_scaler().clone());
350 intrinsics.set_max_lines(painter.max_lines());
351 intrinsics.set_strut_style(painter.strut_style().cloned());
352 intrinsics.set_text_width_basis(painter.text_width_basis());
353 intrinsics.set_text_height_behavior(painter.text_height_behavior());
354 (intrinsics, fonts)
355 }
356
357 fn mark_needs_paint_listener(self: RenderHandle<Self>) -> Listener {
358 Listener::handle_method(self.handle(), offset_or_cursor_changed)
359 }
360
361 pub fn text(self: RenderHandle<Self>, app: &App) -> Option<InlineSpanRef> {
363 self.get(app).text_painter.text().cloned()
364 }
365
366 pub fn set_text(self: RenderHandle<Self>, app: &mut App, value: Option<InlineSpanRef>) {
368 let current = self.get(app).text_painter.text().cloned();
369 if current.as_ref().map(|s| s.as_ref() as *const _)
370 == value.as_ref().map(|s| s.as_ref() as *const _)
371 {
372 return;
373 }
374 self.get_mut(app).text_painter.set_text(value);
375 self.get_mut(app).text_intrinsics = None;
376 self.mark_needs_layout(app);
377 }
378
379 pub fn text_align(self: RenderHandle<Self>, app: &App) -> TextAlign {
381 self.get(app).text_painter.text_align()
382 }
383
384 pub fn set_text_align(self: RenderHandle<Self>, app: &mut App, value: TextAlign) {
386 if self.text_align(app) == value {
387 return;
388 }
389 self.get_mut(app).text_painter.set_text_align(value);
390 self.mark_needs_paint(app);
391 }
392
393 pub fn text_direction(self: RenderHandle<Self>, app: &App) -> TextDirection {
395 self.get(app)
396 .text_painter
397 .text_direction()
398 .expect("an editable always has a direction")
399 }
400
401 pub fn set_text_direction(self: RenderHandle<Self>, app: &mut App, value: TextDirection) {
403 if self.get(app).text_painter.text_direction() == Some(value) {
404 return;
405 }
406 self.get_mut(app)
407 .text_painter
408 .set_text_direction(Some(value));
409 self.mark_needs_layout(app);
410 }
411
412 pub fn cursor_color(self: RenderHandle<Self>, app: &App) -> Option<Color> {
414 self.get(app).cursor_color
415 }
416
417 pub fn set_cursor_color(self: RenderHandle<Self>, app: &mut App, value: Option<Color>) {
419 if self.get(app).cursor_color == value {
420 return;
421 }
422 self.get_mut(app).cursor_color = value;
423 self.mark_needs_paint(app);
424 }
425
426 pub fn background_cursor_color(self: RenderHandle<Self>, app: &App) -> Option<Color> {
429 self.get(app).background_cursor_color
430 }
431
432 pub fn set_background_cursor_color(
434 self: RenderHandle<Self>,
435 app: &mut App,
436 value: Option<Color>,
437 ) {
438 if self.get(app).background_cursor_color == value {
439 return;
440 }
441 self.get_mut(app).background_cursor_color = value;
442 self.mark_needs_paint(app);
443 }
444
445 pub fn show_cursor(self: RenderHandle<Self>, app: &App) -> Handle<ValueNotifier<bool>> {
447 self.get(app).show_cursor.handle()
448 }
449
450 pub fn set_show_cursor(
452 self: RenderHandle<Self>,
453 app: &mut App,
454 value: Ref<ValueNotifier<bool>>,
455 ) {
456 let old = self.get(app).show_cursor.handle();
457 if old == value {
458 return;
459 }
460 if self.attached(app) {
461 old.remove_listener(app, &self.mark_needs_paint_listener());
462 }
463 let new = value.handle();
464 let _old = std::mem::replace(&mut self.get_mut(app).show_cursor, value);
466 self.get_mut(app).dispose_show_cursor = false;
467 if self.attached(app) {
468 new.add_listener(app, self.mark_needs_paint_listener());
469 }
470 self.mark_needs_paint(app);
471 }
472
473 pub fn has_focus(self: RenderHandle<Self>, app: &App) -> bool {
475 self.get(app).has_focus
476 }
477
478 pub fn set_has_focus(self: RenderHandle<Self>, app: &mut App, value: bool) {
480 if self.get(app).has_focus == value {
481 return;
482 }
483 self.get_mut(app).has_focus = value;
484 }
485
486 pub fn start_handle_layer_link(self: RenderHandle<Self>, app: &App) -> Handle<LayerLink> {
488 self.get(app).start_handle_layer_link.handle()
489 }
490
491 pub fn set_start_handle_layer_link(
493 self: RenderHandle<Self>,
494 app: &mut App,
495 value: Ref<LayerLink>,
496 ) {
497 if self.get(app).start_handle_layer_link == value {
498 return;
499 }
500 self.get_mut(app).start_handle_layer_link = value;
501 self.mark_needs_paint(app);
502 }
503
504 pub fn end_handle_layer_link(self: RenderHandle<Self>, app: &App) -> Handle<LayerLink> {
506 self.get(app).end_handle_layer_link.handle()
507 }
508
509 pub fn set_end_handle_layer_link(
511 self: RenderHandle<Self>,
512 app: &mut App,
513 value: Ref<LayerLink>,
514 ) {
515 if self.get(app).end_handle_layer_link == value {
516 return;
517 }
518 self.get_mut(app).end_handle_layer_link = value;
519 self.mark_needs_paint(app);
520 }
521
522 pub fn max_lines(self: RenderHandle<Self>, app: &App) -> Option<i32> {
524 self.get(app).max_lines
525 }
526
527 pub fn set_max_lines(self: RenderHandle<Self>, app: &mut App, value: Option<i32>) {
529 debug_assert!(value.is_none_or(|n| n > 0));
530 if self.get(app).max_lines == value {
531 return;
532 }
533 self.get_mut(app).max_lines = value;
534 self.get_mut(app)
535 .text_painter
536 .set_max_lines(if value == Some(1) { Some(1) } else { None });
537 self.get_mut(app).text_intrinsics = None;
538 self.mark_needs_layout(app);
539 }
540
541 pub fn min_lines(self: RenderHandle<Self>, app: &App) -> Option<i32> {
543 self.get(app).min_lines
544 }
545
546 pub fn set_min_lines(self: RenderHandle<Self>, app: &mut App, value: Option<i32>) {
548 debug_assert!(value.is_none_or(|n| n > 0));
549 if self.get(app).min_lines == value {
550 return;
551 }
552 self.get_mut(app).min_lines = value;
553 self.mark_needs_layout(app);
554 }
555
556 pub fn expands(self: RenderHandle<Self>, app: &App) -> bool {
558 self.get(app).expands
559 }
560
561 pub fn set_expands(self: RenderHandle<Self>, app: &mut App, value: bool) {
563 if self.get(app).expands == value {
564 return;
565 }
566 self.get_mut(app).expands = value;
567 self.mark_needs_layout(app);
568 }
569
570 pub fn selection_color(self: RenderHandle<Self>, app: &App) -> Option<Color> {
572 self.get(app).selection_color
573 }
574
575 pub fn set_selection_color(self: RenderHandle<Self>, app: &mut App, value: Option<Color>) {
577 if self.get(app).selection_color == value {
578 return;
579 }
580 self.get_mut(app).selection_color = value;
581 self.mark_needs_paint(app);
582 }
583
584 pub fn text_scaler(self: RenderHandle<Self>, app: &App) -> TextScaler {
586 self.get(app).text_painter.text_scaler().clone()
587 }
588
589 pub fn set_text_scaler(self: RenderHandle<Self>, app: &mut App, value: TextScaler) {
591 if self.get(app).text_painter.text_scaler() == &value {
592 return;
593 }
594 self.get_mut(app).text_painter.set_text_scaler(value);
595 self.get_mut(app).text_intrinsics = None;
596 self.mark_needs_layout(app);
597 }
598
599 pub fn selection(self: RenderHandle<Self>, app: &App) -> Option<TextSelection> {
601 self.get(app).selection
602 }
603
604 pub fn set_selection(self: RenderHandle<Self>, app: &mut App, value: Option<TextSelection>) {
606 if self.get(app).selection == value {
607 return;
608 }
609 self.get_mut(app).selection = value;
610 self.mark_needs_paint(app);
611 }
612
613 pub fn offset(self: RenderHandle<Self>, app: &App) -> AnyViewportOffset {
615 self.get(app).offset.handle()
616 }
617
618 pub fn set_offset(self: RenderHandle<Self>, app: &mut App, value: ViewportOffsetRef) {
620 let old = self.offset(app);
621 if old == value {
622 return;
623 }
624 if self.attached(app) {
625 old.remove_listener(app, &self.mark_needs_paint_listener());
626 }
627 let new = value.handle();
628 let _old = std::mem::replace(&mut self.get_mut(app).offset, value);
630 if self.attached(app) {
631 new.add_listener(app, self.mark_needs_paint_listener());
632 }
633 self.mark_needs_layout(app);
634 }
635
636 pub fn read_only(self: RenderHandle<Self>, app: &App) -> bool {
638 self.get(app).read_only
639 }
640
641 pub fn set_read_only(self: RenderHandle<Self>, app: &mut App, value: bool) {
643 if self.get(app).read_only == value {
644 return;
645 }
646 self.get_mut(app).read_only = value;
647 }
648
649 pub fn force_line(self: RenderHandle<Self>, app: &App) -> bool {
651 self.get(app).force_line
652 }
653
654 pub fn set_force_line(self: RenderHandle<Self>, app: &mut App, value: bool) {
656 if self.get(app).force_line == value {
657 return;
658 }
659 self.get_mut(app).force_line = value;
660 self.mark_needs_layout(app);
661 }
662
663 pub fn text_height_behavior(self: RenderHandle<Self>, app: &App) -> Option<TextHeightBehavior> {
665 self.get(app).text_painter.text_height_behavior()
666 }
667
668 pub fn set_text_height_behavior(
670 self: RenderHandle<Self>,
671 app: &mut App,
672 value: Option<TextHeightBehavior>,
673 ) {
674 if self.text_height_behavior(app) == value {
675 return;
676 }
677 self.get_mut(app)
678 .text_painter
679 .set_text_height_behavior(value);
680 self.mark_needs_layout(app);
681 }
682
683 pub fn strut_style(self: RenderHandle<Self>, app: &App) -> Option<&StrutStyle> {
686 self.get(app).text_painter.strut_style()
687 }
688
689 pub fn set_strut_style(self: RenderHandle<Self>, app: &mut App, value: Option<StrutStyle>) {
691 if self.strut_style(app) == value.as_ref() {
692 return;
693 }
694 self.get_mut(app).text_painter.set_strut_style(value);
695 self.mark_needs_layout(app);
696 }
697
698 pub fn text_width_basis(self: RenderHandle<Self>, app: &App) -> TextWidthBasis {
700 self.get(app).text_painter.text_width_basis()
701 }
702
703 pub fn set_text_width_basis(self: RenderHandle<Self>, app: &mut App, value: TextWidthBasis) {
705 if self.text_width_basis(app) == value {
706 return;
707 }
708 self.get_mut(app).text_painter.set_text_width_basis(value);
709 self.mark_needs_layout(app);
710 }
711
712 pub fn obscuring_character(self: RenderHandle<Self>, app: &App) -> &str {
714 &self.get(app).obscuring_character
715 }
716
717 pub fn set_obscuring_character(
719 self: RenderHandle<Self>,
720 app: &mut App,
721 value: impl Into<String>,
722 ) {
723 let value = value.into();
724 if self.get(app).obscuring_character == value {
725 return;
726 }
727 self.get_mut(app).obscuring_character = value;
728 self.mark_needs_layout(app);
729 }
730
731 pub fn obscure_text(self: RenderHandle<Self>, app: &App) -> bool {
733 self.get(app).obscure_text
734 }
735
736 pub fn set_obscure_text(self: RenderHandle<Self>, app: &mut App, value: bool) {
738 if self.get(app).obscure_text == value {
739 return;
740 }
741 self.get_mut(app).obscure_text = value;
742 }
743
744 pub fn cursor_width(self: RenderHandle<Self>, app: &App) -> f64 {
746 self.get(app).cursor_width
747 }
748
749 pub fn set_cursor_width(self: RenderHandle<Self>, app: &mut App, value: f64) {
751 if self.get(app).cursor_width == value {
752 return;
753 }
754 self.get_mut(app).cursor_width = value;
755 self.mark_needs_layout(app);
756 }
757
758 pub fn cursor_height(self: RenderHandle<Self>, app: &mut App) -> f64 {
760 self.get(app)
761 .cursor_height
762 .unwrap_or_else(|| self.preferred_line_height(app))
763 }
764
765 pub fn set_cursor_height(self: RenderHandle<Self>, app: &mut App, value: Option<f64>) {
767 if self.get(app).cursor_height == value {
768 return;
769 }
770 self.get_mut(app).cursor_height = value;
771 self.mark_needs_layout(app);
772 }
773
774 pub fn cursor_radius(self: RenderHandle<Self>, app: &App) -> Option<Radius> {
776 self.get(app).cursor_radius
777 }
778
779 pub fn set_cursor_radius(self: RenderHandle<Self>, app: &mut App, value: Option<Radius>) {
781 if self.get(app).cursor_radius == value {
782 return;
783 }
784 self.get_mut(app).cursor_radius = value;
785 self.mark_needs_paint(app);
786 }
787
788 pub fn paint_cursor_above_text(self: RenderHandle<Self>, app: &App) -> bool {
790 self.get(app).paint_cursor_above_text
791 }
792
793 pub fn set_paint_cursor_above_text(self: RenderHandle<Self>, app: &mut App, value: bool) {
795 if self.get(app).paint_cursor_above_text == value {
796 return;
797 }
798 self.get_mut(app).paint_cursor_above_text = value;
799 self.mark_needs_paint(app);
800 }
801
802 pub fn cursor_offset(self: RenderHandle<Self>, app: &App) -> Offset {
804 self.get(app).cursor_offset
805 }
806
807 pub fn set_cursor_offset(self: RenderHandle<Self>, app: &mut App, value: Offset) {
809 if self.get(app).cursor_offset == value {
810 return;
811 }
812 self.get_mut(app).cursor_offset = value;
813 self.mark_needs_paint(app);
814 }
815
816 pub fn device_pixel_ratio(self: RenderHandle<Self>, app: &App) -> f64 {
818 self.get(app).device_pixel_ratio
819 }
820
821 pub fn set_device_pixel_ratio(self: RenderHandle<Self>, app: &mut App, value: f64) {
823 if self.get(app).device_pixel_ratio == value {
824 return;
825 }
826 self.get_mut(app).device_pixel_ratio = value;
827 self.mark_needs_layout(app);
828 }
829
830 pub fn selection_height_style(self: RenderHandle<Self>, app: &App) -> BoxHeightStyle {
832 self.get(app).selection_height_style
833 }
834
835 pub fn set_selection_height_style(
837 self: RenderHandle<Self>,
838 app: &mut App,
839 value: BoxHeightStyle,
840 ) {
841 if self.get(app).selection_height_style == value {
842 return;
843 }
844 self.get_mut(app).selection_height_style = value;
845 self.mark_needs_paint(app);
846 }
847
848 pub fn selection_width_style(self: RenderHandle<Self>, app: &App) -> BoxWidthStyle {
850 self.get(app).selection_width_style
851 }
852
853 pub fn set_selection_width_style(
855 self: RenderHandle<Self>,
856 app: &mut App,
857 value: BoxWidthStyle,
858 ) {
859 if self.get(app).selection_width_style == value {
860 return;
861 }
862 self.get_mut(app).selection_width_style = value;
863 self.mark_needs_paint(app);
864 }
865
866 pub fn enable_interactive_selection(self: RenderHandle<Self>, app: &App) -> Option<bool> {
868 self.get(app).enable_interactive_selection
869 }
870
871 pub fn set_enable_interactive_selection(
873 self: RenderHandle<Self>,
874 app: &mut App,
875 value: Option<bool>,
876 ) {
877 if self.get(app).enable_interactive_selection == value {
878 return;
879 }
880 self.get_mut(app).enable_interactive_selection = value;
881 self.mark_needs_paint(app);
882 }
883
884 pub fn text_selection_delegate(
887 self: RenderHandle<Self>,
888 app: &App,
889 ) -> AnyTextSelectionDelegate {
890 self.get(app).text_selection_delegate
891 }
892
893 pub fn set_text_selection_delegate(
895 self: RenderHandle<Self>,
896 app: &mut App,
897 value: AnyTextSelectionDelegate,
898 ) {
899 self.get_mut(app).text_selection_delegate = value;
900 }
901
902 pub fn prompt_rect_color(self: RenderHandle<Self>, app: &App) -> Option<Color> {
904 self.get(app).prompt_rect_color
905 }
906
907 pub fn set_prompt_rect_color(self: RenderHandle<Self>, app: &mut App, value: Option<Color>) {
909 if self.get(app).prompt_rect_color == value {
910 return;
911 }
912 self.get_mut(app).prompt_rect_color = value;
913 self.mark_needs_paint(app);
914 }
915
916 pub fn set_prompt_rect_range(
918 self: RenderHandle<Self>,
919 app: &mut App,
920 value: Option<TextRange>,
921 ) {
922 if self.get(app).prompt_rect_range == value {
923 return;
924 }
925 self.get_mut(app).prompt_rect_range = value;
926 self.mark_needs_paint(app);
927 }
928
929 pub fn clip_behavior(self: RenderHandle<Self>, app: &App) -> Clip {
931 self.get(app).clip_behavior
932 }
933
934 pub fn set_clip_behavior(self: RenderHandle<Self>, app: &mut App, value: Clip) {
936 if self.get(app).clip_behavior == value {
937 return;
938 }
939 self.get_mut(app).clip_behavior = value;
940 self.mark_needs_paint(app);
941 }
942
943 pub fn get_boxes_for_selection(
949 self: RenderHandle<Self>,
950 app: &mut App,
951 selection: TextSelection,
952 ) -> Vec<TextBox> {
953 self.compute_text_metrics_if_needed(app);
954 let paint_offset = self.paint_offset(app);
955 let this = self.get(app);
956 this.text_painter
957 .get_boxes_for_selection(
958 selection,
959 this.selection_height_style,
960 this.selection_width_style,
961 )
962 .into_iter()
963 .map(|text_box| {
964 TextBox::from_ltrbd(
965 text_box.left + paint_offset.dx(),
966 text_box.top + paint_offset.dy(),
967 text_box.right + paint_offset.dx(),
968 text_box.bottom + paint_offset.dy(),
969 text_box.direction,
970 )
971 })
972 .collect()
973 }
974
975 pub fn selection_start_in_viewport(
978 self: RenderHandle<Self>,
979 app: &App,
980 ) -> Handle<ValueNotifier<bool>> {
981 self.get(app).selection_start_in_viewport.handle()
982 }
983
984 pub fn selection_end_in_viewport(
987 self: RenderHandle<Self>,
988 app: &App,
989 ) -> Handle<ValueNotifier<bool>> {
990 self.get(app).selection_end_in_viewport.handle()
991 }
992
993 fn update_selection_extents_visibility(
994 self: RenderHandle<Self>,
995 app: &mut App,
996 effective_offset: Offset,
997 ) {
998 let Some(selection) = self.selection(app) else {
999 return;
1000 };
1001 let start_notifier = self.get(app).selection_start_in_viewport.handle();
1002 let end_notifier = self.get(app).selection_end_in_viewport.handle();
1003 if !selection.is_valid() {
1004 start_notifier.set_value(app, false);
1005 end_notifier.set_value(app, false);
1006 return;
1007 }
1008 let visible_region = Offset::ZERO & self.size(app);
1009 let caret_prototype = self.get(app).caret_prototype;
1010 let start = TextPosition::with_affinity(selection.start(), selection.affinity);
1011 let end = TextPosition::with_affinity(selection.end(), selection.affinity);
1012 let (start_offset, end_offset) = {
1013 let (painter, fonts) = self.painter_with_fonts(app);
1014 (
1015 painter.get_offset_for_caret(fonts, start, caret_prototype),
1016 painter.get_offset_for_caret(fonts, end, caret_prototype),
1017 )
1018 };
1019 const VISIBLE_REGION_SLOP: f64 = 0.5;
1020 let region = visible_region.inflate(VISIBLE_REGION_SLOP);
1021 start_notifier.set_value(app, region.contains(start_offset + effective_offset));
1022 end_notifier.set_value(app, region.contains(end_offset + effective_offset));
1023 }
1024
1025 pub fn plain_text(self: RenderHandle<Self>, app: &mut App) -> String {
1027 self.get_mut(app).text_painter.plain_text().to_owned()
1028 }
1029
1030 pub fn preferred_line_height(self: RenderHandle<Self>, app: &mut App) -> f64 {
1032 let (painter, fonts) = self.painter_with_fonts(app);
1033 painter.preferred_line_height(fonts)
1034 }
1035
1036 fn caret_margin(self: RenderHandle<Self>, app: &App) -> f64 {
1037 K_CARET_GAP + self.get(app).cursor_width
1038 }
1039
1040 fn is_multiline(self: RenderHandle<Self>, app: &App) -> bool {
1041 self.get(app).max_lines != Some(1)
1042 }
1043
1044 fn paint_offset(self: RenderHandle<Self>, app: &App) -> Offset {
1045 let pixels = self.get(app).offset.pixels(app);
1046 if self.is_multiline(app) {
1047 Offset::new(0.0, -pixels)
1048 } else {
1049 Offset::new(-pixels, 0.0)
1050 }
1051 }
1052
1053 fn viewport_extent(self: RenderHandle<Self>, app: &App) -> f64 {
1054 let size = self.size(app);
1055 if self.is_multiline(app) {
1056 size.height()
1057 } else {
1058 size.width()
1059 }
1060 }
1061
1062 fn get_max_scroll_extent(self: RenderHandle<Self>, app: &App, content_size: Size) -> f64 {
1063 let size = self.size(app);
1064 if self.is_multiline(app) {
1065 (content_size.height() - size.height()).max(0.0)
1066 } else {
1067 (content_size.width() - size.width()).max(0.0)
1068 }
1069 }
1070
1071 fn has_visual_overflow(self: RenderHandle<Self>, app: &App) -> bool {
1072 self.get(app).max_scroll_extent > 0.0 || self.paint_offset(app) != Offset::ZERO
1073 }
1074
1075 fn adjust_constraints(
1076 self: RenderHandle<Self>,
1077 app: &App,
1078 min_width: f64,
1079 max_width: f64,
1080 ) -> (f64, f64) {
1081 let available_max_width = (max_width - self.caret_margin(app)).max(0.0);
1082 let available_min_width = min_width.min(available_max_width);
1083 let min = if self.get(app).force_line {
1084 available_max_width
1085 } else {
1086 available_min_width
1087 };
1088 let max = if self.is_multiline(app) {
1089 available_max_width
1090 } else {
1091 f64::INFINITY
1092 };
1093 (min, max)
1094 }
1095
1096 fn compute_text_metrics_if_needed(self: RenderHandle<Self>, app: &mut App) {
1097 let constraints = self.constraints(app);
1098 let (min_width, max_width) =
1099 self.adjust_constraints(app, constraints.min_width, constraints.max_width);
1100 let (painter, fonts) = self.painter_with_fonts(app);
1101 painter.layout(fonts, min_width, max_width);
1102 }
1103
1104 fn compute_caret_prototype(self: RenderHandle<Self>, app: &mut App) {
1105 let cursor_width = self.get(app).cursor_width;
1106 let cursor_height = self.cursor_height(app);
1107 let prototype = match app.platform().target_platform() {
1108 TargetPlatform::IOS | TargetPlatform::MacOS => {
1109 Rect::from_ltwh(0.0, 0.0, cursor_width, cursor_height + 2.0)
1110 }
1111 TargetPlatform::Android
1112 | TargetPlatform::Fuchsia
1113 | TargetPlatform::Linux
1114 | TargetPlatform::Windows => Rect::from_ltwh(
1115 0.0,
1116 K_CARET_HEIGHT_OFFSET,
1117 cursor_width,
1118 cursor_height - 2.0 * K_CARET_HEIGHT_OFFSET,
1119 ),
1120 };
1121 self.get_mut(app).caret_prototype = prototype;
1122 }
1123
1124 fn snap_to_physical_pixel(
1125 self: RenderHandle<Self>,
1126 app: &App,
1127 source_offset: Offset,
1128 ) -> Offset {
1129 let global = self.as_box().local_to_global(app, source_offset, None);
1130 let pixel_multiple = 1.0 / self.get(app).device_pixel_ratio;
1131 Offset::new(
1132 if global.dx().is_finite() {
1133 (global.dx() / pixel_multiple).round() * pixel_multiple - global.dx()
1134 } else {
1135 0.0
1136 },
1137 if global.dy().is_finite() {
1138 (global.dy() / pixel_multiple).round() * pixel_multiple - global.dy()
1139 } else {
1140 0.0
1141 },
1142 )
1143 }
1144
1145 pub fn get_endpoints_for_selection(
1147 self: RenderHandle<Self>,
1148 app: &mut App,
1149 selection: TextSelection,
1150 ) -> Vec<TextSelectionPoint> {
1151 self.compute_text_metrics_if_needed(app);
1152 let paint_offset = self.paint_offset(app);
1153 let height_style = self.get(app).selection_height_style;
1154 let width_style = self.get(app).selection_width_style;
1155 let boxes = if selection.is_collapsed() {
1156 Vec::new()
1157 } else {
1158 self.get(app)
1159 .text_painter
1160 .get_boxes_for_selection(selection, height_style, width_style)
1161 };
1162 if boxes.is_empty() {
1163 let caret_prototype = self.get(app).caret_prototype;
1164 let (painter, fonts) = self.painter_with_fonts(app);
1165 let caret_offset =
1166 painter.get_offset_for_caret(fonts, selection.extent(), caret_prototype);
1167 let line_height = painter.preferred_line_height(fonts);
1168 let start = Offset::new(0.0, line_height) + caret_offset + paint_offset;
1169 return vec![TextSelectionPoint::new(start, None)];
1170 }
1171 let painter_width = self.get(app).text_painter.size().width();
1172 let start = Offset::new(
1173 clamp_double(boxes[0].start(), 0.0, painter_width),
1174 boxes[0].bottom,
1175 ) + paint_offset;
1176 let last = boxes[boxes.len() - 1];
1177 let end =
1178 Offset::new(clamp_double(last.end(), 0.0, painter_width), last.bottom) + paint_offset;
1179 vec![
1180 TextSelectionPoint::new(start, Some(boxes[0].direction)),
1181 TextSelectionPoint::new(end, Some(last.direction)),
1182 ]
1183 }
1184
1185 pub fn get_rect_for_composing_range(
1188 self: RenderHandle<Self>,
1189 app: &mut App,
1190 range: TextRange,
1191 ) -> Option<Rect> {
1192 if !range.is_valid() || range.is_collapsed() {
1193 return None;
1194 }
1195 self.compute_text_metrics_if_needed(app);
1196 let boxes = self.get(app).text_painter.get_boxes_for_selection(
1197 TextSelection::new(range.start, range.end),
1198 self.get(app).selection_height_style,
1199 self.get(app).selection_width_style,
1200 );
1201 if boxes.is_empty() {
1202 return None;
1203 }
1204 let paint_offset = self.paint_offset(app);
1205 let mut rect = boxes[0].to_rect();
1206 for box_ in boxes.iter().skip(1) {
1207 rect = rect.expand_to_include(box_.to_rect());
1208 }
1209 Some(rect.shift(paint_offset))
1210 }
1211
1212 pub fn get_position_for_point(
1214 self: RenderHandle<Self>,
1215 app: &mut App,
1216 global_position: Offset,
1217 ) -> TextPosition {
1218 self.compute_text_metrics_if_needed(app);
1219 let local =
1220 self.as_box().global_to_local(app, global_position, None) - self.paint_offset(app);
1221 self.get(app).text_painter.get_position_for_offset(local)
1222 }
1223
1224 pub fn get_local_rect_for_caret(
1227 self: RenderHandle<Self>,
1228 app: &mut App,
1229 caret_position: TextPosition,
1230 ) -> Rect {
1231 self.compute_text_metrics_if_needed(app);
1232 let caret_prototype = self.get(app).caret_prototype;
1233 let cursor_offset = self.get(app).cursor_offset;
1234 let (painter, fonts) = self.painter_with_fonts(app);
1235 let caret_offset = painter.get_offset_for_caret(fonts, caret_position, caret_prototype);
1236 let mut caret_rect = caret_prototype.shift(caret_offset + cursor_offset);
1237 let painter_width = painter.width();
1238 let size = self.size(app);
1239 let caret_margin = self.caret_margin(app);
1240 let scrollable_width = (painter_width + caret_margin).max(size.width());
1241 let caret_x = clamp_double(
1242 caret_rect.left,
1243 0.0,
1244 (scrollable_width - caret_margin).max(0.0),
1245 );
1246 caret_rect = Offset::new(caret_x, caret_rect.top) & caret_rect.size();
1247 let (painter, fonts) = self.painter_with_fonts(app);
1248 let full_height = painter.get_full_height_for_caret(fonts, caret_position, caret_prototype);
1249 caret_rect = match app.platform().target_platform() {
1250 TargetPlatform::IOS | TargetPlatform::MacOS => {
1251 let height_diff = full_height - caret_rect.height();
1252 Rect::from_ltwh(
1253 caret_rect.left,
1254 caret_rect.top + height_diff / 2.0,
1255 caret_rect.width(),
1256 caret_rect.height(),
1257 )
1258 }
1259 TargetPlatform::Android
1260 | TargetPlatform::Fuchsia
1261 | TargetPlatform::Linux
1262 | TargetPlatform::Windows => {
1263 let caret_height = self.cursor_height(app);
1264 let height_diff = full_height - caret_height;
1265 Rect::from_ltwh(
1266 caret_rect.left,
1267 caret_rect.top - K_CARET_HEIGHT_OFFSET + height_diff / 2.0,
1268 caret_rect.width(),
1269 caret_height,
1270 )
1271 }
1272 };
1273 caret_rect = caret_rect.shift(self.paint_offset(app));
1274 caret_rect.shift(self.snap_to_physical_pixel(app, caret_rect.top_left()))
1275 }
1276
1277 fn set_text_editing_value(
1278 self: RenderHandle<Self>,
1279 app: &mut App,
1280 new_value: waft_embedder::TextEditingValue,
1281 cause: SelectionChangedCause,
1282 ) {
1283 self.get(app)
1284 .text_selection_delegate
1285 .user_update_text_editing_value(app, new_value, cause);
1286 }
1287
1288 fn apply_selection(
1289 self: RenderHandle<Self>,
1290 app: &mut App,
1291 mut next_selection: TextSelection,
1292 cause: SelectionChangedCause,
1293 ) {
1294 if next_selection.is_valid() {
1295 let text_length = utf16_len(
1296 &self
1297 .get(app)
1298 .text_selection_delegate
1299 .text_editing_value(app)
1300 .text,
1301 );
1302 next_selection = next_selection
1303 .copy_with()
1304 .base_offset(next_selection.base_offset.min(text_length))
1305 .extent_offset(next_selection.extent_offset.min(text_length));
1306 }
1307 let value = self
1308 .get(app)
1309 .text_selection_delegate
1310 .text_editing_value(app)
1311 .copy_with()
1312 .selection(next_selection);
1313 self.set_text_editing_value(app, value, cause);
1314 }
1315
1316 pub fn handle_tap_down(self: RenderHandle<Self>, _app: &mut App, details: &TapDownDetails) {
1319 self.get_mut(_app).last_tap_down_position = Some(details.global_position);
1320 }
1321
1322 pub fn last_secondary_tap_down_position(self: RenderHandle<Self>, app: &App) -> Option<Offset> {
1325 self.get(app).last_secondary_tap_down_position
1326 }
1327
1328 pub fn handle_secondary_tap_down(
1333 self: RenderHandle<Self>,
1334 app: &mut App,
1335 details: &TapDownDetails,
1336 ) {
1337 self.get_mut(app).last_tap_down_position = Some(details.global_position);
1338 self.get_mut(app).last_secondary_tap_down_position = Some(details.global_position);
1339 }
1340
1341 pub fn handle_tap(self: RenderHandle<Self>, app: &mut App) {
1343 self.select_position(app, SelectionChangedCause::Tap);
1344 }
1345
1346 pub fn handle_double_tap(self: RenderHandle<Self>, app: &mut App) {
1348 self.select_word(app, SelectionChangedCause::DoubleTap);
1349 }
1350
1351 pub fn handle_long_press(self: RenderHandle<Self>, app: &mut App) {
1353 self.select_word(app, SelectionChangedCause::LongPress);
1354 }
1355
1356 pub fn select_position(self: RenderHandle<Self>, app: &mut App, cause: SelectionChangedCause) {
1358 let from = self
1359 .get(app)
1360 .last_tap_down_position
1361 .expect("select_position needs a tap-down");
1362 self.select_position_at(app, from, None, cause);
1363 }
1364
1365 pub fn select_position_at(
1367 self: RenderHandle<Self>,
1368 app: &mut App,
1369 from: Offset,
1370 to: Option<Offset>,
1371 cause: SelectionChangedCause,
1372 ) {
1373 self.compute_text_metrics_if_needed(app);
1374 let paint_offset = self.paint_offset(app);
1375 let from_position = self
1376 .get(app)
1377 .text_painter
1378 .get_position_for_offset(self.as_box().global_to_local(app, from, None) - paint_offset);
1379 let to_position = to.map(|to| {
1380 self.get(app).text_painter.get_position_for_offset(
1381 self.as_box().global_to_local(app, to, None) - paint_offset,
1382 )
1383 });
1384 let new_selection = TextSelection {
1385 base_offset: from_position.offset,
1386 extent_offset: to_position.unwrap_or(from_position).offset,
1387 affinity: from_position.affinity,
1388 is_directional: false,
1389 };
1390 self.apply_selection(app, new_selection, cause);
1391 }
1392
1393 pub fn select_word(self: RenderHandle<Self>, app: &mut App, cause: SelectionChangedCause) {
1395 let from = self
1396 .get(app)
1397 .last_tap_down_position
1398 .expect("select_word needs a tap-down");
1399 self.select_words_in_range(app, from, None, cause);
1400 }
1401
1402 pub fn select_words_in_range(
1404 self: RenderHandle<Self>,
1405 app: &mut App,
1406 from: Offset,
1407 to: Option<Offset>,
1408 cause: SelectionChangedCause,
1409 ) {
1410 self.compute_text_metrics_if_needed(app);
1411 let paint_offset = self.paint_offset(app);
1412 let from_position = self
1413 .get(app)
1414 .text_painter
1415 .get_position_for_offset(self.as_box().global_to_local(app, from, None) - paint_offset);
1416 let from_word = self.get_word_at_offset(app, from_position);
1417 let to_position = match to {
1418 None => from_position,
1419 Some(to) => self.get(app).text_painter.get_position_for_offset(
1420 self.as_box().global_to_local(app, to, None) - paint_offset,
1421 ),
1422 };
1423 let to_word = if to_position == from_position {
1424 from_word
1425 } else {
1426 self.get_word_at_offset(app, to_position)
1427 };
1428 let is_from_word_before_to_word = from_word.start() < to_word.end();
1429 self.apply_selection(
1430 app,
1431 TextSelection {
1432 base_offset: if is_from_word_before_to_word {
1433 from_word.base().offset
1434 } else {
1435 from_word.extent().offset
1436 },
1437 extent_offset: if is_from_word_before_to_word {
1438 to_word.extent().offset
1439 } else {
1440 to_word.base().offset
1441 },
1442 affinity: from_word.affinity,
1443 is_directional: false,
1444 },
1445 cause,
1446 );
1447 }
1448
1449 pub fn select_word_edge(self: RenderHandle<Self>, app: &mut App, cause: SelectionChangedCause) {
1451 self.compute_text_metrics_if_needed(app);
1452 let from = self
1453 .get(app)
1454 .last_tap_down_position
1455 .expect("select_word_edge needs a tap-down");
1456 let paint_offset = self.paint_offset(app);
1457 let position = self
1458 .get(app)
1459 .text_painter
1460 .get_position_for_offset(self.as_box().global_to_local(app, from, None) - paint_offset);
1461 let word = self.get(app).text_painter.get_word_boundary(position);
1462 let new_selection = if position.offset <= word.start {
1463 TextSelection::collapsed(word.start, TextAffinity::Downstream)
1464 } else {
1465 TextSelection::collapsed(word.end, TextAffinity::Upstream)
1466 };
1467 self.apply_selection(app, new_selection, cause);
1468 }
1469
1470 pub fn get_word_at_offset(
1473 self: RenderHandle<Self>,
1474 app: &mut App,
1475 position: TextPosition,
1476 ) -> TextSelection {
1477 let plain = self.plain_text(app);
1478 let length = utf16_len(&plain);
1479 if position.offset >= length {
1480 return TextSelection::from_position(TextPosition::with_affinity(
1481 length,
1482 TextAffinity::Upstream,
1483 ));
1484 }
1485 if self.get(app).obscure_text {
1486 return TextSelection::new(0, length);
1487 }
1488 let word = self.get(app).text_painter.get_word_boundary(position);
1489 let effective_offset = match position.affinity {
1490 TextAffinity::Upstream => position.offset - 1,
1491 TextAffinity::Downstream => position.offset,
1492 };
1493 debug_assert!(effective_offset >= 0);
1494 if effective_offset > 0 && code_unit_at(&plain, effective_offset).is_some_and(is_whitespace)
1495 {
1496 if let Some(previous_word) = self.get_previous_word(app, word.start) {
1497 match app.platform().target_platform() {
1498 TargetPlatform::IOS => {
1499 return TextSelection::new(previous_word.start, position.offset);
1500 }
1501 TargetPlatform::Android if self.get(app).read_only => {
1502 return TextSelection::new(previous_word.start, position.offset);
1503 }
1504 _ => {}
1505 }
1506 } else {
1507 match app.platform().target_platform() {
1508 TargetPlatform::IOS => {
1509 if let Some(next_word) = self.get_next_word(app, word.start) {
1510 return TextSelection::new(position.offset, next_word.end);
1511 }
1512 return TextSelection::collapsed(position.offset, position.affinity);
1513 }
1514 TargetPlatform::Android if self.get(app).read_only => {
1515 return TextSelection::new(position.offset, position.offset + 1);
1516 }
1517 _ => {}
1518 }
1519 }
1520 }
1521 TextSelection::new(word.start, word.end)
1522 }
1523
1524 fn get_next_word(
1525 self: RenderHandle<Self>,
1526 app: &mut App,
1527 mut offset: i32,
1528 ) -> Option<TextRange> {
1529 loop {
1530 let range = self
1531 .get(app)
1532 .text_painter
1533 .get_word_boundary(TextPosition::new(offset));
1534 if !range.is_valid() || range.is_collapsed() {
1535 return None;
1536 }
1537 if !self.only_whitespace(app, range) {
1538 return Some(range);
1539 }
1540 offset = range.end;
1541 }
1542 }
1543
1544 fn get_previous_word(
1545 self: RenderHandle<Self>,
1546 app: &mut App,
1547 mut offset: i32,
1548 ) -> Option<TextRange> {
1549 while offset >= 0 {
1550 let range = self
1551 .get(app)
1552 .text_painter
1553 .get_word_boundary(TextPosition::new(offset));
1554 if !range.is_valid() || range.is_collapsed() {
1555 return None;
1556 }
1557 if !self.only_whitespace(app, range) {
1558 return Some(range);
1559 }
1560 offset = range.start - 1;
1561 }
1562 None
1563 }
1564
1565 fn only_whitespace(self: RenderHandle<Self>, app: &mut App, range: TextRange) -> bool {
1566 let plain = self.plain_text(app);
1567 for i in range.start..range.end {
1568 if let Some(unit) = code_unit_at(&plain, i)
1569 && !is_whitespace(unit)
1570 {
1571 return false;
1572 }
1573 }
1574 true
1575 }
1576
1577 pub fn get_line_at_offset(
1579 self: RenderHandle<Self>,
1580 app: &mut App,
1581 position: TextPosition,
1582 ) -> TextSelection {
1583 self.compute_text_metrics_if_needed(app);
1584 let line = self.get(app).text_painter.get_line_boundary(position);
1585 if self.get(app).obscure_text {
1586 return TextSelection::new(0, utf16_len(&self.plain_text(app)));
1587 }
1588 TextSelection::new(line.start, line.end)
1589 }
1590
1591 pub fn word_boundaries(
1595 self: RenderHandle<Self>,
1596 app: &App,
1597 ) -> WordBoundary<RenderHandle<RenderEditable>> {
1598 WordBoundary::new(
1599 self.text(app).expect("RenderEditable always has text"),
1600 self,
1601 )
1602 }
1603
1604 pub fn get_word_boundary(
1606 self: RenderHandle<Self>,
1607 app: &mut App,
1608 position: TextPosition,
1609 ) -> TextRange {
1610 self.compute_text_metrics_if_needed(app);
1611 self.get(app).text_painter.get_word_boundary(position)
1612 }
1613
1614 pub fn get_text_position_above(
1616 self: RenderHandle<Self>,
1617 app: &mut App,
1618 position: TextPosition,
1619 ) -> TextPosition {
1620 self.compute_text_metrics_if_needed(app);
1621 let line_height = self.preferred_line_height(app);
1622 self.get_text_position_vertical(app, position, -0.5 * line_height)
1623 }
1624
1625 pub fn get_text_position_below(
1627 self: RenderHandle<Self>,
1628 app: &mut App,
1629 position: TextPosition,
1630 ) -> TextPosition {
1631 self.compute_text_metrics_if_needed(app);
1632 let line_height = self.preferred_line_height(app);
1633 self.get_text_position_vertical(app, position, 1.5 * line_height)
1634 }
1635
1636 fn get_text_position_vertical(
1637 self: RenderHandle<Self>,
1638 app: &mut App,
1639 position: TextPosition,
1640 vertical_offset: f64,
1641 ) -> TextPosition {
1642 let caret_prototype = self.get(app).caret_prototype;
1643 let (painter, fonts) = self.painter_with_fonts(app);
1644 let caret_offset = painter.get_offset_for_caret(fonts, position, caret_prototype);
1645 painter.get_position_for_offset(caret_offset.translate(0.0, vertical_offset))
1646 }
1647
1648 pub fn start_vertical_caret_movement(
1650 self: RenderHandle<Self>,
1651 app: &mut App,
1652 start_position: TextPosition,
1653 ) -> VerticalCaretMovementRun {
1654 self.compute_text_metrics_if_needed(app);
1655 let metrics = self.get_mut(app).text_painter.compute_line_metrics();
1656 let (painter, fonts) = self.painter_with_fonts(app);
1657 let (line, offset) = line_number_for(painter, fonts, start_position, &metrics);
1658 VerticalCaretMovementRun {
1659 editable: self,
1660 layout_generation: self.get(app).layout_generation,
1661 current_offset: offset,
1662 current_line: line,
1663 current_text_position: start_position,
1664 line_metrics: metrics,
1665 position_cache: HashMap::new(),
1666 is_valid: true,
1667 }
1668 }
1669
1670 fn paint_highlights(
1671 self: RenderHandle<Self>,
1672 app: &App,
1673 canvas: &mut waft_embedder::Canvas,
1674 offset: Offset,
1675 ) {
1676 let paint_offset = offset + self.paint_offset(app);
1677 let painter_size = self.get(app).text_painter.size();
1678 let clip = Rect::from_ltwh(0.0, 0.0, painter_size.width(), painter_size.height());
1679 if let (Some(color), Some(range)) = (
1680 self.get(app).prompt_rect_color,
1681 self.get(app).prompt_rect_range,
1682 ) && !range.is_collapsed()
1683 {
1684 paint_range(
1685 canvas,
1686 &self.get(app).text_painter,
1687 range,
1688 color,
1689 paint_offset,
1690 clip,
1691 self.get(app).selection_height_style,
1692 self.get(app).selection_width_style,
1693 );
1694 }
1695 if let (Some(color), Some(selection)) =
1696 (self.get(app).selection_color, self.get(app).selection)
1697 && !selection.is_collapsed()
1698 {
1699 paint_range(
1700 canvas,
1701 &self.get(app).text_painter,
1702 selection.range(),
1703 color,
1704 paint_offset,
1705 clip,
1706 self.get(app).selection_height_style,
1707 self.get(app).selection_width_style,
1708 );
1709 }
1710 }
1711
1712 fn paint_caret(
1713 self: RenderHandle<Self>,
1714 app: &mut App,
1715 canvas: &mut waft_embedder::Canvas,
1716 offset: Offset,
1717 ) {
1718 let Some(selection) = self.get(app).selection else {
1719 return;
1720 };
1721 let show_cursor = self.get(app).show_cursor.handle();
1722 if !selection.is_collapsed() || !*show_cursor.value(app) {
1723 return;
1724 }
1725 let Some(color) = self.get(app).cursor_color else {
1726 return;
1727 };
1728 let caret = self
1729 .get_local_rect_for_caret(app, selection.extent())
1730 .shift(offset);
1731 canvas.draw_rect(
1732 caret,
1733 &Paint {
1734 color: color.into(),
1735 ..Paint::default()
1736 },
1737 );
1738 }
1739
1740 fn paint_contents(
1741 self: RenderHandle<Self>,
1742 app: &mut App,
1743 context: &mut PaintingContext,
1744 offset: Offset,
1745 ) {
1746 let effective = offset + self.paint_offset(app);
1747 if self.selection(app).is_some() {
1748 self.update_selection_extents_visibility(app, effective);
1749 }
1750 let above = self.get(app).paint_cursor_above_text;
1751 if !above {
1752 self.paint_caret(app, context.canvas(), offset);
1753 }
1754 self.paint_highlights(app, context.canvas(), offset);
1755 let (painter, fonts) = self.painter_with_fonts(app);
1756 painter.paint(fonts, context.canvas(), effective);
1757 self.paint_inline_children(app, context, effective);
1758 if above {
1759 self.paint_caret(app, context.canvas(), offset);
1760 }
1761 }
1762
1763 fn preferred_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1764 let max_lines = self.get(app).max_lines;
1765 let min_lines = self.get(app).min_lines.or(max_lines);
1766 let line_height = self.preferred_line_height(app);
1767 let min_height = line_height * f64::from(min_lines.unwrap_or(0));
1768 match max_lines {
1769 None => {
1770 let estimated = if width.is_infinite() {
1771 line_height * f64::from(count_hard_line_breaks(&self.plain_text(app)) + 1)
1772 } else {
1773 let (min_width, max_width) = self.adjust_constraints(app, 0.0, width);
1774 let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
1775 intrinsics.layout(fonts, min_width, max_width);
1776 intrinsics.height()
1777 };
1778 estimated.max(min_height)
1779 }
1780 Some(1) => {
1781 let (min_width, max_width) = self.adjust_constraints(app, 0.0, width);
1782 let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
1783 intrinsics.layout(fonts, min_width, max_width);
1784 intrinsics.height()
1785 }
1786 Some(max) if min_lines == Some(max) => min_height,
1787 Some(max) => {
1788 let max_height = line_height * f64::from(max);
1789 let (min_width, max_width) = self.adjust_constraints(app, 0.0, width);
1790 let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
1791 intrinsics.layout(fonts, min_width, max_width);
1792 clamp_double(intrinsics.height(), min_height, max_height)
1793 }
1794 }
1795 }
1796}
1797
1798fn offset_or_cursor_changed(this: Handle<RenderEditable>, app: &mut App) {
1799 RenderHandle::from_handle(this).mark_needs_paint(app);
1800}
1801
1802fn utf16_len(text: &str) -> i32 {
1803 text.encode_utf16().count() as i32
1804}
1805
1806fn code_unit_at(text: &str, offset: i32) -> Option<i32> {
1807 text.encode_utf16().nth(offset as usize).map(i32::from)
1808}
1809
1810fn count_hard_line_breaks(text: &str) -> i32 {
1811 text.encode_utf16()
1812 .filter(|unit| matches!(*unit, 0x000A | 0x0085 | 0x000B | 0x000C | 0x2028 | 0x2029))
1813 .count() as i32
1814}
1815
1816fn line_number_for(
1817 painter: &mut TextPainter,
1818 fonts: &mut FontCollection,
1819 start_position: TextPosition,
1820 metrics: &[LineMetrics],
1821) -> (i32, Offset) {
1822 let offset = painter.get_offset_for_caret(fonts, start_position, Rect::ZERO);
1823 for line in metrics {
1824 if line.baseline > offset.dy() {
1825 return (line.line_number, Offset::new(offset.dx(), line.baseline));
1826 }
1827 }
1828 let last = metrics.last();
1829 (
1830 last.map(|m| m.line_number).unwrap_or(0).max(0),
1831 Offset::new(
1832 offset.dx(),
1833 last.map(|m| m.baseline + m.descent).unwrap_or(0.0),
1834 ),
1835 )
1836}
1837
1838#[allow(clippy::too_many_arguments)]
1839fn paint_range(
1840 canvas: &mut waft_embedder::Canvas,
1841 painter: &TextPainter,
1842 range: TextRange,
1843 color: Color,
1844 paint_offset: Offset,
1845 clip: Rect,
1846 height_style: BoxHeightStyle,
1847 width_style: BoxWidthStyle,
1848) {
1849 if !range.is_valid() || range.is_collapsed() {
1850 return;
1851 }
1852 let boxes = painter.get_boxes_for_selection(
1853 TextSelection::new(range.start, range.end),
1854 height_style,
1855 width_style,
1856 );
1857 let paint = Paint {
1858 color: color.into(),
1859 ..Paint::default()
1860 };
1861 for box_ in boxes {
1862 let rect = box_
1863 .to_rect()
1864 .shift(paint_offset)
1865 .intersect(clip.shift(paint_offset));
1866 if !rect.is_empty() {
1867 canvas.draw_rect(rect, &paint);
1868 }
1869 }
1870}
1871
1872impl RelayoutWhenSystemFontsChangeMixin for RenderEditable {
1873 fn relayout_when_system_fonts_change_data(
1874 self: RenderHandle<Self>,
1875 app: &App,
1876 ) -> &RelayoutWhenSystemFontsChangeData {
1877 &self.get(app).system_fonts
1878 }
1879
1880 fn relayout_when_system_fonts_change_data_mut(
1881 self: RenderHandle<Self>,
1882 app: &mut App,
1883 ) -> &mut RelayoutWhenSystemFontsChangeData {
1884 &mut self.get_mut(app).system_fonts
1885 }
1886
1887 fn system_fonts_did_change(self: RenderHandle<Self>, app: &mut App) {
1888 self.as_render_object(app).mark_needs_layout(app);
1889 self.get_mut(app).text_painter.mark_needs_layout();
1890 }
1891}
1892
1893impl ContainerRenderObjectMixin for RenderEditable {
1894 type ChildType = AnyRenderBox;
1895 type ParentDataType = TextParentData;
1896
1897 fn container_data(
1898 self: RenderHandle<Self>,
1899 app: &App,
1900 ) -> &ContainerRenderObjectData<AnyRenderBox> {
1901 &self.get(app).container
1902 }
1903
1904 fn container_data_mut(
1905 self: RenderHandle<Self>,
1906 app: &mut App,
1907 ) -> &mut ContainerRenderObjectData<AnyRenderBox> {
1908 &mut self.get_mut(app).container
1909 }
1910}
1911
1912impl RenderInlineChildrenContainerDefaults for RenderEditable {}
1913
1914impl RenderObject for RenderEditable {
1915 crate::render_object_accessors!();
1916
1917 fn debug_fill_properties(
1918 self: RenderHandle<Self>,
1919 app: &App,
1920 properties: &mut DiagnosticPropertiesBuilder,
1921 ) {
1922 let this = self.get(app);
1923 properties.add(ColorProperty::new("cursorColor", this.cursor_color));
1924 properties.add(DiagnosticsProperty::<String>::new(
1926 "showCursor",
1927 Some("Instance of 'ValueNotifier<bool>'".to_string()),
1928 ));
1929 properties.add(IntProperty::<i32>::new("maxLines", this.max_lines));
1930 properties.add(IntProperty::<i32>::new("minLines", this.min_lines));
1931 properties.add(
1932 DiagnosticsProperty::new("expands", Some(this.expands)).default_value(Some(false)),
1933 );
1934 properties.add(ColorProperty::new("selectionColor", this.selection_color));
1935 properties.add(
1936 DiagnosticsProperty::new("textScaler", self.text_scaler(app))
1937 .default_value(Some(TextScaler::NO_SCALING)),
1938 );
1939 properties.add(DiagnosticsProperty::<TextSelection>::new(
1940 "selection",
1941 this.selection,
1942 ));
1943 properties.add(DiagnosticsProperty::<String>::new(
1944 "offset",
1945 Some("Instance of 'ViewportOffset'".to_string()),
1946 ));
1947 }
1948
1949 fn debug_describe_children(
1951 self: RenderHandle<Self>,
1952 app: &App,
1953 ) -> Vec<std::rc::Rc<dyn DiagnosticsNode>> {
1954 let this = self.get(app);
1955 match this.text_painter.text() {
1956 Some(text) => vec![std::rc::Rc::new(text.diagnostics_node(
1957 Some("text".to_string()),
1958 Some(DiagnosticsTreeStyle::Transition),
1959 )) as std::rc::Rc<dyn DiagnosticsNode>],
1960 None => Vec::new(),
1961 }
1962 }
1963
1964 fn visit_children(
1965 self: RenderHandle<Self>,
1966 app: &App,
1967 visitor: &mut dyn FnMut(AnyRenderObject),
1968 ) {
1969 ContainerRenderObjectMixin::visit_children(self, app, visitor)
1971 }
1972
1973 fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
1974 ContainerRenderObjectMixin::redepth_children(self, app)
1975 }
1976
1977 fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
1978 RelayoutWhenSystemFontsChangeMixin::attach_system_fonts(self, app);
1979 ContainerRenderObjectMixin::did_attach(self, app, owner);
1980 let offset = self.get(app).offset.handle();
1981 offset.add_listener(app, self.mark_needs_paint_listener());
1982 let show_cursor = self.get(app).show_cursor.handle();
1983 show_cursor.add_listener(app, self.mark_needs_paint_listener());
1984 }
1985
1986 fn did_detach(self: RenderHandle<Self>, app: &mut App) {
1987 let offset = self.get(app).offset.handle();
1988 offset.remove_listener(app, &self.mark_needs_paint_listener());
1989 let show_cursor = self.get(app).show_cursor.handle();
1990 show_cursor.remove_listener(app, &self.mark_needs_paint_listener());
1991 RelayoutWhenSystemFontsChangeMixin::detach_system_fonts(self, app);
1992 ContainerRenderObjectMixin::did_detach(self, app);
1993 }
1994
1995 fn dispose(self: RenderHandle<Self>, app: &mut App) {
1996 LayerHandle::set_layer(app, |app| &mut self.get_mut(app).leader_layer_handler, None);
1997 LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, None);
1998 let start_in_viewport = self.get(app).selection_start_in_viewport.handle();
1999 let end_in_viewport = self.get(app).selection_end_in_viewport.handle();
2000 start_in_viewport.dispose(app);
2001 end_in_viewport.dispose(app);
2002 crate::object::RenderObjectBase::dispose(self, app);
2003 }
2004
2005 fn describe_approximate_paint_clip(
2008 self: RenderHandle<Self>,
2009 app: &App,
2010 _child: AnyRenderObject,
2011 ) -> Option<Rect> {
2012 match self.get(app).clip_behavior {
2013 Clip::None => None,
2014 Clip::HardEdge | Clip::AntiAlias | Clip::AntiAliasWithSaveLayer => self
2015 .has_visual_overflow(app)
2016 .then(|| Offset::ZERO & self.size(app)),
2017 }
2018 }
2019
2020 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2021 let constraints = self.constraints(app);
2022 let placeholder_dimensions = self.layout_inline_children(
2023 app,
2024 constraints.max_width,
2025 ChildLayoutHelper::layout_child,
2026 ChildLayoutHelper::get_baseline,
2027 );
2028 self.get_mut(app).placeholder_dimensions = Some(placeholder_dimensions.clone());
2029 let (min_width, max_width) =
2030 self.adjust_constraints(app, constraints.min_width, constraints.max_width);
2031 let (painter, fonts) = self.painter_with_fonts(app);
2032 painter.set_placeholder_dimensions(Some(placeholder_dimensions));
2033 painter.layout(fonts, min_width, max_width);
2034 let boxes = self
2035 .get_mut(app)
2036 .text_painter
2037 .inline_placeholder_boxes()
2038 .expect("laid out just now");
2039 self.position_inline_children(app, &boxes);
2040 self.compute_caret_prototype(app);
2041 let caret_margin = self.caret_margin(app);
2042 let painter_width = self.get(app).text_painter.width();
2043 let painter_height = self.get(app).text_painter.height();
2044 let width = if self.get(app).force_line {
2045 constraints.max_width
2046 } else {
2047 constraints.constrain_width(painter_width + caret_margin)
2048 };
2049 let preferred_height = match self.get(app).max_lines {
2050 None => {
2051 let min_lines = self.get(app).min_lines.unwrap_or(0);
2052 painter_height.max(self.preferred_line_height(app) * f64::from(min_lines))
2053 }
2054 Some(1) => painter_height,
2055 Some(max_lines) => {
2056 let line_height = self.preferred_line_height(app);
2057 let min_lines = self.get(app).min_lines.unwrap_or(max_lines);
2058 clamp_double(
2059 painter_height,
2060 line_height * f64::from(min_lines),
2061 line_height * f64::from(max_lines),
2062 )
2063 }
2064 };
2065 let size = Size::new(width, constraints.constrain_height(preferred_height));
2066 self.set_size(app, size);
2067 let content_size = Size::new(painter_width + caret_margin, painter_height);
2068 self.get_mut(app).max_scroll_extent = self.get_max_scroll_extent(app, content_size);
2069 self.get_mut(app).layout_generation += 1;
2070 let viewport_extent = self.viewport_extent(app);
2071 let max_scroll = self.get(app).max_scroll_extent;
2072 let offset = self.get(app).offset.handle();
2073 offset.apply_viewport_dimension(app, viewport_extent);
2074 offset.apply_content_dimensions(app, 0.0, max_scroll);
2075 }
2076
2077 fn paint(
2078 self: RenderHandle<Self>,
2079 app: &mut App,
2080 context: &mut PaintingContext,
2081 offset: Offset,
2082 ) {
2083 self.compute_text_metrics_if_needed(app);
2084 if self.has_visual_overflow(app) && self.get(app).clip_behavior != Clip::None {
2085 let size = self.size(app);
2086 let clip_behavior = self.get(app).clip_behavior;
2087 let old = self.get(app).clip_rect_layer.layer();
2088 let layer = context.push_clip_rect(
2089 app,
2090 self.as_object().needs_compositing(app),
2091 offset,
2092 Offset::ZERO & size,
2093 |app, context, offset| {
2094 self.paint_contents(app, context, offset);
2095 },
2096 clip_behavior,
2097 old,
2098 );
2099 LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, layer);
2100 } else {
2101 LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, None);
2102 self.paint_contents(app, context, offset);
2103 }
2104 if let Some(selection) = self.selection(app)
2105 && selection.is_valid()
2106 {
2107 let endpoints = self.get_endpoints_for_selection(app, selection);
2108 self.paint_handle_layers(app, context, &endpoints, offset);
2109 }
2110 }
2111}
2112
2113impl RenderBox for RenderEditable {
2114 crate::render_box_accessors!();
2115
2116 fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
2117 RenderInlineChildrenContainerDefaults::setup_parent_data(self, app, child);
2118 }
2119
2120 fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, _height: f64) -> f64 {
2121 let placeholder_dimensions = self.layout_inline_children(
2122 app,
2123 f64::INFINITY,
2124 |app, child, _| Size::new(child.get_min_intrinsic_width(app, f64::INFINITY), 0.0),
2125 ChildLayoutHelper::get_dry_baseline,
2126 );
2127 let (min_width, max_width) = self.adjust_constraints(app, 0.0, f64::INFINITY);
2128 let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
2129 intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
2130 intrinsics.layout(fonts, min_width, max_width);
2131 intrinsics.min_intrinsic_width()
2132 }
2133
2134 fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, _height: f64) -> f64 {
2135 let placeholder_dimensions = self.layout_inline_children(
2136 app,
2137 f64::INFINITY,
2138 |app, child, _| Size::new(child.get_max_intrinsic_width(app, f64::INFINITY), 0.0),
2141 ChildLayoutHelper::get_dry_baseline,
2142 );
2143 let (min_width, max_width) = self.adjust_constraints(app, 0.0, f64::INFINITY);
2144 let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
2145 intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
2146 intrinsics.layout(fonts, min_width, max_width);
2147 intrinsics.max_intrinsic_width() + self.caret_margin(app)
2148 }
2149
2150 fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2151 self.compute_max_intrinsic_height(app, width)
2152 }
2153
2154 fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2155 let placeholder_dimensions = self.layout_inline_children(
2156 app,
2157 width,
2158 ChildLayoutHelper::dry_layout_child,
2159 ChildLayoutHelper::get_dry_baseline,
2160 );
2161 let (intrinsics, _) = self.text_intrinsics_with_fonts(app);
2162 intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
2163 self.preferred_height(app, width)
2164 }
2165
2166 fn compute_dry_layout(
2167 self: RenderHandle<Self>,
2168 app: &mut App,
2169 constraints: BoxConstraints,
2170 ) -> Size {
2171 let placeholder_dimensions = self.layout_inline_children(
2172 app,
2173 constraints.max_width,
2174 ChildLayoutHelper::dry_layout_child,
2175 ChildLayoutHelper::get_dry_baseline,
2176 );
2177 let (min_width, max_width) =
2178 self.adjust_constraints(app, constraints.min_width, constraints.max_width);
2179 let force_line = self.get(app).force_line;
2180 let caret_margin = self.caret_margin(app);
2181 let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
2182 intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
2183 intrinsics.layout(fonts, min_width, max_width);
2184 let painter_width = intrinsics.width();
2185 let width = if force_line {
2186 constraints.max_width
2187 } else {
2188 constraints.constrain_width(painter_width + caret_margin)
2189 };
2190 let height = self.preferred_height(app, constraints.max_width);
2191 Size::new(width, constraints.constrain_height(height))
2192 }
2193
2194 fn compute_dry_baseline(
2195 self: RenderHandle<Self>,
2196 app: &mut App,
2197 constraints: BoxConstraints,
2198 baseline: TextBaseline,
2199 ) -> Option<f64> {
2200 let (min_width, max_width) =
2201 self.adjust_constraints(app, constraints.min_width, constraints.max_width);
2202 let placeholder_dimensions = self.layout_inline_children(
2203 app,
2204 constraints.max_width,
2205 ChildLayoutHelper::dry_layout_child,
2206 ChildLayoutHelper::get_dry_baseline,
2207 );
2208 let (intrinsics, fonts) = self.text_intrinsics_with_fonts(app);
2209 intrinsics.set_placeholder_dimensions(Some(placeholder_dimensions));
2210 intrinsics.layout(fonts, min_width, max_width);
2211 Some(intrinsics.compute_distance_to_actual_baseline(baseline))
2212 }
2213
2214 fn compute_distance_to_actual_baseline(
2215 self: RenderHandle<Self>,
2216 app: &mut App,
2217 baseline: TextBaseline,
2218 ) -> Option<f64> {
2219 self.compute_text_metrics_if_needed(app);
2220 Some(
2221 self.get(app)
2222 .text_painter
2223 .compute_distance_to_actual_baseline(baseline),
2224 )
2225 }
2226
2227 fn hit_test_self(self: RenderHandle<Self>, _app: &App, _position: Offset) -> bool {
2228 true
2229 }
2230
2231 fn hit_test_children(
2232 self: RenderHandle<Self>,
2233 app: &mut App,
2234 result: &mut BoxHitTestResult<'_>,
2235 position: Offset,
2236 ) -> bool {
2237 let effective_position = position - self.paint_offset(app);
2239 self.hit_test_inline_children(app, result, effective_position)
2240 }
2241
2242 fn apply_paint_transform(
2243 self: RenderHandle<Self>,
2244 app: &App,
2245 child: AnyRenderObject,
2246 transform: &mut Matrix4,
2247 ) {
2248 self.default_apply_paint_transform(app, child, transform);
2250 }
2251}
2252
2253impl RenderEditable {
2254 fn paint_handle_layers(
2257 self: RenderHandle<Self>,
2258 app: &mut App,
2259 context: &mut PaintingContext,
2260 endpoints: &[TextSelectionPoint],
2261 offset: Offset,
2262 ) {
2263 let size = self.size(app);
2264 let clamp = |point: Offset| {
2265 Offset::new(
2266 point.dx().clamp(0.0, size.width()),
2267 point.dy().clamp(0.0, size.height()),
2268 )
2269 };
2270 let Some(start) = endpoints.first() else {
2271 return;
2272 };
2273 let start_point = clamp(start.point);
2274 let (start_link, end_link) = {
2275 let this = self.get(app);
2276 (
2277 this.start_handle_layer_link.clone(),
2278 this.end_handle_layer_link.clone(),
2279 )
2280 };
2281 let start_layer = LeaderLayer::new(app, start_link);
2282 start_layer.set_offset(app, start_point + offset);
2283 LayerHandle::set_layer(
2284 app,
2285 |app| &mut self.get_mut(app).leader_layer_handler,
2286 Some(start_layer),
2287 );
2288 context.push_layer(
2289 app,
2290 start_layer.as_container_layer(),
2291 |_, _, _| {},
2292 Offset::ZERO,
2293 None,
2294 );
2295 if let Some(end) = endpoints.get(1) {
2296 let end_point = clamp(end.point);
2297 let end_layer = LeaderLayer::new(app, end_link);
2298 end_layer.set_offset(app, end_point + offset);
2299 context.push_layer(
2300 app,
2301 end_layer.as_container_layer(),
2302 |_, _, _| {},
2303 Offset::ZERO,
2304 None,
2305 );
2306 } else if self
2307 .selection(app)
2308 .is_some_and(|selection| selection.is_collapsed())
2309 {
2310 let end_layer = LeaderLayer::new(app, end_link);
2311 end_layer.set_offset(app, start_point + offset);
2312 context.push_layer(
2313 app,
2314 end_layer.as_container_layer(),
2315 |_, _, _| {},
2316 Offset::ZERO,
2317 None,
2318 );
2319 }
2320 }
2321}
2322
2323impl TextLayoutMetrics for RenderHandle<RenderEditable> {
2324 fn get_line_at_offset(
2325 self,
2326 app: &mut App,
2327 position: TextPosition,
2328 ) -> waft_embedder::TextSelection {
2329 RenderEditable::get_line_at_offset(self, app, position)
2330 }
2331
2332 fn get_word_boundary(self, app: &mut App, position: TextPosition) -> waft_embedder::TextRange {
2333 RenderEditable::get_word_boundary(self, app, position)
2334 }
2335
2336 fn get_text_position_above(self, app: &mut App, position: TextPosition) -> TextPosition {
2337 RenderEditable::get_text_position_above(self, app, position)
2338 }
2339
2340 fn get_text_position_below(self, app: &mut App, position: TextPosition) -> TextPosition {
2341 RenderEditable::get_text_position_below(self, app, position)
2342 }
2343}
2344
2345#[cfg(test)]
2346mod tests {
2347 use std::cell::Cell;
2348 use std::rc::Rc;
2349
2350 use valo::{Font, FontAttrs};
2351 use waft_embedder::{FontSource, TextAffinity};
2352 use waft_foundation::{AppCell, Task};
2353 use waft_painting::{AlignmentGeometry, PaintingBinding, TextSpan, TextStyle};
2354 use waft_scheduler::SchedulerBinding;
2355 use waft_services::{TextEditingValue, TextSelectionDelegate};
2356
2357 use super::*;
2358 use crate::proxy_box::RenderConstrainedBox;
2359 use crate::testing::{EnginePhase, layout_with, pump_frame};
2360 use crate::viewport_offset::FixedViewportOffset;
2361
2362 #[derive(Default)]
2363 struct TestDelegate {
2364 value: TextEditingValue,
2365 }
2366
2367 impl TextSelectionDelegate for TestDelegate {
2368 fn text_editing_value(self: Handle<Self>, app: &App) -> TextEditingValue {
2369 app.get(self).value.clone()
2370 }
2371
2372 fn user_update_text_editing_value(
2373 self: Handle<Self>,
2374 app: &mut App,
2375 value: TextEditingValue,
2376 _cause: SelectionChangedCause,
2377 ) {
2378 app.get_mut(self).value = value;
2379 }
2380
2381 fn hide_toolbar(self: Handle<Self>, _app: &mut App, _hide_handles: bool) {}
2382
2383 fn bring_into_view(self: Handle<Self>, _app: &mut App, _position: TextPosition) {}
2384
2385 fn cut_selection(self: Handle<Self>, _app: &mut App, _cause: SelectionChangedCause) {}
2386
2387 fn paste_text(
2388 self: Handle<Self>,
2389 _app: &mut App,
2390 _cause: SelectionChangedCause,
2391 ) -> Task<()> {
2392 Task::ready(())
2393 }
2394
2395 fn select_all(self: Handle<Self>, _app: &mut App, _cause: SelectionChangedCause) {}
2396
2397 fn copy_selection(self: Handle<Self>, _app: &mut App, _cause: SelectionChangedCause) {}
2398 }
2399
2400 fn install_fonts(app: &mut App) {
2401 let binding = PaintingBinding::instance(app);
2402 if !binding.has_fonts(app) {
2403 binding.install_fonts(app, |fonts| {
2404 fonts.add_source(valo_system_fonts::SystemFonts::load());
2405 });
2406 }
2407 }
2408
2409 fn span(text: &str) -> InlineSpanRef {
2410 TextSpan::new()
2411 .text(text)
2412 .style(TextStyle::new().font_size(20.0))
2413 .into_span()
2414 }
2415
2416 fn laid_out(app: &mut App, text: &str) -> RenderHandle<RenderEditable> {
2417 install_fonts(app);
2418 let delegate = app.create(TestDelegate {
2419 value: TextEditingValue::new()
2420 .text(text)
2421 .selection(TextSelection::collapsed(0, TextAffinity::Downstream)),
2422 });
2423 let start = LayerLink::new(app);
2424 let end = LayerLink::new(app);
2425 let offset = FixedViewportOffset::zero(app).erase();
2426 let editable = RenderEditable::new(
2427 app,
2428 TextDirection::Ltr,
2429 start,
2430 end,
2431 offset,
2432 delegate.as_text_selection_delegate(),
2433 );
2434 editable.set_text(app, Some(span(text)));
2435 editable.set_cursor_color(app, Some(Color::from_argb(255, 0, 0, 0)));
2436 layout_with(
2437 app,
2438 editable.as_box(),
2439 Some(BoxConstraints::tight_for(Some(200.0), Some(40.0))),
2440 AlignmentGeometry::CENTER,
2441 EnginePhase::Layout,
2442 );
2443 editable
2444 }
2445
2446 #[test]
2449 fn editable_respects_clip_behavior_when_described() {
2450 let cell = AppCell::new();
2451 let mut app = cell.borrow_mut();
2452 install_fonts(&mut app);
2453 let text = "a".repeat(10_000);
2454 let delegate = app.create(TestDelegate {
2455 value: TextEditingValue::new()
2456 .text(text.clone())
2457 .selection(TextSelection::collapsed(0, TextAffinity::Downstream)),
2458 });
2459 let start = LayerLink::new(&mut app);
2460 let end = LayerLink::new(&mut app);
2461 let offset = FixedViewportOffset::zero(&mut app).erase();
2462 let editable = RenderEditable::new(
2463 &mut app,
2464 TextDirection::Ltr,
2465 start,
2466 end,
2467 offset,
2468 delegate.as_text_selection_delegate(),
2469 );
2470 editable.set_text(&mut app, Some(span(&text)));
2471 editable.set_clip_behavior(&mut app, Clip::None);
2472 layout_with(
2473 &mut app,
2474 editable.as_box(),
2475 Some(BoxConstraints::tight_for(Some(200.0), Some(40.0))),
2476 AlignmentGeometry::CENTER,
2477 EnginePhase::Layout,
2478 );
2479 let child =
2482 RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(10.0, 10.0)), None);
2483 editable.add(&mut app, child.as_box());
2484
2485 let mut visited = false;
2486 editable
2487 .as_object()
2488 .visit_children(&app, &mut |visited_child| {
2489 visited = true;
2490 assert_eq!(
2491 editable
2492 .as_object()
2493 .describe_approximate_paint_clip(&app, visited_child),
2494 None
2495 );
2496 });
2497 assert!(visited, "the editable has a child to describe");
2498
2499 editable.set_clip_behavior(&mut app, Clip::HardEdge);
2500 let expected = Some(Offset::ZERO & editable.size(&app));
2501 editable
2502 .as_object()
2503 .visit_children(&app, &mut |visited_child| {
2504 assert_eq!(
2505 editable
2506 .as_object()
2507 .describe_approximate_paint_clip(&app, visited_child),
2508 expected
2509 );
2510 });
2511 }
2512
2513 #[test]
2515 fn an_editable_dump_shows_its_text() {
2516 let cell = AppCell::new();
2517 let mut app = cell.borrow_mut();
2518 let delegate = app.create(TestDelegate::default());
2519 let start = LayerLink::new(&mut app);
2520 let end = LayerLink::new(&mut app);
2521 let offset = FixedViewportOffset::zero(&mut app).erase();
2522 let editable = RenderEditable::new(
2523 &mut app,
2524 TextDirection::Ltr,
2525 start,
2526 end,
2527 offset,
2528 delegate.as_text_selection_delegate(),
2529 );
2530 editable.set_text(
2531 &mut app,
2532 Some(
2533 TextSpan::new()
2534 .text("12345")
2535 .style(TextStyle::new().height(1.0).font_size(10.0))
2536 .into_span(),
2537 ),
2538 );
2539 let dump = editable.as_object().to_string_deep(&app);
2540 assert!(
2541 dump.ends_with(
2542 " ╘═╦══ text ═══\n\
2543 \u{20}\u{20} ║ TextSpan:\n\
2544 \u{20}\u{20} ║ inherit: true\n\
2545 \u{20}\u{20} ║ size: 10.0\n\
2546 \u{20}\u{20} ║ height: 1.0x\n\
2547 \u{20}\u{20} ║ \"12345\"\n\
2548 \u{20}\u{20} ╚═══════════\n"
2549 ),
2550 "{dump}"
2551 );
2552 }
2553
2554 #[test]
2555 fn move_by_word_boundary_skips_spaces_and_punctuation() {
2556 let cell = AppCell::new();
2557 let mut app = cell.borrow_mut();
2558 let text = concat!(
2559 "ABC ABC\n", "A\u{41}\u{301} \u{41}\u{301}\n", " \n", "ABC!!!ABC\n", " !ABC !!\n", "A \u{115CB}\u{115CB} A\n", );
2566 let editable = laid_out(&mut app, text);
2567 let boundary = editable.word_boundaries(&app).move_by_word_boundary();
2568
2569 assert_eq!(boundary.get_leading_text_boundary_at(&mut app, 4), Some(0));
2572 assert_eq!(boundary.get_trailing_text_boundary_at(&mut app, 4), Some(9));
2573
2574 assert_eq!(
2576 boundary.get_leading_text_boundary_at(&mut app, 14),
2577 Some(10)
2578 );
2579 assert_eq!(
2580 boundary.get_trailing_text_boundary_at(&mut app, 14),
2581 Some(19)
2582 );
2583
2584 assert_eq!(
2586 boundary.get_leading_text_boundary_at(&mut app, 24),
2587 Some(20)
2588 );
2589 assert_eq!(
2590 boundary.get_trailing_text_boundary_at(&mut app, 24),
2591 Some(29)
2592 );
2593
2594 assert_eq!(
2596 boundary.get_leading_text_boundary_at(&mut app, 34),
2597 Some(30)
2598 );
2599 assert_eq!(
2600 boundary.get_trailing_text_boundary_at(&mut app, 34),
2601 Some(39)
2602 );
2603
2604 assert_eq!(
2606 boundary.get_leading_text_boundary_at(&mut app, 44),
2607 Some(43)
2608 );
2609 assert_eq!(
2610 boundary.get_trailing_text_boundary_at(&mut app, 44),
2611 Some(46)
2612 );
2613
2614 assert_eq!(
2616 boundary.get_leading_text_boundary_at(&mut app, 54),
2617 Some(50)
2618 );
2619 assert_eq!(
2620 boundary.get_trailing_text_boundary_at(&mut app, 54),
2621 Some(59)
2622 );
2623 }
2624
2625 #[test]
2627 fn strut_style_affects_intrinsics() {
2628 let cell = AppCell::new();
2629 let mut app = cell.borrow_mut();
2630 crate::testing::install_test_fonts(&mut app);
2631 let delegate = app.create(TestDelegate::default());
2632 let start = LayerLink::new(&mut app);
2633 let end = LayerLink::new(&mut app);
2634 let offset = FixedViewportOffset::zero(&mut app).erase();
2635 let editable = RenderEditable::new(
2636 &mut app,
2637 TextDirection::Ltr,
2638 start,
2639 end,
2640 offset,
2641 delegate.as_text_selection_delegate(),
2642 );
2643 editable.set_text(
2644 &mut app,
2645 Some(
2646 TextSpan::new()
2647 .text("Hello World")
2648 .style(TextStyle::new().font_size(10.0))
2649 .into_span(),
2650 ),
2651 );
2652
2653 assert_eq!(
2654 editable
2655 .as_box()
2656 .get_max_intrinsic_height(&mut app, f64::INFINITY),
2657 10.0
2658 );
2659
2660 editable.set_strut_style(
2661 &mut app,
2662 Some(StrutStyle::new().font_size(100.0).force_strut_height(true)),
2663 );
2664 assert_eq!(
2665 editable
2666 .as_box()
2667 .get_max_intrinsic_height(&mut app, f64::INFINITY),
2668 100.0
2669 );
2670 }
2671
2672 #[test]
2673 fn display_names_the_direction() {
2674 let point = Offset::new(1.0, 2.0);
2675 assert_eq!(
2676 TextSelectionPoint::new(point, Some(TextDirection::Ltr)).to_string(),
2677 format!("{point:?}-ltr")
2678 );
2679 assert_eq!(
2680 TextSelectionPoint::new(point, None).to_string(),
2681 format!("{point:?}")
2682 );
2683 }
2684
2685 #[test]
2686 fn layout_gives_the_text_a_size() {
2687 let cell = AppCell::new();
2688 let mut app = cell.borrow_mut();
2689 let editable = laid_out(&mut app, "hi");
2690 let size = editable.size(&app);
2691 assert!(size.width() > 0.0);
2692 assert!(size.height() > 0.0);
2693 }
2694
2695 #[test]
2698 fn a_dry_layout_follows_force_line() {
2699 let cell = AppCell::new();
2700 let mut app = cell.borrow_mut();
2701 let editable = laid_out(&mut app, "A");
2702 let constraints = BoxConstraints::new().min_width(100.0).max_width(500.0);
2703
2704 let initial_width = editable.get_dry_layout(&mut app, constraints).width();
2705 assert_eq!(initial_width, 500.0);
2706
2707 editable.set_force_line(&mut app, false);
2708 assert!(editable.get_dry_layout(&mut app, constraints).width() < initial_width);
2709 }
2710
2711 #[test]
2713 fn a_dry_baseline_is_the_baseline_of_the_layout() {
2714 let cell = AppCell::new();
2715 let mut app = cell.borrow_mut();
2716 let editable = laid_out(&mut app, "hi");
2717 let constraints = BoxConstraints::tight_for(Some(200.0), Some(40.0));
2718
2719 let dry = editable.get_dry_baseline(&mut app, constraints, TextBaseline::Alphabetic);
2720 let laid_out = editable.get_distance_to_baseline(&mut app, TextBaseline::Alphabetic, false);
2721 assert!(dry.is_some_and(|dry| dry > 0.0));
2722 assert_eq!(dry, laid_out);
2723 }
2724
2725 #[test]
2726 fn select_position_updates_the_delegate() {
2727 let cell = AppCell::new();
2728 let mut app = cell.borrow_mut();
2729 let editable = laid_out(&mut app, "hello");
2730 let origin = editable.as_box().local_to_global(&app, Offset::ZERO, None);
2731 editable.select_position_at(
2732 &mut app,
2733 origin + Offset::new(2.0, 2.0),
2734 None,
2735 SelectionChangedCause::Tap,
2736 );
2737 let value = editable
2738 .text_selection_delegate(&app)
2739 .text_editing_value(&app);
2740 assert!(value.selection.is_valid());
2741 assert!(value.selection.is_collapsed());
2742 }
2743
2744 #[test]
2745 fn handle_secondary_tap_down_records_the_position() {
2746 let cell = AppCell::new();
2747 let mut app = cell.borrow_mut();
2748 let editable = laid_out(&mut app, "hello");
2749 let at = Offset::new(12.0, 8.0);
2750 editable.handle_secondary_tap_down(&mut app, &TapDownDetails::new(at, None, None));
2751 assert_eq!(editable.last_secondary_tap_down_position(&app), Some(at));
2752 }
2753
2754 #[test]
2755 fn selection_extents_default_in_the_viewport() {
2756 let cell = AppCell::new();
2757 let mut app = cell.borrow_mut();
2758 let editable = laid_out(&mut app, "hello");
2759 assert!(
2760 *editable.selection_start_in_viewport(&app).value(&app),
2761 "Flutter defaults selectionStartInViewport to true"
2762 );
2763 assert!(
2764 *editable.selection_end_in_viewport(&app).value(&app),
2765 "Flutter defaults selectionEndInViewport to true"
2766 );
2767 }
2768
2769 #[test]
2770 fn system_fonts_change_marks_the_editable_dirty() {
2771 let cell = AppCell::new();
2772 let mut app = cell.borrow_mut();
2773 let editable = laid_out(&mut app, "hello");
2774 assert!(!editable.as_object().debug_needs_layout(&app));
2775 PaintingBinding::instance(&mut app).handle_system_fonts_did_change(&mut app);
2776 SchedulerBinding::handle_begin_frame(&mut app, &[], None);
2777 assert!(
2778 editable.as_object().debug_needs_layout(&app),
2779 "RenderEditable listens to PaintingBinding.system_fonts"
2780 );
2781 }
2782
2783 struct GatedFonts {
2786 inner: valo_system_fonts::SystemFonts,
2787 allow_non_ascii: Rc<Cell<bool>>,
2788 }
2789
2790 impl FontSource for GatedFonts {
2791 fn family(&mut self, _name: &str) -> Vec<Font> {
2792 Vec::new()
2795 }
2796
2797 fn face_for_codepoint(&mut self, codepoint: char, attrs: FontAttrs) -> Option<Font> {
2798 if !self.allow_non_ascii.get() && !codepoint.is_ascii() {
2799 return None;
2800 }
2801 self.inner.face_for_codepoint(codepoint, attrs)
2802 }
2803 }
2804
2805 #[test]
2806 fn system_fonts_change_relayouts_the_editable_once_a_fallback_face_arrives() {
2807 let allow_non_ascii = Rc::new(Cell::new(false));
2808 let cell = AppCell::new();
2809 let mut app = cell.borrow_mut();
2810 PaintingBinding::instance(&mut app).install_fonts(&mut app, {
2811 let allow_non_ascii = Rc::clone(&allow_non_ascii);
2812 move |fonts| {
2813 fonts.add_source(waft_embedder::TestFontSource::new());
2817 fonts.add_source(GatedFonts {
2818 inner: valo_system_fonts::SystemFonts::load(),
2819 allow_non_ascii,
2820 });
2821 }
2822 });
2823
2824 let text = "a你";
2825 let delegate = app.create(TestDelegate {
2826 value: TextEditingValue::new()
2827 .text(text)
2828 .selection(TextSelection::collapsed(0, TextAffinity::Downstream)),
2829 });
2830 let start = LayerLink::new(&mut app);
2831 let end = LayerLink::new(&mut app);
2832 let offset = FixedViewportOffset::zero(&mut app).erase();
2833 let editable = RenderEditable::new(
2834 &mut app,
2835 TextDirection::Ltr,
2836 start,
2837 end,
2838 offset,
2839 delegate.as_text_selection_delegate(),
2840 );
2841 editable.set_text(&mut app, Some(span(text)));
2842 layout_with(
2843 &mut app,
2844 editable.as_box(),
2845 Some(BoxConstraints::tight_for(Some(200.0), Some(40.0))),
2846 AlignmentGeometry::CENTER,
2847 EnginePhase::Layout,
2848 );
2849
2850 let cjk = TextRange::new(1, 2);
2851 editable
2852 .get_rect_for_composing_range(&mut app, cjk)
2853 .expect("an uncovered CJK character still occupies .notdef space");
2854
2855 allow_non_ascii.set(true);
2856 PaintingBinding::instance(&mut app).handle_system_fonts_did_change(&mut app);
2862 SchedulerBinding::handle_begin_frame(&mut app, &[], None);
2863 pump_frame(&mut app, EnginePhase::Layout);
2864 editable
2865 .get_rect_for_composing_range(&mut app, cjk)
2866 .expect("the rebuilt paragraph still places the CJK character");
2867 }
2868}