1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
use core::num::NonZeroU16;
use bevy_clipboard::ClipboardRead;
use bevy_math::{Rect, Vec2};
use bevy_reflect::Reflect;
use parley::{PlainEditorDriver, StyleProperty};
use smol_str::SmolStr;
use swash::FontRef;
use crate::scroll::{TextLineYBounds, TextViewport};
use crate::TextBrush;
/// A selection within IME preedit text, expressed as byte offsets from the start of the preedit.
///
/// The anchor and focus map directly onto parley's `Selection::new(anchor, focus)` when
/// the preedit is applied. If `anchor == focus`, the selection is a caret.
///
/// This corresponds to [`ImePredit::Commit.cursor`](https://docs.rs/bevy/latest/bevy/prelude/enum.Ime.html#variant.Preedit.field.cursor)
/// from `bevy_window`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Reflect)]
pub struct PreeditCursor {
/// Anchor byte offset within the preedit text.
pub anchor: usize,
/// Focus (caret) byte offset within the preedit text.
pub focus: usize,
}
/// Deferred text input edit and navigation actions applied by the `apply_text_edits` system.
#[derive(Debug, Clone, PartialEq, Reflect)]
pub enum TextEdit {
/// Copy the current selection into the clipboard.
///
/// Typically generated in response to copy commands such as Ctrl + C or Cmd + C.
Copy,
/// Copy the current selection into the clipboard, and the delete the selected text.
///
/// Typically generated in response to cut commands such as Ctrl + X or Cmd + X.
Cut,
/// Paste the current clipboard contents at the cursor. If there is a selection, replaces the selection with the clipboard contents instead.
///
/// Typically generated in response to paste commands such as Ctrl + V or Cmd + V.
Paste,
/// Insert a character or string at the cursor. If there is a selection, replaces the selection with the character instead.
///
/// Ordinarily, this is derived from `bevy_input::keyboard::KeyboardInput::logical_key`,
/// which stores a [`SmolStr`] inside of the `Key::Character` variant, which may represent multiple bytes.
Insert(SmolStr),
/// Delete the character behind the cursor.
/// If there is a selection, deletes the selection instead.
///
/// Typically generated in response to the Backspace key.
///
/// This operation removes an entire Unicode grapheme cluster, which may consist of multiple bytes,
/// shifting the cursor position accordingly.
Backspace,
/// Delete the word behind the cursor.
/// If there is a selection, deletes the selection instead.
///
/// Typically generated in response to Ctrl + Backspace or Option + Backspace.
BackspaceWord,
/// Delete the character at the cursor.
/// If there is a selection, deletes the selection instead.
///
/// Typically generated in response to the Delete key.
///
/// This operation removes an entire Unicode grapheme cluster, which may consist of multiple bytes,
/// shifting the cursor position accordingly.
Delete,
/// Delete the word at the cursor.
/// If there is a selection, deletes the selection instead.
///
/// Typically generated in response to Ctrl + Delete or Option + Delete.
DeleteWord,
/// Moves the cursor by one position to the left.
/// `true` moves and extends selection.
///
/// Typically generated in response to the Left key.
Left(bool),
/// Moves the cursor by one position to the right.
/// `true` moves and extends selection.
///
/// Typically generated in response to the Right key.
Right(bool),
/// Moves the cursor a word to the left.
/// `true` moves and extends selection.
///
/// Typically generated in response to Ctrl + Left or Option + Left.
WordLeft(bool),
/// Moves the cursor a word to the right.
/// `true` moves and extends selection.
///
/// Typically generated in response to Ctrl + Right or Option + Right.
WordRight(bool),
/// Moves the cursor up by one visual line.
/// `true` moves and extends selection.
///
/// Typically generated in response to the Up key.
Up(bool),
/// Moves the cursor down by one visual line.
/// `true` moves and extends selection.
///
/// Typically generated in response to the Down key.
Down(bool),
/// Moves the cursor to the start of the text.
/// `true` moves and extends selection.
///
/// Typically generated in response to Ctrl + Home or Command + Up.
TextStart(bool),
/// Moves the cursor to the end of the text.
/// `true` moves and extends selection.
///
/// Typically generated in response to Ctrl + End or Command + Down.
TextEnd(bool),
/// Moves the cursor to the start of the current hard line.
/// A hardline is a line separated by a newline character.
/// `true` moves and extends selection.
///
/// Typically generated in response to Command + Left.
HardLineStart(bool),
/// Moves the cursor to the end of the current hard line.
/// `true` moves and extends selection.
///
/// Typically generated in response to Command + Right.
HardLineEnd(bool),
/// Moves the cursor to the start of the current visual line.
/// `true` moves and extends selection.
///
/// Typically generated in response to the Home key.
LineStart(bool),
/// Moves the cursor to the end of the current visual line.
/// `true` moves and extends selection.
///
/// Typically generated in response to the End key.
LineEnd(bool),
/// Collapses the current selection to a caret.
///
/// Typically generated in response to the Escape key.
CollapseSelection,
/// Selects all text.
///
/// Typically generated in response to select-all commands such as Ctrl + A or Cmd + A.
SelectAll,
/// Selects all text if the current selection is collapsed.
///
/// Typically generated in response to a chain of focus gained by pointer press into
/// pointer release events.
SelectAllIfCollapsed,
/// Moves the cursor to the given point.
///
/// Typically generated in response to a pointer press within the text area.
MoveToPoint(Vec2),
/// Selects the word at the given point.
///
/// Typically generated in response to a double-click within the text area.
SelectWordAtPoint(Vec2),
/// Selects the line at the given point.
///
/// A line here means a single row of glyphs, all sharing the same baseline.
///
/// Typically generated in response to a triple-click within the text area.
SelectLineAtPoint(Vec2),
/// Selects the hard line at the given point.
///
/// A “hard line” is the portion of text between explicit newline characters.
///
/// Typically generated in response to a triple-click within the text area.
SelectedHardLineAtPoint(Vec2),
/// Extends the current selection to the given point.
///
/// Typically generated in response to dragging a pointer within the text area.
ExtendSelectionToPoint(Vec2),
/// Extends the current selection from the existing anchor to the given point.
///
/// Typically generated in response to shift-clicking within the text area.
ShiftClickExtension(Vec2),
/// Set the IME preedit/composing text at the cursor, or clear it if `value` is empty.
///
/// The preedit text is excluded from [`EditableText::value`](crate::EditableText::value).
/// `cursor` describes the selection within the preedit text, or `None` to hide the cursor.
///
/// Passing an empty `value` clears any in-progress composition; `cursor` is ignored in
/// that case. Use [`TextEdit::clear_ime_compose`] as a convenience constructor.
///
/// Typically generated in response to [`bevy_window::Ime::Preedit`] events.
///
/// [`bevy_window::Ime::Preedit`]: https://docs.rs/bevy/latest/bevy/prelude/enum.Ime.html#variant.Preedit
ImeSetCompose {
/// The current preedit string. An empty string clears the composition.
value: SmolStr,
/// Selection within the preedit text, or `None` to hide the cursor.
cursor: Option<PreeditCursor>,
},
/// Accept IME composition and insert `value` at the cursor.
///
/// Clears any in-progress preedit first, then inserts the committed string,
/// respecting [`EditableText::max_characters`](crate::EditableText::max_characters)
/// and the `char_filter`.
///
/// Typically generated in response to [`bevy_window::Ime::Commit`] events.
///
/// [`bevy_window::Ime::Commit`]: https://docs.rs/bevy/latest/bevy/prelude/enum.Ime.html#variant.Commit
ImeCommit {
/// The committed text to insert at the cursor.
value: SmolStr,
},
/// Scroll vertically by the given number of visual lines, increasing downwards.
///
/// Fractional values scroll by the corresponding fraction of a visual line.
ScrollByLines(f32),
/// Scroll the minimum amount such that the given point is in view.
ScrollTo(Vec2),
/// Scroll by the given displacement
ScrollBy(Vec2),
}
impl TextEdit {
/// Convenience constructor for a [`TextEdit::ImeSetCompose`] that clears the preedit.
pub fn clear_ime_compose() -> Self {
Self::ImeSetCompose {
value: SmolStr::new_inline(""),
cursor: None,
}
}
/// Returns whether this actually affects the text, or is just cursor movement
pub fn is_destructive(&self) -> bool {
match self {
// Destructive actions
TextEdit::Cut
| TextEdit::Paste
| TextEdit::Insert(_)
| TextEdit::Backspace
| TextEdit::BackspaceWord
| TextEdit::Delete
| TextEdit::DeleteWord
| TextEdit::ImeSetCompose {
value: _,
cursor: _,
}
| TextEdit::ImeCommit { value: _ } => true,
// Nondestructive actions
TextEdit::Copy
| TextEdit::Left(_)
| TextEdit::Right(_)
| TextEdit::WordLeft(_)
| TextEdit::WordRight(_)
| TextEdit::Up(_)
| TextEdit::Down(_)
| TextEdit::TextStart(_)
| TextEdit::TextEnd(_)
| TextEdit::HardLineStart(_)
| TextEdit::HardLineEnd(_)
| TextEdit::LineStart(_)
| TextEdit::LineEnd(_)
| TextEdit::CollapseSelection
| TextEdit::SelectAll
| TextEdit::SelectAllIfCollapsed
| TextEdit::MoveToPoint(_)
| TextEdit::SelectWordAtPoint(_)
| TextEdit::SelectLineAtPoint(_)
| TextEdit::SelectedHardLineAtPoint(_)
| TextEdit::ExtendSelectionToPoint(_)
| TextEdit::ShiftClickExtension(_)
| TextEdit::ScrollByLines(_)
| TextEdit::ScrollTo(_)
| TextEdit::ScrollBy(_) => false,
}
}
/// Apply the [`TextEdit`] to the text editor driver and viewport.
///
/// Note that some edits, such as [`TextEdit::Paste`], may need to be deferred across frames due to asynchronous clipboard I/O.
/// For proper handling of deferred edits, use [`EditableText::apply_pending_edits`](super::EditableText::apply_pending_edits) instead,
/// which manages the queuing and application of edits by storing them in the [`EditableText`](super::EditableText) component.
pub fn apply<'a>(
self,
driver: &'a mut PlainEditorDriver<TextBrush>,
viewport: &mut TextViewport,
cursor_margin: Vec2,
clipboard: &mut bevy_clipboard::Clipboard,
max_characters: Option<usize>,
char_filter: impl Fn(char) -> bool,
) {
match self {
TextEdit::Copy => {
if let Some(text) = driver.editor.selected_text()
&& let Err(e) = clipboard.set_text(text)
{
bevy_log::warn!("Failed to write selection to clipboard: {e:?}");
}
}
TextEdit::Cut => {
if let Some(text) = driver.editor.selected_text() {
match clipboard.set_text(text) {
Ok(()) => driver.delete(),
Err(e) => bevy_log::warn!("Failed to write selection to clipboard: {e:?}"),
}
}
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::Paste => {
// It's nice to be able to provide apply as a public method, but Paste is a little buggy.
// We'll try our best since that works on native, but we should warn users away from doing so.
bevy_log::warn_once!("Directly applying a Paste edit is not recommended, as it cannot defer asynchronous clipboard reads.
For proper handling of async clipboard operations, use `EditableText::apply_pending_edits` instead.");
let mut read = clipboard.fetch_text();
poll_and_apply_paste(&mut read, driver, max_characters, char_filter);
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::Insert(text) => {
let _ = insert_filtered(driver, text.as_str(), max_characters, char_filter);
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::Backspace => {
driver.backdelete();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::BackspaceWord => {
driver.backdelete_word();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::Delete => {
driver.delete();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::DeleteWord => {
driver.delete_word();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::Left(false) => {
driver.move_left();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::Right(false) => {
driver.move_right();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::WordLeft(false) => {
driver.move_word_left();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::WordRight(false) => {
driver.move_word_right();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::Up(false) => {
driver.move_up();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::Down(false) => {
driver.move_down();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::TextStart(false) => {
driver.move_to_text_start();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::TextEnd(false) => {
driver.move_to_text_end();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::HardLineStart(false) => {
driver.move_to_hard_line_start();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::HardLineEnd(false) => {
driver.move_to_hard_line_end();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::LineStart(false) => {
driver.move_to_line_start();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::LineEnd(false) => {
driver.move_to_line_end();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::Left(true) => {
driver.select_left();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::Right(true) => {
driver.select_right();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::WordLeft(true) => {
driver.select_word_left();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::WordRight(true) => {
driver.select_word_right();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::Up(true) => {
driver.select_up();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::Down(true) => {
driver.select_down();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::TextStart(true) => {
driver.select_to_text_start();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::TextEnd(true) => {
driver.select_to_text_end();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::HardLineStart(true) => {
driver.select_to_hard_line_start();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::HardLineEnd(true) => {
driver.select_to_hard_line_end();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::LineStart(true) => {
driver.select_to_line_start();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::LineEnd(true) => {
driver.select_to_line_end();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::CollapseSelection => {
driver.collapse_selection();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::SelectAll => {
driver.select_all();
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::SelectAllIfCollapsed => {
if driver.editor.raw_selection().is_collapsed() {
driver.select_all();
}
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::MoveToPoint(point) => driver.move_to_point(point.x, point.y),
TextEdit::SelectWordAtPoint(point) => driver.select_word_at_point(point.x, point.y),
TextEdit::SelectLineAtPoint(point) => driver.select_line_at_point(point.x, point.y),
TextEdit::SelectedHardLineAtPoint(point) => {
driver.select_hard_line_at_point(point.x, point.y);
}
TextEdit::ExtendSelectionToPoint(point) => {
driver.extend_selection_to_point(point.x, point.y);
}
TextEdit::ShiftClickExtension(point) => driver.shift_click_extension(point.x, point.y),
TextEdit::ImeSetCompose { value, cursor } => {
if value.is_empty() {
driver.clear_compose();
} else {
let cursor = cursor.map(|c| (c.anchor, c.focus));
driver.set_compose(&value, cursor);
}
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::ImeCommit { value: text } => {
driver.clear_compose();
if text.chars().all(&char_filter)
&& max_characters.is_none_or(|max| {
driver.editor.text().chars().count() + text.chars().count() <= max
})
{
driver.insert_or_replace_selection(text.as_str());
}
reveal_cursor(driver, viewport, cursor_margin);
}
TextEdit::ScrollByLines(n) => {
driver.refresh_layout();
let content_size = scroll_content_size(driver);
let layout = driver.layout();
viewport.scroll_by_lines(
n,
content_size,
layout.lines().map(|line| TextLineYBounds::from_line(&line)),
);
}
TextEdit::ScrollTo(target) => {
driver.refresh_layout();
viewport.scroll_to(target, scroll_content_size(driver));
}
TextEdit::ScrollBy(displacement) => {
driver.refresh_layout();
viewport.scroll_by(displacement, scroll_content_size(driver));
}
}
}
}
fn scroll_content_size(driver: &mut PlainEditorDriver<'_, TextBrush>) -> Vec2 {
let cursor_max = cursor_reveal_rect(driver).map_or(Vec2::ZERO, |cursor| cursor.max);
let layout = driver.layout();
Vec2::new(layout.full_width(), layout.height()).max(cursor_max)
}
/// Returns the caret rectangle extended by one `0` advance.
pub fn cursor_reveal_rect(driver: &mut PlainEditorDriver<'_, TextBrush>) -> Option<Rect> {
let cluster = driver
.editor
.raw_selection()
.focus()
.logical_clusters(driver.layout())
.into_iter()
.rev()
.flatten()
.next();
let cursor_advance = cluster
.map(|cluster| {
let run = cluster.run();
let font = run.font();
FontRef::from_index(font.data.as_ref(), font.index as usize)
.and_then(|font_ref| {
NonZeroU16::new(font_ref.charmap().map('0')).map(|glyph_id| {
font_ref
.glyph_metrics(run.normalized_coords())
.scale(run.font_size())
.advance_width(glyph_id.get())
})
})
.unwrap_or(0.6 * run.font_size())
})
.unwrap_or_else(|| {
0.6 * driver.editor.get_scale()
* driver
.editor
.get_styles()
.inner()
.values()
.find_map(|property| match property {
StyleProperty::FontSize(font_size) => Some(*font_size),
_ => None,
})
.unwrap_or_default()
});
driver.editor.cursor_geometry(cursor_advance).map(|cursor| {
Rect::new(
cursor.x0 as f32,
cursor.y0 as f32,
cursor.x1 as f32,
cursor.y1 as f32,
)
})
}
pub(crate) fn reveal_cursor(
driver: &mut PlainEditorDriver<'_, TextBrush>,
viewport: &mut TextViewport,
cursor_margin: Vec2,
) {
driver.refresh_layout();
let Some(cursor) = cursor_reveal_rect(driver) else {
return;
};
let layout = driver.layout();
viewport.reveal_caret(
cursor,
Vec2::new(layout.full_width(), layout.height()),
cursor_margin,
layout.lines().map(|line| TextLineYBounds::from_line(&line)),
);
}
/// Reason an [`insert_filtered`] call was rejected.
///
/// The two branches matter to callers (paste warns on [`CharFilter`](Self::CharFilter) but
/// not on [`MaxLength`](Self::MaxLength)), so a bool return wouldn't suffice.
enum InsertRejection {
/// At least one character failed the user-supplied filter.
CharFilter,
/// The insertion would exceed `max_characters`.
MaxLength,
}
/// Insert (or replace the current selection with) `text`, subject to the char filter and
/// `max_characters`.
///
/// Shared by [`TextEdit::Insert`] and [`TextEdit::Paste`] paths to ensure consistent behavior.
fn insert_filtered(
driver: &mut PlainEditorDriver<TextBrush>,
text: &str,
max_characters: Option<usize>,
char_filter: impl Fn(char) -> bool,
) -> Result<(), InsertRejection> {
if !text.chars().all(char_filter) {
return Err(InsertRejection::CharFilter);
}
if let Some(max) = max_characters {
let select_len = driver
.editor
.selected_text()
.map(str::chars)
.map(Iterator::count)
.unwrap_or(0);
if max < driver.editor.text().chars().count() - select_len + text.chars().count() {
return Err(InsertRejection::MaxLength);
}
}
driver.insert_or_replace_selection(text);
Ok(())
}
/// Polls a clipboard read and, if ready, applies the resulting text as a paste.
///
/// Returns `true` when the read has resolved (applied, filter-rejected, or errored)
/// and the caller should move on.
/// Returns `false` when the read is still pending
/// and the caller should hold onto the [`ClipboardRead`] to poll again on a later frame.
pub(crate) fn poll_and_apply_paste(
read: &mut ClipboardRead,
driver: &mut PlainEditorDriver<TextBrush>,
max_characters: Option<usize>,
char_filter: impl Fn(char) -> bool,
) -> bool {
match read.poll_result() {
Some(Ok(text)) => {
if matches!(
insert_filtered(driver, &text, max_characters, char_filter),
Err(InsertRejection::CharFilter)
) {
bevy_log::debug!(
"Paste rejected: clipboard contents contained characters not allowed by the char filter."
);
}
true
}
Some(Err(e)) => {
bevy_log::warn!("Failed to read clipboard for paste: {e:?}");
true
}
None => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::borrow::Cow;
use parley::{FontContext, FontFamilyName, LayoutContext, PlainEditor};
fn fira_mono_editor() -> (
PlainEditor<TextBrush>,
FontContext,
LayoutContext<TextBrush>,
) {
let mut editor = PlainEditor::<TextBrush>::new(20.);
editor
.edit_styles()
.insert(FontFamilyName::Named(Cow::Borrowed("Fira Mono")).into());
let mut font_context = FontContext::new();
let font = crate::Font::from_bytes(include_bytes!("FiraMono-subset.ttf").to_vec());
font_context.collection.register_fonts(font.data, None);
(editor, font_context, LayoutContext::new())
}
fn apply_edit(
edit: TextEdit,
driver: &mut PlainEditorDriver<'_, TextBrush>,
viewport: &mut TextViewport,
) {
edit.apply(
driver,
viewport,
Vec2::ZERO,
&mut bevy_clipboard::Clipboard::default(),
None,
|_| true,
);
}
#[test]
fn scroll_right_includes_caret_reveal() {
let (mut editor, mut font_context, mut layout_context) = fira_mono_editor();
editor.set_text("A long line of text that can be scrolled horizontally.");
let mut driver = editor.driver(&mut font_context, &mut layout_context);
let mut viewport = TextViewport {
size: Vec2::splat(40.),
..Default::default()
};
apply_edit(TextEdit::TextEnd(false), &mut driver, &mut viewport);
let reveal_offset = viewport.offset.x;
apply_edit(
TextEdit::ScrollBy(-1000. * Vec2::X),
&mut driver,
&mut viewport,
);
assert_eq!(viewport.offset.x, 0.);
apply_edit(
TextEdit::ScrollBy(1000. * Vec2::X),
&mut driver,
&mut viewport,
);
assert_eq!(viewport.offset.x, reveal_offset);
}
#[test]
fn cursor_navigation_reveals_cursor() {
let (mut editor, mut font_context, mut layout_context) = fira_mono_editor();
editor.set_text("A long line of text that can be scrolled horizontally.");
let mut driver = editor.driver(&mut font_context, &mut layout_context);
let mut viewport = TextViewport {
size: Vec2::splat(40.),
..Default::default()
};
apply_edit(
TextEdit::ScrollBy(1000. * Vec2::X),
&mut driver,
&mut viewport,
);
assert!(0. < viewport.offset.x);
apply_edit(TextEdit::TextStart(false), &mut driver, &mut viewport);
assert_eq!(viewport.offset.x, 0.);
}
#[test]
fn reveal_cursor_on_right() {
let (mut editor, mut font_context, mut layout_context) = fira_mono_editor();
editor.set_text("A line of text");
let mut driver = editor.driver(&mut font_context, &mut layout_context);
driver.refresh_layout();
let mut viewport = TextViewport {
size: Vec2::new(driver.layout().full_width(), driver.layout().height()),
..Default::default()
};
apply_edit(TextEdit::TextEnd(false), &mut driver, &mut viewport);
let caret_x = driver.editor.cursor_geometry(0.).unwrap().x0 as f32;
assert!(0. < viewport.offset.x);
assert!(caret_x < viewport.rect().max.x);
viewport.clamp_inside(Vec2::new(
driver.layout().full_width(),
driver.layout().height(),
));
assert_eq!(viewport.offset.x, 0.);
reveal_cursor(&mut driver, &mut viewport, Vec2::ZERO);
assert!(0. < viewport.offset.x);
assert!(caret_x < viewport.rect().max.x);
}
#[test]
fn empty_right_aligned_caret_is_scrolled_inside_view() {
let (mut editor, mut font_context, mut layout_context) = fira_mono_editor();
editor.set_alignment(parley::Alignment::Right);
editor.set_width(Some(100.));
let mut driver = editor.driver(&mut font_context, &mut layout_context);
let mut viewport = TextViewport {
size: Vec2::new(100., 40.),
..Default::default()
};
apply_edit(TextEdit::TextEnd(false), &mut driver, &mut viewport);
let caret_x = driver.editor.cursor_geometry(0.).unwrap().x0 as f32;
assert!(0. < viewport.offset.x);
assert!(caret_x < viewport.rect().max.x);
}
}