bevy_ui_widgets 0.20.0

Unstyled common widgets for Bevy Engine
Documentation
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
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
//! Input handling for [`TextInput`] widgets.
//!
//! This module provides systems to process keyboard input events and apply text edits
//! to focused [`TextInput`] widgets.
//!
//! Note that this module is distinct from the core `bevy_text` crate to avoid pulling in
//! [`bevy_input`] to that crate, which is intended to be usable in non-interactive contexts.

use accesskit::Role;
use bevy_a11y::{AccessibilityNode, AccessibilitySystems};
use bevy_app::{App, Plugin, PostUpdate, PreUpdate};
use bevy_ecs::{prelude::*, reflect::ReflectComponent};
use bevy_input::keyboard::{Key, KeyCode, KeyboardInput};
use bevy_input::{ButtonInput, InputSystems};
use bevy_input_focus::{
    FocusCause, FocusGained, FocusLost, FocusedInput, InputFocus, InputFocusSystems,
};
use bevy_math::Vec2;
use bevy_picking::events::{PointerDrag, PointerPress, PointerRelease, PointerState};
use bevy_picking::pointer::PointerButton;
use bevy_reflect::Reflect;
use bevy_text::{
    scrollable_text_layout_width, EditableText, EditableTextSystems, PreeditCursor, TextEdit,
    TextLayout, TextLayoutInfo, TextReadWriteMode,
};
use bevy_time::{Real, Time};
use bevy_ui::widget::{sync_editable_text_viewports, update_editable_text_layout};
use bevy_ui::{
    widget::TextNodeFlags, ComputedNode, ComputedUiRenderTargetInfo, ContentSize, Node,
    UiGlobalTransform, UiScale,
};
use bevy_ui::{InteractionDisabled, UiSystems};
use bevy_window::{Ime, PrimaryWindow, Window};

const NONE: u8 = 0;
const SUPER: u8 = 1;
const CTRL: u8 = 2;
const ALT: u8 = 4;
const SHIFT: u8 = 8;
const SHIFT_SUPER: u8 = SHIFT | SUPER;
const SHIFT_ALT: u8 = SHIFT | ALT;

/// Whether shortcuts follow the macOS layout (Cmd as the command key, Option
/// for word navigation). Compile-time everywhere except wasm32, where one
/// binary serves every host OS and the browser has to be asked at runtime.
fn mac_host() -> bool {
    #[cfg(not(target_arch = "wasm32"))]
    {
        cfg!(target_os = "macos")
    }
    #[cfg(target_arch = "wasm32")]
    {
        use bevy_platform::sync::OnceLock;
        static MAC: OnceLock<bool> = OnceLock::new();
        *MAC.get_or_init(|| {
            web_sys::window().is_some_and(|w| {
                let nav = w.navigator();
                // platform() is deprecated but universally shipped; fall back
                // to the UA string. "iP" covers iPhone/iPad with keyboards.
                let platform = nav.platform().unwrap_or_default();
                platform.starts_with("Mac")
                    || platform.starts_with("iP")
                    || (platform.is_empty() && nav.user_agent().unwrap_or_default().contains("Mac"))
            })
        })
    }
}

/// Editable text widget.
#[derive(Component, Clone, Default, Reflect)]
#[require(EditableText, AccessibilityNode(accesskit::Node::new(Role::TextInput)))]
#[reflect(Component)]
pub struct TextInput;

/// Autoscroll speed is proportional to the input size
const AUTOSCROLL_BASE_SPEED: f32 = 0.75;
const AUTOSCROLL_MAX_SPEED: f32 = 2.0;
/// Distance from the input to the point along an axis where `AUTOSCROLL_MAX_SPEED` is reached.
/// Proportional to the input size.
const AUTOSCROLL_RAMP_DISTANCE: f32 = 0.5;

/// Returns `true` if the given keyboard input matches an editing-shortcut
/// character (like the `C` in `Ctrl+C`).
///
/// Shortcut matching uses a hybrid strategy, mirroring the behavior of native
/// text fields and browsers:
///
/// - The layout-aware [`logical_key`](KeyboardInput::logical_key) is checked
///   first, so Latin non-QWERTY layouts (AZERTY, Dvorak, ...) keep their
///   conventional shortcut positions.
/// - If the logical key is not an ASCII character (non-Latin layouts such as
///   Cyrillic, Greek, Arabic or Hebrew), the physical
///   [`key_code`](KeyboardInput::key_code) is used as a layout-independent
///   fallback.
///
/// Matching purely on `logical_key` breaks these shortcuts on non-Latin
/// layouts, while matching purely on `key_code` breaks Latin non-QWERTY
/// conventions. See <https://github.com/bevyengine/bevy/issues/24997>.
fn matches_edit_shortcut(input: &KeyboardInput, character: &str, key_code: KeyCode) -> bool {
    match &input.logical_key {
        Key::Character(c) if c.is_ascii() => c.eq_ignore_ascii_case(character),
        Key::Character(_) => input.key_code == key_code,
        _ => false,
    }
}

/// System that processes keyboard input events into text edit actions for focused [`EditableText`] widgets.
///
/// See [`EditableText`] for more details on the standard mapping from keyboard events to text edit actions
/// used by this system.
///
/// Note that this does not immediately apply the edits; they are queued up in [`EditableText::pending_edits`],
/// and then applied later by the [`apply_text_edits`](`bevy_text::apply_text_edits`) system.
fn on_focused_keyboard_input(
    mut keyboard_input: On<FocusedInput<KeyboardInput>>,
    mut query: Query<
        (
            &mut EditableText,
            &TextReadWriteMode,
            Has<InteractionDisabled>,
        ),
        With<TextInput>,
    >,
    mut input_focus: ResMut<InputFocus>,
    keys: Res<ButtonInput<Key>>,
) {
    let Ok((mut editable_text, rwmode, disabled)) = query.get_mut(keyboard_input.focused_entity)
    else {
        return; // Focused entity is not an EditableText, nothing to do
    };

    // While the IME is composing, all keyboard input (including Tab) belongs to the IME.
    // Stopping propagation prevents `handle_tab_navigation` (registered on the window,
    // which sits further up the `FocusedInput` bubble chain) from responding to Tab;
    // inadvertently changing focus while the IME is active.
    if editable_text.is_composing() {
        keyboard_input.propagate(false);
        return;
    }

    let allow_newlines = editable_text.allow_newlines;

    // Bitflags representing states of modifier keys.
    // On macOS Option is mapped to `Key::Alt` by `bevy_input`.
    let mod_flags = (SUPER * u8::from(keys.pressed(Key::Super)))
        | (CTRL * u8::from(keys.pressed(Key::Control)))
        | (ALT * u8::from(keys.pressed(Key::Alt)))
        | (SHIFT * u8::from(keys.pressed(Key::Shift)));

    let shift_pressed = (mod_flags & SHIFT) != 0;

    // Runtime values rather than consts (and guards rather than patterns
    // below): on wasm the layout depends on the HOST os, not the compile
    // target. See `mac_host`.
    let mac = mac_host();
    let command = if mac { SUPER } else { CTRL };
    // Modifier key for word-level navigation and selection. Alt on macOS, Control otherwise.
    let word = if mac { ALT } else { CTRL };
    let shift_command = SHIFT | command;
    let shift_word = SHIFT | word;

    let mut should_propagate = true;

    let mut queue_edit = |edit: TextEdit| {
        if (*rwmode == TextReadWriteMode::Editable
            || (!edit.is_destructive() && (!disabled || *rwmode == TextReadWriteMode::ReadOnly)))
            && keyboard_input.input.state.is_pressed()
        {
            editable_text.queue_edit(edit);
        }
        should_propagate = false;
    };

    match (mod_flags, &keyboard_input.input.logical_key) {
        (NONE, Key::Copy) => queue_edit(TextEdit::Copy),
        (NONE, Key::Cut) => queue_edit(TextEdit::Cut),
        (NONE, Key::Paste) => queue_edit(TextEdit::Paste),
        (m, Key::Character(_))
            if m == command && matches_edit_shortcut(&keyboard_input.input, "a", KeyCode::KeyA) =>
        {
            queue_edit(TextEdit::SelectAll);
        }
        (m, Key::Character(_))
            if m == command && matches_edit_shortcut(&keyboard_input.input, "c", KeyCode::KeyC) =>
        {
            queue_edit(TextEdit::Copy);
        }
        (m, Key::Character(_))
            if m == command && matches_edit_shortcut(&keyboard_input.input, "x", KeyCode::KeyX) =>
        {
            queue_edit(TextEdit::Cut);
        }
        (m, Key::Character(_))
            if m == command && matches_edit_shortcut(&keyboard_input.input, "v", KeyCode::KeyV) =>
        {
            queue_edit(TextEdit::Paste);
        }
        (SHIFT, Key::Delete) if !mac => queue_edit(TextEdit::Cut),
        (m, Key::Backspace) if m == word => queue_edit(TextEdit::BackspaceWord),
        (m, Key::Delete) if m == word => queue_edit(TextEdit::DeleteWord),
        (SUPER | SHIFT_SUPER, Key::ArrowLeft) if mac => {
            queue_edit(TextEdit::HardLineStart(shift_pressed));
        }
        (SUPER | SHIFT_SUPER, Key::ArrowRight) if mac => {
            queue_edit(TextEdit::HardLineEnd(shift_pressed));
        }
        (ALT | SHIFT_ALT, Key::Home) if !mac => queue_edit(TextEdit::HardLineStart(shift_pressed)),
        (ALT | SHIFT_ALT, Key::End) if !mac => queue_edit(TextEdit::HardLineEnd(shift_pressed)),
        (m, Key::ArrowLeft) if m == word || m == shift_word => {
            queue_edit(TextEdit::WordLeft(shift_pressed));
        }
        (m, Key::ArrowRight) if m == word || m == shift_word => {
            queue_edit(TextEdit::WordRight(shift_pressed));
        }
        (NONE | SHIFT, Key::ArrowLeft) => queue_edit(TextEdit::Left(shift_pressed)),
        (NONE | SHIFT, Key::ArrowRight) => queue_edit(TextEdit::Right(shift_pressed)),
        (m, Key::ArrowUp) if mac && (m == command || m == shift_command) => {
            queue_edit(TextEdit::TextStart(shift_pressed));
        }
        (m, Key::ArrowDown) if mac && (m == command || m == shift_command) => {
            queue_edit(TextEdit::TextEnd(shift_pressed));
        }
        (NONE | SHIFT, Key::ArrowUp) => queue_edit(TextEdit::Up(shift_pressed)),
        (NONE | SHIFT, Key::ArrowDown) => queue_edit(TextEdit::Down(shift_pressed)),
        (CTRL, Key::ArrowUp) if !mac => queue_edit(TextEdit::ScrollByLines(-1.0)),
        (CTRL, Key::ArrowDown) if !mac => queue_edit(TextEdit::ScrollByLines(1.0)),
        (m, Key::Home) if m == command || m == shift_command => {
            queue_edit(TextEdit::TextStart(shift_pressed));
        }
        (m, Key::End) if m == command || m == shift_command => {
            queue_edit(TextEdit::TextEnd(shift_pressed));
        }
        (NONE | SHIFT, Key::Home) => queue_edit(TextEdit::LineStart(shift_pressed)),
        (NONE | SHIFT, Key::End) => queue_edit(TextEdit::LineEnd(shift_pressed)),
        (NONE | SHIFT, Key::Backspace) => queue_edit(TextEdit::Backspace),
        (NONE, Key::Delete) => queue_edit(TextEdit::Delete),
        (NONE, Key::Escape) => {
            queue_edit(TextEdit::CollapseSelection);
            if keyboard_input.input.state.is_pressed() {
                input_focus.clear();
            }
            // Escape belongs to the surrounding context (close a dialog, cancel,
            // back out) -- collapse and blur, but do NOT consume: the same press
            // keeps bubbling. `InputFocus` is already cleared by the time ancestors
            // see it; check `original_event_target()` to tell it came from a field.
            should_propagate = true;
        }
        (NONE | SHIFT, Key::Character(_) | Key::Unidentified(_)) | (NONE, Key::Space) => {
            if let Some(text) = &keyboard_input.input.text
                && !text.is_empty()
            {
                queue_edit(TextEdit::Insert(text.clone()));
            }
        }
        (NONE, Key::Enter) if allow_newlines => {
            queue_edit(TextEdit::Insert("\n".into()));
        }
        _ => {
            // Ignore and propagate to allow for tab navigation and submit actions.
        }
    }

    keyboard_input.propagate(should_propagate);
}

/// System that processes pointer press events into text edit actions for [`EditableText`] widgets.
///
/// Note that this does not immediately apply the edits; they are queued up in [`EditableText::pending_edits`],
/// and then applied later by the [`apply_text_edits`](`bevy_text::apply_text_edits`) system.
fn on_pointer_press(
    mut press: On<PointerPress>,
    mut text_input_query: Query<
        (
            &mut EditableText,
            &TextReadWriteMode,
            &ComputedNode,
            &ComputedUiRenderTargetInfo,
            &UiGlobalTransform,
        ),
        With<TextInput>,
    >,
    keys: Res<ButtonInput<Key>>,
    ui_scale: Res<UiScale>,
) {
    if press.button != PointerButton::Primary {
        return;
    }

    let Ok((mut editable_text, rwmode, node, target, transform)) =
        text_input_query.get_mut(press.entity)
    else {
        // The press landed on something that isn't an `EditableText`. Clicking away to blur a
        // focused text input is handled by `PointerFocusPlugin` (in `bevy_input_focus`), which
        // triggers a bubbling `AcquireFocus` that clears focus at the window, so there is nothing
        // to do here.
        return;
    };

    if *rwmode == TextReadWriteMode::Static {
        return;
    }

    press.propagate(false);

    if editable_text.is_composing() {
        // The IME is active; all input needs to be routed there, including pointer presses.
        return;
    }

    let Some(local_pos) = transform.try_inverse().and_then(|inverse| {
        let local_pos =
            inverse.transform_point2(press.pointer.position * target.scale_factor() / ui_scale.0);
        node.content_box()
            .contains(local_pos)
            .then(|| local_pos - node.content_box().min + editable_text.viewport.offset)
    }) else {
        return;
    };

    match press.count {
        1 => {
            editable_text
                .pending_edits
                .push(if keys.pressed(Key::Shift) {
                    TextEdit::ShiftClickExtension
                } else {
                    TextEdit::MoveToPoint
                }(local_pos));
        }
        2 => editable_text.queue_edit(TextEdit::SelectWordAtPoint(local_pos)),
        _ => editable_text.queue_edit(TextEdit::SelectAll),
    }
}

/// System that processes pointer drag events into text edit actions for [`EditableText`] widgets.
///
/// Note that this does not immediately apply the edits; they are queued up in [`EditableText::pending_edits`],
/// and then applied later by the [`apply_text_edits`](`bevy_text::apply_text_edits`) system.
fn on_pointer_drag(
    mut drag: On<PointerDrag>,
    mut text_input_query: Query<
        (
            &mut EditableText,
            &TextReadWriteMode,
            &ComputedNode,
            &ComputedUiRenderTargetInfo,
            &UiGlobalTransform,
        ),
        With<TextInput>,
    >,
    ui_scale: Res<UiScale>,
) {
    if drag.button != PointerButton::Primary {
        return;
    }

    let Ok((mut editable_text, rwmode, node, target, transform)) =
        text_input_query.get_mut(drag.entity)
    else {
        return;
    };

    if *rwmode == TextReadWriteMode::Static {
        return;
    }

    drag.propagate(false);

    if editable_text.is_composing() {
        // The IME is active; all input needs to be routed there, including pointer drags.
        return;
    }

    let Some(local_point) = transform.try_inverse().map(|inverse| {
        inverse.transform_point2(drag.pointer.position * target.scale_factor() / ui_scale.0)
    }) else {
        return;
    };

    let clamped_local_point = node.content_box().clamp_point(local_point);
    let current_offset = editable_text.viewport.offset;
    editable_text.queue_edit(TextEdit::ExtendSelectionToPoint(
        clamped_local_point - node.content_box().min + current_offset,
    ));
}

pub(crate) fn text_input_autoscroll_system(
    time: Res<Time<Real>>,
    pointer_state: Res<PointerState>,
    input_focus: Res<InputFocus>,
    mut text_input_query: Query<(
        &mut EditableText,
        &ComputedNode,
        &ComputedUiRenderTargetInfo,
        &UiGlobalTransform,
        &TextLayoutInfo,
        &TextLayout,
    )>,
    ui_scale: Res<UiScale>,
) {
    let Some(entity) = input_focus.get() else {
        return;
    };
    let Some(pointer_position) = pointer_state
        .pointer_buttons
        .iter()
        .filter(|((_, button), ..)| *button == PointerButton::Primary)
        .find_map(|(_, state)| state.dragging.get(&entity).map(|drag| drag.latest_pos))
    else {
        return;
    };

    let Ok((mut editable_text, node, target, transform, layout_info, text_layout)) =
        text_input_query.get_mut(entity)
    else {
        return;
    };

    if editable_text.is_composing()
        || editable_text
            .pending_edits
            .iter()
            .any(|edit| matches!(edit, TextEdit::ImeSetCompose { value, .. } if !value.is_empty()))
    {
        return;
    }

    if editable_text.viewport.size.cmple(Vec2::ZERO).any() {
        return;
    }

    let Some(local_point) = transform.try_inverse().map(|inverse| {
        inverse.transform_point2(pointer_position * target.scale_factor() / ui_scale.0)
    }) else {
        return;
    };

    let clamped_local_point = node.content_box().clamp_point(local_point);

    // Signed per-axis distance of the pointer from the text viewport
    let signed_distance = local_point - clamped_local_point;
    if signed_distance == Vec2::ZERO {
        return;
    }

    // Distance to scroll on each axis
    let scroll_delta = Vec2::new(
        autoscroll_axis(
            signed_distance.x,
            editable_text.viewport.size.x,
            time.delta_secs(),
        ),
        autoscroll_axis(
            signed_distance.y,
            editable_text.viewport.size.y,
            time.delta_secs(),
        ),
    );

    // Calculate the full text layout size, including space for the cursor.
    let full_layout_size = Vec2::new(
        scrollable_text_layout_width(
            text_layout.linebreak,
            layout_info.size.x,
            editable_text.viewport.size.x,
            layout_info.cursor.map(|(_, rect)| rect),
        ),
        layout_info.size.y,
    );

    let clamped_offset = (editable_text.viewport.offset + scroll_delta).clamp(
        Vec2::ZERO,
        (full_layout_size - editable_text.viewport.size).max(Vec2::ZERO),
    );
    let clamped_scroll_delta = clamped_offset - editable_text.viewport.offset;

    if clamped_scroll_delta == Vec2::ZERO {
        return;
    }

    editable_text.queue_edit(TextEdit::ScrollBy(clamped_scroll_delta));

    // Extend the selection using the post-scroll viewport offset.
    editable_text.queue_edit(TextEdit::ExtendSelectionToPoint(
        clamped_local_point - node.content_box().min + clamped_offset,
    ));
}

fn autoscroll_axis(overflow: f32, view_size: f32, time_delta: f32) -> f32 {
    if overflow == 0. || view_size == 0. {
        return 0.;
    }
    let ramp_distance = (overflow.abs() / (view_size * AUTOSCROLL_RAMP_DISTANCE)).min(1.0);
    let speed =
        AUTOSCROLL_BASE_SPEED + ramp_distance * (AUTOSCROLL_MAX_SPEED - AUTOSCROLL_BASE_SPEED);
    overflow.signum() * view_size * speed * time_delta
}

/// System that processes [`Ime`] events into [`TextEdit`] actions for the focused [`EditableText`] widget.
///
/// Preedit text (in-progress IME composition) is excluded from [`EditableText::value`].
/// On commit, the preedit is cleared and the committed string is inserted.
///
/// Note that this does not immediately apply the edits; they are queued up in [`EditableText::pending_edits`],
/// and then applied later by the [`apply_text_edits`](`bevy_text::apply_text_edits`) system.
fn on_ime_input(
    mut ime_reader: MessageReader<Ime>,
    input_focus: Res<InputFocus>,
    mut editable_text_query: Query<
        (
            &mut EditableText,
            &TextReadWriteMode,
            Has<InteractionDisabled>,
        ),
        With<TextInput>,
    >,
) {
    let Some(focused_entity) = input_focus.get() else {
        // No focused entity, nothing to do.
        // Still need to drain the reader to prevent stale events on next focus.
        ime_reader.read().for_each(drop);
        return;
    };

    let Ok((mut editable_text, rwmode, disabled)) = editable_text_query.get_mut(focused_entity)
    else {
        // Focused entity is not an EditableText, nothing to do.
        // Still need to drain the reader to prevent stale events on next focus.
        ime_reader.read().for_each(drop);
        return;
    };

    if *rwmode != TextReadWriteMode::Editable || disabled {
        // Still need to drain the reader to prevent stale events on next focus.
        ime_reader.read().for_each(drop);
        return;
    }

    for ime in ime_reader.read() {
        match ime {
            Ime::Preedit { value, cursor, .. } => {
                editable_text.queue_edit(TextEdit::ImeSetCompose {
                    value: value.as_str().into(),
                    cursor: cursor.map(|(anchor, focus)| PreeditCursor { anchor, focus }),
                });
            }
            Ime::Commit { value, .. } => {
                editable_text.queue_edit(TextEdit::ImeCommit {
                    value: value.as_str().into(),
                });
            }
            Ime::Disabled { .. } => {
                // IME was force-disabled; cancel any in-progress composition.
                editable_text.queue_edit(TextEdit::clear_ime_compose());
            }
            Ime::Enabled { .. } => {
                // Defensively clear any stale compose state before a fresh composition starts.
                editable_text.queue_edit(TextEdit::clear_ime_compose());
            }
        }
    }
}

/// System that updates the IME candidate window position to track the text cursor.
///
/// Reads the cursor bounding area from parley's layout and transforms it to screen coordinates
/// so the OS places the IME candidate popup near the active cursor.
///
/// The position reported to the OS is the bottom-left of the cursor/preedit area so the candidate box appears below the
/// composing text rather than overlapping it.
fn update_ime_position(
    input_focus: Res<InputFocus>,
    editable_text_query: Query<
        (
            &EditableText,
            &TextReadWriteMode,
            &ComputedNode,
            &UiGlobalTransform,
            &ComputedUiRenderTargetInfo,
            Has<InteractionDisabled>,
        ),
        With<TextInput>,
    >,
    // TODO: support multiple windows and track which one has focus
    mut windows: Query<&mut Window, With<PrimaryWindow>>,
    ui_scale: Res<UiScale>,
) {
    let Some(focused) = input_focus.get() else {
        return;
    };

    let Ok((editable_text, rwmode, node, transform, target, disabled)) =
        editable_text_query.get(focused)
    else {
        return;
    };

    if *rwmode != TextReadWriteMode::Editable || disabled {
        return;
    }

    let Ok(mut window) = windows.single_mut() else {
        return;
    };

    let area = editable_text.editor.ime_cursor_area();
    // area is in parley text-layout space (origin at top-left of the text layout).
    // Use `y1` (bottom edge) so the OS-drawn candidate box sits below the current line
    // rather than overlapping it.
    let parley_local = Vec2::new(area.x0 as f32, area.y1 as f32);
    let ui_local = parley_local + node.content_box().min - editable_text.viewport.offset;
    window.ime_position =
        transform.affine().transform_point2(ui_local) * ui_scale.0 / target.scale_factor();
}

/// System that enables or disables IME on the primary window based on whether the focused entity
/// is an editable text field.
///
/// IME is enabled when an editable `EditableText` gains focus and disabled when focus moves
/// elsewhere. The IME state is also re-evaluated whenever the focused entity's read/write mode
/// changes. Because [`TextReadWriteMode`] is an optional component, such a change can happen when the
/// component is overwritten, inserted, or removed; removal reverts the effective mode to the
/// [`Editable`](TextReadWriteMode::Editable) default and is detected via [`RemovedComponents`].
fn listen_for_ime_input_when_text_input_focused(
    input_focus: Res<InputFocus>,
    mut editable_text_query: Query<(&mut EditableText, Ref<TextReadWriteMode>), With<TextInput>>,
    mut windows: Query<&mut Window, With<PrimaryWindow>>,
) {
    let focused_entity = input_focus.get();

    let Ok(mut window) = windows.single_mut() else {
        return;
    };

    // Fetch the focused editable text field (if any).
    let focused = focused_entity.and_then(|e| editable_text_query.get_mut(e).ok());

    let editable_text_focused = focused.is_some_and(|(mut editable_text, rwmode)| {
        let rwmode_changed = rwmode.is_changed();
        if rwmode_changed && *rwmode != TextReadWriteMode::Editable {
            editable_text.queue_edit(TextEdit::clear_ime_compose());
        }
        *rwmode == TextReadWriteMode::Editable
    });

    // The IME should be enabled whenever an EditableText is focused and editable,
    // even if the IME isn't currently composing (i.e. there's no preedit text).
    // The field here is about "should" we accept IME input, not "are we currently" accepting IME input
    window.ime_enabled = editable_text_focused;
}

/// Observer that clears in-progress IME composition and
/// collapses the current selection to a caret when an [`EditableText`] loses focus .
///
/// We need to clear the composition on focus loss because IME composition state is not automatically tied to widget focus;
/// the IME remains active until explicitly disabled,
/// even if the focused widget changes to another `EditableText` or to a non-`EditableText`.
///
/// Without this, switching focus between two text inputs leaves stale preedit state on the
/// previous input.
/// The IME stays enabled because both entities are [`EditableText`],
/// and no [`Ime::Disabled`] event is ever fired to trigger the cleanup in [`on_ime_input`].
///
/// A [`TextEdit::CollapseSelection`] is also fired to collapse any active highlighted text
/// selection back to the caret cursor position, preventing text styles from getting stuck in a
/// focused color state.
fn on_focus_lost(
    trigger: On<FocusLost>,
    mut editable_text_query: Query<&mut EditableText, With<TextInput>>,
) {
    if let Ok(mut editable_text) = editable_text_query.get_mut(trigger.entity) {
        editable_text.queue_edit(TextEdit::clear_ime_compose());
        editable_text.queue_edit(TextEdit::CollapseSelection);
    }
}

/// Marker component for [`EditableText`] widgets that should select all text on focus.
///
/// If a pointer press is what caused the focus, the select all is deferred until
/// pointer release and is only applied if there is no other selection by then.
/// For example, if pointer dragging caused a selection to be made, we don't want
/// to replace it with a select all.
#[derive(Component, Clone, Default, Reflect)]
#[reflect(Component)]
pub struct SelectAllOnFocus;

/// Resource to track when a pointer press caused focus on an [`EditableText`].
/// A corresponding pointer release will select all text if there is no other selection.
#[derive(Resource, Default, Reflect)]
#[reflect(Resource)]
struct QueuedSelectAll(Option<Entity>);

fn on_focus_select_all(
    focus_gained: On<FocusGained>,
    mut q_text_input: Query<(&mut EditableText, Has<SelectAllOnFocus>), With<TextInput>>,
    mut queued_select_all: ResMut<QueuedSelectAll>,
) {
    let target = focus_gained.event_target();
    if let Ok((mut editable_text, select_all_on_focus)) = q_text_input.get_mut(target) {
        match focus_gained.event().cause {
            FocusCause::Pressed => {
                if select_all_on_focus {
                    queued_select_all.0 = Some(target);
                }
            }
            FocusCause::Auto | FocusCause::Navigated => {
                if select_all_on_focus {
                    editable_text.queue_edit(TextEdit::SelectAll);
                }
            }
        }
    }
}

/// `on_focus_select_all` defers selection until pointer release if the focus was gained
/// by a pointer press. This system applies the queued selection.
///
/// Note, that the `PointerRelease` does not have to happen on the same entity.
fn apply_queued_select_all(
    mut pointer_releases: MessageReader<PointerRelease>,
    mut queued_select_all: ResMut<QueuedSelectAll>,
    mut q_text_input: Query<&mut EditableText, With<SelectAllOnFocus>>,
) {
    let Some(target) = queued_select_all.0 else {
        return;
    };
    for pointer_release in pointer_releases.read() {
        if pointer_release.button == PointerButton::Primary
            && let Ok(mut editable_text) = q_text_input.get_mut(target)
        {
            editable_text.queue_edit(TextEdit::SelectAllIfCollapsed);
            queued_select_all.0 = None;
        }
    }
}

/// System sets for IME-related systems used by [`TextInputPlugin`].
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
pub enum ImeSystems {
    /// Processes [`Ime`] events into [`TextEdit`] actions for the focused [`EditableText`].
    ///
    /// Runs in [`PreUpdate`].
    HandleEvents,
    /// Enables or disables IME on the window based on focus state.
    ///
    /// Runs in [`PreUpdate`].
    ToggleWindowIMEInput,
    /// Updates the IME candidate window position to track the text cursor.
    ///
    /// Runs in [`PostUpdate`].
    UpdatePosition,
}

/// Enables support for the [`EditableText`] widget.
///
/// Contains the systems and observers necessary to update widget state and handle user input.
///
/// This plugin is included in the [`UiWidgetsPlugins`](crate::UiWidgetsPlugins) group, but can also be added individually
/// if only editable text input is needed.
///
/// Note that [`TextEdit`]s are applied during [`PostUpdate`]
/// in the [`EditableTextSystems`] system set.
pub struct TextInputPlugin;

impl Plugin for TextInputPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<QueuedSelectAll>()
            .add_observer(on_focused_keyboard_input)
            .add_observer(on_pointer_drag)
            .add_observer(on_pointer_press)
            .add_observer(on_focus_lost)
            .add_observer(on_focus_select_all)
            .configure_sets(
                PreUpdate,
                (
                    ImeSystems::ToggleWindowIMEInput,
                    ImeSystems::HandleEvents,
                    ImeSystems::UpdatePosition,
                )
                    .chain(),
            )
            .add_systems(
                PreUpdate,
                (
                    on_ime_input.in_set(ImeSystems::HandleEvents),
                    listen_for_ime_input_when_text_input_focused
                        .in_set(ImeSystems::ToggleWindowIMEInput),
                )
                    .after(InputSystems)
                    .after(InputFocusSystems::Dispatch)
                    .after(UiSystems::Focus),
            )
            .add_systems(
                PostUpdate,
                update_ime_position
                    .in_set(ImeSystems::UpdatePosition)
                    .in_set(UiSystems::PostLayout)
                    .before(AccessibilitySystems::Update)
                    .after(update_editable_text_layout)
                    // FocusChangeEvents does not mutate the actual InputFocus;
                    // this is a false positive that can be ignored
                    .ambiguous_with(InputFocusSystems::FocusChangeEvents),
            )
            .add_systems(
                PostUpdate,
                text_input_autoscroll_system
                    .after(sync_editable_text_viewports)
                    .before(EditableTextSystems),
            )
            .add_systems(
                PostUpdate,
                apply_queued_select_all
                    .in_set(UiSystems::PostLayout)
                    .before(update_editable_text_layout),
            );

        // These components cannot be registered in `bevy_text` where `EditableText` is defined,
        // because that would create a circular dependency between `bevy_text` and `bevy_ui`.
        app.register_required_components::<EditableText, Node>()
            .register_required_components::<EditableText, TextNodeFlags>()
            .register_required_components::<EditableText, ContentSize>();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bevy_app::Update;
    use bevy_input::{
        keyboard::{KeyCode, NativeKey, NativeKeyCode},
        ButtonState, InputPlugin,
    };
    use bevy_input_focus::InputDispatchPlugin;
    use bevy_math::Rect;
    use bevy_picking::{events::DragEntry, pointer::PointerId};
    use core::time::Duration;

    #[test]
    fn steam_osk_unidentified_keys_insert_produced_text() {
        let mut app = App::new();
        app.add_plugins((InputPlugin, InputDispatchPlugin))
            .init_resource::<InputFocus>()
            .add_observer(on_focused_keyboard_input);

        let window = app
            .world_mut()
            .spawn((Window::default(), PrimaryWindow))
            .id();
        let editable_text = app
            .world_mut()
            .spawn((EditableText::default(), TextInput))
            .id();
        app.insert_resource(InputFocus::from_entity(editable_text));

        for (text, repeat) in [("J", false), ("#", true)] {
            app.world_mut().write_message(KeyboardInput {
                key_code: KeyCode::Unidentified(NativeKeyCode::Windows(0)),
                logical_key: Key::Unidentified(NativeKey::Windows(231)),
                state: ButtonState::Pressed,
                text: Some(text.into()),
                repeat,
                window,
            });
        }
        app.update();

        assert_eq!(
            app.world()
                .entity(editable_text)
                .get::<EditableText>()
                .unwrap()
                .pending_edits,
            [TextEdit::Insert("J".into()), TextEdit::Insert("#".into())]
        );
    }

    #[test]
    fn autoscroll_speed_is_zero_inside_then_ramps_and_caps() {
        let visible_size = 100.0;

        assert_eq!(autoscroll_axis(0.0, visible_size, 1.0), 0.0);
        assert_eq!(autoscroll_axis(25.0, visible_size, 1.0), 137.5);
        assert_eq!(autoscroll_axis(-25.0, visible_size, 1.0), -137.5);
        assert_eq!(autoscroll_axis(50.0, visible_size, 1.0), 200.0);
        assert_eq!(autoscroll_axis(-100.0, visible_size, 1.0), -200.0);
    }

    #[test]
    fn autoscroll_displacement_is_frame_rate_independent() {
        let overflow = 25.0;
        let view_size = 100.0;

        let one_frame = autoscroll_axis(overflow, view_size, 1.0 / 30.0);
        let two_frames = autoscroll_axis(overflow, view_size, 1.0 / 60.0) * 2.0;

        assert!((one_frame - two_frames).abs() < 1e-5);
    }

    fn autoscroll_app(initial_drag_pos: Vec2) -> (App, Entity) {
        let mut app = App::new();
        app.init_resource::<Time<Real>>()
            .init_resource::<PointerState>()
            .init_resource::<UiScale>()
            .add_systems(Update, text_input_autoscroll_system);

        let mut editable_text = EditableText::default();
        editable_text.viewport.size = Vec2::splat(100.0);
        let entity = app
            .world_mut()
            .spawn((
                editable_text,
                ComputedNode {
                    size: Vec2::splat(100.0),
                    ..Default::default()
                },
                ComputedUiRenderTargetInfo::default(),
                UiGlobalTransform::default(),
                TextLayoutInfo {
                    size: Vec2::splat(300.0),
                    ..Default::default()
                },
            ))
            .id();

        app.insert_resource(InputFocus::from_entity(entity));
        app.world_mut()
            .resource_mut::<PointerState>()
            .get_mut(PointerId::Mouse, PointerButton::Primary)
            .dragging
            .insert(
                entity,
                DragEntry {
                    start_pos: initial_drag_pos,
                    latest_pos: initial_drag_pos,
                },
            );
        app.world_mut()
            .resource_mut::<Time<Real>>()
            .advance_by(Duration::from_secs_f32(1.0 / 60.0));

        (app, entity)
    }

    #[test]
    fn active_drag_autoscrolls_until_reentry() {
        let (mut app, entity) = autoscroll_app(Vec2::new(100.0, 0.0));

        app.update();

        assert_eq!(
            app.world()
                .entity(entity)
                .get::<EditableText>()
                .unwrap()
                .pending_edits
                .len(),
            2
        );

        app.world_mut()
            .entity_mut(entity)
            .get_mut::<EditableText>()
            .unwrap()
            .pending_edits
            .clear();
        app.update();

        assert_eq!(
            app.world()
                .entity(entity)
                .get::<EditableText>()
                .unwrap()
                .pending_edits
                .len(),
            2
        );

        app.world_mut()
            .entity_mut(entity)
            .get_mut::<EditableText>()
            .unwrap()
            .pending_edits
            .clear();
        app.world_mut()
            .resource_mut::<PointerState>()
            .get_mut(PointerId::Mouse, PointerButton::Primary)
            .dragging
            .get_mut(&entity)
            .unwrap()
            .latest_pos = Vec2::ZERO;
        app.update();

        assert!(app
            .world()
            .entity(entity)
            .get::<EditableText>()
            .unwrap()
            .pending_edits
            .is_empty());
    }

    #[test]
    fn autoscroll_into_cursor_space() {
        let (mut app, entity) = autoscroll_app(Vec2::new(100.0, 0.0));
        let mut entity_mut = app.world_mut().entity_mut(entity);
        let mut editable_text = entity_mut.get_mut::<EditableText>().unwrap();
        // set up the viewport with the caret fitting exactly
        editable_text.viewport.reveal_caret(
            Rect::new(295.0, 0.0, 300.0, 20.0),
            Vec2::new(300.0, 300.0),
            Vec2::ZERO,
            core::iter::empty(),
        );
        assert_eq!(editable_text.viewport.offset.x, 200.0);

        // set layout caret outside of viewport
        entity_mut.insert(TextLayout::no_wrap());
        entity_mut.get_mut::<TextLayoutInfo>().unwrap().cursor =
            Some((true, Rect::new(295.0, 0.0, 320.0, 20.0)));

        app.update();

        // expect autoscroll will have queued a scroll right edit
        assert!(matches!(
            app.world().entity(entity).get::<EditableText>().unwrap().pending_edits.first(),
            Some(TextEdit::ScrollBy(delta)) if 0. < delta.x
        ));
    }

    #[test]
    fn autoscroll_stops_after_release_cancellation_or_focus_loss() {
        let (mut app, entity) = autoscroll_app(Vec2::new(100.0, 0.0));
        app.update();

        assert_eq!(
            app.world()
                .entity(entity)
                .get::<EditableText>()
                .unwrap()
                .pending_edits
                .len(),
            2
        );

        app.world_mut()
            .entity_mut(entity)
            .get_mut::<EditableText>()
            .unwrap()
            .pending_edits
            .clear();

        app.insert_resource(InputFocus::default());
        app.update();
        let editable_text = app.world().entity(entity).get::<EditableText>().unwrap();
        assert!(editable_text.pending_edits.is_empty());
    }

    #[test]
    fn ime_composition_stops_autoscroll() {
        let (mut app, entity) = autoscroll_app(Vec2::new(100.0, 0.0));
        app.world_mut()
            .entity_mut(entity)
            .get_mut::<EditableText>()
            .unwrap()
            .queue_edit(TextEdit::ImeSetCompose {
                value: "compose".into(),
                cursor: Some(PreeditCursor {
                    anchor: 0,
                    focus: 7,
                }),
            });

        app.update();

        assert_eq!(
            app.world()
                .entity(entity)
                .get::<EditableText>()
                .unwrap()
                .pending_edits
                .len(),
            1
        );
    }

    fn shortcut_keyboard_input(logical_key: Key, key_code: KeyCode) -> KeyboardInput {
        KeyboardInput {
            key_code,
            logical_key,
            state: ButtonState::Pressed,
            text: None,
            repeat: false,
            window: World::default().spawn_empty().id(),
        }
    }

    #[test]
    fn logical_key_wins_on_latin_layouts() {
        // US QWERTY: logical "c" on the physical `KeyC`.
        let event = shortcut_keyboard_input(Key::Character("c".into()), KeyCode::KeyC);
        assert!(matches_edit_shortcut(&event, "c", KeyCode::KeyC));

        // AZERTY: logical "a" lives on the physical `KeyQ`.
        // The layout convention must win over the physical location.
        let event = shortcut_keyboard_input(Key::Character("a".into()), KeyCode::KeyQ);
        assert!(matches_edit_shortcut(&event, "a", KeyCode::KeyA));
        assert!(!matches_edit_shortcut(&event, "q", KeyCode::KeyQ));
    }

    #[test]
    fn physical_fallback_on_non_latin_layouts() {
        // Cyrillic layout: the key at the `KeyC` position produces Cyrillic "с".
        let event = shortcut_keyboard_input(Key::Character("с".into()), KeyCode::KeyC);
        assert!(matches_edit_shortcut(&event, "c", KeyCode::KeyC));
        // ...but it must not match a different physical key.
        assert!(!matches_edit_shortcut(&event, "a", KeyCode::KeyA));
    }

    #[test]
    fn named_keys_never_match() {
        let event = shortcut_keyboard_input(Key::Enter, KeyCode::Enter);
        assert!(!matches_edit_shortcut(&event, "c", KeyCode::KeyC));
    }

    #[test]
    fn escape_blurs_field_and_propagates_to_window() {
        #[derive(Resource, Default)]
        struct WindowSawEscape(u32);

        let mut app = App::new();
        app.add_plugins((InputPlugin, InputDispatchPlugin))
            .init_resource::<InputFocus>()
            .init_resource::<WindowSawEscape>()
            .add_observer(on_focused_keyboard_input);

        // Manual registration needed to prevent `WindowTraversal` failure during artificial test
        app.world_mut().register_component::<ChildOf>();

        let window = app
            .world_mut()
            .spawn((Window::default(), PrimaryWindow))
            .id();

        let editable_text = app
            .world_mut()
            .spawn((TextInput, EditableText::default()))
            .id();
        app.world_mut().entity_mut(window).observe(
            move |input: On<FocusedInput<KeyboardInput>>, mut saw: ResMut<WindowSawEscape>| {
                if matches!(input.input.logical_key, Key::Escape) && input.input.state.is_pressed()
                {
                    // The target field is rewritten at each hop; the origin
                    // survives on the trigger. The migration guide's guard
                    // depends on exactly this.
                    assert_eq!(input.focused_entity, window);
                    assert_eq!(input.original_event_target(), editable_text);
                    saw.0 += 1;
                }
            },
        );
        app.insert_resource(InputFocus::from_entity(editable_text));

        app.world_mut().write_message(KeyboardInput {
            key_code: KeyCode::Escape,
            logical_key: Key::Escape,
            state: ButtonState::Pressed,
            text: None,
            repeat: false,
            window,
        });
        app.update();

        // The field released focus...
        assert!(app.world().resource::<InputFocus>().get().is_none());
        // ...and the same press reached the window observer.
        assert_eq!(app.world().resource::<WindowSawEscape>().0, 1);
    }
}