egui/widgets/text_edit/
builder.rs

1use std::sync::Arc;
2
3use emath::{Rect, TSTransform};
4use epaint::{
5    text::{cursor::CCursor, Galley, LayoutJob},
6    StrokeKind,
7};
8
9use crate::{
10    epaint,
11    os::OperatingSystem,
12    output::OutputEvent,
13    response, text_selection,
14    text_selection::{
15        text_cursor_state::cursor_rect, visuals::paint_text_selection, CCursorRange, CursorRange,
16    },
17    vec2, Align, Align2, Color32, Context, CursorIcon, Event, EventFilter, FontSelection, Id,
18    ImeEvent, Key, KeyboardShortcut, Margin, Modifiers, NumExt, Response, Sense, Shape, TextBuffer,
19    TextStyle, TextWrapMode, Ui, Vec2, Widget, WidgetInfo, WidgetText, WidgetWithState,
20};
21
22use super::{TextEditOutput, TextEditState};
23
24/// A text region that the user can edit the contents of.
25///
26/// See also [`Ui::text_edit_singleline`] and [`Ui::text_edit_multiline`].
27///
28/// Example:
29///
30/// ```
31/// # egui::__run_test_ui(|ui| {
32/// # let mut my_string = String::new();
33/// let response = ui.add(egui::TextEdit::singleline(&mut my_string));
34/// if response.changed() {
35///     // …
36/// }
37/// if response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
38///     // …
39/// }
40/// # });
41/// ```
42///
43/// To fill an [`Ui`] with a [`TextEdit`] use [`Ui::add_sized`]:
44///
45/// ```
46/// # egui::__run_test_ui(|ui| {
47/// # let mut my_string = String::new();
48/// ui.add_sized(ui.available_size(), egui::TextEdit::multiline(&mut my_string));
49/// # });
50/// ```
51///
52///
53/// You can also use [`TextEdit`] to show text that can be selected, but not edited.
54/// To do so, pass in a `&mut` reference to a `&str`, for instance:
55///
56/// ```
57/// fn selectable_text(ui: &mut egui::Ui, mut text: &str) {
58///     ui.add(egui::TextEdit::multiline(&mut text));
59/// }
60/// ```
61///
62/// ## Advanced usage
63/// See [`TextEdit::show`].
64///
65/// ## Other
66/// The background color of a [`crate::TextEdit`] is [`crate::Visuals::extreme_bg_color`] or can be set with [`crate::TextEdit::background_color`].
67#[must_use = "You should put this widget in a ui with `ui.add(widget);`"]
68pub struct TextEdit<'t> {
69    text: &'t mut dyn TextBuffer,
70    hint_text: WidgetText,
71    hint_text_font: Option<FontSelection>,
72    id: Option<Id>,
73    id_salt: Option<Id>,
74    font_selection: FontSelection,
75    text_color: Option<Color32>,
76    layouter: Option<&'t mut dyn FnMut(&Ui, &str, f32) -> Arc<Galley>>,
77    password: bool,
78    frame: bool,
79    margin: Margin,
80    multiline: bool,
81    interactive: bool,
82    desired_width: Option<f32>,
83    desired_height_rows: usize,
84    event_filter: EventFilter,
85    cursor_at_end: bool,
86    min_size: Vec2,
87    align: Align2,
88    clip_text: bool,
89    char_limit: usize,
90    return_key: Option<KeyboardShortcut>,
91    background_color: Option<Color32>,
92}
93
94impl WidgetWithState for TextEdit<'_> {
95    type State = TextEditState;
96}
97
98impl TextEdit<'_> {
99    pub fn load_state(ctx: &Context, id: Id) -> Option<TextEditState> {
100        TextEditState::load(ctx, id)
101    }
102
103    pub fn store_state(ctx: &Context, id: Id, state: TextEditState) {
104        state.store(ctx, id);
105    }
106}
107
108impl<'t> TextEdit<'t> {
109    /// No newlines (`\n`) allowed. Pressing enter key will result in the [`TextEdit`] losing focus (`response.lost_focus`).
110    pub fn singleline(text: &'t mut dyn TextBuffer) -> Self {
111        Self {
112            desired_height_rows: 1,
113            multiline: false,
114            clip_text: true,
115            ..Self::multiline(text)
116        }
117    }
118
119    /// A [`TextEdit`] for multiple lines. Pressing enter key will create a new line by default (can be changed with [`return_key`](TextEdit::return_key)).
120    pub fn multiline(text: &'t mut dyn TextBuffer) -> Self {
121        Self {
122            text,
123            hint_text: Default::default(),
124            hint_text_font: None,
125            id: None,
126            id_salt: None,
127            font_selection: Default::default(),
128            text_color: None,
129            layouter: None,
130            password: false,
131            frame: true,
132            margin: Margin::symmetric(4, 2),
133            multiline: true,
134            interactive: true,
135            desired_width: None,
136            desired_height_rows: 4,
137            event_filter: EventFilter {
138                // moving the cursor is really important
139                horizontal_arrows: true,
140                vertical_arrows: true,
141                tab: false, // tab is used to change focus, not to insert a tab character
142                ..Default::default()
143            },
144            cursor_at_end: true,
145            min_size: Vec2::ZERO,
146            align: Align2::LEFT_TOP,
147            clip_text: false,
148            char_limit: usize::MAX,
149            return_key: Some(KeyboardShortcut::new(Modifiers::NONE, Key::Enter)),
150            background_color: None,
151        }
152    }
153
154    /// Build a [`TextEdit`] focused on code editing.
155    /// By default it comes with:
156    /// - monospaced font
157    /// - focus lock (tab will insert a tab character instead of moving focus)
158    pub fn code_editor(self) -> Self {
159        self.font(TextStyle::Monospace).lock_focus(true)
160    }
161
162    /// Use if you want to set an explicit [`Id`] for this widget.
163    #[inline]
164    pub fn id(mut self, id: Id) -> Self {
165        self.id = Some(id);
166        self
167    }
168
169    /// A source for the unique [`Id`], e.g. `.id_source("second_text_edit_field")` or `.id_source(loop_index)`.
170    #[inline]
171    pub fn id_source(self, id_salt: impl std::hash::Hash) -> Self {
172        self.id_salt(id_salt)
173    }
174
175    /// A source for the unique [`Id`], e.g. `.id_salt("second_text_edit_field")` or `.id_salt(loop_index)`.
176    #[inline]
177    pub fn id_salt(mut self, id_salt: impl std::hash::Hash) -> Self {
178        self.id_salt = Some(Id::new(id_salt));
179        self
180    }
181
182    /// Show a faint hint text when the text field is empty.
183    ///
184    /// If the hint text needs to be persisted even when the text field has input,
185    /// the following workaround can be used:
186    /// ```
187    /// # egui::__run_test_ui(|ui| {
188    /// # let mut my_string = String::new();
189    /// # use egui::{ Color32, FontId };
190    /// let text_edit = egui::TextEdit::multiline(&mut my_string)
191    ///     .desired_width(f32::INFINITY);
192    /// let output = text_edit.show(ui);
193    /// let painter = ui.painter_at(output.response.rect);
194    /// let text_color = Color32::from_rgba_premultiplied(100, 100, 100, 100);
195    /// let galley = painter.layout(
196    ///     String::from("Enter text"),
197    ///     FontId::default(),
198    ///     text_color,
199    ///     f32::INFINITY
200    /// );
201    /// painter.galley(output.galley_pos, galley, text_color);
202    /// # });
203    /// ```
204    #[inline]
205    pub fn hint_text(mut self, hint_text: impl Into<WidgetText>) -> Self {
206        self.hint_text = hint_text.into();
207        self
208    }
209
210    /// Set the background color of the [`TextEdit`]. The default is [`crate::Visuals::extreme_bg_color`].
211    // TODO(bircni): remove this once #3284 is implemented
212    #[inline]
213    pub fn background_color(mut self, color: Color32) -> Self {
214        self.background_color = Some(color);
215        self
216    }
217
218    /// Set a specific style for the hint text.
219    #[inline]
220    pub fn hint_text_font(mut self, hint_text_font: impl Into<FontSelection>) -> Self {
221        self.hint_text_font = Some(hint_text_font.into());
222        self
223    }
224
225    /// If true, hide the letters from view and prevent copying from the field.
226    #[inline]
227    pub fn password(mut self, password: bool) -> Self {
228        self.password = password;
229        self
230    }
231
232    /// Pick a [`crate::FontId`] or [`TextStyle`].
233    #[inline]
234    pub fn font(mut self, font_selection: impl Into<FontSelection>) -> Self {
235        self.font_selection = font_selection.into();
236        self
237    }
238
239    #[inline]
240    pub fn text_color(mut self, text_color: Color32) -> Self {
241        self.text_color = Some(text_color);
242        self
243    }
244
245    #[inline]
246    pub fn text_color_opt(mut self, text_color: Option<Color32>) -> Self {
247        self.text_color = text_color;
248        self
249    }
250
251    /// Override how text is being shown inside the [`TextEdit`].
252    ///
253    /// This can be used to implement things like syntax highlighting.
254    ///
255    /// This function will be called at least once per frame,
256    /// so it is strongly suggested that you cache the results of any syntax highlighter
257    /// so as not to waste CPU highlighting the same string every frame.
258    ///
259    /// The arguments is the enclosing [`Ui`] (so you can access e.g. [`Ui::fonts`]),
260    /// the text and the wrap width.
261    ///
262    /// ```
263    /// # egui::__run_test_ui(|ui| {
264    /// # let mut my_code = String::new();
265    /// # fn my_memoized_highlighter(s: &str) -> egui::text::LayoutJob { Default::default() }
266    /// let mut layouter = |ui: &egui::Ui, string: &str, wrap_width: f32| {
267    ///     let mut layout_job: egui::text::LayoutJob = my_memoized_highlighter(string);
268    ///     layout_job.wrap.max_width = wrap_width;
269    ///     ui.fonts(|f| f.layout_job(layout_job))
270    /// };
271    /// ui.add(egui::TextEdit::multiline(&mut my_code).layouter(&mut layouter));
272    /// # });
273    /// ```
274    #[inline]
275    pub fn layouter(mut self, layouter: &'t mut dyn FnMut(&Ui, &str, f32) -> Arc<Galley>) -> Self {
276        self.layouter = Some(layouter);
277
278        self
279    }
280
281    /// Default is `true`. If set to `false` then you cannot interact with the text (neither edit or select it).
282    ///
283    /// Consider using [`Ui::add_enabled`] instead to also give the [`TextEdit`] a greyed out look.
284    #[inline]
285    pub fn interactive(mut self, interactive: bool) -> Self {
286        self.interactive = interactive;
287        self
288    }
289
290    /// Default is `true`. If set to `false` there will be no frame showing that this is editable text!
291    #[inline]
292    pub fn frame(mut self, frame: bool) -> Self {
293        self.frame = frame;
294        self
295    }
296
297    /// Set margin of text. Default is `Margin::symmetric(4.0, 2.0)`
298    #[inline]
299    pub fn margin(mut self, margin: impl Into<Margin>) -> Self {
300        self.margin = margin.into();
301        self
302    }
303
304    /// Set to 0.0 to keep as small as possible.
305    /// Set to [`f32::INFINITY`] to take up all available space (i.e. disable automatic word wrap).
306    #[inline]
307    pub fn desired_width(mut self, desired_width: f32) -> Self {
308        self.desired_width = Some(desired_width);
309        self
310    }
311
312    /// Set the number of rows to show by default.
313    /// The default for singleline text is `1`.
314    /// The default for multiline text is `4`.
315    #[inline]
316    pub fn desired_rows(mut self, desired_height_rows: usize) -> Self {
317        self.desired_height_rows = desired_height_rows;
318        self
319    }
320
321    /// When `false` (default), pressing TAB will move focus
322    /// to the next widget.
323    ///
324    /// When `true`, the widget will keep the focus and pressing TAB
325    /// will insert the `'\t'` character.
326    #[inline]
327    pub fn lock_focus(mut self, tab_will_indent: bool) -> Self {
328        self.event_filter.tab = tab_will_indent;
329        self
330    }
331
332    /// When `true` (default), the cursor will initially be placed at the end of the text.
333    ///
334    /// When `false`, the cursor will initially be placed at the beginning of the text.
335    #[inline]
336    pub fn cursor_at_end(mut self, b: bool) -> Self {
337        self.cursor_at_end = b;
338        self
339    }
340
341    /// When `true` (default), overflowing text will be clipped.
342    ///
343    /// When `false`, widget width will expand to make all text visible.
344    ///
345    /// This only works for singleline [`TextEdit`].
346    #[inline]
347    pub fn clip_text(mut self, b: bool) -> Self {
348        // always show everything in multiline
349        if !self.multiline {
350            self.clip_text = b;
351        }
352        self
353    }
354
355    /// Sets the limit for the amount of characters can be entered
356    ///
357    /// This only works for singleline [`TextEdit`]
358    #[inline]
359    pub fn char_limit(mut self, limit: usize) -> Self {
360        self.char_limit = limit;
361        self
362    }
363
364    /// Set the horizontal align of the inner text.
365    #[inline]
366    pub fn horizontal_align(mut self, align: Align) -> Self {
367        self.align.0[0] = align;
368        self
369    }
370
371    /// Set the vertical align of the inner text.
372    #[inline]
373    pub fn vertical_align(mut self, align: Align) -> Self {
374        self.align.0[1] = align;
375        self
376    }
377
378    /// Set the minimum size of the [`TextEdit`].
379    #[inline]
380    pub fn min_size(mut self, min_size: Vec2) -> Self {
381        self.min_size = min_size;
382        self
383    }
384
385    /// Set the return key combination.
386    ///
387    /// This combination will cause a newline on multiline,
388    /// whereas on singleline it will cause the widget to lose focus.
389    ///
390    /// This combination is optional and can be disabled by passing [`None`] into this function.
391    #[inline]
392    pub fn return_key(mut self, return_key: impl Into<Option<KeyboardShortcut>>) -> Self {
393        self.return_key = return_key.into();
394        self
395    }
396}
397
398// ----------------------------------------------------------------------------
399
400impl Widget for TextEdit<'_> {
401    fn ui(self, ui: &mut Ui) -> Response {
402        self.show(ui).response
403    }
404}
405
406impl TextEdit<'_> {
407    /// Show the [`TextEdit`], returning a rich [`TextEditOutput`].
408    ///
409    /// ```
410    /// # egui::__run_test_ui(|ui| {
411    /// # let mut my_string = String::new();
412    /// let output = egui::TextEdit::singleline(&mut my_string).show(ui);
413    /// if let Some(text_cursor_range) = output.cursor_range {
414    ///     use egui::TextBuffer as _;
415    ///     let selected_chars = text_cursor_range.as_sorted_char_range();
416    ///     let selected_text = my_string.char_range(selected_chars);
417    ///     ui.label("Selected text: ");
418    ///     ui.monospace(selected_text);
419    /// }
420    /// # });
421    /// ```
422    pub fn show(self, ui: &mut Ui) -> TextEditOutput {
423        let is_mutable = self.text.is_mutable();
424        let frame = self.frame;
425        let where_to_put_background = ui.painter().add(Shape::Noop);
426        let background_color = self
427            .background_color
428            .unwrap_or(ui.visuals().extreme_bg_color);
429        let margin = self.margin;
430        let mut output = self.show_content(ui);
431
432        // TODO(emilk): return full outer_rect in `TextEditOutput`.
433        // Can't do it now because this fix is ging into a patch release.
434        let outer_rect = output.response.rect;
435        let inner_rect = outer_rect - margin;
436        output.response.rect = inner_rect;
437
438        if frame {
439            let visuals = ui.style().interact(&output.response);
440            let frame_rect = outer_rect.expand(visuals.expansion);
441            let shape = if is_mutable {
442                if output.response.has_focus() {
443                    epaint::RectShape::new(
444                        frame_rect,
445                        visuals.corner_radius,
446                        background_color,
447                        ui.visuals().selection.stroke,
448                        StrokeKind::Inside,
449                    )
450                } else {
451                    epaint::RectShape::new(
452                        frame_rect,
453                        visuals.corner_radius,
454                        background_color,
455                        visuals.bg_stroke, // TODO(emilk): we want to show something here, or a text-edit field doesn't "pop".
456                        StrokeKind::Inside,
457                    )
458                }
459            } else {
460                let visuals = &ui.style().visuals.widgets.inactive;
461                epaint::RectShape::stroke(
462                    frame_rect,
463                    visuals.corner_radius,
464                    visuals.bg_stroke, // TODO(emilk): we want to show something here, or a text-edit field doesn't "pop".
465                    StrokeKind::Inside,
466                )
467            };
468
469            ui.painter().set(where_to_put_background, shape);
470        }
471
472        output
473    }
474
475    fn show_content(self, ui: &mut Ui) -> TextEditOutput {
476        let TextEdit {
477            text,
478            hint_text,
479            hint_text_font,
480            id,
481            id_salt,
482            font_selection,
483            text_color,
484            layouter,
485            password,
486            frame: _,
487            margin,
488            multiline,
489            interactive,
490            desired_width,
491            desired_height_rows,
492            event_filter,
493            cursor_at_end,
494            min_size,
495            align,
496            clip_text,
497            char_limit,
498            return_key,
499            background_color: _,
500        } = self;
501
502        let text_color = text_color
503            .or(ui.visuals().override_text_color)
504            // .unwrap_or_else(|| ui.style().interact(&response).text_color()); // too bright
505            .unwrap_or_else(|| ui.visuals().widgets.inactive.text_color());
506
507        let prev_text = text.as_str().to_owned();
508
509        let font_id = font_selection.resolve(ui.style());
510        let row_height = ui.fonts(|f| f.row_height(&font_id));
511        const MIN_WIDTH: f32 = 24.0; // Never make a [`TextEdit`] more narrow than this.
512        let available_width = (ui.available_width() - margin.sum().x).at_least(MIN_WIDTH);
513        let desired_width = desired_width.unwrap_or_else(|| ui.spacing().text_edit_width);
514        let wrap_width = if ui.layout().horizontal_justify() {
515            available_width
516        } else {
517            desired_width.min(available_width)
518        };
519
520        let font_id_clone = font_id.clone();
521        let mut default_layouter = move |ui: &Ui, text: &str, wrap_width: f32| {
522            let text = mask_if_password(password, text);
523            let layout_job = if multiline {
524                LayoutJob::simple(text, font_id_clone.clone(), text_color, wrap_width)
525            } else {
526                LayoutJob::simple_singleline(text, font_id_clone.clone(), text_color)
527            };
528            ui.fonts(|f| f.layout_job(layout_job))
529        };
530
531        let layouter = layouter.unwrap_or(&mut default_layouter);
532
533        let mut galley = layouter(ui, text.as_str(), wrap_width);
534
535        let desired_inner_width = if clip_text {
536            wrap_width // visual clipping with scroll in singleline input.
537        } else {
538            galley.size().x.max(wrap_width)
539        };
540        let desired_height = (desired_height_rows.at_least(1) as f32) * row_height;
541        let desired_inner_size = vec2(desired_inner_width, galley.size().y.max(desired_height));
542        let desired_outer_size = (desired_inner_size + margin.sum()).at_least(min_size);
543        let (auto_id, outer_rect) = ui.allocate_space(desired_outer_size);
544        let rect = outer_rect - margin; // inner rect (excluding frame/margin).
545
546        let id = id.unwrap_or_else(|| {
547            if let Some(id_salt) = id_salt {
548                ui.make_persistent_id(id_salt)
549            } else {
550                auto_id // Since we are only storing the cursor a persistent Id is not super important
551            }
552        });
553        let mut state = TextEditState::load(ui.ctx(), id).unwrap_or_default();
554
555        // On touch screens (e.g. mobile in `eframe` web), should
556        // dragging select text, or scroll the enclosing [`ScrollArea`] (if any)?
557        // Since currently copying selected text in not supported on `eframe` web,
558        // we prioritize touch-scrolling:
559        let allow_drag_to_select =
560            ui.input(|i| !i.has_touch_screen()) || ui.memory(|mem| mem.has_focus(id));
561
562        let sense = if interactive {
563            if allow_drag_to_select {
564                Sense::click_and_drag()
565            } else {
566                Sense::click()
567            }
568        } else {
569            Sense::hover()
570        };
571        let mut response = ui.interact(outer_rect, id, sense);
572        response.intrinsic_size = Some(Vec2::new(desired_width, desired_outer_size.y));
573
574        // Don't sent `OutputEvent::Clicked` when a user presses the space bar
575        response.flags -= response::Flags::FAKE_PRIMARY_CLICKED;
576        let text_clip_rect = rect;
577        let painter = ui.painter_at(text_clip_rect.expand(1.0)); // expand to avoid clipping cursor
578
579        if interactive {
580            if let Some(pointer_pos) = ui.ctx().pointer_interact_pos() {
581                if response.hovered() && text.is_mutable() {
582                    ui.output_mut(|o| o.mutable_text_under_cursor = true);
583                }
584
585                // TODO(emilk): drag selected text to either move or clone (ctrl on windows, alt on mac)
586
587                let singleline_offset = vec2(state.singleline_offset, 0.0);
588                let cursor_at_pointer =
589                    galley.cursor_from_pos(pointer_pos - rect.min + singleline_offset);
590
591                if ui.visuals().text_cursor.preview
592                    && response.hovered()
593                    && ui.input(|i| i.pointer.is_moving())
594                {
595                    // text cursor preview:
596                    let cursor_rect = TSTransform::from_translation(rect.min.to_vec2())
597                        * cursor_rect(&galley, &cursor_at_pointer, row_height);
598                    text_selection::visuals::paint_cursor_end(&painter, ui.visuals(), cursor_rect);
599                }
600
601                let is_being_dragged = ui.ctx().is_being_dragged(response.id);
602                let did_interact = state.cursor.pointer_interaction(
603                    ui,
604                    &response,
605                    cursor_at_pointer,
606                    &galley,
607                    is_being_dragged,
608                );
609
610                if did_interact || response.clicked() {
611                    ui.memory_mut(|mem| mem.request_focus(response.id));
612
613                    state.last_interaction_time = ui.ctx().input(|i| i.time);
614                }
615            }
616        }
617
618        if interactive && response.hovered() {
619            ui.ctx().set_cursor_icon(CursorIcon::Text);
620        }
621
622        let mut cursor_range = None;
623        let prev_cursor_range = state.cursor.range(&galley);
624        if interactive && ui.memory(|mem| mem.has_focus(id)) {
625            ui.memory_mut(|mem| mem.set_focus_lock_filter(id, event_filter));
626
627            let default_cursor_range = if cursor_at_end {
628                CursorRange::one(galley.end())
629            } else {
630                CursorRange::default()
631            };
632
633            let (changed, new_cursor_range) = events(
634                ui,
635                &mut state,
636                text,
637                &mut galley,
638                layouter,
639                id,
640                wrap_width,
641                multiline,
642                password,
643                default_cursor_range,
644                char_limit,
645                event_filter,
646                return_key,
647            );
648
649            if changed {
650                response.mark_changed();
651            }
652            cursor_range = Some(new_cursor_range);
653        }
654
655        let mut galley_pos = align
656            .align_size_within_rect(galley.size(), rect)
657            .intersect(rect) // limit pos to the response rect area
658            .min;
659        let align_offset = rect.left() - galley_pos.x;
660
661        // Visual clipping for singleline text editor with text larger than width
662        if clip_text && align_offset == 0.0 {
663            let cursor_pos = match (cursor_range, ui.memory(|mem| mem.has_focus(id))) {
664                (Some(cursor_range), true) => galley.pos_from_cursor(&cursor_range.primary).min.x,
665                _ => 0.0,
666            };
667
668            let mut offset_x = state.singleline_offset;
669            let visible_range = offset_x..=offset_x + desired_inner_size.x;
670
671            if !visible_range.contains(&cursor_pos) {
672                if cursor_pos < *visible_range.start() {
673                    offset_x = cursor_pos;
674                } else {
675                    offset_x = cursor_pos - desired_inner_size.x;
676                }
677            }
678
679            offset_x = offset_x
680                .at_most(galley.size().x - desired_inner_size.x)
681                .at_least(0.0);
682
683            state.singleline_offset = offset_x;
684            galley_pos -= vec2(offset_x, 0.0);
685        } else {
686            state.singleline_offset = align_offset;
687        }
688
689        let selection_changed = if let (Some(cursor_range), Some(prev_cursor_range)) =
690            (cursor_range, prev_cursor_range)
691        {
692            prev_cursor_range.as_ccursor_range() != cursor_range.as_ccursor_range()
693        } else {
694            false
695        };
696
697        if ui.is_rect_visible(rect) {
698            if text.as_str().is_empty() && !hint_text.is_empty() {
699                let hint_text_color = ui.visuals().weak_text_color();
700                let hint_text_font_id = hint_text_font.unwrap_or(font_id.into());
701                let galley = if multiline {
702                    hint_text.into_galley(
703                        ui,
704                        Some(TextWrapMode::Wrap),
705                        desired_inner_size.x,
706                        hint_text_font_id,
707                    )
708                } else {
709                    hint_text.into_galley(
710                        ui,
711                        Some(TextWrapMode::Extend),
712                        f32::INFINITY,
713                        hint_text_font_id,
714                    )
715                };
716                let galley_pos = align
717                    .align_size_within_rect(galley.size(), rect)
718                    .intersect(rect)
719                    .min;
720                painter.galley(galley_pos, galley, hint_text_color);
721            }
722
723            let has_focus = ui.memory(|mem| mem.has_focus(id));
724
725            if has_focus {
726                if let Some(cursor_range) = state.cursor.range(&galley) {
727                    // Add text selection rectangles to the galley:
728                    paint_text_selection(&mut galley, ui.visuals(), &cursor_range, None);
729                }
730            }
731
732            // Allocate additional space if edits were made this frame that changed the size. This is important so that,
733            // if there's a ScrollArea, it can properly scroll to the cursor.
734            let extra_size = galley.size() - rect.size();
735            if extra_size.x > 0.0 || extra_size.y > 0.0 {
736                ui.allocate_rect(
737                    Rect::from_min_size(outer_rect.max, extra_size),
738                    Sense::hover(),
739                );
740            }
741
742            painter.galley(galley_pos, galley.clone(), text_color);
743
744            if has_focus {
745                if let Some(cursor_range) = state.cursor.range(&galley) {
746                    let primary_cursor_rect =
747                        cursor_rect(&galley, &cursor_range.primary, row_height)
748                            .translate(galley_pos.to_vec2());
749
750                    if response.changed() || selection_changed {
751                        // Scroll to keep primary cursor in view:
752                        ui.scroll_to_rect(primary_cursor_rect + margin, None);
753                    }
754
755                    if text.is_mutable() && interactive {
756                        let now = ui.ctx().input(|i| i.time);
757                        if response.changed() || selection_changed {
758                            state.last_interaction_time = now;
759                        }
760
761                        // Only show (and blink) cursor if the egui viewport has focus.
762                        // This is for two reasons:
763                        // * Don't give the impression that the user can type into a window without focus
764                        // * Don't repaint the ui because of a blinking cursor in an app that is not in focus
765                        let viewport_has_focus = ui.ctx().input(|i| i.focused);
766                        if viewport_has_focus {
767                            text_selection::visuals::paint_text_cursor(
768                                ui,
769                                &painter,
770                                primary_cursor_rect,
771                                now - state.last_interaction_time,
772                            );
773                        }
774
775                        // Set IME output (in screen coords) when text is editable and visible
776                        let to_global = ui
777                            .ctx()
778                            .layer_transform_to_global(ui.layer_id())
779                            .unwrap_or_default();
780
781                        ui.ctx().output_mut(|o| {
782                            o.ime = Some(crate::output::IMEOutput {
783                                rect: to_global * rect,
784                                cursor_rect: to_global * primary_cursor_rect,
785                            });
786                        });
787                    }
788                }
789            }
790        }
791
792        // Ensures correct IME behavior when the text input area gains or loses focus.
793        if state.ime_enabled && (response.gained_focus() || response.lost_focus()) {
794            state.ime_enabled = false;
795            if let Some(mut ccursor_range) = state.cursor.char_range() {
796                ccursor_range.secondary.index = ccursor_range.primary.index;
797                state.cursor.set_char_range(Some(ccursor_range));
798            }
799            ui.input_mut(|i| i.events.retain(|e| !matches!(e, Event::Ime(_))));
800        }
801
802        state.clone().store(ui.ctx(), id);
803
804        if response.changed() {
805            response.widget_info(|| {
806                WidgetInfo::text_edit(
807                    ui.is_enabled(),
808                    mask_if_password(password, prev_text.as_str()),
809                    mask_if_password(password, text.as_str()),
810                )
811            });
812        } else if selection_changed {
813            let cursor_range = cursor_range.unwrap();
814            let char_range =
815                cursor_range.primary.ccursor.index..=cursor_range.secondary.ccursor.index;
816            let info = WidgetInfo::text_selection_changed(
817                ui.is_enabled(),
818                char_range,
819                mask_if_password(password, text.as_str()),
820            );
821            response.output_event(OutputEvent::TextSelectionChanged(info));
822        } else {
823            response.widget_info(|| {
824                WidgetInfo::text_edit(
825                    ui.is_enabled(),
826                    mask_if_password(password, prev_text.as_str()),
827                    mask_if_password(password, text.as_str()),
828                )
829            });
830        }
831
832        #[cfg(feature = "accesskit")]
833        {
834            let role = if password {
835                accesskit::Role::PasswordInput
836            } else if multiline {
837                accesskit::Role::MultilineTextInput
838            } else {
839                accesskit::Role::TextInput
840            };
841
842            crate::text_selection::accesskit_text::update_accesskit_for_text_widget(
843                ui.ctx(),
844                id,
845                cursor_range,
846                role,
847                TSTransform::from_translation(galley_pos.to_vec2()),
848                &galley,
849            );
850        }
851
852        TextEditOutput {
853            response,
854            galley,
855            galley_pos,
856            text_clip_rect,
857            state,
858            cursor_range,
859        }
860    }
861}
862
863fn mask_if_password(is_password: bool, text: &str) -> String {
864    fn mask_password(text: &str) -> String {
865        std::iter::repeat(epaint::text::PASSWORD_REPLACEMENT_CHAR)
866            .take(text.chars().count())
867            .collect::<String>()
868    }
869
870    if is_password {
871        mask_password(text)
872    } else {
873        text.to_owned()
874    }
875}
876
877// ----------------------------------------------------------------------------
878
879/// Check for (keyboard) events to edit the cursor and/or text.
880#[allow(clippy::too_many_arguments)]
881fn events(
882    ui: &crate::Ui,
883    state: &mut TextEditState,
884    text: &mut dyn TextBuffer,
885    galley: &mut Arc<Galley>,
886    layouter: &mut dyn FnMut(&Ui, &str, f32) -> Arc<Galley>,
887    id: Id,
888    wrap_width: f32,
889    multiline: bool,
890    password: bool,
891    default_cursor_range: CursorRange,
892    char_limit: usize,
893    event_filter: EventFilter,
894    return_key: Option<KeyboardShortcut>,
895) -> (bool, CursorRange) {
896    let os = ui.ctx().os();
897
898    let mut cursor_range = state.cursor.range(galley).unwrap_or(default_cursor_range);
899
900    // We feed state to the undoer both before and after handling input
901    // so that the undoer creates automatic saves even when there are no events for a while.
902    state.undoer.lock().feed_state(
903        ui.input(|i| i.time),
904        &(cursor_range.as_ccursor_range(), text.as_str().to_owned()),
905    );
906
907    let copy_if_not_password = |ui: &Ui, text: String| {
908        if !password {
909            ui.ctx().copy_text(text);
910        }
911    };
912
913    let mut any_change = false;
914
915    let mut events = ui.input(|i| i.filtered_events(&event_filter));
916
917    if state.ime_enabled {
918        remove_ime_incompatible_events(&mut events);
919        // Process IME events first:
920        events.sort_by_key(|e| !matches!(e, Event::Ime(_)));
921    }
922
923    for event in &events {
924        let did_mutate_text = match event {
925            // First handle events that only changes the selection cursor, not the text:
926            event if cursor_range.on_event(os, event, galley, id) => None,
927
928            Event::Copy => {
929                if cursor_range.is_empty() {
930                    None
931                } else {
932                    copy_if_not_password(ui, cursor_range.slice_str(text.as_str()).to_owned());
933                    None
934                }
935            }
936            Event::Cut => {
937                if cursor_range.is_empty() {
938                    None
939                } else {
940                    copy_if_not_password(ui, cursor_range.slice_str(text.as_str()).to_owned());
941                    Some(CCursorRange::one(text.delete_selected(&cursor_range)))
942                }
943            }
944            Event::Paste(text_to_insert) => {
945                if !text_to_insert.is_empty() {
946                    let mut ccursor = text.delete_selected(&cursor_range);
947
948                    text.insert_text_at(&mut ccursor, text_to_insert, char_limit);
949
950                    Some(CCursorRange::one(ccursor))
951                } else {
952                    None
953                }
954            }
955            Event::Text(text_to_insert) => {
956                // Newlines are handled by `Key::Enter`.
957                if !text_to_insert.is_empty() && text_to_insert != "\n" && text_to_insert != "\r" {
958                    let mut ccursor = text.delete_selected(&cursor_range);
959
960                    text.insert_text_at(&mut ccursor, text_to_insert, char_limit);
961
962                    Some(CCursorRange::one(ccursor))
963                } else {
964                    None
965                }
966            }
967            Event::Key {
968                key: Key::Tab,
969                pressed: true,
970                modifiers,
971                ..
972            } if multiline => {
973                let mut ccursor = text.delete_selected(&cursor_range);
974                if modifiers.shift {
975                    // TODO(emilk): support removing indentation over a selection?
976                    text.decrease_indentation(&mut ccursor);
977                } else {
978                    text.insert_text_at(&mut ccursor, "\t", char_limit);
979                }
980                Some(CCursorRange::one(ccursor))
981            }
982            Event::Key {
983                key,
984                pressed: true,
985                modifiers,
986                ..
987            } if return_key.is_some_and(|return_key| {
988                *key == return_key.logical_key && modifiers.matches_logically(return_key.modifiers)
989            }) =>
990            {
991                if multiline {
992                    let mut ccursor = text.delete_selected(&cursor_range);
993                    text.insert_text_at(&mut ccursor, "\n", char_limit);
994                    // TODO(emilk): if code editor, auto-indent by same leading tabs, + one if the lines end on an opening bracket
995                    Some(CCursorRange::one(ccursor))
996                } else {
997                    ui.memory_mut(|mem| mem.surrender_focus(id)); // End input with enter
998                    break;
999                }
1000            }
1001
1002            Event::Key {
1003                key,
1004                pressed: true,
1005                modifiers,
1006                ..
1007            } if (modifiers.matches_logically(Modifiers::COMMAND) && *key == Key::Y)
1008                || (modifiers.matches_logically(Modifiers::SHIFT | Modifiers::COMMAND)
1009                    && *key == Key::Z) =>
1010            {
1011                if let Some((redo_ccursor_range, redo_txt)) = state
1012                    .undoer
1013                    .lock()
1014                    .redo(&(cursor_range.as_ccursor_range(), text.as_str().to_owned()))
1015                {
1016                    text.replace_with(redo_txt);
1017                    Some(*redo_ccursor_range)
1018                } else {
1019                    None
1020                }
1021            }
1022
1023            Event::Key {
1024                key: Key::Z,
1025                pressed: true,
1026                modifiers,
1027                ..
1028            } if modifiers.matches_logically(Modifiers::COMMAND) => {
1029                if let Some((undo_ccursor_range, undo_txt)) = state
1030                    .undoer
1031                    .lock()
1032                    .undo(&(cursor_range.as_ccursor_range(), text.as_str().to_owned()))
1033                {
1034                    text.replace_with(undo_txt);
1035                    Some(*undo_ccursor_range)
1036                } else {
1037                    None
1038                }
1039            }
1040
1041            Event::Key {
1042                modifiers,
1043                key,
1044                pressed: true,
1045                ..
1046            } => check_for_mutating_key_press(os, &cursor_range, text, galley, modifiers, *key),
1047
1048            Event::Ime(ime_event) => match ime_event {
1049                ImeEvent::Enabled => {
1050                    state.ime_enabled = true;
1051                    state.ime_cursor_range = cursor_range;
1052                    None
1053                }
1054                ImeEvent::Preedit(text_mark) => {
1055                    if text_mark == "\n" || text_mark == "\r" {
1056                        None
1057                    } else {
1058                        // Empty prediction can be produced when user press backspace
1059                        // or escape during IME, so we clear current text.
1060                        let mut ccursor = text.delete_selected(&cursor_range);
1061                        let start_cursor = ccursor;
1062                        if !text_mark.is_empty() {
1063                            text.insert_text_at(&mut ccursor, text_mark, char_limit);
1064                        }
1065                        state.ime_cursor_range = cursor_range;
1066                        Some(CCursorRange::two(start_cursor, ccursor))
1067                    }
1068                }
1069                ImeEvent::Commit(prediction) => {
1070                    if prediction == "\n" || prediction == "\r" {
1071                        None
1072                    } else {
1073                        state.ime_enabled = false;
1074
1075                        if !prediction.is_empty()
1076                            && cursor_range.secondary.ccursor.index
1077                                == state.ime_cursor_range.secondary.ccursor.index
1078                        {
1079                            let mut ccursor = text.delete_selected(&cursor_range);
1080                            text.insert_text_at(&mut ccursor, prediction, char_limit);
1081                            Some(CCursorRange::one(ccursor))
1082                        } else {
1083                            let ccursor = cursor_range.primary.ccursor;
1084                            Some(CCursorRange::one(ccursor))
1085                        }
1086                    }
1087                }
1088                ImeEvent::Disabled => {
1089                    state.ime_enabled = false;
1090                    None
1091                }
1092            },
1093
1094            _ => None,
1095        };
1096
1097        if let Some(new_ccursor_range) = did_mutate_text {
1098            any_change = true;
1099
1100            // Layout again to avoid frame delay, and to keep `text` and `galley` in sync.
1101            *galley = layouter(ui, text.as_str(), wrap_width);
1102
1103            // Set cursor_range using new galley:
1104            cursor_range = CursorRange {
1105                primary: galley.from_ccursor(new_ccursor_range.primary),
1106                secondary: galley.from_ccursor(new_ccursor_range.secondary),
1107            };
1108        }
1109    }
1110
1111    state.cursor.set_range(Some(cursor_range));
1112
1113    state.undoer.lock().feed_state(
1114        ui.input(|i| i.time),
1115        &(cursor_range.as_ccursor_range(), text.as_str().to_owned()),
1116    );
1117
1118    (any_change, cursor_range)
1119}
1120
1121// ----------------------------------------------------------------------------
1122
1123fn remove_ime_incompatible_events(events: &mut Vec<Event>) {
1124    // Remove key events which cause problems while 'IME' is being used.
1125    // See https://github.com/emilk/egui/pull/4509
1126    events.retain(|event| {
1127        !matches!(
1128            event,
1129            Event::Key { repeat: true, .. }
1130                | Event::Key {
1131                    key: Key::Backspace
1132                        | Key::ArrowUp
1133                        | Key::ArrowDown
1134                        | Key::ArrowLeft
1135                        | Key::ArrowRight,
1136                    ..
1137                }
1138        )
1139    });
1140}
1141
1142// ----------------------------------------------------------------------------
1143
1144/// Returns `Some(new_cursor)` if we did mutate `text`.
1145fn check_for_mutating_key_press(
1146    os: OperatingSystem,
1147    cursor_range: &CursorRange,
1148    text: &mut dyn TextBuffer,
1149    galley: &Galley,
1150    modifiers: &Modifiers,
1151    key: Key,
1152) -> Option<CCursorRange> {
1153    match key {
1154        Key::Backspace => {
1155            let ccursor = if modifiers.mac_cmd {
1156                text.delete_paragraph_before_cursor(galley, cursor_range)
1157            } else if let Some(cursor) = cursor_range.single() {
1158                if modifiers.alt || modifiers.ctrl {
1159                    // alt on mac, ctrl on windows
1160                    text.delete_previous_word(cursor.ccursor)
1161                } else {
1162                    text.delete_previous_char(cursor.ccursor)
1163                }
1164            } else {
1165                text.delete_selected(cursor_range)
1166            };
1167            Some(CCursorRange::one(ccursor))
1168        }
1169
1170        Key::Delete if !modifiers.shift || os != OperatingSystem::Windows => {
1171            let ccursor = if modifiers.mac_cmd {
1172                text.delete_paragraph_after_cursor(galley, cursor_range)
1173            } else if let Some(cursor) = cursor_range.single() {
1174                if modifiers.alt || modifiers.ctrl {
1175                    // alt on mac, ctrl on windows
1176                    text.delete_next_word(cursor.ccursor)
1177                } else {
1178                    text.delete_next_char(cursor.ccursor)
1179                }
1180            } else {
1181                text.delete_selected(cursor_range)
1182            };
1183            let ccursor = CCursor {
1184                prefer_next_row: true,
1185                ..ccursor
1186            };
1187            Some(CCursorRange::one(ccursor))
1188        }
1189
1190        Key::H if modifiers.ctrl => {
1191            let ccursor = text.delete_previous_char(cursor_range.primary.ccursor);
1192            Some(CCursorRange::one(ccursor))
1193        }
1194
1195        Key::K if modifiers.ctrl => {
1196            let ccursor = text.delete_paragraph_after_cursor(galley, cursor_range);
1197            Some(CCursorRange::one(ccursor))
1198        }
1199
1200        Key::U if modifiers.ctrl => {
1201            let ccursor = text.delete_paragraph_before_cursor(galley, cursor_range);
1202            Some(CCursorRange::one(ccursor))
1203        }
1204
1205        Key::W if modifiers.ctrl => {
1206            let ccursor = if let Some(cursor) = cursor_range.single() {
1207                text.delete_previous_word(cursor.ccursor)
1208            } else {
1209                text.delete_selected(cursor_range)
1210            };
1211            Some(CCursorRange::one(ccursor))
1212        }
1213
1214        _ => None,
1215    }
1216}